ccdserver.cpp 884 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402
  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 dependencyIndexes;
  792. IntArray dependencyControlIds;
  793. IArrayOf<IActivityGraph> childGraphs;
  794. CachedOutputMetaData meta;
  795. IHThorArg *colocalParent;
  796. IEngineRowAllocator *rowAllocator;
  797. CriticalSection statecrit;
  798. mutable StatsCollector stats;
  799. unsigned processed;
  800. unsigned __int64 totalCycles;
  801. unsigned activityId;
  802. activityState state;
  803. bool createPending;
  804. bool debugging;
  805. public:
  806. IMPLEMENT_IINTERFACE;
  807. CRoxieServerActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  808. : factory(_factory),
  809. basehelper(_factory->getHelper()),
  810. activityId(_factory->queryId())
  811. {
  812. input = NULL;
  813. ctx = NULL;
  814. meta.set(basehelper.queryOutputMeta());
  815. processed = 0;
  816. totalCycles = 0;
  817. if (factory)
  818. factory->createChildQueries(childGraphs, this, _probeManager, *this);
  819. state=STATEreset;
  820. rowAllocator = NULL;
  821. debugging = _probeManager != NULL; // Don't want to collect timing stats from debug sessions
  822. colocalParent = NULL;
  823. createPending = true;
  824. }
  825. CRoxieServerActivity(IHThorArg & _helper) : factory(NULL), basehelper(_helper)
  826. {
  827. activityId = 0;
  828. input = NULL;
  829. ctx = NULL;
  830. meta.set(basehelper.queryOutputMeta());
  831. processed = 0;
  832. totalCycles = 0;
  833. state=STATEreset;
  834. rowAllocator = NULL;
  835. debugging = false;
  836. colocalParent = NULL;
  837. createPending = true;
  838. }
  839. inline ~CRoxieServerActivity()
  840. {
  841. CriticalBlock cb(statecrit);
  842. if (traceStartStop)
  843. DBGLOG("%p destroy state=%s", this, queryStateText(state)); // Note- CTXLOG may not be safe
  844. if (state!=STATEreset)
  845. {
  846. DBGLOG("STATE: Activity %d destroyed but not reset", activityId);
  847. state = STATEreset; // bit pointless but there you go...
  848. }
  849. basehelper.Release();
  850. ::Release(rowAllocator);
  851. }
  852. virtual const IRoxieContextLogger &queryLogCtx()const
  853. {
  854. return *this;
  855. }
  856. inline void createRowAllocator()
  857. {
  858. if (!rowAllocator)
  859. rowAllocator = ctx->queryCodeContext()->getRowAllocator(meta.queryOriginal(), activityId);
  860. }
  861. // MORE - most of this is copied from ccd.hpp - can't we refactor?
  862. virtual void CTXLOG(const char *format, ...) const
  863. {
  864. va_list args;
  865. va_start(args, format);
  866. CTXLOGva(format, args);
  867. va_end(args);
  868. }
  869. virtual void CTXLOGva(const char *format, va_list args) const
  870. {
  871. StringBuffer text, prefix;
  872. getLogPrefix(prefix);
  873. text.valist_appendf(format, args);
  874. CTXLOGa(LOG_TRACING, prefix.str(), text.str());
  875. }
  876. virtual void CTXLOGa(TracingCategory category, const char *prefix, const char *text) const
  877. {
  878. if (ctx)
  879. ctx->CTXLOGa(category, prefix, text);
  880. else
  881. DBGLOG("[%s] %s", prefix, text);
  882. }
  883. virtual void logOperatorException(IException *E, const char *file, unsigned line, const char *format, ...) const
  884. {
  885. va_list args;
  886. va_start(args, format);
  887. StringBuffer prefix;
  888. getLogPrefix(prefix);
  889. CTXLOGaeva(E, file, line, prefix.str(), format, args);
  890. va_end(args);
  891. }
  892. virtual void logOperatorExceptionVA(IException *E, const char *file, unsigned line, const char *format, va_list args) const
  893. {
  894. StringBuffer prefix;
  895. getLogPrefix(prefix);
  896. CTXLOGaeva(E, file, line, prefix.str(), format, args);
  897. }
  898. virtual void CTXLOGae(IException *E, const char *file, unsigned line, const char *prefix, const char *format, ...) const
  899. {
  900. va_list args;
  901. va_start(args, format);
  902. CTXLOGaeva(E, file, line, prefix, format, args);
  903. va_end(args);
  904. }
  905. virtual void CTXLOGaeva(IException *E, const char *file, unsigned line, const char *prefix, const char *format, va_list args) const
  906. {
  907. if (ctx)
  908. ctx->CTXLOGaeva(E, file, line, prefix, format, args);
  909. else
  910. {
  911. StringBuffer ss;
  912. ss.appendf("[%s] ERROR", prefix);
  913. if (E)
  914. ss.append(": ").append(E->errorCode());
  915. if (file)
  916. ss.appendf(": %s(%d) ", file, line);
  917. if (E)
  918. E->errorMessage(ss.append(": "));
  919. if (format)
  920. {
  921. ss.append(": ").valist_appendf(format, args);
  922. }
  923. LOG(MCoperatorProgress, unknownJob, "%s", ss.str());
  924. }
  925. }
  926. virtual void CTXLOGl(LogItem *log) const
  927. {
  928. if (ctx)
  929. ctx->CTXLOGl(log);
  930. else
  931. {
  932. assert(ctx);
  933. log->Release(); // Should never happen
  934. }
  935. }
  936. virtual void noteStatistic(unsigned statCode, unsigned __int64 value, unsigned count) const
  937. {
  938. if (factory)
  939. factory->noteStatistic(statCode, value, count);
  940. if (ctx)
  941. ctx->noteStatistic(statCode, value, count);
  942. stats.noteStatistic(statCode, value, count);
  943. }
  944. virtual StringBuffer &getLogPrefix(StringBuffer &ret) const
  945. {
  946. if (ctx)
  947. ctx->getLogPrefix(ret);
  948. return ret.append('@').append(activityId);
  949. }
  950. virtual bool isIntercepted() const
  951. {
  952. return ctx ? ctx->isIntercepted() : false;
  953. }
  954. virtual bool isBlind() const
  955. {
  956. return ctx ? ctx->isBlind() : blindLogging;
  957. }
  958. virtual unsigned queryTraceLevel() const
  959. {
  960. if (ctx)
  961. return ctx->queryTraceLevel();
  962. else
  963. return traceLevel;
  964. }
  965. virtual bool isPassThrough()
  966. {
  967. return false;
  968. }
  969. virtual const IResolvedFile *resolveLFN(const char *filename, bool isOpt)
  970. {
  971. return ctx->resolveLFN(filename, isOpt);
  972. }
  973. virtual const IResolvedFile *queryVarFileInfo() const
  974. {
  975. throwUnexpected(); // should be implemented in more derived class by anyone that has a remote adaptor
  976. return NULL;
  977. }
  978. virtual void serializeSkipInfo(MemoryBuffer &out, unsigned seekLen, const void *rawSeek, unsigned numFields, const void * seek, const SmartStepExtra &stepExtra) const
  979. {
  980. throwUnexpected(); // should be implemented in more derived class wherever needed
  981. }
  982. virtual IRoxieSlaveContext *queryContext()
  983. {
  984. return ctx;
  985. }
  986. virtual IRoxieServerActivity *queryActivity() { return this; }
  987. virtual IIndexReadActivityInfo *queryIndexReadActivity() { return NULL; }
  988. virtual bool needsAllocator() const { return false; }
  989. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  990. {
  991. ctx = _ctx;
  992. colocalParent = _colocalParent;
  993. createPending = true;
  994. if (needsAllocator())
  995. createRowAllocator();
  996. processed = 0;
  997. totalCycles = 0;
  998. if (factory)
  999. factory->onCreateChildQueries(_ctx, &basehelper, childGraphs);
  1000. }
  1001. virtual void serializeCreateStartContext(MemoryBuffer &out)
  1002. {
  1003. //This should only be called after onStart has been called on the helper
  1004. assertex(!createPending);
  1005. assertex(state==STATEstarted);
  1006. unsigned startlen = out.length();
  1007. basehelper.serializeCreateContext(out);
  1008. basehelper.serializeStartContext(out);
  1009. if (queryTraceLevel() > 10)
  1010. CTXLOG("serializeCreateStartContext for %d added %d bytes", activityId, out.length()-startlen);
  1011. }
  1012. virtual void serializeExtra(MemoryBuffer &out) {}
  1013. inline void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  1014. {
  1015. CriticalBlock cb(statecrit);
  1016. if (state != STATEreset && state != STATEstarting)
  1017. {
  1018. CTXLOG("STATE: Expected state to be reset, but was %s, in activity %d", queryStateText(state), activityId);
  1019. }
  1020. state=STATEstarted;
  1021. #ifdef TRACE_STARTSTOP
  1022. if (traceStartStop)
  1023. {
  1024. CTXLOG("start %d", activityId);
  1025. if (watchActivityId && watchActivityId==activityId)
  1026. {
  1027. CTXLOG("WATCH: start %d", activityId);
  1028. }
  1029. }
  1030. #endif
  1031. executeDependencies(parentExtractSize, parentExtract, 0);
  1032. if (input)
  1033. input->start(parentExtractSize, parentExtract, paused);
  1034. ensureCreated();
  1035. basehelper.onStart(parentExtract, NULL);
  1036. if (factory)
  1037. factory->noteStarted();
  1038. }
  1039. void executeDependencies(unsigned parentExtractSize, const byte *parentExtract, unsigned controlId)
  1040. {
  1041. //MORE: Create a filtered list and then use asyncfor
  1042. ForEachItemIn(idx, dependencies)
  1043. {
  1044. if (dependencyControlIds.item(idx) == controlId)
  1045. dependencies.item(idx).execute(parentExtractSize, parentExtract);
  1046. }
  1047. }
  1048. void stopDependencies(unsigned parentExtractSize, const byte *parentExtract, unsigned controlId)
  1049. {
  1050. ForEachItemIn(idx, dependencies)
  1051. {
  1052. if (dependencyControlIds.item(idx) == controlId)
  1053. dependencies.item(idx).stop(false);
  1054. }
  1055. }
  1056. virtual unsigned __int64 queryTotalCycles() const
  1057. {
  1058. return totalCycles;
  1059. }
  1060. virtual unsigned __int64 queryLocalCycles() const
  1061. {
  1062. __int64 ret = totalCycles;
  1063. if (input) ret -= input->queryTotalCycles();
  1064. if (ret < 0)
  1065. ret = 0;
  1066. return ret;
  1067. }
  1068. virtual IRoxieInput *queryInput(unsigned idx) const
  1069. {
  1070. if (idx==0)
  1071. return input;
  1072. else
  1073. return NULL;
  1074. }
  1075. void noteProcessed(unsigned _idx, unsigned _processed, unsigned __int64 _totalCycles, unsigned __int64 _localCycles) const
  1076. {
  1077. if (factory)
  1078. {
  1079. if (!debugging)
  1080. factory->noteProcessed(_idx, _processed, _totalCycles, _localCycles);
  1081. if (ctx)
  1082. ctx->noteProcessed(*this, this, _idx, _processed, _totalCycles, _localCycles);
  1083. }
  1084. }
  1085. inline void ensureCreated()
  1086. {
  1087. if (createPending)
  1088. {
  1089. createPending = false;
  1090. basehelper.onCreate(ctx->queryCodeContext(), colocalParent, NULL);
  1091. }
  1092. }
  1093. inline void stop(bool aborting)
  1094. {
  1095. if (state != STATEstopped)
  1096. {
  1097. CriticalBlock cb(statecrit);
  1098. if (state != STATEstopped)
  1099. {
  1100. if (state != STATEreset)
  1101. state=STATEstopped;
  1102. #ifdef TRACE_STARTSTOP
  1103. if (traceStartStop)
  1104. {
  1105. CTXLOG("stop %d", activityId);
  1106. if (watchActivityId && watchActivityId==activityId)
  1107. {
  1108. CTXLOG("WATCH: stop %d", activityId);
  1109. }
  1110. }
  1111. #endif
  1112. // NOTE - this is needed to ensure that dependencies which were not used are properly stopped
  1113. ForEachItemIn(idx, dependencies)
  1114. {
  1115. if (dependencyControlIds.item(idx) == 0)
  1116. dependencies.item(idx).stopSink(dependencyIndexes.item(idx));
  1117. }
  1118. if (input)
  1119. input->stop(aborting);
  1120. }
  1121. }
  1122. }
  1123. inline void reset()
  1124. {
  1125. if (state != STATEreset)
  1126. {
  1127. CriticalBlock cb(statecrit);
  1128. if (state != STATEreset)
  1129. {
  1130. if (state==STATEstarted || state==STATEstarting)
  1131. {
  1132. if (traceStartStop || traceLevel > 2)
  1133. CTXLOG("STATE: activity %d reset without stop", activityId);
  1134. stop(false);
  1135. }
  1136. if (ctx->queryTimeActivities())
  1137. {
  1138. stats.dumpStats(*this);
  1139. StringBuffer prefix, text;
  1140. getLogPrefix(prefix);
  1141. text.appendf("records processed - %d", processed);
  1142. CTXLOGa(LOG_STATISTICS, prefix.str(), text.str());
  1143. text.clear().appendf("total time - %d us", (unsigned) (cycle_to_nanosec(totalCycles)/1000));
  1144. CTXLOGa(LOG_STATISTICS, prefix.str(), text.str());
  1145. text.clear().appendf("local time - %d us", (unsigned) (cycle_to_nanosec(queryLocalCycles())/1000));
  1146. CTXLOGa(LOG_STATISTICS, prefix.str(), text.str());
  1147. }
  1148. state = STATEreset;
  1149. #ifdef TRACE_STARTSTOP
  1150. if (traceStartStop)
  1151. {
  1152. CTXLOG("reset %d", activityId);
  1153. if (watchActivityId && watchActivityId==activityId)
  1154. {
  1155. CTXLOG("WATCH: reset %d", activityId);
  1156. }
  1157. }
  1158. #endif
  1159. ForEachItemIn(idx, dependencies)
  1160. dependencies.item(idx).reset();
  1161. noteProcessed(0, processed, totalCycles, queryLocalCycles());
  1162. if (input)
  1163. input->reset();
  1164. processed = 0;
  1165. totalCycles = 0;
  1166. }
  1167. }
  1168. }
  1169. virtual void addDependency(IRoxieServerActivity &source, unsigned sourceIdx, int controlId)
  1170. {
  1171. dependencies.append(source);
  1172. dependencyIndexes.append(sourceIdx);
  1173. dependencyControlIds.append(controlId);
  1174. }
  1175. virtual void resetEOF()
  1176. {
  1177. //would make more sense if the default implementation (and eof member) were in the base class
  1178. }
  1179. // Sink activities should override this....
  1180. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  1181. {
  1182. throw MakeStringException(ROXIE_SINK, "Internal error: execute() requires a sink");
  1183. }
  1184. virtual void executeChild(size32_t & retSize, void * & ret, unsigned parentExtractSize, const byte * parentExtract)
  1185. {
  1186. throw MakeStringException(ROXIE_SINK, "Internal error: executeChild() requires a suitable sink");
  1187. }
  1188. virtual void stopSink(unsigned idx)
  1189. {
  1190. throw MakeStringException(ROXIE_SINK, "Internal error: stopSink() requires a suitable sink");
  1191. }
  1192. virtual __int64 evaluate()
  1193. {
  1194. throw MakeStringException(ROXIE_SINK, "Internal error: evaluate() requires a function");
  1195. }
  1196. virtual IRoxieInput * querySelectOutput(unsigned id)
  1197. {
  1198. return NULL;
  1199. }
  1200. virtual bool querySetStreamInput(unsigned id, IRoxieInput * _input)
  1201. {
  1202. return false;
  1203. }
  1204. virtual void setInput(unsigned idx, IRoxieInput *_in)
  1205. {
  1206. assertex(!idx);
  1207. input = _in;
  1208. }
  1209. virtual IRoxieInput *queryOutput(unsigned idx)
  1210. {
  1211. if (idx == (unsigned) -1)
  1212. idx = 0;
  1213. return idx ? NULL : this;
  1214. }
  1215. virtual IOutputMetaData *queryOutputMeta() const
  1216. {
  1217. return meta.queryOriginal();
  1218. }
  1219. virtual unsigned queryId() const
  1220. {
  1221. return activityId;
  1222. }
  1223. virtual unsigned querySubgraphId() const
  1224. {
  1225. return factory->querySubgraphId();
  1226. }
  1227. virtual void checkAbort()
  1228. {
  1229. ctx->checkAbort();
  1230. }
  1231. IException *makeWrappedException(IException *e)
  1232. {
  1233. StringBuffer msg;
  1234. ThorActivityKind activityKind = factory ? factory->getKind() : TAKnone;
  1235. CTXLOG("makeWrappedException - %s (in %s %d)", e->errorMessage(msg).str(), getActivityText(activityKind), activityId);
  1236. if (QUERYINTERFACE(e, CWrappedException) || QUERYINTERFACE(e, IUserException))
  1237. return e;
  1238. else
  1239. return new CWrappedException(e, activityKind, activityId);
  1240. }
  1241. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract)
  1242. {
  1243. }
  1244. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract, IProbeManager *probeManager, IArrayOf<IRoxieInput> &probes)
  1245. {
  1246. }
  1247. virtual void resetOutputsUsed()
  1248. {
  1249. }
  1250. virtual void noteOutputUsed()
  1251. {
  1252. }
  1253. virtual IRoxieServerSideCache *queryServerSideCache() const
  1254. {
  1255. return factory->queryServerSideCache();
  1256. }
  1257. virtual const IRoxieServerActivityFactory *queryFactory() const
  1258. {
  1259. return factory;
  1260. }
  1261. inline ThorActivityKind getKind() const
  1262. {
  1263. return factory->getKind();
  1264. }
  1265. inline bool isSink() const
  1266. {
  1267. return (factory != NULL) && factory->isSink();
  1268. }
  1269. };
  1270. //=====================================================================================================
  1271. class CRoxieServerLateStartActivity : public CRoxieServerActivity
  1272. {
  1273. protected:
  1274. IRoxieInput *input; // Don't use base class input field as we want to delay starts
  1275. bool prefiltered;
  1276. bool eof;
  1277. void lateStart(unsigned parentExtractSize, const byte *parentExtract, bool any)
  1278. {
  1279. prefiltered = !any;
  1280. eof = prefiltered;
  1281. if (!prefiltered)
  1282. input->start(parentExtractSize, parentExtract, false);
  1283. else
  1284. {
  1285. if (traceStartStop)
  1286. CTXLOG("lateStart activity stopping input early as prefiltered");
  1287. input->stop(false);
  1288. }
  1289. }
  1290. public:
  1291. CRoxieServerLateStartActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  1292. : CRoxieServerActivity(_factory, _probeManager)
  1293. {
  1294. input = NULL;
  1295. prefiltered = false;
  1296. eof = false;
  1297. }
  1298. virtual void stop(bool aborting)
  1299. {
  1300. if (!prefiltered)
  1301. {
  1302. input->stop(aborting);
  1303. }
  1304. else if (traceStartStop)
  1305. CTXLOG("lateStart activity NOT stopping input late as prefiltered");
  1306. CRoxieServerActivity::stop(aborting);
  1307. }
  1308. virtual unsigned __int64 queryLocalCycles() const
  1309. {
  1310. __int64 localCycles = totalCycles - input->queryTotalCycles();
  1311. if (localCycles < 0)
  1312. localCycles = 0;
  1313. return localCycles;
  1314. }
  1315. virtual IRoxieInput *queryInput(unsigned idx) const
  1316. {
  1317. if (idx==0)
  1318. return input;
  1319. else
  1320. return NULL;
  1321. }
  1322. virtual void reset()
  1323. {
  1324. CRoxieServerActivity::reset();
  1325. input->reset();
  1326. prefiltered = false;
  1327. }
  1328. virtual void setInput(unsigned idx, IRoxieInput *_in)
  1329. {
  1330. assertex(!idx);
  1331. input = _in;
  1332. }
  1333. };
  1334. //=====================================================================================================
  1335. atomic_t nextInstanceId;
  1336. extern unsigned getNextInstanceId()
  1337. {
  1338. return atomic_add_exchange(&nextInstanceId, 1)+1;
  1339. }
  1340. atomic_t nextRuid;
  1341. ruid_t getNextRuid()
  1342. {
  1343. ruid_t ret = atomic_add_exchange(&nextRuid, 1)+1;
  1344. while (ret < RUID_FIRST)
  1345. ret = atomic_add_exchange(&nextRuid, 1)+1; // ruids 0 and 1 are reserved for pings/unwanted discarder.
  1346. return ret;
  1347. }
  1348. void setStartRuid(unsigned restarts)
  1349. {
  1350. atomic_set(&nextRuid, restarts * 0x10000);
  1351. atomic_set(&nextInstanceId, restarts * 10000);
  1352. }
  1353. enum { LimitSkipErrorCode = 0, KeyedLimitSkipErrorCode = 1 };
  1354. class LimitSkipException : public CInterface, public IException
  1355. {
  1356. int code;
  1357. public:
  1358. LimitSkipException(int _code) { code = _code; }
  1359. IMPLEMENT_IINTERFACE;
  1360. virtual int errorCode() const { return code; }
  1361. virtual StringBuffer & errorMessage(StringBuffer &msg) const { return msg.append("LimitSkipException"); }
  1362. virtual MessageAudience errorAudience() const { return MSGAUD_internal; }
  1363. };
  1364. IException *makeLimitSkipException(bool isKeyed)
  1365. {
  1366. // We need to make sure what we throw is IException not something derived from it....
  1367. return new LimitSkipException(isKeyed ? KeyedLimitSkipErrorCode : LimitSkipErrorCode);
  1368. }
  1369. //=================================================================================
  1370. interface IRecordPullerCallback : extends IExceptionHandler
  1371. {
  1372. virtual void processRow(const void *row) = 0;
  1373. virtual void processEOG() = 0;
  1374. virtual void processGroup(const ConstPointerArray &rows) = 0;
  1375. virtual void processDone() = 0;
  1376. };
  1377. class RecordPullerThread : public RestartableThread
  1378. {
  1379. protected:
  1380. IRoxieInput *input;
  1381. IRecordPullerCallback *helper;
  1382. Semaphore started; // MORE: GH->RKC I'm pretty sure this can be deleted, since handled by RestartableThread
  1383. bool groupAtOnce, eof, eog;
  1384. CriticalSection crit;
  1385. public:
  1386. RecordPullerThread(bool _groupAtOnce)
  1387. : RestartableThread("RecordPullerThread"), groupAtOnce(_groupAtOnce)
  1388. {
  1389. input = NULL;
  1390. helper = NULL;
  1391. eof = eog = FALSE;
  1392. }
  1393. inline unsigned __int64 queryTotalCycles() const
  1394. {
  1395. return input->queryTotalCycles();
  1396. }
  1397. void setInput(IRecordPullerCallback *_helper, IRoxieInput *_input)
  1398. {
  1399. helper = _helper;
  1400. input = _input;
  1401. }
  1402. IRoxieInput *queryInput() const
  1403. {
  1404. return input;
  1405. }
  1406. void start(unsigned parentExtractSize, const byte *parentExtract, bool paused, unsigned preload, bool noThread, IRoxieSlaveContext *ctx)
  1407. {
  1408. eof = false;
  1409. eog = false;
  1410. input->start(parentExtractSize, parentExtract, paused);
  1411. try
  1412. {
  1413. if (preload && !paused)
  1414. {
  1415. if (traceLevel > 4)
  1416. DBGLOG("Preload fetching first %d records", preload);
  1417. if (groupAtOnce)
  1418. pullGroups(preload);
  1419. else
  1420. pullRecords(preload);
  1421. }
  1422. if (eof)
  1423. {
  1424. if (traceLevel > 4)
  1425. DBGLOG("No need to start puller after preload");
  1426. helper->processDone();
  1427. }
  1428. else
  1429. {
  1430. if (!noThread)
  1431. {
  1432. StringBuffer logPrefix("[");
  1433. if (ctx) ctx->getLogPrefix(logPrefix);
  1434. logPrefix.append("] ");
  1435. RestartableThread::start(logPrefix);
  1436. started.wait();
  1437. }
  1438. }
  1439. }
  1440. catch (IException *e)
  1441. {
  1442. helper->fireException(e);
  1443. }
  1444. catch (...)
  1445. {
  1446. helper->fireException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unexpected exception caught in RecordPullerThread::start"));
  1447. }
  1448. }
  1449. void stop(bool aborting)
  1450. {
  1451. if (traceStartStop)
  1452. DBGLOG("RecordPullerThread::stop");
  1453. {
  1454. 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.
  1455. input->stop(aborting);
  1456. }
  1457. RestartableThread::join();
  1458. }
  1459. void reset()
  1460. {
  1461. input->reset();
  1462. }
  1463. virtual int run()
  1464. {
  1465. started.signal();
  1466. try
  1467. {
  1468. if (groupAtOnce)
  1469. pullGroups((unsigned) -1);
  1470. else
  1471. pullRecords((unsigned) -1);
  1472. helper->processDone();
  1473. }
  1474. catch (IException *e)
  1475. {
  1476. helper->fireException(e);
  1477. }
  1478. catch (...)
  1479. {
  1480. helper->fireException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unexpected exception caught in RecordPullerThread::run"));
  1481. }
  1482. return 0;
  1483. }
  1484. void done()
  1485. {
  1486. helper->processDone();
  1487. }
  1488. bool pullRecords(unsigned preload)
  1489. {
  1490. if (eof)
  1491. return false;
  1492. while (preload)
  1493. {
  1494. const void * row;
  1495. {
  1496. CriticalBlock c(crit); // See comments in stop for why this is needed
  1497. row = input->nextInGroup();
  1498. }
  1499. if (row)
  1500. {
  1501. eog = false;
  1502. helper->processRow(row);
  1503. }
  1504. else if (!eog)
  1505. {
  1506. helper->processEOG();
  1507. eog = true;
  1508. }
  1509. else
  1510. {
  1511. eof = true;
  1512. return false;
  1513. }
  1514. if (preload != (unsigned) -1)
  1515. preload--;
  1516. }
  1517. return true;
  1518. }
  1519. void pullGroups(unsigned preload)
  1520. {
  1521. ConstPointerArray thisGroup;
  1522. unsigned rowsDone = 0;
  1523. while (preload && !eof)
  1524. {
  1525. const void *row;
  1526. {
  1527. CriticalBlock c(crit);
  1528. row = input->nextInGroup();
  1529. }
  1530. if (row)
  1531. {
  1532. thisGroup.append(row);
  1533. rowsDone++;
  1534. }
  1535. else if (thisGroup.length())
  1536. {
  1537. helper->processGroup(thisGroup);
  1538. thisGroup.kill();
  1539. if (preload != (unsigned) -1)
  1540. {
  1541. if (preload > rowsDone)
  1542. preload -= rowsDone;
  1543. else
  1544. break;
  1545. }
  1546. rowsDone = 0;
  1547. }
  1548. else
  1549. {
  1550. eof = true;
  1551. break;
  1552. }
  1553. }
  1554. }
  1555. };
  1556. //=================================================================================
  1557. #define READAHEAD_SIZE 1000
  1558. // MORE - this code copied from ThreadedConcat code - may be able to common up some.
  1559. class CRoxieServerReadAheadInput : public CInterface, implements IRoxieInput, implements IRecordPullerCallback
  1560. {
  1561. QueueOf<const void, true> buffer;
  1562. InterruptableSemaphore ready;
  1563. InterruptableSemaphore space;
  1564. CriticalSection crit;
  1565. bool eof;
  1566. bool disabled;
  1567. RecordPullerThread puller;
  1568. unsigned preload;
  1569. unsigned __int64 totalCycles;
  1570. IRoxieSlaveContext *ctx;
  1571. public:
  1572. IMPLEMENT_IINTERFACE;
  1573. CRoxieServerReadAheadInput(unsigned _preload) : puller(true), preload(_preload)
  1574. {
  1575. eof = false;
  1576. disabled = false;
  1577. totalCycles = 0;
  1578. ctx = NULL;
  1579. }
  1580. void onCreate(IRoxieSlaveContext *_ctx)
  1581. {
  1582. ctx = _ctx;
  1583. disabled = (ctx->queryDebugContext() != NULL);
  1584. }
  1585. virtual IRoxieServerActivity *queryActivity()
  1586. {
  1587. return puller.queryInput()->queryActivity();
  1588. }
  1589. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  1590. {
  1591. return puller.queryInput()->queryIndexReadActivity();
  1592. }
  1593. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  1594. {
  1595. eof = false;
  1596. totalCycles = 0;
  1597. if (disabled)
  1598. puller.queryInput()->start(parentExtractSize, parentExtract, paused);
  1599. else
  1600. {
  1601. space.reinit(READAHEAD_SIZE);
  1602. ready.reinit();
  1603. puller.start(parentExtractSize, parentExtract, paused, preload, false, ctx);
  1604. }
  1605. }
  1606. virtual void stop(bool aborting)
  1607. {
  1608. if (disabled)
  1609. puller.queryInput()->stop(aborting);
  1610. else
  1611. {
  1612. space.interrupt();
  1613. ready.interrupt();
  1614. puller.stop(aborting);
  1615. }
  1616. }
  1617. virtual void reset()
  1618. {
  1619. if (disabled)
  1620. puller.queryInput()->reset();
  1621. else
  1622. {
  1623. puller.reset();
  1624. ForEachItemIn(idx1, buffer)
  1625. ReleaseRoxieRow(buffer.item(idx1));
  1626. buffer.clear();
  1627. }
  1628. }
  1629. virtual void resetEOF()
  1630. {
  1631. throwUnexpected();
  1632. }
  1633. virtual IOutputMetaData * queryOutputMeta() const
  1634. {
  1635. return puller.queryInput()->queryOutputMeta();
  1636. }
  1637. virtual void checkAbort()
  1638. {
  1639. puller.queryInput()->checkAbort();
  1640. }
  1641. void setInput(unsigned idx, IRoxieInput *_in)
  1642. {
  1643. assertex(!idx);
  1644. puller.setInput(this, _in);
  1645. }
  1646. virtual unsigned __int64 queryTotalCycles() const
  1647. {
  1648. return totalCycles;
  1649. }
  1650. virtual unsigned __int64 queryLocalCycles() const
  1651. {
  1652. __int64 ret = totalCycles - puller.queryInput()->queryTotalCycles();
  1653. if (ret < 0) ret = 0;
  1654. return ret;
  1655. }
  1656. virtual IRoxieInput *queryInput(unsigned idx) const
  1657. {
  1658. return puller.queryInput()->queryInput(idx);
  1659. }
  1660. virtual const void * nextInGroup()
  1661. {
  1662. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  1663. if (disabled)
  1664. return puller.queryInput()->nextInGroup();
  1665. else
  1666. {
  1667. loop
  1668. {
  1669. {
  1670. CriticalBlock b(crit);
  1671. if (eof && !buffer.ordinality())
  1672. return NULL; // eof
  1673. }
  1674. ready.wait();
  1675. const void *ret;
  1676. {
  1677. CriticalBlock b(crit);
  1678. ret = buffer.dequeue();
  1679. }
  1680. space.signal();
  1681. return ret;
  1682. }
  1683. }
  1684. }
  1685. virtual unsigned queryId() const { throwUnexpected(); }
  1686. virtual bool fireException(IException *e)
  1687. {
  1688. // called from puller thread on failure
  1689. ready.interrupt(LINK(e));
  1690. space.interrupt(e);
  1691. return true;
  1692. }
  1693. virtual void processRow(const void *row)
  1694. {
  1695. {
  1696. CriticalBlock b(crit);
  1697. buffer.enqueue(row);
  1698. }
  1699. ready.signal();
  1700. space.wait();
  1701. }
  1702. virtual void processGroup(const ConstPointerArray &rows)
  1703. {
  1704. // NOTE - a bit bizarre in that it waits for the space AFTER using it.
  1705. // But the space semaphore is only there to stop infinite readahead. And otherwise it would deadlock
  1706. // if group was larger than max(space)
  1707. {
  1708. CriticalBlock b(crit);
  1709. ForEachItemIn(idx, rows)
  1710. buffer.enqueue(rows.item(idx));
  1711. buffer.enqueue(NULL);
  1712. }
  1713. for (unsigned i2 = 0; i2 <= rows.length(); i2++) // note - does 1 extra for the null
  1714. {
  1715. ready.signal();
  1716. space.wait();
  1717. }
  1718. }
  1719. virtual void processEOG()
  1720. {
  1721. // Used when output is not grouped - just ignore
  1722. }
  1723. virtual void processDone()
  1724. {
  1725. CriticalBlock b(crit);
  1726. eof = true;
  1727. ready.signal();
  1728. }
  1729. };
  1730. //=================================================================================
  1731. class CRoxieServerTwoInputActivity : public CRoxieServerActivity
  1732. {
  1733. protected:
  1734. IRoxieInput *input1;
  1735. Owned<CRoxieServerReadAheadInput> puller;
  1736. public:
  1737. CRoxieServerTwoInputActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  1738. : CRoxieServerActivity(_factory, _probeManager)
  1739. {
  1740. input1 = NULL;
  1741. }
  1742. ~CRoxieServerTwoInputActivity()
  1743. {
  1744. }
  1745. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  1746. {
  1747. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  1748. input1->start(parentExtractSize, parentExtract, paused);
  1749. }
  1750. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  1751. {
  1752. if (puller)
  1753. puller->onCreate(_ctx);
  1754. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  1755. }
  1756. virtual void stop(bool aborting)
  1757. {
  1758. input1->stop(aborting);
  1759. CRoxieServerActivity::stop(aborting);
  1760. }
  1761. virtual unsigned __int64 queryLocalCycles() const
  1762. {
  1763. __int64 ret;
  1764. __int64 inputCycles = input->queryTotalCycles();
  1765. __int64 input1Cycles = input1->queryTotalCycles();
  1766. if (puller)
  1767. ret = totalCycles - (inputCycles > input1Cycles ? inputCycles : input1Cycles);
  1768. else
  1769. ret = totalCycles - (inputCycles + input1Cycles);
  1770. if (ret < 0)
  1771. ret = 0;
  1772. return ret;
  1773. }
  1774. virtual IRoxieInput *queryInput(unsigned idx) const
  1775. {
  1776. switch (idx)
  1777. {
  1778. case 0:
  1779. return input;
  1780. case 1:
  1781. return input1;
  1782. default:
  1783. return NULL;
  1784. }
  1785. }
  1786. virtual void reset()
  1787. {
  1788. CRoxieServerActivity::reset();
  1789. if (input1)
  1790. input1->reset();
  1791. }
  1792. virtual void setInput(unsigned idx, IRoxieInput *_in)
  1793. {
  1794. switch(idx)
  1795. {
  1796. case 0:
  1797. input = _in;
  1798. break;
  1799. case 1:
  1800. input1 = _in;
  1801. break;
  1802. default:
  1803. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  1804. }
  1805. }
  1806. };
  1807. //=================================================================================
  1808. class CRoxieServerMultiInputBaseActivity : public CRoxieServerActivity
  1809. {
  1810. protected:
  1811. unsigned numInputs;
  1812. IRoxieInput **inputArray;
  1813. public:
  1814. CRoxieServerMultiInputBaseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  1815. : CRoxieServerActivity(_factory, _probeManager), numInputs(_numInputs)
  1816. {
  1817. inputArray = new IRoxieInput*[numInputs];
  1818. for (unsigned i = 0; i < numInputs; i++)
  1819. inputArray[i] = NULL;
  1820. }
  1821. ~CRoxieServerMultiInputBaseActivity()
  1822. {
  1823. delete [] inputArray;
  1824. }
  1825. virtual unsigned __int64 queryLocalCycles() const
  1826. {
  1827. __int64 localCycles = totalCycles;
  1828. for (unsigned i = 0; i < numInputs; i++)
  1829. localCycles -= inputArray[i]->queryTotalCycles();
  1830. if (localCycles < 0)
  1831. localCycles = 0;
  1832. return localCycles;
  1833. }
  1834. virtual IRoxieInput *queryInput(unsigned idx) const
  1835. {
  1836. if (idx < numInputs)
  1837. return inputArray[idx];
  1838. else
  1839. return NULL;
  1840. }
  1841. virtual void reset()
  1842. {
  1843. for (unsigned i = 0; i < numInputs; i++)
  1844. inputArray[i]->reset();
  1845. CRoxieServerActivity::reset();
  1846. }
  1847. virtual void setInput(unsigned idx, IRoxieInput *_in)
  1848. {
  1849. inputArray[idx] = _in;
  1850. }
  1851. };
  1852. //=================================================================================
  1853. class CRoxieServerMultiInputActivity : public CRoxieServerMultiInputBaseActivity
  1854. {
  1855. public:
  1856. CRoxieServerMultiInputActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  1857. : CRoxieServerMultiInputBaseActivity(_factory, _probeManager, _numInputs)
  1858. {
  1859. }
  1860. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  1861. {
  1862. CRoxieServerMultiInputBaseActivity::start(parentExtractSize, parentExtract, paused);
  1863. for (unsigned i = 0; i < numInputs; i++)
  1864. {
  1865. inputArray[i]->start(parentExtractSize, parentExtract, paused);
  1866. }
  1867. }
  1868. virtual void stop(bool aborting)
  1869. {
  1870. for (unsigned i = 0; i < numInputs; i++)
  1871. {
  1872. inputArray[i]->stop(aborting);
  1873. }
  1874. CRoxieServerMultiInputBaseActivity::stop(aborting);
  1875. }
  1876. };
  1877. //=====================================================================================================
  1878. class CRoxieServerInternalSinkActivity : public CRoxieServerActivity
  1879. {
  1880. protected:
  1881. unsigned numOutputs;
  1882. bool executed;
  1883. bool *stopped;
  1884. CriticalSection ecrit;
  1885. Owned<IException> exception;
  1886. public:
  1887. CRoxieServerInternalSinkActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  1888. : CRoxieServerActivity(_factory, _probeManager), numOutputs(_numOutputs)
  1889. {
  1890. executed = false;
  1891. stopped = new bool[numOutputs];
  1892. for (unsigned s = 0; s < numOutputs; s++)
  1893. stopped[s] = false;
  1894. }
  1895. ~CRoxieServerInternalSinkActivity()
  1896. {
  1897. delete [] stopped;
  1898. }
  1899. virtual void reset()
  1900. {
  1901. for (unsigned s = 0; s < numOutputs; s++)
  1902. stopped[s] = false;
  1903. executed = false;
  1904. exception.clear();
  1905. CRoxieServerActivity::reset();
  1906. }
  1907. virtual IRoxieInput *queryOutput(unsigned idx)
  1908. {
  1909. return NULL;
  1910. }
  1911. virtual void stopSink(unsigned outputIdx)
  1912. {
  1913. if (!stopped[outputIdx])
  1914. {
  1915. stopped[outputIdx] = true;
  1916. for (unsigned s = 0; s < numOutputs; s++)
  1917. if (!stopped[s])
  1918. return;
  1919. stop(false); // all outputs stopped - stop parent.
  1920. }
  1921. }
  1922. virtual const void *nextInGroup()
  1923. {
  1924. throwUnexpected(); // I am nobody's input
  1925. }
  1926. virtual void onExecute() = 0;
  1927. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  1928. {
  1929. CriticalBlock b(ecrit);
  1930. if (exception)
  1931. throw exception.getLink();
  1932. if (!executed)
  1933. {
  1934. try
  1935. {
  1936. start(parentExtractSize, parentExtract, false);
  1937. {
  1938. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext()); // unfortunately this is not really best place for seeing in debugger.
  1939. onExecute();
  1940. }
  1941. stop(false);
  1942. executed = true;
  1943. }
  1944. catch (IException *E)
  1945. {
  1946. exception.set(E); // (or maybe makeWrappedException?)
  1947. stop(true);
  1948. throw;
  1949. }
  1950. catch (...)
  1951. {
  1952. exception.set(MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught at %s:%d", __FILE__, __LINE__));
  1953. stop(true);
  1954. throw;
  1955. }
  1956. }
  1957. }
  1958. };
  1959. //=================================================================================
  1960. class CRoxieServerQueryPacket : public CInterface, implements IRoxieServerQueryPacket
  1961. {
  1962. protected:
  1963. Owned<IMessageResult> result;
  1964. Owned<IRoxieQueryPacket> packet;
  1965. Linked<IRoxieServerQueryPacket> continuation;
  1966. unsigned hash;
  1967. unsigned seq;
  1968. unsigned lastDebugSequence;
  1969. Owned<IRoxieQueryPacket> lastDebugResponse;
  1970. ILRUChain *prev;
  1971. ILRUChain *next;
  1972. bool delayed;
  1973. public:
  1974. IMPLEMENT_IINTERFACE;
  1975. CRoxieServerQueryPacket(IRoxieQueryPacket *p) : packet(p)
  1976. {
  1977. hash = 0;
  1978. seq = 0;
  1979. prev = NULL;
  1980. next = NULL;
  1981. delayed = false;
  1982. lastDebugSequence = 0;
  1983. }
  1984. virtual IRoxieQueryPacket *queryPacket() const
  1985. {
  1986. return packet;
  1987. }
  1988. virtual bool isContinuation() const
  1989. {
  1990. return packet && (packet->queryHeader().continueSequence & ~CONTINUE_SEQUENCE_SKIPTO) != 0;
  1991. }
  1992. virtual bool isDelayed() const
  1993. {
  1994. return delayed;
  1995. }
  1996. virtual bool isEnd() const
  1997. {
  1998. return false;
  1999. }
  2000. virtual bool isLimit(unsigned __int64 &_rowLimit, unsigned __int64 &_keyedLimit, unsigned __int64 &_stopAfter) const
  2001. {
  2002. return false;
  2003. }
  2004. virtual bool hasResult() const
  2005. {
  2006. return result != NULL;
  2007. }
  2008. virtual bool hasContinuation() const
  2009. {
  2010. return continuation != NULL;
  2011. }
  2012. virtual void setDelayed(bool _delayed)
  2013. {
  2014. delayed = _delayed;
  2015. }
  2016. virtual void setPacket(IRoxieQueryPacket *_packet)
  2017. {
  2018. packet.setown(_packet);
  2019. }
  2020. virtual void setSequence(unsigned _seq)
  2021. {
  2022. assertex(!IsShared());
  2023. seq = _seq;
  2024. }
  2025. virtual unsigned getSequence() const
  2026. {
  2027. return seq;
  2028. }
  2029. IMessageResult *getResult()
  2030. {
  2031. return result.getLink();
  2032. }
  2033. IMessageResult *queryResult()
  2034. {
  2035. return result;
  2036. }
  2037. void setResult(IMessageResult *r)
  2038. {
  2039. result.setown(r);
  2040. }
  2041. IRoxieServerQueryPacket *queryContinuation()
  2042. {
  2043. return continuation;
  2044. }
  2045. void setContinuation(IRoxieServerQueryPacket *c)
  2046. {
  2047. continuation.setown(c);
  2048. }
  2049. virtual unsigned queryHash() const
  2050. {
  2051. return hash;
  2052. }
  2053. virtual void setHash(unsigned _hash)
  2054. {
  2055. hash = _hash;
  2056. }
  2057. virtual ILRUChain *queryPrev() const { return prev; }
  2058. virtual ILRUChain *queryNext() const { return next; }
  2059. virtual void setPrev(ILRUChain *p) { prev = p; }
  2060. virtual void setNext(ILRUChain *n) { next = n; }
  2061. virtual void unchain()
  2062. {
  2063. if (prev && next)
  2064. {
  2065. prev->setNext(next);
  2066. next->setPrev(prev);
  2067. }
  2068. next = NULL;
  2069. prev = NULL;
  2070. }
  2071. virtual IRoxieQueryPacket *getDebugResponse(unsigned sequence)
  2072. {
  2073. if (sequence == lastDebugSequence)
  2074. return lastDebugResponse.getLink();
  2075. else if (sequence > lastDebugSequence)
  2076. {
  2077. lastDebugResponse.clear();
  2078. return NULL;
  2079. }
  2080. else
  2081. throwUnexpected();
  2082. }
  2083. virtual void setDebugResponse(unsigned sequence, IRoxieQueryPacket *response)
  2084. {
  2085. lastDebugSequence = sequence;
  2086. lastDebugResponse.set(response);
  2087. }
  2088. };
  2089. class CRoxieServerQueryPacketEndMarker : public CRoxieServerQueryPacket
  2090. {
  2091. public:
  2092. CRoxieServerQueryPacketEndMarker() : CRoxieServerQueryPacket(NULL)
  2093. {
  2094. }
  2095. virtual bool isEnd() const
  2096. {
  2097. return true;
  2098. }
  2099. };
  2100. class CRoxieServerQueryPacketLimitMarker : public CRoxieServerQueryPacket
  2101. {
  2102. unsigned __int64 rowLimit;
  2103. unsigned __int64 keyedLimit;
  2104. unsigned __int64 stopAfter;
  2105. public:
  2106. CRoxieServerQueryPacketLimitMarker(unsigned __int64 _rowLimit, unsigned __int64 _keyedLimit, unsigned __int64 _stopAfter) : CRoxieServerQueryPacket(NULL)
  2107. {
  2108. rowLimit = _rowLimit;
  2109. keyedLimit = _keyedLimit;
  2110. stopAfter = _stopAfter;
  2111. }
  2112. virtual bool isLimit(unsigned __int64 &_rowLimit, unsigned __int64 &_keyedLimit, unsigned __int64 &_stopAfter) const
  2113. {
  2114. _rowLimit = rowLimit;
  2115. _keyedLimit = keyedLimit;
  2116. _stopAfter = stopAfter;
  2117. return true;
  2118. }
  2119. };
  2120. class CRoxieServerSideCache : implements IRoxieServerSideCache, implements ILRUChain
  2121. {
  2122. protected:
  2123. unsigned cacheTableSize;
  2124. unsigned cacheTableSpace;
  2125. IRoxieServerQueryPacket **cacheTable;
  2126. mutable ILRUChain *prev;
  2127. mutable ILRUChain *next;
  2128. mutable CriticalSection crit;
  2129. virtual ILRUChain *queryPrev() const { return prev; }
  2130. virtual ILRUChain *queryNext() const { return next; }
  2131. virtual void setPrev(ILRUChain *p) { prev = p; }
  2132. virtual void setNext(ILRUChain *n) { next = n; }
  2133. virtual void unchain()
  2134. {
  2135. prev->setNext(next);
  2136. next->setPrev(prev);
  2137. next = NULL;
  2138. prev = NULL;
  2139. }
  2140. void moveToHead(IRoxieServerQueryPacket *mru)
  2141. {
  2142. mru->unchain();
  2143. mru->setNext(next);
  2144. next->setPrev(mru);
  2145. mru->setPrev(this);
  2146. next = mru;
  2147. }
  2148. IRoxieServerQueryPacket *removeLRU()
  2149. {
  2150. if (next==this)
  2151. assertex(next != this);
  2152. IRoxieServerQueryPacket *goer = (IRoxieServerQueryPacket *) next;
  2153. goer->unchain(); // NOTE - this will modify the value of next
  2154. return goer;
  2155. }
  2156. void removeEntry(IRoxieServerQueryPacket *goer)
  2157. {
  2158. unsigned v = goer->queryHash() % cacheTableSize;
  2159. loop
  2160. {
  2161. IRoxieServerQueryPacket *found = cacheTable[v];
  2162. assertex(found);
  2163. if (found == goer)
  2164. {
  2165. cacheTable[v] = NULL;
  2166. unsigned vn = v;
  2167. loop
  2168. {
  2169. vn++;
  2170. if (vn==cacheTableSize) vn = 0;
  2171. IRoxieServerQueryPacket *found2 = cacheTable[vn];
  2172. if (!found2)
  2173. break;
  2174. unsigned vm = found2->queryHash() % cacheTableSize;
  2175. if (((vn+cacheTableSize-vm) % cacheTableSize)>=((vn+cacheTableSize-v) % cacheTableSize)) // diff(vn,vm)>=diff(vn,v)
  2176. {
  2177. cacheTable[v] = found2;
  2178. v = vn;
  2179. cacheTable[v] = NULL;
  2180. }
  2181. }
  2182. cacheTableSpace++;
  2183. break;
  2184. }
  2185. v++;
  2186. if (v==cacheTableSize)
  2187. v = 0;
  2188. }
  2189. goer->Release();
  2190. }
  2191. public:
  2192. CRoxieServerSideCache(unsigned _cacheSize)
  2193. {
  2194. cacheTableSize = (_cacheSize*4)/3;
  2195. cacheTable = new IRoxieServerQueryPacket *[cacheTableSize];
  2196. memset(cacheTable, 0, cacheTableSize * sizeof(IRoxieServerQueryPacket *));
  2197. cacheTableSpace = _cacheSize;
  2198. prev = this;
  2199. next = this;
  2200. }
  2201. ~CRoxieServerSideCache()
  2202. {
  2203. for (unsigned i = 0; i < cacheTableSize; i++)
  2204. {
  2205. ::Release(cacheTable[i]);
  2206. }
  2207. delete [] cacheTable;
  2208. }
  2209. virtual IRoxieServerQueryPacket *findCachedResult(const IRoxieContextLogger &logctx, IRoxieQueryPacket *p) const
  2210. {
  2211. unsigned hash = p->hash();
  2212. unsigned et = hash % cacheTableSize;
  2213. if (traceServerSideCache)
  2214. {
  2215. StringBuffer s;
  2216. logctx.CTXLOG("CRoxieServerSideCache::findCachedResult hash %x slot %d %s", hash, et, p->queryHeader().toString(s).str());
  2217. }
  2218. CriticalBlock b(crit);
  2219. loop
  2220. {
  2221. IRoxieServerQueryPacket *found = cacheTable[et];
  2222. if (!found)
  2223. return NULL;
  2224. if (found->queryHash() == hash && found->queryPacket()->cacheMatch(p))
  2225. {
  2226. const_cast<CRoxieServerSideCache *>(this)->moveToHead(found);
  2227. if (traceServerSideCache)
  2228. logctx.CTXLOG("CRoxieServerSideCache::findCachedResult cache hit");
  2229. logctx.noteStatistic(STATS_SERVERCACHEHIT, 1, 1);
  2230. return NULL;
  2231. // 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....
  2232. //IRoxieServerQueryPacket *ret = new CRoxieServerQueryPacket(p);
  2233. //ret->setResult(found->getResult());
  2234. //return ret;
  2235. }
  2236. et++;
  2237. if (et == cacheTableSize)
  2238. et = 0;
  2239. }
  2240. }
  2241. virtual void noteCachedResult(IRoxieServerQueryPacket *out, IMessageResult *in)
  2242. {
  2243. if (true) //!in->getLength()) // MORE - separate caches for hits and nohits
  2244. {
  2245. unsigned hash = out->queryPacket()->hash();
  2246. out->setHash(hash);
  2247. unsigned et = hash % cacheTableSize;
  2248. if (traceServerSideCache)
  2249. {
  2250. StringBuffer s;
  2251. DBGLOG("CRoxieServerSideCache::noteCachedResult hash %x slot %d %s", hash, et, out->queryPacket()->queryHeader().toString(s).str());
  2252. }
  2253. CriticalBlock b(crit);
  2254. loop
  2255. {
  2256. IRoxieServerQueryPacket *found = cacheTable[et];
  2257. if (!found)
  2258. {
  2259. if (cacheTableSpace)
  2260. {
  2261. out->setResult(LINK(in));
  2262. cacheTable[et] = LINK(out);
  2263. cacheTableSpace--;
  2264. moveToHead(out);
  2265. break;
  2266. }
  2267. else
  2268. {
  2269. IRoxieServerQueryPacket *goer = removeLRU();
  2270. removeEntry(goer);
  2271. et = hash % cacheTableSize;
  2272. continue;
  2273. }
  2274. }
  2275. else if (found->queryHash()==hash && found->queryPacket()->cacheMatch(out->queryPacket()))
  2276. {
  2277. moveToHead(found);
  2278. return; // already in the cache. Because we don't cache until we have result, this can happen where
  2279. // multiple copies of a slave query are in-flight at once.
  2280. }
  2281. et++;
  2282. if (et == cacheTableSize)
  2283. et = 0;
  2284. }
  2285. }
  2286. // MORE - do we need to worry about the attachment between the MessageUnpacker and the current row manager. May all fall out ok...
  2287. // Can I easily spot a null result? Do I want to cache null results separately? only?
  2288. }
  2289. // Note that this caching mechanism (unlike the old keyed-join specific one) does not common up cases where multiple
  2290. // identical queries are in-flight at the same time. But if we can make it persistant between queries that will
  2291. // more than make up for it
  2292. };
  2293. class CRowArrayMessageUnpackCursor : public CInterface, implements IMessageUnpackCursor
  2294. {
  2295. ConstPointerArray &data;
  2296. Linked<IMessageResult> result;
  2297. public:
  2298. IMPLEMENT_IINTERFACE;
  2299. CRowArrayMessageUnpackCursor(ConstPointerArray &_data, IMessageResult *_result)
  2300. : data(_data), result(_result)
  2301. {
  2302. }
  2303. virtual bool atEOF() const
  2304. {
  2305. return data.length()==0;
  2306. }
  2307. virtual bool isSerialized() const
  2308. {
  2309. return false;
  2310. }
  2311. virtual const void * getNext(int length)
  2312. {
  2313. if (!data.length())
  2314. return NULL;
  2315. const void *ret = data.item(0);
  2316. data.remove(0);
  2317. return ret;
  2318. }
  2319. };
  2320. // MORE - should possibly move more over to the lazy version used in indexread?
  2321. class CRowArrayMessageResult : public CInterface, implements IMessageResult
  2322. {
  2323. ConstPointerArray data;
  2324. IRowManager &rowManager;
  2325. bool variableSize;
  2326. public:
  2327. IMPLEMENT_IINTERFACE;
  2328. CRowArrayMessageResult(IRowManager &_rowManager, bool _variableSize) : rowManager(_rowManager), variableSize(_variableSize)
  2329. {
  2330. }
  2331. ~CRowArrayMessageResult()
  2332. {
  2333. ReleaseRoxieRowSet(data);
  2334. }
  2335. virtual IMessageUnpackCursor *getCursor(IRowManager *rowMgr) const
  2336. {
  2337. CRowArrayMessageResult *_this = (CRowArrayMessageResult *) this;
  2338. return new CRowArrayMessageUnpackCursor(_this->data, _this);
  2339. }
  2340. virtual const void *getMessageHeader(unsigned &length) const
  2341. {
  2342. throwUnexpected(); // should never get called - I don't have a header available
  2343. length = 0;
  2344. return NULL;
  2345. }
  2346. virtual const void *getMessageMetadata(unsigned &length) const
  2347. {
  2348. length = 0;
  2349. return NULL;
  2350. }
  2351. virtual void discard() const
  2352. {
  2353. throwUnexpected();
  2354. }
  2355. void append(const void *row)
  2356. {
  2357. data.append(row);
  2358. }
  2359. };
  2360. void throwRemoteException(IMessageUnpackCursor *extra)
  2361. {
  2362. RecordLengthType *rowlen = (RecordLengthType *) extra->getNext(sizeof(RecordLengthType));
  2363. if (rowlen)
  2364. {
  2365. char *xml = (char *) extra->getNext(*rowlen);
  2366. ReleaseRoxieRow(rowlen);
  2367. Owned<IPropertyTree> p = createPTreeFromXMLString(xml);
  2368. ReleaseRoxieRow(xml);
  2369. unsigned code = p->getPropInt("Code", 0);
  2370. const char *msg = p->queryProp("Message");
  2371. if (!msg)
  2372. msg = xml;
  2373. throw MakeStringException(code, "%s", msg);
  2374. }
  2375. throwUnexpected();
  2376. }
  2377. class CRemoteResultAdaptor :public CInterface, implements IRoxieInput, implements IExceptionHandler
  2378. {
  2379. friend class CRemoteResultMerger;
  2380. class CRemoteResultMerger
  2381. {
  2382. class HeapEntry : public CInterface
  2383. {
  2384. private:
  2385. CRemoteResultAdaptor &adaptor;
  2386. IMessageUnpackCursor *cursor;
  2387. public:
  2388. const void *current;
  2389. bool isLast;
  2390. bool lastIsComplete;
  2391. IRoxieServerQueryPacket *packet;
  2392. unsigned seq;
  2393. public:
  2394. inline const void *noteResult(IMessageUnpackCursor *_cursor, bool _lastIsComplete)
  2395. {
  2396. cursor = _cursor;
  2397. lastIsComplete = _lastIsComplete;
  2398. return next();
  2399. }
  2400. public:
  2401. HeapEntry(CRemoteResultAdaptor &_adaptor, IRoxieServerQueryPacket *_packet, unsigned _seq) : adaptor(_adaptor), packet(_packet), seq(_seq)
  2402. {
  2403. cursor = NULL;
  2404. current = NULL;
  2405. isLast = false;
  2406. lastIsComplete = true;
  2407. }
  2408. ~HeapEntry()
  2409. {
  2410. ::Release(packet);
  2411. ::Release(cursor);
  2412. ReleaseRoxieRow(current);
  2413. }
  2414. bool isCompleteMatch() const
  2415. {
  2416. if (!isLast || lastIsComplete)
  2417. return true;
  2418. else
  2419. return false;
  2420. }
  2421. const void *next()
  2422. {
  2423. if (cursor)
  2424. {
  2425. ReleaseClearRoxieRow(current);
  2426. current = adaptor.getRow(cursor);
  2427. isLast = cursor->atEOF();
  2428. if (!current)
  2429. {
  2430. cursor->Release();
  2431. cursor = NULL;
  2432. }
  2433. }
  2434. return current;
  2435. }
  2436. unsigned skipTo(IRangeCompare *compare, const void *seek, unsigned numFields, bool requireExactMatch)
  2437. {
  2438. // MORE - This loop should possibly be a binchop... though it's not absolutely clear that is true (depends on term frequencies)
  2439. unsigned skipped = 0;
  2440. loop
  2441. {
  2442. int c = compare->docompare(current, seek, numFields);
  2443. //If larger than the seek values, then we may be allowed to return an inexact match,
  2444. //if equal then it is required to be an exact match,
  2445. if (c > 0)
  2446. {
  2447. if (!requireExactMatch || isCompleteMatch())
  2448. break;
  2449. }
  2450. else if ((c == 0) && isCompleteMatch())
  2451. break;
  2452. skipped++;
  2453. if (!next())
  2454. break;
  2455. }
  2456. return skipped;
  2457. }
  2458. };
  2459. CRemoteResultAdaptor &adaptor;
  2460. CIArrayOf<HeapEntry> heapEntries;
  2461. UnsignedArray heap;
  2462. IRowManager *rowManager;
  2463. unsigned numPending;
  2464. unsigned numFields;
  2465. bool endSeen;
  2466. bool remakePending;
  2467. IRangeCompare *compare;
  2468. bool deferredContinuation;
  2469. inline int doCompare(unsigned l, unsigned r)
  2470. {
  2471. int ret = compare->docompare(heapEntries.item(l).current, heapEntries.item(r).current, numFields);
  2472. if (!ret) ret = heapEntries.item(l).seq - heapEntries.item(r).seq;
  2473. return ret;
  2474. }
  2475. void makeHeap()
  2476. {
  2477. /* Permute blocks to establish the heap property
  2478. For each element p, the children are p*2+1 and p*2+2 (provided these are in range)
  2479. The children of p must both be greater than or equal to p
  2480. The parent of a child c is given by p = (c-1)/2
  2481. */
  2482. unsigned i;
  2483. unsigned n = heap.length();
  2484. unsigned *s = heap.getArray();
  2485. for (i=1; i<n; i++)
  2486. {
  2487. unsigned r = s[i];
  2488. int c = i; /* child */
  2489. while (c > 0)
  2490. {
  2491. int p = (c-1)/2; /* parent */
  2492. if ( doCompare( s[c], s[p] ) >= 0 )
  2493. break;
  2494. s[c] = s[p];
  2495. s[p] = r;
  2496. c = p;
  2497. }
  2498. }
  2499. remakePending = false;
  2500. }
  2501. void remakeHeap()
  2502. {
  2503. /* The row associated with block[0] will have changed
  2504. This code restores the heap property
  2505. */
  2506. unsigned p = 0; /* parent */
  2507. unsigned n = heap.length();
  2508. unsigned *s = heap.getArray();
  2509. while (1)
  2510. {
  2511. unsigned c = p*2 + 1; /* child */
  2512. if ( c >= n )
  2513. break;
  2514. /* Select smaller child */
  2515. if ( c+1 < n && doCompare( s[c+1], s[c] ) < 0 ) c += 1;
  2516. /* If child is greater or equal than parent then we are done */
  2517. if ( doCompare( s[c], s[p] ) >= 0 )
  2518. break;
  2519. /* Swap parent and child */
  2520. unsigned r = s[c];
  2521. s[c] = s[p];
  2522. s[p] = r;
  2523. /* child becomes parent */
  2524. p = c;
  2525. }
  2526. remakePending = false;
  2527. }
  2528. void append(IRoxieServerQueryPacket *p, unsigned seq)
  2529. {
  2530. HeapEntry &h = *new HeapEntry(adaptor, LINK(p), seq);
  2531. IMessageResult *result = p->queryResult();
  2532. assertex(result);
  2533. if (h.noteResult(result->getCursor(rowManager), isCompleteMatchFlag(result)))
  2534. {
  2535. heapEntries.append(h);
  2536. heap.append(heap.ordinality());
  2537. }
  2538. else
  2539. h.Release();
  2540. }
  2541. void removeHeap(unsigned idx)
  2542. {
  2543. heapEntries.remove(idx);
  2544. ForEachItemIn(i, heap)
  2545. {
  2546. unsigned v = heap.item(i);
  2547. assertex(v != idx);
  2548. if (v > idx)
  2549. heap.replace(v-1, i);
  2550. }
  2551. }
  2552. bool isCompleteMatchFlag(IMessageResult *result)
  2553. {
  2554. unsigned metaLen;
  2555. const byte *metaInfo = (const byte *) result->getMessageMetadata(metaLen);
  2556. if (metaLen)
  2557. {
  2558. unsigned short continuationLen = *(unsigned short *) metaInfo;
  2559. if (continuationLen >= sizeof(bool))
  2560. {
  2561. metaInfo += sizeof(unsigned short);
  2562. return *(bool *) metaInfo;
  2563. }
  2564. }
  2565. return true; // if no continuation info, last row was complete.
  2566. }
  2567. public:
  2568. CRemoteResultMerger(CRemoteResultAdaptor &_adaptor) : adaptor(_adaptor)
  2569. {
  2570. init(NULL, NULL);
  2571. }
  2572. void init(ISteppingMeta *meta, IRowManager *_rowManager)
  2573. {
  2574. if (meta)
  2575. {
  2576. numFields = meta->getNumFields();
  2577. compare = meta->queryCompare();
  2578. }
  2579. else
  2580. {
  2581. numFields = 0;
  2582. compare = NULL;
  2583. }
  2584. rowManager = _rowManager;
  2585. numPending = 0;
  2586. endSeen = false;
  2587. remakePending = false;
  2588. deferredContinuation = false;
  2589. }
  2590. void reset()
  2591. {
  2592. heapEntries.kill();
  2593. heap.kill();
  2594. numPending = 0;
  2595. endSeen = false;
  2596. remakePending = false;
  2597. deferredContinuation = false;
  2598. }
  2599. inline bool noteEndSeen()
  2600. {
  2601. bool hadSeen = endSeen;
  2602. if (!endSeen)
  2603. makeHeap();
  2604. endSeen = true;
  2605. return !hadSeen;
  2606. }
  2607. void noteResult(IRoxieServerQueryPacket *p, unsigned seq)
  2608. {
  2609. if (!p->isContinuation())
  2610. append(p, seq);
  2611. else
  2612. {
  2613. ForEachItemIn(idx, heapEntries)
  2614. {
  2615. HeapEntry &h = heapEntries.item(idx);
  2616. if (h.packet == p)
  2617. {
  2618. IMessageResult *result = p->queryResult();
  2619. if (!h.noteResult(result->getCursor(rowManager), isCompleteMatchFlag(result)))
  2620. {
  2621. heap.zap(idx);
  2622. removeHeap(idx);
  2623. }
  2624. numPending--;
  2625. if (!numPending)
  2626. makeHeap();
  2627. return;
  2628. }
  2629. }
  2630. }
  2631. // If we get here it must be a continuation for one that I have not yet consumed... we don't need to do anything.
  2632. return;
  2633. }
  2634. unsigned skipRows(unsigned &idx, const void *seek, const void *rawSeek, unsigned numFields, unsigned seekLen, const SmartStepExtra & stepExtra)
  2635. {
  2636. HeapEntry &entry = heapEntries.item(idx);
  2637. unsigned skipped = entry.current ? entry.skipTo(compare, seek, numFields, !stepExtra.returnMismatches()) : 0;
  2638. if (!entry.current)
  2639. {
  2640. IRoxieServerQueryPacket *continuation = entry.packet->queryContinuation();
  2641. if (continuation)
  2642. {
  2643. continuation->Link();
  2644. entry.packet->Release();
  2645. entry.packet = continuation;
  2646. if (continuation->hasResult())
  2647. {
  2648. IMessageResult *result = continuation->queryResult();
  2649. bool lastIsCompleteMatch = isCompleteMatchFlag(result);
  2650. entry.noteResult(result->getCursor(rowManager), lastIsCompleteMatch);
  2651. }
  2652. else
  2653. {
  2654. if (continuation->isDelayed())
  2655. {
  2656. continuation->setDelayed(false);
  2657. MemoryBuffer serializedSkip;
  2658. adaptor.activity.serializeSkipInfo(serializedSkip, seekLen, rawSeek, numFields, seek, stepExtra);
  2659. continuation->setPacket(continuation->queryPacket()->insertSkipData(serializedSkip.length(), serializedSkip.toByteArray()));
  2660. ROQ->sendPacket(continuation->queryPacket(), adaptor.activity.queryLogCtx());
  2661. adaptor.sentsome.signal();
  2662. }
  2663. numPending++;
  2664. }
  2665. }
  2666. else
  2667. {
  2668. heap.zap(idx);
  2669. removeHeap(idx);
  2670. idx--;
  2671. }
  2672. }
  2673. return skipped;
  2674. }
  2675. const void * nextSteppedGE(const void * seek, const void *rawSeek, unsigned numFields, unsigned seeklen, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  2676. {
  2677. // We discard all rows < seekval from all entries in heap
  2678. // If this results in additional slave requests, we return NULL so that we can wait for them
  2679. // If not, we rebuild the heap (if any were skipped) and return the first row
  2680. deferredContinuation = false;
  2681. if (heap.length())
  2682. {
  2683. unsigned skipped = 0;
  2684. unsigned idx = 0;
  2685. while(heapEntries.isItem(idx))
  2686. {
  2687. skipped += skipRows(idx, seek, rawSeek, numFields, seeklen, stepExtra);
  2688. idx++;
  2689. }
  2690. if (numPending)
  2691. return NULL; // can't answer yet, need more results from slaves
  2692. else
  2693. {
  2694. if (skipped)
  2695. makeHeap();
  2696. return next(wasCompleteMatch, stepExtra);
  2697. }
  2698. }
  2699. else
  2700. return NULL;
  2701. }
  2702. bool doContinuation(HeapEntry &topEntry, bool canDefer)
  2703. {
  2704. IRoxieServerQueryPacket *continuation = topEntry.packet->queryContinuation();
  2705. if (continuation)
  2706. {
  2707. if (continuation->isDelayed() && canDefer)
  2708. {
  2709. if (adaptor.activity.queryLogCtx().queryTraceLevel() > 10)
  2710. adaptor.activity.queryLogCtx().CTXLOG("Deferring continuation");
  2711. deferredContinuation = true;
  2712. }
  2713. else
  2714. {
  2715. deferredContinuation = false;
  2716. continuation->Link();
  2717. topEntry.packet->Release();
  2718. topEntry.packet = continuation;
  2719. if (continuation->hasResult())
  2720. {
  2721. IMessageResult *result = continuation->queryResult();
  2722. bool lastIsCompleteMatch = isCompleteMatchFlag(result);
  2723. topEntry.noteResult(result->getCursor(rowManager), lastIsCompleteMatch);
  2724. }
  2725. else
  2726. {
  2727. if (continuation->isDelayed()) // has the continuation been requested yet?
  2728. {
  2729. continuation->Link();
  2730. topEntry.packet->Release();
  2731. topEntry.packet = continuation;
  2732. continuation->setDelayed(false);
  2733. if (adaptor.activity.queryLogCtx().queryTraceLevel() > 10)
  2734. adaptor.activity.queryLogCtx().CTXLOG("About to send continuation, from doContinuation");
  2735. ROQ->sendPacket(continuation->queryPacket(), adaptor.activity.queryLogCtx());
  2736. adaptor.sentsome.signal();
  2737. }
  2738. numPending++; // we are waiting for one that is already in flight
  2739. }
  2740. }
  2741. return true; // next not known yet
  2742. }
  2743. else
  2744. return false;
  2745. }
  2746. const void *next(bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  2747. {
  2748. OwnedConstRoxieRow ret;
  2749. if (heap.length())
  2750. {
  2751. if (deferredContinuation)
  2752. {
  2753. unsigned top = heap.item(0);
  2754. HeapEntry &topEntry = heapEntries.item(top);
  2755. doContinuation(topEntry, false);
  2756. return NULL;
  2757. }
  2758. if (remakePending)
  2759. remakeHeap();
  2760. unsigned top = heap.item(0);
  2761. HeapEntry &topEntry = heapEntries.item(top);
  2762. ret.set(topEntry.current);
  2763. wasCompleteMatch = topEntry.isCompleteMatch();
  2764. const void *next = topEntry.next();
  2765. if (!next)
  2766. {
  2767. if (!doContinuation(topEntry, stepExtra.returnMismatches()))
  2768. {
  2769. unsigned last = heap.pop();
  2770. if (heap.length())
  2771. heap.replace(last, 0);
  2772. removeHeap(top);
  2773. }
  2774. }
  2775. remakePending = true;
  2776. }
  2777. return ret.getClear();
  2778. }
  2779. bool ready()
  2780. {
  2781. return endSeen && numPending == 0;
  2782. }
  2783. };
  2784. IRoxieServerQueryPacket *createRoxieServerQueryPacket(IRoxieQueryPacket *p, bool &cached)
  2785. {
  2786. if (serverSideCache && !debugContext)
  2787. {
  2788. IRoxieServerQueryPacket *ret = serverSideCache->findCachedResult(activity.queryLogCtx(), p);
  2789. if (ret)
  2790. {
  2791. p->Release();
  2792. cached = true;
  2793. return ret;
  2794. }
  2795. }
  2796. cached = false;
  2797. return new CRoxieServerQueryPacket(p);
  2798. }
  2799. #ifdef _DEBUG
  2800. void dumpPending()
  2801. {
  2802. CriticalBlock b(pendingCrit);
  2803. ForEachItemIn(idx, pending)
  2804. {
  2805. IRoxieServerQueryPacket &p = pending.item(idx);
  2806. StringBuffer s;
  2807. unsigned __int64 dummy;
  2808. if (p.isEnd())
  2809. s.append("END");
  2810. else if (p.isLimit(dummy, dummy, dummy))
  2811. s.append("LIMIT");
  2812. else
  2813. {
  2814. IRoxieQueryPacket *i = p.queryPacket();
  2815. s.appendf("%s", p.hasResult() ? "COMPLETE " : "PENDING ");
  2816. if (i)
  2817. {
  2818. RoxiePacketHeader &header = i->queryHeader();
  2819. header.toString(s);
  2820. }
  2821. }
  2822. DBGLOG("Pending %d %s", idx, s.str());
  2823. }
  2824. }
  2825. #endif
  2826. void abortPending()
  2827. {
  2828. CriticalBlock b(pendingCrit);
  2829. ForEachItemIn(idx, pending)
  2830. {
  2831. IRoxieServerQueryPacket &p = pending.item(idx);
  2832. if (!p.hasResult())
  2833. {
  2834. IRoxieQueryPacket *i = p.queryPacket();
  2835. if (i)
  2836. {
  2837. RoxiePacketHeader &header = i->queryHeader();
  2838. ROQ->sendAbort(header, activity.queryLogCtx());
  2839. }
  2840. }
  2841. }
  2842. pending.kill();
  2843. }
  2844. void checkDelayed()
  2845. {
  2846. if (ctx->queryDebugContext() && ctx->queryDebugContext()->getExecuteSequentially())
  2847. {
  2848. bool allDelayed = true;
  2849. CriticalBlock b(pendingCrit);
  2850. unsigned sendIdx = (unsigned) -1;
  2851. ForEachItemIn(idx, pending)
  2852. {
  2853. IRoxieServerQueryPacket &p = pending.item(idx);
  2854. if (p.queryPacket())
  2855. {
  2856. if (p.isDelayed())
  2857. {
  2858. if (sendIdx == (unsigned) -1)
  2859. sendIdx = idx;
  2860. }
  2861. else if (!p.hasResult())
  2862. {
  2863. allDelayed = false;
  2864. break;
  2865. }
  2866. }
  2867. }
  2868. if (allDelayed && sendIdx != (unsigned) -1)
  2869. {
  2870. if (activity.queryLogCtx().queryTraceLevel() > 10)
  2871. activity.queryLogCtx().CTXLOG("About to send debug-deferred from next");
  2872. pending.item(sendIdx).setDelayed(false);
  2873. ROQ->sendPacket(pending.item(sendIdx).queryPacket(), activity.queryLogCtx());
  2874. sentsome.signal();
  2875. }
  2876. }
  2877. else if (deferredStart)
  2878. {
  2879. CriticalBlock b(pendingCrit);
  2880. ForEachItemIn(idx, pending)
  2881. {
  2882. IRoxieServerQueryPacket &p = pending.item(idx);
  2883. if (p.isDelayed())
  2884. {
  2885. if (activity.queryLogCtx().queryTraceLevel() > 10)
  2886. activity.queryLogCtx().CTXLOG("About to send deferred start from next");
  2887. p.setDelayed(false);
  2888. ROQ->sendPacket(p.queryPacket(), activity.queryLogCtx());
  2889. sentsome.signal();
  2890. }
  2891. }
  2892. deferredStart = false;
  2893. }
  2894. }
  2895. void retryPending()
  2896. {
  2897. CriticalBlock b(pendingCrit);
  2898. checkDelayed();
  2899. ForEachItemIn(idx, pending)
  2900. {
  2901. IRoxieServerQueryPacket &p = pending.item(idx);
  2902. if (!p.hasResult() && !p.isDelayed())
  2903. {
  2904. IRoxieQueryPacket *i = p.queryPacket();
  2905. if (i)
  2906. {
  2907. if (!i->queryHeader().retry())
  2908. {
  2909. StringBuffer s;
  2910. IException *E = MakeStringException(ROXIE_MULTICAST_ERROR, "Failed to get response from slave(s) for %s in activity %d", i->queryHeader().toString(s).str(), queryId());
  2911. activity.queryLogCtx().logOperatorException(E, __FILE__, __LINE__, "CRemoteResultAdaptor::retry");
  2912. throw E;
  2913. }
  2914. if (!localSlave)
  2915. {
  2916. ROQ->sendPacket(i, activity.queryLogCtx());
  2917. atomic_inc(&retriesSent);
  2918. }
  2919. }
  2920. }
  2921. }
  2922. }
  2923. class ChannelBuffer
  2924. {
  2925. protected:
  2926. unsigned bufferLeft;
  2927. MemoryBuffer buffer;
  2928. char *nextBuf;
  2929. unsigned overflowSequence;
  2930. unsigned channel; // == bonded channel
  2931. bool needsFlush;
  2932. InterruptableSemaphore flowController;
  2933. const CRemoteResultAdaptor &owner;
  2934. CriticalSection crit;
  2935. public:
  2936. ChannelBuffer(const CRemoteResultAdaptor &_owner, unsigned _channel) : owner(_owner), channel(_channel), flowController(perChannelFlowLimit)
  2937. {
  2938. overflowSequence = 0;
  2939. needsFlush = false;
  2940. bufferLeft = 0;
  2941. nextBuf = NULL;
  2942. }
  2943. void init(unsigned minSize)
  2944. {
  2945. assertex(!buffer.length());
  2946. if (minSize < MIN_PAYLOAD_SIZE)
  2947. minSize = MIN_PAYLOAD_SIZE;
  2948. unsigned headerSize = sizeof(RoxiePacketHeader)+owner.headerLength();
  2949. unsigned bufferSize = headerSize+minSize;
  2950. if (bufferSize < mtu_size)
  2951. bufferSize = mtu_size;
  2952. buffer.reserveTruncate(bufferSize);
  2953. bufferLeft = bufferSize - headerSize;
  2954. assertex(buffer.toByteArray());
  2955. nextBuf = (char *) buffer.toByteArray() + headerSize;
  2956. needsFlush = false;
  2957. }
  2958. inline IRoxieQueryPacket *flush()
  2959. {
  2960. CriticalBlock cb(crit);
  2961. Owned<IRoxieQueryPacket> ret;
  2962. if (needsFlush)
  2963. {
  2964. buffer.setLength(nextBuf - buffer.toByteArray());
  2965. RoxiePacketHeader *h = (RoxiePacketHeader *) buffer.toByteArray();
  2966. h->init(owner.remoteId, owner.ruid, channel, overflowSequence);
  2967. //patch logPrefix, cachedContext and parent extract into the place reserved in the message buffer
  2968. byte * tgt = (byte*)(h+1);
  2969. owner.copyHeader(tgt, channel);
  2970. ret.setown(createRoxiePacket(buffer));
  2971. if (overflowSequence == OVERFLOWSEQUENCE_MAX)
  2972. overflowSequence = 1; // don't wrap to 0 - that is a bit special
  2973. else
  2974. overflowSequence++;
  2975. needsFlush = false;
  2976. bufferLeft = 0;
  2977. if (owner.flowControlled)
  2978. {
  2979. CriticalUnblock cub(crit);
  2980. while (!flowController.wait(1000))
  2981. {
  2982. StringBuffer s;
  2983. owner.activity.queryLogCtx().CTXLOG("Channel %d blocked by flow control: %s", channel, h->toString(s).str());
  2984. }
  2985. }
  2986. }
  2987. return ret.getClear();
  2988. }
  2989. inline void signal()
  2990. {
  2991. if (owner.flowControlled)
  2992. flowController.signal();
  2993. }
  2994. inline void interrupt(IException *e)
  2995. {
  2996. flowController.interrupt(e);
  2997. }
  2998. inline void *getBuffer(unsigned size)
  2999. {
  3000. CriticalBlock cb(crit);
  3001. if (bufferLeft >= size)
  3002. {
  3003. needsFlush = true;
  3004. void * ret = nextBuf;
  3005. nextBuf += size;
  3006. bufferLeft -= size;
  3007. return ret;
  3008. }
  3009. else if (!needsFlush)
  3010. {
  3011. init(size);
  3012. return getBuffer(size);
  3013. }
  3014. else if (owner.mergeOrder)
  3015. {
  3016. return buffer.reserve(size); // whole query needs to go as single packet if we are to merge
  3017. }
  3018. else
  3019. return NULL; // will force it to flush and start a new packet
  3020. }
  3021. };
  3022. private:
  3023. friend class CRemoteResultMerger;
  3024. bool allread;
  3025. bool contextCached;
  3026. bool preserveOrder;
  3027. InterruptableSemaphore sentsome;
  3028. Owned <IMessageCollator> mc;
  3029. Owned<IMessageUnpackCursor> mu;
  3030. Owned<IMessageResult> mr;
  3031. ChannelBuffer **buffers;
  3032. IHThorArg &helper;
  3033. unsigned __int64 stopAfter;
  3034. unsigned resendSequence;
  3035. IHThorArg *colocalArg;
  3036. IArrayOf<IRoxieServerQueryPacket> pending;
  3037. CriticalSection pendingCrit;
  3038. IRoxieServerSideCache *serverSideCache;
  3039. unsigned sentSequence;
  3040. Owned<IOutputRowDeserializer> deserializer;
  3041. Owned<IEngineRowAllocator> rowAllocator;
  3042. CRemoteResultMerger merger;
  3043. // this is only used to avoid recreating a bufferStream for each row. A better solution may be needed
  3044. MemoryBuffer tempRowBuffer;
  3045. Owned<ISerialStream> bufferStream;
  3046. CThorStreamDeserializerSource rowSource;
  3047. protected:
  3048. IRowManager *rowManager;
  3049. IRoxieInput *owner;
  3050. unsigned __int64 rowLimit;
  3051. unsigned __int64 keyedLimit;
  3052. IRoxieServerErrorHandler *errorHandler;
  3053. CachedOutputMetaData meta;
  3054. public:
  3055. ISteppingMeta *mergeOrder;
  3056. IRoxieSlaveContext *ctx;
  3057. IDebuggableContext *debugContext;
  3058. IRoxieServerActivity &activity;
  3059. unsigned parentExtractSize;
  3060. const byte * parentExtract;
  3061. bool flowControlled;
  3062. bool deferredStart;
  3063. MemoryBuffer logInfo;
  3064. MemoryBuffer cachedContext;
  3065. const RemoteActivityId &remoteId;
  3066. ruid_t ruid;
  3067. mutable CriticalSection buffersCrit;
  3068. unsigned processed;
  3069. unsigned __int64 totalCycles;
  3070. //private: //vc6 doesn't like this being private yet accessed by nested class...
  3071. const void *getRow(IMessageUnpackCursor *mu)
  3072. {
  3073. if (!mu->isSerialized() || (meta.isFixedSize() && !deserializer))
  3074. return mu->getNext(meta.getFixedSize());
  3075. else
  3076. {
  3077. RecordLengthType *rowlen = (RecordLengthType *) mu->getNext(sizeof(RecordLengthType));
  3078. if (rowlen)
  3079. {
  3080. RecordLengthType len = *rowlen;
  3081. ReleaseRoxieRow(rowlen);
  3082. const void *slaveRec = mu->getNext(len);
  3083. if (deserializer && mu->isSerialized())
  3084. {
  3085. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  3086. tempRowBuffer.setBuffer(len, const_cast<void *>(slaveRec), false);
  3087. size_t outsize = deserializer->deserialize(rowBuilder, rowSource);
  3088. ReleaseRoxieRow(slaveRec);
  3089. return rowBuilder.finalizeRowClear(outsize);
  3090. }
  3091. else
  3092. return slaveRec;
  3093. }
  3094. else
  3095. return NULL;
  3096. }
  3097. }
  3098. private:
  3099. ChannelBuffer *queryChannelBuffer(unsigned channel, bool force=false)
  3100. {
  3101. CriticalBlock cb(buffersCrit);
  3102. ChannelBuffer *b = buffers[channel];
  3103. if (!b && force)
  3104. {
  3105. if (!contextCached)
  3106. {
  3107. logInfo.clear();
  3108. unsigned char loggingFlags = LOGGING_FLAGSPRESENT | LOGGING_TRACELEVELSET;
  3109. unsigned char ctxTraceLevel = activity.queryLogCtx().queryTraceLevel() + 1; // Avoid passing a 0
  3110. if (activity.queryLogCtx().isIntercepted())
  3111. loggingFlags |= LOGGING_INTERCEPTED;
  3112. if (ctx->queryTimeActivities())
  3113. loggingFlags |= LOGGING_TIMEACTIVITIES;
  3114. if (activity.queryLogCtx().isBlind())
  3115. loggingFlags |= LOGGING_BLIND;
  3116. if (ctx->queryCheckingHeap())
  3117. loggingFlags |= LOGGING_CHECKINGHEAP;
  3118. if (ctx->queryWorkUnit())
  3119. loggingFlags |= LOGGING_WUID;
  3120. if (debugContext)
  3121. {
  3122. loggingFlags |= LOGGING_DEBUGGERACTIVE;
  3123. logInfo.append(loggingFlags).append(ctxTraceLevel);
  3124. MemoryBuffer bpInfo;
  3125. debugContext->serialize(bpInfo);
  3126. bpInfo.append((__uint64)(memsize_t) &activity);
  3127. logInfo.append((unsigned short) bpInfo.length());
  3128. logInfo.append(bpInfo.length(), bpInfo.toByteArray());
  3129. }
  3130. else
  3131. logInfo.append(loggingFlags).append(ctxTraceLevel);
  3132. StringBuffer logPrefix;
  3133. activity.queryLogCtx().getLogPrefix(logPrefix);
  3134. logInfo.append(logPrefix);
  3135. activity.serializeCreateStartContext(cachedContext.clear());
  3136. activity.serializeExtra(cachedContext);
  3137. if (activity.queryVarFileInfo())
  3138. {
  3139. activity.queryVarFileInfo()->queryTimeStamp().serialize(cachedContext);
  3140. cachedContext.append(activity.queryVarFileInfo()->queryCheckSum());
  3141. }
  3142. contextCached = true;
  3143. }
  3144. b = buffers[channel] = new ChannelBuffer(*this, channel);
  3145. }
  3146. return b;
  3147. }
  3148. void processRow(const void *got)
  3149. {
  3150. processed++;
  3151. if (processed > rowLimit)
  3152. {
  3153. ReleaseRoxieRow(got);
  3154. errorHandler->onLimitExceeded(false); // NOTE - should throw exception
  3155. throwUnexpected();
  3156. }
  3157. else if (processed > keyedLimit)
  3158. {
  3159. ReleaseRoxieRow(got);
  3160. errorHandler->onLimitExceeded(true); // NOTE - should throw exception
  3161. throwUnexpected();
  3162. }
  3163. }
  3164. public:
  3165. IMPLEMENT_IINTERFACE;
  3166. CRemoteResultAdaptor(const RemoteActivityId &_remoteId, IOutputMetaData *_meta, IHThorArg &_helper, IRoxieServerActivity &_activity, bool _preserveOrder, bool _flowControlled)
  3167. : remoteId(_remoteId), meta(_meta), activity(_activity), helper(_helper), preserveOrder(_preserveOrder), flowControlled(_flowControlled), merger(*this)
  3168. {
  3169. rowLimit = (unsigned __int64) -1;
  3170. keyedLimit = (unsigned __int64) -1;
  3171. contextCached = false;
  3172. stopAfter = I64C(0x7FFFFFFFFFFFFFFF);
  3173. buffers = new ChannelBuffer*[numChannels+1];
  3174. memset(buffers, 0, (numChannels+1)*sizeof(ChannelBuffer *));
  3175. parentExtractSize = 0;
  3176. parentExtract = NULL;
  3177. owner = NULL;
  3178. mergeOrder = NULL;
  3179. deferredStart = false;
  3180. processed = 0;
  3181. totalCycles = 0;
  3182. sentSequence = 0;
  3183. serverSideCache = activity.queryServerSideCache();
  3184. bufferStream.setown(createMemoryBufferSerialStream(tempRowBuffer));
  3185. rowSource.setStream(bufferStream);
  3186. }
  3187. ~CRemoteResultAdaptor()
  3188. {
  3189. if (mc)
  3190. {
  3191. ROQ->queryReceiveManager()->detachCollator(mc);
  3192. mc.clear();
  3193. }
  3194. for (unsigned channel = 0; channel <= numChannels; channel++)
  3195. {
  3196. delete(buffers[channel]);
  3197. }
  3198. delete [] buffers;
  3199. }
  3200. void setMeta(IOutputMetaData *newmeta)
  3201. {
  3202. meta.set(newmeta);
  3203. }
  3204. virtual IRoxieServerActivity *queryActivity()
  3205. {
  3206. return &activity;
  3207. }
  3208. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  3209. {
  3210. return NULL;
  3211. }
  3212. void setMergeInfo(ISteppingMeta *_mergeOrder)
  3213. {
  3214. mergeOrder = _mergeOrder;
  3215. deferredStart = true;
  3216. }
  3217. void send(IRoxieQueryPacket *p)
  3218. {
  3219. if (p)
  3220. {
  3221. Linked<IRoxieQueryPacket> saver(p); // avoids a race with abortPending, without keeping pendingCrit locked over the send which we might prefer not to
  3222. assertex(p->queryHeader().uid==ruid);
  3223. // MORE: Maybe we should base the fastlane flag on some other
  3224. // criteria !! (i.e A Roxie server prediction based on the
  3225. // activity type/activity behaviour/expected reply size .. etc).
  3226. //
  3227. // Currently (code below) based on high priority, seq=0, and none-child activity.
  3228. // But this could still cause too many reply packets on the fatlane
  3229. // (higher priority output Q), which may cause the activities on the
  3230. // low priority output Q to not get service on time.
  3231. if ((colocalArg == 0) && // not a child query activity??
  3232. (p->queryHeader().activityId & (ROXIE_SLA_PRIORITY | ROXIE_HIGH_PRIORITY)) &&
  3233. (p->queryHeader().overflowSequence == 0) &&
  3234. (p->queryHeader().continueSequence & ~CONTINUE_SEQUENCE_SKIPTO)==0)
  3235. p->queryHeader().retries |= ROXIE_FASTLANE;
  3236. if (p->queryHeader().channel)
  3237. {
  3238. bool cached = false;
  3239. IRoxieServerQueryPacket *rsqp = createRoxieServerQueryPacket(p, cached);
  3240. if (deferredStart)
  3241. rsqp->setDelayed(true);
  3242. rsqp->setSequence(sentSequence++);
  3243. {
  3244. CriticalBlock b(pendingCrit);
  3245. pending.append(*rsqp);
  3246. }
  3247. if (!deferredStart)
  3248. {
  3249. if (!cached)
  3250. ROQ->sendPacket(p, activity.queryLogCtx());
  3251. sentsome.signal();
  3252. }
  3253. }
  3254. else
  3255. {
  3256. // 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
  3257. // Need to add first, then send
  3258. unsigned i;
  3259. bool allCached = true;
  3260. for (i = 1; i <= numChannels; i++)
  3261. {
  3262. IRoxieQueryPacket *q = p->clonePacket(i);
  3263. bool thisChannelCached;
  3264. IRoxieServerQueryPacket *rsqp = createRoxieServerQueryPacket(q, thisChannelCached);
  3265. if (!thisChannelCached)
  3266. allCached = false;
  3267. rsqp->setSequence(sentSequence++);
  3268. if (deferredStart)
  3269. {
  3270. rsqp->setDelayed(true);
  3271. }
  3272. {
  3273. CriticalBlock b(pendingCrit);
  3274. pending.append(*rsqp);
  3275. }
  3276. if (!deferredStart)
  3277. sentsome.signal();
  3278. }
  3279. if (!allCached && !deferredStart)
  3280. ROQ->sendPacket(p, activity.queryLogCtx());
  3281. buffers[0]->signal(); // since replies won't come back on that channel...
  3282. p->Release();
  3283. }
  3284. }
  3285. }
  3286. void *getMem(unsigned partNo, unsigned fileNo, unsigned size)
  3287. {
  3288. unsigned channel = partNo ? getBondedChannel(partNo) : 0;
  3289. size += sizeof(PartNoType);
  3290. ChannelBuffer *b = queryChannelBuffer(channel, true);
  3291. char *buffer = (char *) b->getBuffer(size);
  3292. if (!buffer)
  3293. {
  3294. send(b->flush());
  3295. buffer = (char *) b->getBuffer(size);
  3296. }
  3297. PartNoType sp;
  3298. sp.partNo = partNo;
  3299. sp.fileNo = fileNo;
  3300. memcpy(buffer, &sp, sizeof(sp));
  3301. buffer += sizeof(sp);
  3302. return buffer;
  3303. }
  3304. void injectResult(IMessageResult *result)
  3305. {
  3306. IRoxieServerQueryPacket *f = new CRoxieServerQueryPacket(NULL);
  3307. f->setSequence(sentSequence++);
  3308. f->setResult(result);
  3309. CriticalBlock b(pendingCrit);
  3310. pending.append(*f);
  3311. sentsome.signal(); // MORE - arguably should only send if there is any point waking up the listener thread, to save context swicth
  3312. }
  3313. void flush()
  3314. {
  3315. for (unsigned channel = 0; channel <= numChannels; channel++)
  3316. {
  3317. ChannelBuffer *b = queryChannelBuffer(channel, false);
  3318. if (b)
  3319. send(b->flush());
  3320. }
  3321. }
  3322. void interruptBuffers(IException *e)
  3323. {
  3324. for (unsigned channel = 0; channel <= numChannels; channel++)
  3325. {
  3326. ChannelBuffer *b = queryChannelBuffer(channel, false);
  3327. if (b)
  3328. b->interrupt(LINK(e));
  3329. }
  3330. }
  3331. void senddone()
  3332. {
  3333. CriticalBlock b(pendingCrit);
  3334. pending.append(*new CRoxieServerQueryPacketEndMarker);
  3335. sentsome.signal();
  3336. }
  3337. bool fireException(IException *e)
  3338. {
  3339. {
  3340. CriticalBlock b(pendingCrit);
  3341. pending.append(*new CRoxieServerQueryPacketEndMarker);
  3342. }
  3343. interruptBuffers(e);
  3344. if (mc)
  3345. mc->interrupt(LINK(e));
  3346. sentsome.interrupt(e);
  3347. return true;
  3348. }
  3349. virtual void onCreate(IRoxieInput *_owner, IRoxieServerErrorHandler *_errorHandler, IRoxieSlaveContext *_ctx, IHThorArg *_colocalArg)
  3350. {
  3351. owner = _owner;
  3352. errorHandler = _errorHandler;
  3353. ctx = _ctx;
  3354. debugContext = ctx->queryDebugContext();
  3355. colocalArg = _colocalArg;
  3356. if (meta.needsSerializeDisk())
  3357. {
  3358. deserializer.setown(meta.createDiskDeserializer(_ctx->queryCodeContext(), activity.queryId()));
  3359. rowAllocator.setown(ctx->queryCodeContext()->getRowAllocator(meta.queryOriginal(), activity.queryId()));
  3360. }
  3361. if (ctx->queryDebugContext() && ctx->queryDebugContext()->getExecuteSequentially())
  3362. deferredStart = true;
  3363. }
  3364. virtual unsigned queryId() const
  3365. {
  3366. return owner->queryId();
  3367. }
  3368. virtual void onStart(unsigned _parentExtractSize, const byte * _parentExtract)
  3369. {
  3370. #ifdef TRACE_STARTSTOP
  3371. if (traceStartStop)
  3372. activity.queryLogCtx().CTXLOG("RRAonstart");
  3373. #endif
  3374. sentsome.reinit();
  3375. ruid = getNextRuid();
  3376. rowManager = &ctx->queryRowManager();
  3377. if (mergeOrder)
  3378. merger.init(mergeOrder, rowManager);
  3379. if (mc)
  3380. {
  3381. ROQ->queryReceiveManager()->detachCollator(mc); // Should never happen - implies someone forgot to call onReset!
  3382. }
  3383. mc.setown(ROQ->queryReceiveManager()->createMessageCollator(rowManager, ruid));
  3384. allread = false;
  3385. mu.clear();
  3386. contextCached = false;
  3387. processed = 0;
  3388. totalCycles = 0;
  3389. resendSequence = 0;
  3390. sentSequence = 0;
  3391. for (unsigned channel = 0; channel <= numChannels; channel++)
  3392. {
  3393. delete(buffers[channel]);
  3394. buffers[channel] = NULL;
  3395. }
  3396. flush();
  3397. parentExtractSize = _parentExtractSize;
  3398. parentExtract = _parentExtract;
  3399. }
  3400. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  3401. {
  3402. #ifdef TRACE_STARTSTOP
  3403. if (traceStartStop)
  3404. activity.queryLogCtx().CTXLOG("RRAstart");
  3405. #endif
  3406. owner->start(parentExtractSize, parentExtract, paused);
  3407. totalCycles = 0;
  3408. }
  3409. void checkAbort()
  3410. {
  3411. owner->checkAbort();
  3412. }
  3413. void setLimits(unsigned __int64 _rowLimit, unsigned __int64 _keyedLimit, unsigned __int64 _stopAfter)
  3414. {
  3415. if (ctx->queryProbeManager())
  3416. {
  3417. if (_rowLimit != (unsigned __int64) -1) ctx->queryProbeManager()->setNodePropertyInt(&activity, "rowLimit", _rowLimit);
  3418. if (_keyedLimit != (unsigned __int64) -1) ctx->queryProbeManager()->setNodePropertyInt(&activity, "keyedLimit", _keyedLimit);
  3419. if (_stopAfter != I64C(0x7FFFFFFFFFFFFFFF)) ctx->queryProbeManager()->setNodePropertyInt(&activity, "choosenLimit", _stopAfter);
  3420. }
  3421. {
  3422. CriticalBlock b(pendingCrit);
  3423. if (pending.length())
  3424. {
  3425. #ifdef _DEBUG
  3426. dumpPending(); // MORE - only defined in debug build - could have put the ifdef inside the dumpPending method
  3427. #endif
  3428. assertex(pending.length()==0);
  3429. }
  3430. pending.append(*new CRoxieServerQueryPacketLimitMarker(_rowLimit, _keyedLimit, _stopAfter));
  3431. }
  3432. sentsome.signal();
  3433. rowLimit = _rowLimit;
  3434. keyedLimit = _keyedLimit;
  3435. stopAfter = _stopAfter;
  3436. }
  3437. virtual void stop(bool aborting)
  3438. {
  3439. #ifdef TRACE_STARTSTOP
  3440. if (traceStartStop)
  3441. activity.queryLogCtx().CTXLOG("RRAstop");
  3442. #endif
  3443. onStop(aborting);
  3444. owner->stop(aborting);
  3445. }
  3446. void onStop(bool aborting)
  3447. {
  3448. #ifdef TRACE_STARTSTOP
  3449. if (traceStartStop)
  3450. activity.queryLogCtx().CTXLOG("RRAonstop");
  3451. #endif
  3452. abortPending();
  3453. interruptBuffers(NULL);
  3454. sentsome.interrupt();
  3455. if (mc) // May not be set if start() chain threw exception
  3456. mc->interrupt();
  3457. }
  3458. virtual void reset()
  3459. {
  3460. #ifdef TRACE_STARTSTOP
  3461. if (traceStartStop)
  3462. activity.queryLogCtx().CTXLOG("RRAreset");
  3463. #endif
  3464. owner->reset();
  3465. onReset();
  3466. }
  3467. virtual void resetEOF()
  3468. {
  3469. throwUnexpected();
  3470. }
  3471. virtual void onReset()
  3472. {
  3473. #ifdef TRACE_STARTSTOP
  3474. if (traceStartStop)
  3475. activity.queryLogCtx().CTXLOG("RRAonreset");
  3476. #endif
  3477. if (mc)
  3478. ROQ->queryReceiveManager()->detachCollator(mc);
  3479. merger.reset();
  3480. pending.kill();
  3481. if (mc && ctx)
  3482. ctx->addSlavesReplyLen(mc->queryBytesReceived());
  3483. mc.clear(); // Or we won't free memory for graphs that get recreated
  3484. mu.clear(); //ditto
  3485. deferredStart = false;
  3486. // NOTE: do NOT clear mergeOrder - this is set at create time not per child query
  3487. }
  3488. virtual IOutputMetaData * queryOutputMeta() const
  3489. {
  3490. return helper.queryOutputMeta();
  3491. }
  3492. virtual unsigned __int64 queryTotalCycles() const
  3493. {
  3494. return totalCycles;
  3495. }
  3496. virtual unsigned __int64 queryLocalCycles() const
  3497. {
  3498. return owner->queryLocalCycles();
  3499. }
  3500. virtual IRoxieInput *queryInput(unsigned idx) const
  3501. {
  3502. return owner->queryInput(idx);
  3503. }
  3504. const void * nextSteppedGE(const void *seek, const void *rawSeek, unsigned numFields, unsigned seekLen, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  3505. {
  3506. if (activity.queryLogCtx().queryTraceLevel() > 20)
  3507. {
  3508. StringBuffer recstr;
  3509. unsigned i;
  3510. for (i = 0; i < seekLen; i++)
  3511. {
  3512. recstr.appendf("%02x ", ((unsigned char *) rawSeek)[i]);
  3513. }
  3514. activity.queryLogCtx().CTXLOG("CRemoteResultAdaptor::nextSteppedGE(rawSeek=%s numFields=%d, seeklen=%d, returnMismatches=%d)", recstr.str(), numFields, seekLen, stepExtra.returnMismatches());
  3515. }
  3516. assertex(mergeOrder);
  3517. if (deferredStart)
  3518. {
  3519. CriticalBlock b(pendingCrit);
  3520. ForEachItemIn(idx, pending)
  3521. {
  3522. IRoxieServerQueryPacket &p = pending.item(idx);
  3523. if (p.isDelayed())
  3524. {
  3525. p.setDelayed(false);
  3526. if (activity.queryLogCtx().queryTraceLevel() > 10)
  3527. activity.queryLogCtx().CTXLOG("About to send deferred start from nextSteppedGE, setting requireExact to %d", !stepExtra.returnMismatches());
  3528. MemoryBuffer serializedSkip;
  3529. activity.serializeSkipInfo(serializedSkip, seekLen, rawSeek, numFields, seek, stepExtra);
  3530. p.setPacket(p.queryPacket()->insertSkipData(serializedSkip.length(), serializedSkip.toByteArray()));
  3531. ROQ->sendPacket(p.queryPacket(), activity.queryLogCtx());
  3532. sentsome.signal();
  3533. }
  3534. }
  3535. deferredStart = false;
  3536. }
  3537. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  3538. if (processed==stopAfter)
  3539. return NULL;
  3540. if (allread)
  3541. return NULL;
  3542. loop
  3543. {
  3544. if (merger.ready())
  3545. {
  3546. const void *got = merger.nextSteppedGE(seek, rawSeek, numFields, seekLen, wasCompleteMatch, stepExtra);
  3547. if (got)
  3548. {
  3549. processRow(got);
  3550. return got;
  3551. }
  3552. }
  3553. if (!reload()) // MORE - should pass the seek info here...
  3554. return NULL;
  3555. }
  3556. }
  3557. virtual const void *nextInGroup()
  3558. {
  3559. // If we are merging then we need to do a heapsort on all
  3560. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  3561. if (activity.queryLogCtx().queryTraceLevel() > 10)
  3562. {
  3563. activity.queryLogCtx().CTXLOG("CRemoteResultAdaptor::nextInGroup()");
  3564. }
  3565. loop
  3566. {
  3567. checkDelayed();
  3568. if (processed==stopAfter)
  3569. return NULL;
  3570. if (allread)
  3571. return NULL;
  3572. // If we can still consume from the merger or the most recently retrieved mu, do so.
  3573. const void *got = NULL;
  3574. if (mergeOrder && merger.ready())
  3575. {
  3576. bool matched = true;
  3577. got = merger.next(matched, dummySmartStepExtra);
  3578. }
  3579. else if (mu)
  3580. got = getRow(mu);
  3581. if (got)
  3582. {
  3583. processRow(got);
  3584. return got;
  3585. }
  3586. if (!reload())
  3587. return NULL;
  3588. }
  3589. }
  3590. bool reload()
  3591. {
  3592. // Wait for something to be returned from a slave....
  3593. mu.clear();
  3594. sentsome.wait();
  3595. // must be at least an endMarker on the queue since sentsome was signalled
  3596. {
  3597. CriticalBlock b(pendingCrit);
  3598. IRoxieServerQueryPacket &top = pending.item(0);
  3599. if (top.isLimit(rowLimit, keyedLimit, stopAfter)) // This is really a start marker...
  3600. {
  3601. pending.remove(0);
  3602. return true;
  3603. }
  3604. else if (top.isEnd())
  3605. {
  3606. pending.remove(0);
  3607. allread = true;
  3608. if (activity.queryLogCtx().queryTraceLevel() > 5)
  3609. activity.queryLogCtx().CTXLOG("All read on ruid %x", ruid);
  3610. return false;
  3611. }
  3612. else if (mergeOrder)
  3613. {
  3614. unsigned idx = 0;
  3615. bool added = false;
  3616. while (pending.isItem(idx))
  3617. {
  3618. IRoxieServerQueryPacket &item = pending.item(idx);
  3619. if (item.isEnd())
  3620. {
  3621. if (merger.noteEndSeen())
  3622. {
  3623. sentsome.signal(); // Because we waited, yet didn't actually consume anything
  3624. added = true;
  3625. }
  3626. break;
  3627. }
  3628. else if (item.hasResult())
  3629. {
  3630. merger.noteResult(&item, item.getSequence());
  3631. pending.remove(idx);
  3632. added = true;
  3633. }
  3634. else if (item.isContinuation())
  3635. idx++;
  3636. else
  3637. break;
  3638. }
  3639. if (added)
  3640. return true;
  3641. }
  3642. else if (top.hasResult())
  3643. {
  3644. mr.setown(pending.item(0).getResult());
  3645. mu.setown(mr->getCursor(rowManager));
  3646. pending.remove(0);
  3647. return true;
  3648. }
  3649. }
  3650. getNextUnpacker();
  3651. return true;
  3652. }
  3653. void getNextUnpacker()
  3654. {
  3655. mu.clear();
  3656. unsigned ctxTraceLevel = activity.queryLogCtx().queryTraceLevel();
  3657. loop
  3658. {
  3659. checkDelayed();
  3660. unsigned timeout = remoteId.isSLAPriority() ? slaTimeout : (remoteId.isHighPriority() ? highTimeout : lowTimeout);
  3661. owner->checkAbort();
  3662. bool anyActivity;
  3663. if (ctxTraceLevel > 5)
  3664. activity.queryLogCtx().CTXLOG("Calling getNextUnpacker(%d)", timeout);
  3665. mr.setown(mc->getNextResult(timeout, anyActivity));
  3666. if (ctxTraceLevel > 6)
  3667. activity.queryLogCtx().CTXLOG("Called getNextUnpacker(%d), activity=%d", timeout, anyActivity);
  3668. owner->checkAbort();
  3669. if (mr)
  3670. {
  3671. unsigned roxieHeaderLen;
  3672. const RoxiePacketHeader &header = *(const RoxiePacketHeader *) mr->getMessageHeader(roxieHeaderLen);
  3673. #ifdef _DEBUG
  3674. assertex(roxieHeaderLen == sizeof(RoxiePacketHeader));
  3675. #endif
  3676. if (ctxTraceLevel > 5)
  3677. {
  3678. StringBuffer s;
  3679. activity.queryLogCtx().CTXLOG("getNextUnpacker got packet %s", header.toString(s).str());
  3680. }
  3681. CriticalBlock b(pendingCrit);
  3682. unsigned idx = 0;
  3683. IRoxieServerQueryPacket *original = NULL;
  3684. IRoxieQueryPacket *op;
  3685. while (pending.isItem(idx))
  3686. {
  3687. original = &pending.item(idx);
  3688. op = original->queryPacket();
  3689. if (op && header.matchPacket(op->queryHeader()))
  3690. break;
  3691. original = NULL;
  3692. idx++;
  3693. }
  3694. if (!original || original->hasResult())
  3695. {
  3696. switch (header.activityId)
  3697. {
  3698. case ROXIE_FILECALLBACK:
  3699. {
  3700. // tell slave to abort
  3701. //if (ctxTraceLevel > 5)
  3702. {
  3703. StringBuffer s;
  3704. activity.queryLogCtx().CTXLOG("Redundant callback on query %s", header.toString(s).str());
  3705. }
  3706. Owned<IMessageUnpackCursor> callbackData = mr->getCursor(rowManager);
  3707. OwnedConstRoxieRow len = callbackData->getNext(sizeof(RecordLengthType));
  3708. if (len)
  3709. {
  3710. RecordLengthType *rowlen = (RecordLengthType *) len.get();
  3711. OwnedConstRoxieRow row = callbackData->getNext(*rowlen);
  3712. const char *rowdata = (const char *) row.get();
  3713. // bool isOpt = * (bool *) rowdata;
  3714. // bool isLocal = * (bool *) (rowdata+1);
  3715. ROQ->sendAbortCallback(header, rowdata+2, activity.queryLogCtx());
  3716. }
  3717. else
  3718. throwUnexpected();
  3719. break;
  3720. }
  3721. // MORE - ROXIE_ALIVE perhaps should go here too
  3722. case ROXIE_TRACEINFO:
  3723. {
  3724. Owned<IMessageUnpackCursor> extra = mr->getCursor(rowManager);
  3725. loop
  3726. {
  3727. RecordLengthType *rowlen = (RecordLengthType *) extra->getNext(sizeof(RecordLengthType));
  3728. if (rowlen)
  3729. {
  3730. char *logInfo = (char *) extra->getNext(*rowlen);
  3731. MemoryBuffer buf;
  3732. buf.setBuffer(*rowlen, logInfo, false);
  3733. activity.queryLogCtx().CTXLOGl(new LogItem(buf));
  3734. ReleaseRoxieRow(rowlen);
  3735. ReleaseRoxieRow(logInfo);
  3736. }
  3737. else
  3738. break;
  3739. }
  3740. break;
  3741. }
  3742. default:
  3743. if (ctxTraceLevel > 3)
  3744. activity.queryLogCtx().CTXLOG("Discarding packet %p - original %p is NULL or has result already", mr.get(), original);
  3745. mr->discard();
  3746. break;
  3747. }
  3748. mr.clear();
  3749. }
  3750. else
  3751. {
  3752. atomic_inc(&resultsReceived);
  3753. switch (header.activityId)
  3754. {
  3755. case ROXIE_DEBUGCALLBACK:
  3756. {
  3757. Owned<IMessageUnpackCursor> callbackData = mr->getCursor(rowManager);
  3758. OwnedConstRoxieRow len = callbackData->getNext(sizeof(RecordLengthType));
  3759. if (len)
  3760. {
  3761. RecordLengthType *rowlen = (RecordLengthType *) len.get();
  3762. OwnedConstRoxieRow row = callbackData->getNext(*rowlen);
  3763. char *rowdata = (char *) row.get();
  3764. if (ctxTraceLevel > 5)
  3765. {
  3766. StringBuffer s;
  3767. activity.queryLogCtx().CTXLOG("Callback on query %s for debug", header.toString(s).str());
  3768. }
  3769. MemoryBuffer slaveInfo;
  3770. slaveInfo.setBuffer(*rowlen, rowdata, false);
  3771. unsigned debugSequence;
  3772. slaveInfo.read(debugSequence);
  3773. Owned<IRoxieQueryPacket> reply = original->getDebugResponse(debugSequence);
  3774. if (!reply)
  3775. reply.setown(activity.queryContext()->queryDebugContext()->onDebugCallback(header, *rowlen, rowdata));
  3776. if (reply)
  3777. {
  3778. original->setDebugResponse(debugSequence, reply);
  3779. ROQ->sendPacket(reply, activity.queryLogCtx());
  3780. }
  3781. }
  3782. else
  3783. throwUnexpected();
  3784. // MORE - somehow we need to make sure slave gets a reply even if I'm not waiting (in udp layer)
  3785. // Leave original message on pending queue in original location - this is not a reply to it.
  3786. break;
  3787. }
  3788. case ROXIE_FILECALLBACK:
  3789. {
  3790. // we need to send back to the slave a message containing the file info requested.
  3791. Owned<IMessageUnpackCursor> callbackData = mr->getCursor(rowManager);
  3792. OwnedConstRoxieRow len = callbackData->getNext(sizeof(RecordLengthType));
  3793. if (len)
  3794. {
  3795. RecordLengthType *rowlen = (RecordLengthType *) len.get();
  3796. OwnedConstRoxieRow row = callbackData->getNext(*rowlen);
  3797. const char *rowdata = (const char *) row.get();
  3798. bool isOpt = * (bool *) rowdata;
  3799. bool isLocal = * (bool *) (rowdata+1);
  3800. const char *lfn = rowdata+2;
  3801. if (ctxTraceLevel > 5)
  3802. {
  3803. StringBuffer s;
  3804. activity.queryLogCtx().CTXLOG("Callback on query %s file %s", header.toString(s).str(),(const char *) lfn);
  3805. }
  3806. activity.queryContext()->onFileCallback(header, lfn, isOpt, isLocal);
  3807. }
  3808. else
  3809. throwUnexpected();
  3810. // MORE - somehow we need to make sure slave gets a reply even if I'm not waiting (in udp layer)
  3811. // Leave original message on pending queue in original location - this is not a reply to it.
  3812. break;
  3813. }
  3814. case ROXIE_KEYEDLIMIT_EXCEEDED:
  3815. activity.queryLogCtx().CTXLOG("ROXIE_KEYEDLIMIT_EXCEEDED");
  3816. errorHandler->onLimitExceeded(true); // NOTE - should throw exception!
  3817. throwUnexpected();
  3818. case ROXIE_LIMIT_EXCEEDED:
  3819. activity.queryLogCtx().CTXLOG("ROXIE_LIMIT_EXCEEDED");
  3820. errorHandler->onLimitExceeded(false); // NOTE - should throw exception!
  3821. throwUnexpected();
  3822. case ROXIE_TRACEINFO:
  3823. {
  3824. Owned<IMessageUnpackCursor> extra = mr->getCursor(rowManager);
  3825. loop
  3826. {
  3827. RecordLengthType *rowlen = (RecordLengthType *) extra->getNext(sizeof(RecordLengthType));
  3828. if (rowlen)
  3829. {
  3830. char *logInfo = (char *) extra->getNext(*rowlen);
  3831. MemoryBuffer buf;
  3832. buf.setBuffer(*rowlen, logInfo, false);
  3833. activity.queryLogCtx().CTXLOGl(new LogItem(buf));
  3834. ReleaseRoxieRow(rowlen);
  3835. ReleaseRoxieRow(logInfo);
  3836. }
  3837. else
  3838. break;
  3839. }
  3840. break;
  3841. }
  3842. case ROXIE_EXCEPTION:
  3843. if (ctxTraceLevel > 1)
  3844. {
  3845. StringBuffer s;
  3846. activity.queryLogCtx().CTXLOG("Exception on query %s", header.toString(s).str());
  3847. }
  3848. op->queryHeader().noteException(header.retries);
  3849. if (op->queryHeader().allChannelsFailed())
  3850. {
  3851. activity.queryLogCtx().CTXLOG("Multiple exceptions on query - aborting");
  3852. Owned<IMessageUnpackCursor> exceptionData = mr->getCursor(rowManager);
  3853. throwRemoteException(exceptionData);
  3854. }
  3855. // Leave it on pending queue in original location
  3856. break;
  3857. case ROXIE_ALIVE:
  3858. if (ctxTraceLevel > 4)
  3859. {
  3860. StringBuffer s;
  3861. activity.queryLogCtx().CTXLOG("ROXIE_ALIVE: %s", header.toString(s).str());
  3862. }
  3863. op->queryHeader().noteAlive(header.retries & ROXIE_RETRIES_MASK);
  3864. // Leave it on pending queue in original location
  3865. break;
  3866. default:
  3867. if (header.retries & ROXIE_RETRIES_MASK)
  3868. atomic_inc(&retriesNeeded);
  3869. unsigned metaLen;
  3870. const void *metaData = mr->getMessageMetadata(metaLen);
  3871. if (metaLen)
  3872. {
  3873. // We got back first chunk but there is more.
  3874. // resend the packet, with the cursor info provided.
  3875. // MORE - if smart-stepping, we don't want to send the continuation immediately. Other cases it's not clear that we do.
  3876. if (ctxTraceLevel > 1)
  3877. {
  3878. StringBuffer s;
  3879. activity.queryLogCtx().CTXLOG("Additional data size %d on query %s mergeOrder %p", metaLen, header.toString(s).str(), mergeOrder);
  3880. }
  3881. if (*((unsigned short *) metaData) + sizeof(unsigned short) != metaLen)
  3882. {
  3883. StringBuffer s;
  3884. activity.queryLogCtx().CTXLOG("Additional data size %d on query %s mergeOrder %p", metaLen, header.toString(s).str(), mergeOrder);
  3885. activity.queryLogCtx().CTXLOG("Additional data is corrupt");
  3886. throwUnexpected();
  3887. }
  3888. MemoryBuffer nextQuery;
  3889. nextQuery.append(sizeof(RoxiePacketHeader), &header);
  3890. nextQuery.append(metaLen, metaData);
  3891. nextQuery.append(op->getTraceLength(), op->queryTraceInfo());
  3892. nextQuery.append(op->getContextLength(), op->queryContextData());
  3893. if (resendSequence == CONTINUESEQUENCE_MAX)
  3894. {
  3895. activity.queryLogCtx().CTXLOG("ERROR: Continuation sequence wrapped"); // shouldn't actually matter.... but suggests a very iffy query!
  3896. resendSequence = 1;
  3897. }
  3898. else
  3899. resendSequence++;
  3900. RoxiePacketHeader *newHeader = (RoxiePacketHeader *) nextQuery.toByteArray();
  3901. newHeader->continueSequence = resendSequence; // NOTE - we clear the skipTo flag since continuation of a skip is NOT a skip...
  3902. newHeader->retries &= ~ROXIE_RETRIES_MASK;
  3903. IRoxieQueryPacket *resend = createRoxiePacket(nextQuery);
  3904. CRoxieServerQueryPacket *fqp = new CRoxieServerQueryPacket(resend);
  3905. fqp->setSequence(original->getSequence());
  3906. pending.add(*fqp, idx+1); // note that pending takes ownership. sendPacket does not release.
  3907. original->setContinuation(LINK(fqp));
  3908. if (mergeOrder)
  3909. fqp->setDelayed(true);
  3910. else
  3911. {
  3912. ROQ->sendPacket(resend, activity.queryLogCtx());
  3913. sentsome.signal();
  3914. }
  3915. // Note that we don't attempt to cache results that have continuation records - too tricky !
  3916. }
  3917. else
  3918. {
  3919. if (serverSideCache)
  3920. serverSideCache->noteCachedResult(original, mr);
  3921. }
  3922. unsigned channel = header.channel;
  3923. {
  3924. ChannelBuffer *b = queryChannelBuffer(channel); // If not something is wrong, or we sent out on channel 0?
  3925. if (b)
  3926. b->signal();
  3927. }
  3928. original->setResult(mr.getClear());
  3929. sentsome.signal();
  3930. return;
  3931. }
  3932. }
  3933. }
  3934. else
  3935. {
  3936. if (!anyActivity)
  3937. {
  3938. activity.queryLogCtx().CTXLOG("Input has stalled - retry required?");
  3939. retryPending();
  3940. }
  3941. }
  3942. }
  3943. }
  3944. inline unsigned headerLength() const
  3945. {
  3946. return logInfo.length() + cachedContext.length() + sizeof(unsigned) + parentExtractSize;
  3947. }
  3948. void copyHeader(byte *tgt, unsigned channel) const
  3949. {
  3950. unsigned len = logInfo.length();
  3951. memcpy(tgt, logInfo.toByteArray(), len);
  3952. tgt += len;
  3953. *(unsigned *) tgt = parentExtractSize;
  3954. tgt += sizeof(unsigned);
  3955. memcpy(tgt, parentExtract, parentExtractSize);
  3956. tgt += parentExtractSize;
  3957. memcpy(tgt, cachedContext.toByteArray(), cachedContext.length());
  3958. tgt += cachedContext.length();
  3959. }
  3960. };
  3961. class CSkippableRemoteResultAdaptor : public CRemoteResultAdaptor
  3962. {
  3963. Owned <IException> exception;
  3964. bool skipping;
  3965. ConstPointerArray buff;
  3966. unsigned index;
  3967. bool pulled;
  3968. void pullInput()
  3969. {
  3970. try
  3971. {
  3972. if (exception)
  3973. throw exception.getClear();
  3974. unsigned __int64 count = 0;
  3975. loop
  3976. {
  3977. const void * next = CRemoteResultAdaptor::nextInGroup();
  3978. if (next == NULL)
  3979. {
  3980. next = CRemoteResultAdaptor::nextInGroup();
  3981. if(next == NULL)
  3982. break;
  3983. buff.append(NULL);
  3984. }
  3985. count++;
  3986. if (count > rowLimit)
  3987. {
  3988. ReleaseRoxieRow(next);
  3989. ReleaseRoxieRowSet(buff);
  3990. errorHandler->onLimitExceeded(false); // throws an exception - user or LimitSkipException
  3991. throwUnexpected();
  3992. }
  3993. else if (count > keyedLimit)
  3994. {
  3995. ReleaseRoxieRow(next);
  3996. ReleaseRoxieRowSet(buff);
  3997. errorHandler->onLimitExceeded(true); // throws an exception - user or LimitSkipException
  3998. throwUnexpected();
  3999. }
  4000. buff.append(next);
  4001. }
  4002. }
  4003. catch (IException *E)
  4004. {
  4005. if (QUERYINTERFACE(E, LimitSkipException))
  4006. {
  4007. Owned<IException> cleanup = E;
  4008. ReleaseRoxieRowSet(buff);
  4009. const void *onfail = errorHandler->createLimitFailRow(E->errorCode() == KeyedLimitSkipErrorCode);
  4010. if (onfail)
  4011. buff.append(onfail);
  4012. }
  4013. else
  4014. throw;
  4015. }
  4016. pulled = true;
  4017. }
  4018. public:
  4019. CSkippableRemoteResultAdaptor(const RemoteActivityId &_remoteId, IOutputMetaData *_meta, IHThorArg &_helper, IRoxieServerActivity &_activity, bool _preserveOrder, bool _flowControlled, bool _skipping) :
  4020. CRemoteResultAdaptor(_remoteId, _meta, _helper, _activity, _preserveOrder, _flowControlled)
  4021. {
  4022. skipping = _skipping;
  4023. index = 0;
  4024. pulled = false;
  4025. }
  4026. void setException(IException *E)
  4027. {
  4028. exception.setown(E);
  4029. }
  4030. virtual void onReset()
  4031. {
  4032. while (buff.isItem(index))
  4033. ReleaseRoxieRow(buff.item(index++));
  4034. buff.kill();
  4035. pulled = false;
  4036. exception.clear();
  4037. CRemoteResultAdaptor::onReset();
  4038. }
  4039. void onStart(unsigned _parentExtractSize, const byte * _parentExtract)
  4040. {
  4041. index = 0;
  4042. pulled = false;
  4043. CRemoteResultAdaptor::onStart(_parentExtractSize, _parentExtract);
  4044. }
  4045. virtual const void * nextSteppedGE(const void *seek, const void *rawSeek, unsigned numFields, unsigned seeklen, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  4046. {
  4047. // 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
  4048. if (exception)
  4049. throw exception.getClear();
  4050. return CRemoteResultAdaptor::nextSteppedGE(seek, rawSeek, numFields, seeklen, wasCompleteMatch, stepExtra);
  4051. }
  4052. virtual const void *nextInGroup()
  4053. {
  4054. if (skipping)
  4055. {
  4056. if(!pulled)
  4057. pullInput();
  4058. if(buff.isItem(index))
  4059. {
  4060. const void * next = buff.item(index++);
  4061. if(next)
  4062. processed++;
  4063. return next;
  4064. }
  4065. return NULL;
  4066. }
  4067. else
  4068. {
  4069. if (exception)
  4070. throw exception.getClear();
  4071. return CRemoteResultAdaptor::nextInGroup();
  4072. }
  4073. }
  4074. };
  4075. //=================================================================================
  4076. class CRoxieServerApplyActivity : public CRoxieServerInternalSinkActivity
  4077. {
  4078. IHThorApplyArg &helper;
  4079. public:
  4080. CRoxieServerApplyActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4081. : CRoxieServerInternalSinkActivity(_factory, _probeManager, 0), helper((IHThorApplyArg &) basehelper)
  4082. {
  4083. }
  4084. virtual void onExecute()
  4085. {
  4086. helper.start();
  4087. loop
  4088. {
  4089. const void * next = input->nextInGroup();
  4090. if (!next)
  4091. {
  4092. next = input->nextInGroup();
  4093. if (!next)
  4094. break;
  4095. }
  4096. helper.apply(next);
  4097. ReleaseRoxieRow(next);
  4098. }
  4099. helper.end();
  4100. }
  4101. };
  4102. class CRoxieServerApplyActivityFactory : public CRoxieServerActivityFactory
  4103. {
  4104. bool isRoot;
  4105. public:
  4106. CRoxieServerApplyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  4107. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  4108. {
  4109. }
  4110. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4111. {
  4112. return new CRoxieServerApplyActivity(this, _probeManager);
  4113. }
  4114. virtual bool isSink() const
  4115. {
  4116. return isRoot;
  4117. }
  4118. };
  4119. IRoxieServerActivityFactory *createRoxieServerApplyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  4120. {
  4121. return new CRoxieServerApplyActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  4122. }
  4123. //=================================================================================
  4124. class CRoxieServerNullActivity : public CRoxieServerActivity
  4125. {
  4126. public:
  4127. CRoxieServerNullActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4128. : CRoxieServerActivity(_factory, _probeManager)
  4129. {
  4130. }
  4131. virtual const void *nextInGroup()
  4132. {
  4133. return NULL;
  4134. }
  4135. };
  4136. IRoxieServerActivity * createRoxieServerNullActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4137. {
  4138. return new CRoxieServerNullActivity(_factory, _probeManager);
  4139. }
  4140. class CRoxieServerNullActivityFactory : public CRoxieServerActivityFactory
  4141. {
  4142. public:
  4143. CRoxieServerNullActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4144. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4145. {
  4146. }
  4147. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4148. {
  4149. return new CRoxieServerNullActivity(this, _probeManager);
  4150. }
  4151. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  4152. {
  4153. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for null activity");
  4154. }
  4155. };
  4156. IRoxieServerActivityFactory *createRoxieServerNullActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4157. {
  4158. return new CRoxieServerNullActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4159. }
  4160. //=================================================================================
  4161. class CRoxieServerPassThroughActivity : public CRoxieServerActivity
  4162. {
  4163. public:
  4164. CRoxieServerPassThroughActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4165. : CRoxieServerActivity(_factory, _probeManager)
  4166. {
  4167. }
  4168. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  4169. {
  4170. return input->gatherConjunctions(collector);
  4171. }
  4172. virtual void resetEOF()
  4173. {
  4174. input->resetEOF();
  4175. }
  4176. virtual const void *nextInGroup()
  4177. {
  4178. const void * next = input->nextInGroup();
  4179. if (next)
  4180. processed++;
  4181. return next;
  4182. }
  4183. virtual bool isPassThrough()
  4184. {
  4185. return true;
  4186. }
  4187. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  4188. {
  4189. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  4190. const void * next = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  4191. if (next)
  4192. processed++;
  4193. return next;
  4194. }
  4195. IInputSteppingMeta * querySteppingMeta()
  4196. {
  4197. return input->querySteppingMeta();
  4198. }
  4199. };
  4200. IRoxieServerActivity * createRoxieServerPassThroughActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4201. {
  4202. return new CRoxieServerPassThroughActivity(_factory, _probeManager);
  4203. }
  4204. //=================================================================================
  4205. class CRoxieServerChildBaseActivity : public CRoxieServerActivity
  4206. {
  4207. protected:
  4208. bool eof;
  4209. bool first;
  4210. public:
  4211. CRoxieServerChildBaseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4212. : CRoxieServerActivity(_factory, _probeManager)
  4213. {
  4214. eof = false;
  4215. first = true;
  4216. }
  4217. ~CRoxieServerChildBaseActivity()
  4218. {
  4219. }
  4220. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4221. {
  4222. eof = false;
  4223. first = true;
  4224. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  4225. }
  4226. };
  4227. class CRoxieServerChildBaseActivityFactory : public CRoxieServerActivityFactory
  4228. {
  4229. public:
  4230. CRoxieServerChildBaseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4231. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4232. {
  4233. }
  4234. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  4235. {
  4236. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  4237. }
  4238. };
  4239. //=================================================================================
  4240. class CRoxieServerChildIteratorActivity : public CRoxieServerChildBaseActivity
  4241. {
  4242. IHThorChildIteratorArg &helper;
  4243. public:
  4244. CRoxieServerChildIteratorActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4245. : CRoxieServerChildBaseActivity(_factory, _probeManager), helper((IHThorChildIteratorArg &) basehelper)
  4246. {
  4247. }
  4248. virtual bool needsAllocator() const { return true; }
  4249. virtual const void *nextInGroup()
  4250. {
  4251. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  4252. if (eof)
  4253. return NULL;
  4254. bool ok;
  4255. if (first)
  4256. {
  4257. ok = helper.first();
  4258. first = false;
  4259. }
  4260. else
  4261. ok = helper.next();
  4262. try
  4263. {
  4264. while (ok)
  4265. {
  4266. processed++;
  4267. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  4268. unsigned outSize = helper.transform(rowBuilder);
  4269. if (outSize)
  4270. return rowBuilder.finalizeRowClear(outSize);
  4271. ok = helper.next();
  4272. }
  4273. }
  4274. catch (IException *E)
  4275. {
  4276. throw makeWrappedException(E);
  4277. }
  4278. eof = true;
  4279. return NULL;
  4280. }
  4281. };
  4282. class CRoxieServerChildIteratorActivityFactory : public CRoxieServerChildBaseActivityFactory
  4283. {
  4284. public:
  4285. CRoxieServerChildIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4286. : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4287. {
  4288. }
  4289. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4290. {
  4291. return new CRoxieServerChildIteratorActivity(this, _probeManager);
  4292. }
  4293. };
  4294. IRoxieServerActivityFactory *createRoxieServerChildIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4295. {
  4296. return new CRoxieServerChildIteratorActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4297. }
  4298. //=================================================================================
  4299. class CRoxieServerChildNormalizeActivity : public CRoxieServerChildBaseActivity
  4300. {
  4301. IHThorChildNormalizeArg &helper;
  4302. public:
  4303. CRoxieServerChildNormalizeActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4304. : CRoxieServerChildBaseActivity(_factory, _probeManager), helper((IHThorChildNormalizeArg &) basehelper)
  4305. {
  4306. }
  4307. virtual bool needsAllocator() const { return true; }
  4308. virtual const void *nextInGroup()
  4309. {
  4310. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  4311. if (eof)
  4312. return NULL;
  4313. bool ok;
  4314. if (first)
  4315. {
  4316. ok = helper.first();
  4317. first = false;
  4318. }
  4319. else
  4320. ok = helper.next();
  4321. if (ok)
  4322. {
  4323. try
  4324. {
  4325. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  4326. do {
  4327. unsigned outSize = helper.transform(rowBuilder);
  4328. if (outSize)
  4329. {
  4330. processed++;
  4331. return rowBuilder.finalizeRowClear(outSize);
  4332. }
  4333. ok = helper.next();
  4334. }
  4335. while (ok);
  4336. }
  4337. catch (IException *E)
  4338. {
  4339. throw makeWrappedException(E);
  4340. }
  4341. }
  4342. eof = true;
  4343. return NULL;
  4344. }
  4345. };
  4346. class CRoxieServerChildNormalizeActivityFactory : public CRoxieServerChildBaseActivityFactory
  4347. {
  4348. public:
  4349. CRoxieServerChildNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4350. : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4351. {
  4352. }
  4353. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4354. {
  4355. return new CRoxieServerChildNormalizeActivity(this, _probeManager);
  4356. }
  4357. };
  4358. IRoxieServerActivityFactory *createRoxieServerNewChildNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4359. {
  4360. return new CRoxieServerChildNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4361. }
  4362. //=================================================================================
  4363. class CRoxieServerChildAggregateActivity : public CRoxieServerChildBaseActivity
  4364. {
  4365. IHThorChildAggregateArg &helper;
  4366. public:
  4367. CRoxieServerChildAggregateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4368. : CRoxieServerChildBaseActivity(_factory, _probeManager), helper((IHThorChildAggregateArg &) basehelper)
  4369. {
  4370. }
  4371. virtual bool needsAllocator() const { return true; }
  4372. virtual const void *nextInGroup()
  4373. {
  4374. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  4375. if (eof)
  4376. return NULL;
  4377. eof = true;
  4378. processed++;
  4379. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  4380. helper.clearAggregate(rowBuilder);
  4381. helper.processRows(rowBuilder);
  4382. size32_t finalSize = meta.getRecordSize(rowBuilder.getSelf());
  4383. return rowBuilder.finalizeRowClear(finalSize);
  4384. }
  4385. };
  4386. class CRoxieServerChildAggregateActivityFactory : public CRoxieServerChildBaseActivityFactory
  4387. {
  4388. public:
  4389. CRoxieServerChildAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4390. : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4391. {
  4392. }
  4393. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4394. {
  4395. return new CRoxieServerChildAggregateActivity(this, _probeManager);
  4396. }
  4397. };
  4398. IRoxieServerActivityFactory *createRoxieServerNewChildAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4399. {
  4400. return new CRoxieServerChildAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4401. }
  4402. //=================================================================================
  4403. class CRoxieServerChildGroupAggregateActivity : public CRoxieServerChildBaseActivity, public IHThorGroupAggregateCallback
  4404. {
  4405. IHThorChildGroupAggregateArg &helper;
  4406. RowAggregator aggregated;
  4407. public:
  4408. IMPLEMENT_IINTERFACE
  4409. CRoxieServerChildGroupAggregateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4410. : CRoxieServerChildBaseActivity(_factory, _probeManager), helper((IHThorChildGroupAggregateArg &) basehelper),
  4411. aggregated(helper, helper)
  4412. {
  4413. }
  4414. void processRow(const void * next)
  4415. {
  4416. aggregated.addRow(next);
  4417. }
  4418. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4419. {
  4420. CRoxieServerChildBaseActivity::start(parentExtractSize, parentExtract, paused);
  4421. aggregated.start(rowAllocator);
  4422. }
  4423. virtual void reset()
  4424. {
  4425. aggregated.reset();
  4426. CRoxieServerChildBaseActivity::reset();
  4427. }
  4428. virtual bool needsAllocator() const { return true; }
  4429. virtual const void *nextInGroup()
  4430. {
  4431. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  4432. if (eof)
  4433. return NULL;
  4434. if (first)
  4435. {
  4436. helper.processRows(this);
  4437. first = false;
  4438. }
  4439. Owned<AggregateRowBuilder> next = aggregated.nextResult();
  4440. if (next)
  4441. {
  4442. processed++;
  4443. return next->finalizeRowClear();
  4444. }
  4445. eof = true;
  4446. return NULL;
  4447. }
  4448. };
  4449. class CRoxieServerChildGroupAggregateActivityFactory : public CRoxieServerChildBaseActivityFactory
  4450. {
  4451. public:
  4452. CRoxieServerChildGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4453. : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4454. {
  4455. }
  4456. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4457. {
  4458. return new CRoxieServerChildGroupAggregateActivity(this, _probeManager);
  4459. }
  4460. };
  4461. IRoxieServerActivityFactory *createRoxieServerNewChildGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4462. {
  4463. return new CRoxieServerChildGroupAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4464. }
  4465. //=================================================================================
  4466. class CRoxieServerChildThroughNormalizeActivity : public CRoxieServerChildBaseActivity
  4467. {
  4468. IHThorChildThroughNormalizeArg &helper;
  4469. const void * lastInput;
  4470. unsigned numProcessedLastGroup;
  4471. bool ok;
  4472. public:
  4473. CRoxieServerChildThroughNormalizeActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4474. : CRoxieServerChildBaseActivity(_factory, _probeManager), helper((IHThorChildThroughNormalizeArg &) basehelper)
  4475. {
  4476. lastInput = NULL;
  4477. numProcessedLastGroup = 0;
  4478. ok = false;
  4479. }
  4480. virtual void stop(bool aborting)
  4481. {
  4482. CRoxieServerChildBaseActivity::stop(aborting);
  4483. ReleaseRoxieRow(lastInput);
  4484. lastInput = NULL;
  4485. }
  4486. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4487. {
  4488. CRoxieServerChildBaseActivity::start(parentExtractSize, parentExtract, paused);
  4489. numProcessedLastGroup = processed;
  4490. ok = false;
  4491. }
  4492. virtual bool needsAllocator() const { return true; }
  4493. virtual const void *nextInGroup()
  4494. {
  4495. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  4496. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  4497. loop
  4498. {
  4499. if (ok)
  4500. ok = helper.next();
  4501. while (!ok)
  4502. {
  4503. ReleaseRoxieRow(lastInput);
  4504. lastInput = input->nextInGroup();
  4505. if (!lastInput)
  4506. {
  4507. if (numProcessedLastGroup != processed)
  4508. {
  4509. numProcessedLastGroup = processed;
  4510. return NULL;
  4511. }
  4512. lastInput = input->nextInGroup();
  4513. if (!lastInput)
  4514. return NULL;
  4515. }
  4516. ok = helper.first(lastInput);
  4517. }
  4518. try
  4519. {
  4520. do
  4521. {
  4522. unsigned outSize = helper.transform(rowBuilder);
  4523. if (outSize)
  4524. {
  4525. processed++;
  4526. return rowBuilder.finalizeRowClear(outSize);
  4527. }
  4528. ok = helper.next();
  4529. } while (ok);
  4530. }
  4531. catch (IException *E)
  4532. {
  4533. throw makeWrappedException(E);
  4534. }
  4535. }
  4536. }
  4537. };
  4538. class CRoxieServerChildThroughNormalizeActivityFactory : public CRoxieServerActivityFactory
  4539. {
  4540. public:
  4541. CRoxieServerChildThroughNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4542. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4543. {
  4544. }
  4545. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4546. {
  4547. return new CRoxieServerChildThroughNormalizeActivity(this, _probeManager);
  4548. }
  4549. };
  4550. IRoxieServerActivityFactory *createRoxieServerNewChildThroughNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4551. {
  4552. return new CRoxieServerChildThroughNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4553. }
  4554. //=================================================================================
  4555. class CRoxieServerLinkedRawIteratorActivity : public CRoxieServerActivity
  4556. {
  4557. IHThorLinkedRawIteratorArg &helper;
  4558. public:
  4559. CRoxieServerLinkedRawIteratorActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4560. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorLinkedRawIteratorArg &) basehelper)
  4561. {
  4562. }
  4563. virtual const void *nextInGroup()
  4564. {
  4565. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  4566. const void *ret =helper.next();
  4567. if (ret)
  4568. {
  4569. LinkRoxieRow(ret);
  4570. processed++;
  4571. }
  4572. return ret;
  4573. }
  4574. };
  4575. class CRoxieServerLinkedRawIteratorActivityFactory : public CRoxieServerActivityFactory
  4576. {
  4577. public:
  4578. CRoxieServerLinkedRawIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4579. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4580. {
  4581. }
  4582. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4583. {
  4584. return new CRoxieServerLinkedRawIteratorActivity(this, _probeManager);
  4585. }
  4586. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  4587. {
  4588. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  4589. }
  4590. };
  4591. IRoxieServerActivityFactory *createRoxieServerLinkedRawIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4592. {
  4593. return new CRoxieServerLinkedRawIteratorActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4594. }
  4595. //=================================================================================
  4596. class CRoxieServerDatasetResultActivity : public CRoxieServerActivity
  4597. {
  4598. public:
  4599. CRoxieServerDatasetResultActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4600. : CRoxieServerActivity(_factory, _probeManager)
  4601. {
  4602. }
  4603. virtual const void *nextInGroup()
  4604. {
  4605. throwUnexpected();
  4606. }
  4607. virtual void executeChild(size32_t & retSize, void * & ret, unsigned parentExtractSize, const byte * parentExtract)
  4608. {
  4609. try
  4610. {
  4611. start(parentExtractSize, parentExtract, false);
  4612. {
  4613. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  4614. MemoryBuffer result;
  4615. IRecordSize * inputMeta = input->queryOutputMeta();
  4616. loop
  4617. {
  4618. const void *nextrec = input->nextInGroup();
  4619. if (!nextrec)
  4620. {
  4621. nextrec = input->nextInGroup();
  4622. if (!nextrec)
  4623. break;
  4624. }
  4625. result.append(inputMeta->getRecordSize(nextrec), nextrec);
  4626. ReleaseRoxieRow(nextrec);
  4627. }
  4628. retSize = result.length();
  4629. ret = result.detach();
  4630. }
  4631. stop(false);
  4632. reset();
  4633. }
  4634. catch(IException *E)
  4635. {
  4636. ctx->notifyAbort(E);
  4637. stop(true);
  4638. reset();
  4639. throw;
  4640. }
  4641. catch(...)
  4642. {
  4643. Owned<IException> E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught at %s:%d", __FILE__, __LINE__);
  4644. ctx->notifyAbort(E);
  4645. stop(true);
  4646. reset();
  4647. throw;
  4648. }
  4649. }
  4650. };
  4651. class CRoxieServerDatasetResultActivityFactory : public CRoxieServerActivityFactory
  4652. {
  4653. bool isRoot;
  4654. public:
  4655. CRoxieServerDatasetResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  4656. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  4657. {
  4658. }
  4659. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4660. {
  4661. return new CRoxieServerDatasetResultActivity(this, _probeManager);
  4662. }
  4663. virtual bool isSink() const
  4664. {
  4665. return isRoot;
  4666. }
  4667. };
  4668. IRoxieServerActivityFactory *createRoxieServerDatasetResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  4669. {
  4670. return new CRoxieServerDatasetResultActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  4671. }
  4672. //=================================================================================
  4673. class CRoxieServerInlineTableActivity : public CRoxieServerActivity
  4674. {
  4675. IHThorInlineTableArg &helper;
  4676. __uint64 curRow;
  4677. __uint64 numRows;
  4678. public:
  4679. CRoxieServerInlineTableActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4680. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorInlineTableArg &) basehelper)
  4681. {
  4682. }
  4683. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4684. {
  4685. curRow = 0;
  4686. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  4687. numRows = helper.numRows();
  4688. }
  4689. virtual bool needsAllocator() const { return true; }
  4690. virtual const void *nextInGroup()
  4691. {
  4692. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  4693. // Filtering empty rows, returns the next valid row
  4694. while (curRow < numRows)
  4695. {
  4696. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  4697. unsigned outSize = helper.getRow(rowBuilder, curRow++);
  4698. if (outSize)
  4699. {
  4700. processed++;
  4701. return rowBuilder.finalizeRowClear(outSize);
  4702. }
  4703. }
  4704. return NULL;
  4705. }
  4706. virtual void setInput(unsigned idx, IRoxieInput *_in)
  4707. {
  4708. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  4709. }
  4710. };
  4711. class CRoxieServerInlineTableActivityFactory : public CRoxieServerActivityFactory
  4712. {
  4713. public:
  4714. CRoxieServerInlineTableActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4715. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4716. {
  4717. }
  4718. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4719. {
  4720. return new CRoxieServerInlineTableActivity(this, _probeManager);
  4721. }
  4722. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  4723. {
  4724. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for InlineTable activity");
  4725. }
  4726. };
  4727. IRoxieServerActivityFactory *createRoxieServerInlineTableActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4728. {
  4729. return new CRoxieServerInlineTableActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4730. }
  4731. //=================================================================================
  4732. class CRoxieServerWorkUnitReadActivity : public CRoxieServerActivity
  4733. {
  4734. IHThorWorkunitReadArg &helper;
  4735. Owned<IWorkUnitRowReader> wuReader; // MORE - can we use IRoxieInput instead?
  4736. public:
  4737. CRoxieServerWorkUnitReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4738. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorWorkunitReadArg &)basehelper)
  4739. {
  4740. }
  4741. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  4742. {
  4743. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  4744. if (!ctx->queryServerContext())
  4745. {
  4746. throw MakeStringException(ROXIE_INTERNAL_ERROR, "Workunit read activity cannot be executed in slave context");
  4747. }
  4748. }
  4749. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4750. {
  4751. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  4752. IXmlToRowTransformer * xmlTransformer = helper.queryXmlTransformer();
  4753. OwnedRoxieString fromWuid(helper.getWUID());
  4754. if (fromWuid)
  4755. UNIMPLEMENTED;
  4756. wuReader.setown(ctx->getWorkunitRowReader(helper.queryName(), helper.querySequence(), xmlTransformer, rowAllocator, meta.isGrouped()));
  4757. // MORE _ should that be in onCreate?
  4758. }
  4759. virtual void reset()
  4760. {
  4761. wuReader.clear();
  4762. CRoxieServerActivity::reset();
  4763. };
  4764. virtual bool needsAllocator() const { return true; }
  4765. virtual const void *nextInGroup()
  4766. {
  4767. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  4768. const void *ret = wuReader->nextInGroup();
  4769. if (ret)
  4770. processed++;
  4771. return ret;
  4772. }
  4773. virtual void setInput(unsigned idx, IRoxieInput *_in)
  4774. {
  4775. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  4776. }
  4777. };
  4778. class CRoxieServerWorkUnitReadActivityFactory : public CRoxieServerActivityFactory
  4779. {
  4780. public:
  4781. CRoxieServerWorkUnitReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4782. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4783. {
  4784. }
  4785. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4786. {
  4787. return new CRoxieServerWorkUnitReadActivity(this, _probeManager);
  4788. }
  4789. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  4790. {
  4791. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for WorkUnitRead activity");
  4792. }
  4793. };
  4794. IRoxieServerActivityFactory *createRoxieServerWorkUnitReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4795. {
  4796. return new CRoxieServerWorkUnitReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4797. }
  4798. //=================================================================================
  4799. interface ILocalGraphEx : public IEclGraphResults
  4800. {
  4801. public:
  4802. virtual void setResult(unsigned id, IGraphResult * result) = 0;
  4803. virtual IRoxieInput * createResultIterator(unsigned id) = 0;
  4804. virtual void setGraphLoopResult(IGraphResult * result) = 0;
  4805. virtual IRoxieInput * createGraphLoopResultIterator(unsigned id) = 0;
  4806. };
  4807. class CSafeRoxieInput : public CInterface, implements IRoxieInput
  4808. {
  4809. public:
  4810. CSafeRoxieInput(IRoxieInput * _input) : input(_input) {}
  4811. IMPLEMENT_IINTERFACE
  4812. virtual IOutputMetaData * queryOutputMeta() const
  4813. {
  4814. return input->queryOutputMeta();
  4815. }
  4816. virtual unsigned queryId() const
  4817. {
  4818. return input->queryId();
  4819. }
  4820. virtual unsigned __int64 queryTotalCycles() const
  4821. {
  4822. return input->queryTotalCycles();
  4823. }
  4824. virtual unsigned __int64 queryLocalCycles() const
  4825. {
  4826. return input->queryLocalCycles();
  4827. }
  4828. virtual IRoxieInput *queryInput(unsigned idx) const
  4829. {
  4830. return input->queryInput(idx);
  4831. }
  4832. virtual IRoxieServerActivity *queryActivity()
  4833. {
  4834. return input->queryActivity();
  4835. }
  4836. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  4837. {
  4838. return input->queryIndexReadActivity();
  4839. }
  4840. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4841. {
  4842. CriticalBlock procedure(cs);
  4843. input->start(parentExtractSize, parentExtract, paused);
  4844. }
  4845. virtual void stop(bool aborting)
  4846. {
  4847. CriticalBlock procedure(cs);
  4848. input->stop(aborting);
  4849. }
  4850. virtual void reset()
  4851. {
  4852. CriticalBlock procedure(cs);
  4853. input->reset();
  4854. }
  4855. virtual void resetEOF()
  4856. {
  4857. CriticalBlock procedure(cs);
  4858. input->resetEOF();
  4859. }
  4860. virtual void checkAbort()
  4861. {
  4862. CriticalBlock procedure(cs);
  4863. input->checkAbort();
  4864. }
  4865. virtual const void *nextInGroup()
  4866. {
  4867. CriticalBlock procedure(cs);
  4868. return input->nextInGroup();
  4869. }
  4870. virtual bool nextGroup(ConstPointerArray & group)
  4871. {
  4872. CriticalBlock procedure(cs);
  4873. return input->nextGroup(group);
  4874. }
  4875. private:
  4876. CriticalSection cs;
  4877. Linked<IRoxieInput> input;
  4878. };
  4879. //=================================================================================
  4880. class CPseudoRoxieInput : public CInterface, implements IRoxieInput
  4881. {
  4882. protected:
  4883. unsigned __int64 totalCycles;
  4884. public:
  4885. IMPLEMENT_IINTERFACE;
  4886. CPseudoRoxieInput()
  4887. {
  4888. totalCycles = 0;
  4889. }
  4890. virtual unsigned __int64 queryTotalCycles() const
  4891. {
  4892. return totalCycles;
  4893. }
  4894. virtual unsigned __int64 queryLocalCycles() const
  4895. {
  4896. return totalCycles;
  4897. }
  4898. virtual IRoxieInput *queryInput(unsigned idx) const
  4899. {
  4900. return NULL;
  4901. }
  4902. virtual IRoxieServerActivity *queryActivity()
  4903. {
  4904. throwUnexpected();
  4905. }
  4906. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  4907. {
  4908. throwUnexpected();
  4909. }
  4910. virtual IOutputMetaData * queryOutputMeta() const { throwUnexpected(); }
  4911. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused) { }
  4912. virtual void stop(bool aborting) { }
  4913. virtual void reset() { totalCycles = 0; }
  4914. virtual void checkAbort() { }
  4915. virtual unsigned queryId() const { throwUnexpected(); }
  4916. virtual void resetEOF() { }
  4917. };
  4918. class CIndirectRoxieInput : public CPseudoRoxieInput
  4919. {
  4920. public:
  4921. CIndirectRoxieInput(IRoxieInput * _input = NULL) : input(_input)
  4922. {
  4923. }
  4924. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4925. {
  4926. input->start(parentExtractSize, parentExtract, paused);
  4927. }
  4928. virtual void stop(bool aborting)
  4929. {
  4930. input->stop(aborting);
  4931. }
  4932. virtual void reset()
  4933. {
  4934. input->reset();
  4935. totalCycles = 0;
  4936. }
  4937. virtual void checkAbort()
  4938. {
  4939. input->checkAbort();
  4940. }
  4941. virtual const void * nextInGroup()
  4942. {
  4943. return input->nextInGroup();
  4944. }
  4945. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  4946. {
  4947. return input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  4948. }
  4949. virtual unsigned __int64 queryLocalCycles() const
  4950. {
  4951. __int64 ret = totalCycles - input->queryTotalCycles();
  4952. if (ret < 0)
  4953. ret = 0;
  4954. return ret;
  4955. }
  4956. virtual IRoxieInput *queryInput(unsigned idx) const
  4957. {
  4958. return input->queryInput(idx);
  4959. }
  4960. virtual unsigned queryId() const
  4961. {
  4962. return input->queryId();
  4963. }
  4964. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  4965. {
  4966. return input->gatherConjunctions(collector);
  4967. }
  4968. virtual void resetEOF()
  4969. {
  4970. input->resetEOF();
  4971. }
  4972. virtual unsigned numConcreteOutputs() const
  4973. {
  4974. return input->numConcreteOutputs();
  4975. }
  4976. virtual IRoxieInput * queryConcreteInput(unsigned idx)
  4977. {
  4978. return input->queryConcreteInput(idx);
  4979. }
  4980. virtual IOutputMetaData * queryOutputMeta() const
  4981. {
  4982. return input->queryOutputMeta();
  4983. }
  4984. virtual IRoxieServerActivity *queryActivity()
  4985. {
  4986. return input->queryActivity();
  4987. }
  4988. void setInput(IRoxieInput * _input)
  4989. {
  4990. input = _input;
  4991. }
  4992. protected:
  4993. IRoxieInput * input;
  4994. };
  4995. class CExtractMapperInput : public CIndirectRoxieInput
  4996. {
  4997. unsigned savedParentExtractSize;
  4998. const byte * savedParentExtract;
  4999. public:
  5000. CExtractMapperInput(IRoxieInput * _input = NULL) : CIndirectRoxieInput(_input)
  5001. {
  5002. savedParentExtractSize = 0;
  5003. savedParentExtract = NULL;
  5004. }
  5005. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5006. {
  5007. input->start(savedParentExtractSize, savedParentExtract, paused);
  5008. }
  5009. void setParentExtract(unsigned _savedParentExtractSize, const byte * _savedParentExtract)
  5010. {
  5011. savedParentExtractSize = _savedParentExtractSize;
  5012. savedParentExtract = _savedParentExtract;
  5013. }
  5014. };
  5015. class CGraphResult : public CInterface, implements IGraphResult
  5016. {
  5017. CriticalSection cs;
  5018. byte **rowset;
  5019. size32_t count;
  5020. bool complete;
  5021. void clear()
  5022. {
  5023. CriticalBlock func(cs);
  5024. rtlReleaseRowset(count, rowset);
  5025. rowset = NULL;
  5026. count = 0;
  5027. complete = false;
  5028. }
  5029. public:
  5030. IMPLEMENT_IINTERFACE
  5031. CGraphResult()
  5032. {
  5033. complete = false; // dummy result is not supposed to be used...
  5034. rowset = NULL;
  5035. count = 0;
  5036. }
  5037. CGraphResult(size32_t _count, byte **_rowset)
  5038. : count(_count), rowset(_rowset)
  5039. {
  5040. complete = true;
  5041. }
  5042. ~CGraphResult()
  5043. {
  5044. clear();
  5045. }
  5046. // interface IGraphResult
  5047. virtual IRoxieInput * createIterator()
  5048. {
  5049. if (!complete)
  5050. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Internal Error: Reading uninitialised graph result");
  5051. return new CGraphResultIterator(this);
  5052. }
  5053. virtual void getLinkedResult(unsigned & countResult, byte * * & result)
  5054. {
  5055. if (!complete)
  5056. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Internal Error: Reading uninitialised graph result");
  5057. result = rtlLinkRowset(rowset);
  5058. countResult = count;
  5059. }
  5060. //other
  5061. const void * getRow(unsigned i)
  5062. {
  5063. CriticalBlock func(cs);
  5064. if (i >= count)
  5065. return NULL;
  5066. const void * ret = rowset[i];
  5067. if (ret) LinkRoxieRow(ret);
  5068. return ret;
  5069. }
  5070. protected:
  5071. class CGraphResultIterator : public CPseudoRoxieInput
  5072. {
  5073. unsigned i;
  5074. Linked<CGraphResult> result;
  5075. public:
  5076. CGraphResultIterator(CGraphResult * _result) : result(_result) { i = 0; }
  5077. IMPLEMENT_IINTERFACE
  5078. public:
  5079. virtual const void * nextInGroup()
  5080. {
  5081. return result->getRow(i++);
  5082. }
  5083. };
  5084. };
  5085. //=================================================================================
  5086. class CRoxieServerLocalResultReadActivity : public CRoxieServerActivity
  5087. {
  5088. IHThorLocalResultReadArg &helper;
  5089. Owned<IRoxieInput> iter;
  5090. ILocalGraphEx * graph;
  5091. unsigned graphId;
  5092. unsigned sequence;
  5093. public:
  5094. CRoxieServerLocalResultReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId)
  5095. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorLocalResultReadArg &)basehelper), graphId(_graphId)
  5096. {
  5097. graph = NULL;
  5098. sequence = 0;
  5099. }
  5100. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  5101. {
  5102. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  5103. graph = static_cast<ILocalGraphEx *>(_ctx->queryCodeContext()->resolveLocalQuery(graphId));
  5104. sequence = helper.querySequence();
  5105. }
  5106. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5107. {
  5108. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5109. iter.setown(graph->createResultIterator(sequence));
  5110. }
  5111. virtual void reset()
  5112. {
  5113. iter.clear();
  5114. CRoxieServerActivity::reset();
  5115. };
  5116. virtual const void *nextInGroup()
  5117. {
  5118. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  5119. const void * next = iter->nextInGroup();
  5120. if (next)
  5121. {
  5122. processed++;
  5123. atomic_inc(&rowsIn);
  5124. }
  5125. return next;
  5126. }
  5127. virtual void setInput(unsigned idx, IRoxieInput *_in)
  5128. {
  5129. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  5130. }
  5131. };
  5132. class CRoxieServerLocalResultReadActivityFactory : public CRoxieServerActivityFactory
  5133. {
  5134. unsigned graphId;
  5135. public:
  5136. CRoxieServerLocalResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _graphId)
  5137. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), graphId(_graphId)
  5138. {
  5139. }
  5140. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  5141. {
  5142. return new CRoxieServerLocalResultReadActivity(this, _probeManager, graphId);
  5143. }
  5144. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  5145. {
  5146. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for LocalResultRead activity");
  5147. }
  5148. };
  5149. IRoxieServerActivityFactory *createRoxieServerLocalResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned graphId)
  5150. {
  5151. return new CRoxieServerLocalResultReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, graphId);
  5152. }
  5153. //=================================================================================
  5154. class CRoxieServerLocalResultStreamReadActivity : public CRoxieServerActivity
  5155. {
  5156. IHThorLocalResultReadArg &helper;
  5157. Owned<IRoxieInput> streamInput;
  5158. unsigned sequence;
  5159. public:
  5160. CRoxieServerLocalResultStreamReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5161. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorLocalResultReadArg &)basehelper)
  5162. {
  5163. sequence = 0;
  5164. }
  5165. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  5166. {
  5167. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  5168. sequence = helper.querySequence();
  5169. }
  5170. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5171. {
  5172. assertex(streamInput != NULL);
  5173. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5174. streamInput->start(parentExtractSize, parentExtract, paused);
  5175. }
  5176. virtual void stop(bool aborting)
  5177. {
  5178. CRoxieServerActivity::stop(aborting);
  5179. streamInput->stop(aborting);
  5180. }
  5181. virtual void reset()
  5182. {
  5183. streamInput->reset();
  5184. CRoxieServerActivity::reset();
  5185. };
  5186. virtual const void *nextInGroup()
  5187. {
  5188. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  5189. const void * next = streamInput->nextInGroup();
  5190. if (next)
  5191. {
  5192. processed++;
  5193. atomic_inc(&rowsIn);
  5194. }
  5195. return next;
  5196. }
  5197. virtual bool querySetStreamInput(unsigned id, IRoxieInput * _input)
  5198. {
  5199. if (id == sequence)
  5200. {
  5201. streamInput.set(_input);
  5202. return true;
  5203. }
  5204. return false;
  5205. }
  5206. virtual void setInput(unsigned idx, IRoxieInput *_in)
  5207. {
  5208. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  5209. }
  5210. };
  5211. class CRoxieServerLocalResultStreamReadActivityFactory : public CRoxieServerActivityFactory
  5212. {
  5213. public:
  5214. CRoxieServerLocalResultStreamReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  5215. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  5216. {
  5217. }
  5218. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  5219. {
  5220. return new CRoxieServerLocalResultStreamReadActivity(this, _probeManager);
  5221. }
  5222. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  5223. {
  5224. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for LocalResultRead activity");
  5225. }
  5226. };
  5227. IRoxieServerActivityFactory *createRoxieServerLocalResultStreamReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  5228. {
  5229. return new CRoxieServerLocalResultStreamReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  5230. }
  5231. //=====================================================================================================
  5232. class CRoxieServerLocalResultWriteActivity : public CRoxieServerInternalSinkActivity
  5233. {
  5234. IHThorLocalResultWriteArg &helper;
  5235. ILocalGraphEx * graph;
  5236. unsigned graphId;
  5237. public:
  5238. CRoxieServerLocalResultWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId, unsigned _numOutputs)
  5239. : CRoxieServerInternalSinkActivity(_factory, _probeManager, _numOutputs), helper((IHThorLocalResultWriteArg &)basehelper), graphId(_graphId)
  5240. {
  5241. graph = NULL;
  5242. }
  5243. virtual bool needsAllocator() const { return true; }
  5244. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  5245. {
  5246. CRoxieServerInternalSinkActivity::onCreate(_ctx, _colocalParent);
  5247. graph = static_cast<ILocalGraphEx *>(_ctx->queryCodeContext()->resolveLocalQuery(graphId));
  5248. }
  5249. virtual void onExecute()
  5250. {
  5251. RtlLinkedDatasetBuilder builder(rowAllocator);
  5252. input->readAll(builder);
  5253. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  5254. graph->setResult(helper.querySequence(), result);
  5255. }
  5256. IRoxieInput * querySelectOutput(unsigned id)
  5257. {
  5258. if (id == helper.querySequence())
  5259. {
  5260. executed = true;
  5261. return LINK(input);
  5262. }
  5263. return NULL;
  5264. }
  5265. };
  5266. class CRoxieServerLocalResultWriteActivityFactory : public CRoxieServerInternalSinkFactory
  5267. {
  5268. unsigned graphId;
  5269. public:
  5270. CRoxieServerLocalResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, unsigned _graphId, bool _isRoot)
  5271. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot), graphId(_graphId)
  5272. {
  5273. isInternal = true;
  5274. Owned<IHThorLocalResultWriteArg> helper = (IHThorLocalResultWriteArg *) helperFactory();
  5275. }
  5276. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  5277. {
  5278. return new CRoxieServerLocalResultWriteActivity(this, _probeManager, graphId, usageCount);
  5279. }
  5280. };
  5281. IRoxieServerActivityFactory *createRoxieServerLocalResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, unsigned _graphId, bool _isRoot)
  5282. {
  5283. return new CRoxieServerLocalResultWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _graphId, _isRoot);
  5284. }
  5285. //=====================================================================================================
  5286. class CRoxieServerDictionaryResultWriteActivity : public CRoxieServerInternalSinkActivity
  5287. {
  5288. IHThorDictionaryResultWriteArg &helper;
  5289. ILocalGraphEx * graph;
  5290. unsigned graphId;
  5291. public:
  5292. CRoxieServerDictionaryResultWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _usageCount, unsigned _graphId)
  5293. : CRoxieServerInternalSinkActivity(_factory, _probeManager, _usageCount), helper((IHThorDictionaryResultWriteArg &)basehelper), graphId(_graphId)
  5294. {
  5295. graph = NULL;
  5296. }
  5297. virtual bool needsAllocator() const { return true; }
  5298. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  5299. {
  5300. CRoxieServerInternalSinkActivity::onCreate(_ctx, _colocalParent);
  5301. graph = static_cast<ILocalGraphEx *>(_ctx->queryCodeContext()->resolveLocalQuery(graphId));
  5302. }
  5303. virtual void onExecute()
  5304. {
  5305. unsigned sequence = helper.querySequence();
  5306. RtlLinkedDictionaryBuilder builder(rowAllocator, helper.queryHashLookupInfo());
  5307. loop
  5308. {
  5309. const void *row = input->nextInGroup();
  5310. if (!row)
  5311. {
  5312. row = input->nextInGroup();
  5313. if (!row)
  5314. break;
  5315. }
  5316. builder.appendOwn(row);
  5317. processed++;
  5318. }
  5319. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  5320. graph->setResult(helper.querySequence(), result);
  5321. }
  5322. IRoxieInput * querySelectOutput(unsigned id)
  5323. {
  5324. if (id == helper.querySequence())
  5325. {
  5326. executed = true;
  5327. return LINK(input);
  5328. }
  5329. return NULL;
  5330. }
  5331. };
  5332. class CRoxieServerDictionaryResultWriteActivityFactory : public CRoxieServerInternalSinkFactory
  5333. {
  5334. unsigned graphId;
  5335. public:
  5336. CRoxieServerDictionaryResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, unsigned _graphId, bool _isRoot)
  5337. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot), graphId(_graphId)
  5338. {
  5339. isInternal = true;
  5340. }
  5341. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  5342. {
  5343. return new CRoxieServerDictionaryResultWriteActivity(this, _probeManager, usageCount, graphId);
  5344. }
  5345. };
  5346. IRoxieServerActivityFactory *createRoxieServerDictionaryResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, unsigned _graphId, bool _isRoot)
  5347. {
  5348. return new CRoxieServerDictionaryResultWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _graphId, _isRoot);
  5349. }
  5350. //=================================================================================
  5351. class CRoxieServerGraphLoopResultReadActivity : public CRoxieServerActivity
  5352. {
  5353. protected:
  5354. IHThorGraphLoopResultReadArg &helper;
  5355. Owned<IRoxieInput> iter;
  5356. ILocalGraphEx * graph;
  5357. unsigned graphId;
  5358. unsigned sequence;
  5359. public:
  5360. CRoxieServerGraphLoopResultReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId)
  5361. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorGraphLoopResultReadArg &)basehelper), graphId(_graphId)
  5362. {
  5363. graph = NULL;
  5364. sequence = 0;
  5365. }
  5366. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  5367. {
  5368. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  5369. graph = static_cast<ILocalGraphEx *>(_ctx->queryCodeContext()->resolveLocalQuery(graphId));
  5370. }
  5371. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5372. {
  5373. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5374. if (iter)
  5375. iter->start(parentExtractSize, parentExtract, paused);
  5376. else
  5377. {
  5378. sequence = helper.querySequence();
  5379. if ((int)sequence >= 0)
  5380. {
  5381. try
  5382. {
  5383. iter.setown(graph->createGraphLoopResultIterator(sequence));
  5384. }
  5385. catch (IException * E)
  5386. {
  5387. throw makeWrappedException(E);
  5388. }
  5389. }
  5390. }
  5391. }
  5392. virtual void stop(bool aborting)
  5393. {
  5394. if (iter)
  5395. iter->stop(aborting);
  5396. CRoxieServerActivity::stop(aborting);
  5397. }
  5398. virtual void reset()
  5399. {
  5400. if (iter)
  5401. iter->reset();
  5402. iter.clear();
  5403. CRoxieServerActivity::reset();
  5404. };
  5405. virtual const void *nextInGroup()
  5406. {
  5407. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  5408. const void * next = iter ? iter->nextInGroup() : NULL;
  5409. if (next)
  5410. {
  5411. processed++;
  5412. atomic_inc(&rowsIn);
  5413. }
  5414. return next;
  5415. }
  5416. virtual void setInput(unsigned idx, IRoxieInput *_in)
  5417. {
  5418. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  5419. }
  5420. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract)
  5421. {
  5422. ensureCreated();
  5423. basehelper.onStart(parentExtract, NULL);
  5424. processor.noteUseIteration(helper.querySequence());
  5425. }
  5426. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract, IProbeManager *probeManager, IArrayOf<IRoxieInput> &probes)
  5427. {
  5428. //helper already initialised from the gratherIterationUsage() call.
  5429. iter.set(processor.connectIterationOutput(helper.querySequence(), probeManager, probes, this, 0));
  5430. }
  5431. virtual IInputSteppingMeta * querySteppingMeta()
  5432. {
  5433. assertex(iter);
  5434. return iter->querySteppingMeta();
  5435. }
  5436. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  5437. {
  5438. assertex(iter);
  5439. return iter->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  5440. }
  5441. };
  5442. //variety of CRoxieServerGraphLoopResultReadActivity created internally with a predefined sequence number
  5443. class CRoxieServerInternalGraphLoopResultReadActivity : public CRoxieServerGraphLoopResultReadActivity
  5444. {
  5445. public:
  5446. CRoxieServerInternalGraphLoopResultReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId, unsigned _sequence)
  5447. : CRoxieServerGraphLoopResultReadActivity(_factory, _probeManager, _graphId)
  5448. {
  5449. sequence = _sequence;
  5450. }
  5451. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5452. {
  5453. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5454. if ((int)sequence >= 0)
  5455. {
  5456. try
  5457. {
  5458. iter.setown(graph->createGraphLoopResultIterator(sequence));
  5459. }
  5460. catch (IException * E)
  5461. {
  5462. throw makeWrappedException(E);
  5463. }
  5464. }
  5465. }
  5466. };
  5467. class CRoxieServerGraphLoopResultReadActivityFactory : public CRoxieServerActivityFactory
  5468. {
  5469. unsigned graphId;
  5470. public:
  5471. CRoxieServerGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _graphId)
  5472. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), graphId(_graphId)
  5473. {
  5474. }
  5475. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  5476. {
  5477. return new CRoxieServerGraphLoopResultReadActivity(this, _probeManager, graphId);
  5478. }
  5479. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  5480. {
  5481. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for GraphLoopResultRead activity");
  5482. }
  5483. };
  5484. IRoxieServerActivityFactory *createRoxieServerGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned graphId)
  5485. {
  5486. return new CRoxieServerGraphLoopResultReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, graphId);
  5487. }
  5488. //=====================================================================================================
  5489. class CRoxieServerGraphLoopResultWriteActivity : public CRoxieServerInternalSinkActivity
  5490. {
  5491. IHThorGraphLoopResultWriteArg &helper;
  5492. ILocalGraphEx * graph;
  5493. unsigned graphId;
  5494. public:
  5495. CRoxieServerGraphLoopResultWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId, unsigned _numOutputs)
  5496. : CRoxieServerInternalSinkActivity(_factory, _probeManager, _numOutputs), helper((IHThorGraphLoopResultWriteArg &)basehelper), graphId(_graphId)
  5497. {
  5498. graph = NULL;
  5499. }
  5500. virtual bool needsAllocator() const { return true; }
  5501. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  5502. {
  5503. CRoxieServerInternalSinkActivity::onCreate(_ctx, _colocalParent);
  5504. graph = static_cast<ILocalGraphEx *>(_ctx->queryCodeContext()->resolveLocalQuery(graphId));
  5505. }
  5506. virtual void onExecute()
  5507. {
  5508. RtlLinkedDatasetBuilder builder(rowAllocator);
  5509. input->readAll(builder);
  5510. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  5511. graph->setGraphLoopResult(result);
  5512. }
  5513. virtual IRoxieInput *queryOutput(unsigned idx)
  5514. {
  5515. if (idx==0)
  5516. return this;
  5517. else
  5518. return NULL;
  5519. }
  5520. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  5521. {
  5522. return input->gatherConjunctions(collector);
  5523. }
  5524. virtual void resetEOF()
  5525. {
  5526. input->resetEOF();
  5527. }
  5528. virtual const void *nextInGroup()
  5529. {
  5530. const void * next = input->nextInGroup();
  5531. if (next)
  5532. processed++;
  5533. return next;
  5534. }
  5535. virtual bool isPassThrough()
  5536. {
  5537. return true;
  5538. }
  5539. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  5540. {
  5541. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  5542. const void * next = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  5543. if (next)
  5544. processed++;
  5545. return next;
  5546. }
  5547. IInputSteppingMeta * querySteppingMeta()
  5548. {
  5549. return input->querySteppingMeta();
  5550. }
  5551. virtual IOutputMetaData * queryOutputMeta() const
  5552. {
  5553. return input->queryOutputMeta();
  5554. }
  5555. };
  5556. class CRoxieServerGraphLoopResultWriteActivityFactory : public CRoxieServerInternalSinkFactory
  5557. {
  5558. unsigned graphId;
  5559. public:
  5560. CRoxieServerGraphLoopResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, unsigned _graphId)
  5561. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, true), graphId(_graphId)
  5562. {
  5563. isInternal = true;
  5564. Owned<IHThorGraphLoopResultWriteArg> helper = (IHThorGraphLoopResultWriteArg *) helperFactory();
  5565. }
  5566. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  5567. {
  5568. return new CRoxieServerGraphLoopResultWriteActivity(this, _probeManager, graphId, usageCount);
  5569. }
  5570. };
  5571. IRoxieServerActivityFactory *createRoxieServerGraphLoopResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, unsigned _graphId)
  5572. {
  5573. return new CRoxieServerGraphLoopResultWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _graphId);
  5574. }
  5575. #if 0
  5576. //=====================================================================================================
  5577. CHThorLocalResultSpillActivity::CHThorLocalResultSpillActivity(IAgentContext &_agent, ActivityId const & _id, IHThorLocalResultSpillArg &_arg)
  5578. : CHThorSimpleActivityBase(_agent, _id, _arg), helper(_arg)
  5579. {
  5580. next = NULL;
  5581. }
  5582. void CHThorLocalResultSpillActivity::ready()
  5583. {
  5584. CHThorSimpleActivityBase::ready();
  5585. next = input->nextInGroup();
  5586. grouped = input->isGrouped();
  5587. rowdata.clear();
  5588. }
  5589. const void * CHThorLocalResultSpillActivity::nextInGroup()
  5590. {
  5591. const void * ret = next;
  5592. next = input->nextInGroup();
  5593. if (!ret && !next)
  5594. return NULL;
  5595. if (ret)
  5596. {
  5597. size32_t thisSize = outputMeta->getRecordSize(ret);
  5598. rowdata.append(thisSize, ret);
  5599. if (grouped)
  5600. rowdata.append(next == NULL);
  5601. }
  5602. return ret;
  5603. }
  5604. void CHThorLocalResultSpillActivity::done()
  5605. {
  5606. loop
  5607. {
  5608. const void * ret = nextInGroup();
  5609. if (!ret)
  5610. {
  5611. ret = nextInGroup();
  5612. if (!ret)
  5613. break;
  5614. }
  5615. ReleaseRoxieRow(ret);
  5616. }
  5617. agent.setLocalResult(helper.querySequence(), rowdata.length(), rowdata.toByteArray());
  5618. CHThorSimpleActivityBase::done();
  5619. }
  5620. #endif
  5621. //=================================================================================
  5622. class CRoxieServerDedupActivity : public CRoxieServerActivity
  5623. {
  5624. protected:
  5625. IHThorDedupArg &helper;
  5626. unsigned numKept;
  5627. unsigned numToKeep;
  5628. public:
  5629. CRoxieServerDedupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5630. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorDedupArg &)basehelper)
  5631. {
  5632. numKept = 0;
  5633. numToKeep = 0;
  5634. }
  5635. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5636. {
  5637. numKept = 0;
  5638. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5639. numToKeep = helper.numToKeep();
  5640. }
  5641. };
  5642. class CRoxieServerDedupKeepLeftActivity : public CRoxieServerDedupActivity
  5643. {
  5644. IRangeCompare * stepCompare;
  5645. const void *prev;
  5646. public:
  5647. CRoxieServerDedupKeepLeftActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5648. : CRoxieServerDedupActivity(_factory, _probeManager)
  5649. {
  5650. prev = NULL;
  5651. stepCompare = NULL;
  5652. }
  5653. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5654. {
  5655. prev = NULL;
  5656. CRoxieServerDedupActivity::start(parentExtractSize, parentExtract, paused);
  5657. IInputSteppingMeta * stepMeta = input->querySteppingMeta();
  5658. stepCompare = NULL;
  5659. if (stepMeta)
  5660. stepCompare = stepMeta->queryCompare();
  5661. }
  5662. virtual void reset()
  5663. {
  5664. ReleaseClearRoxieRow(prev);
  5665. CRoxieServerDedupActivity::reset();
  5666. }
  5667. virtual const void * nextInGroup()
  5668. {
  5669. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  5670. const void * next;
  5671. loop
  5672. {
  5673. next = input->nextInGroup();
  5674. if (!prev || !next || !helper.matches(prev,next))
  5675. {
  5676. numKept = 0;
  5677. break;
  5678. }
  5679. if (numKept < numToKeep-1)
  5680. {
  5681. numKept++;
  5682. break;
  5683. }
  5684. ReleaseRoxieRow(next);
  5685. }
  5686. ReleaseRoxieRow(prev);
  5687. prev = next;
  5688. if (next)
  5689. {
  5690. LinkRoxieRow(next);
  5691. processed++;
  5692. }
  5693. return next;
  5694. }
  5695. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  5696. {
  5697. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  5698. const void * next;
  5699. loop
  5700. {
  5701. next = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  5702. //If the record was an in-exact match from the index then return it immediately
  5703. //and don't cause it to dedup following legal records.
  5704. if (!wasCompleteMatch)
  5705. {
  5706. assertex(stepExtra.returnMismatches());
  5707. return next;
  5708. }
  5709. if (!prev || !next || !helper.matches(prev,next))
  5710. {
  5711. numKept = 0;
  5712. break;
  5713. }
  5714. if (numKept < numToKeep-1)
  5715. {
  5716. numKept++;
  5717. break;
  5718. }
  5719. //Unusual - deduping by x,y stepped on x,y,z - still want any record back as soon as possible.
  5720. if (stepExtra.returnMismatches())
  5721. {
  5722. //If asked to return mismatches we are only interested in mismatches that will force the stepped
  5723. //condition to advance
  5724. if (stepCompare->docompare(next, seek, numFields) != 0)
  5725. {
  5726. wasCompleteMatch = false;
  5727. break;
  5728. }
  5729. }
  5730. ReleaseRoxieRow(next);
  5731. }
  5732. ReleaseRoxieRow(prev);
  5733. prev = next;
  5734. if (next)
  5735. {
  5736. LinkRoxieRow(next);
  5737. processed++;
  5738. }
  5739. return next;
  5740. }
  5741. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  5742. {
  5743. return input->gatherConjunctions(collector);
  5744. }
  5745. virtual void resetEOF()
  5746. {
  5747. input->resetEOF();
  5748. }
  5749. IInputSteppingMeta * querySteppingMeta()
  5750. {
  5751. return input->querySteppingMeta();
  5752. }
  5753. };
  5754. //=================================================================================
  5755. class CRoxieServerDedupKeepRightActivity : public CRoxieServerDedupActivity
  5756. {
  5757. const void *kept;
  5758. bool first;
  5759. public:
  5760. CRoxieServerDedupKeepRightActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5761. : CRoxieServerDedupActivity(_factory, _probeManager)
  5762. {
  5763. kept = NULL;
  5764. first = true;
  5765. }
  5766. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5767. {
  5768. first = true;
  5769. kept = NULL;
  5770. CRoxieServerDedupActivity::start(parentExtractSize, parentExtract, paused);
  5771. }
  5772. virtual void reset()
  5773. {
  5774. ReleaseClearRoxieRow(kept);
  5775. CRoxieServerActivity::reset();
  5776. }
  5777. virtual const void * nextInGroup()
  5778. {
  5779. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  5780. if (first)
  5781. {
  5782. kept = input->nextInGroup();
  5783. first = false;
  5784. }
  5785. const void * next;
  5786. loop
  5787. {
  5788. next = input->nextInGroup();
  5789. if (!kept || !next || !helper.matches(kept,next))
  5790. {
  5791. numKept = 0;
  5792. break;
  5793. }
  5794. if (numKept < numToKeep-1)
  5795. {
  5796. numKept++;
  5797. break;
  5798. }
  5799. ReleaseRoxieRow(kept);
  5800. kept = next;
  5801. }
  5802. const void * ret = kept;
  5803. kept = next;
  5804. // CTXLOG("dedup returns %p", ret);
  5805. if (ret) processed++;
  5806. return ret;
  5807. }
  5808. };
  5809. class CRoxieServerDedupAllActivity : public CRoxieServerActivity
  5810. {
  5811. IHThorDedupArg &helper;
  5812. unsigned survivorIndex;
  5813. ConstPointerArray survivors;
  5814. bool keepLeft;
  5815. bool eof;
  5816. bool first;
  5817. ICompare *primaryCompare;
  5818. public:
  5819. CRoxieServerDedupAllActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _keepLeft)
  5820. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorDedupArg &)basehelper)
  5821. {
  5822. keepLeft = _keepLeft;
  5823. primaryCompare = helper.queryComparePrimary();
  5824. eof = false;
  5825. first = true;
  5826. survivorIndex = 0;
  5827. }
  5828. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5829. {
  5830. eof = false;
  5831. first = true;
  5832. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5833. }
  5834. virtual void reset()
  5835. {
  5836. #ifdef _DEBUG
  5837. while (survivors.isItem(survivorIndex))
  5838. {
  5839. ReleaseRoxieRow(survivors.item(survivorIndex++));
  5840. }
  5841. #endif
  5842. survivors.kill();
  5843. eof = false;
  5844. first = true;
  5845. CRoxieServerActivity::reset();
  5846. }
  5847. void dedupRange(unsigned first, unsigned last, ConstPointerArray & group)
  5848. {
  5849. for (unsigned idxL = first; idxL < last; idxL++)
  5850. {
  5851. const void * left = group.item(idxL);
  5852. if (left)
  5853. {
  5854. for (unsigned idxR = first; idxR < last; idxR++)
  5855. {
  5856. const void * right = group.item(idxR);
  5857. if ((idxL != idxR) && right)
  5858. {
  5859. if (helper.matches(left, right))
  5860. {
  5861. if (keepLeft)
  5862. {
  5863. group.replace(NULL, idxR);
  5864. ReleaseRoxieRow(right);
  5865. }
  5866. else
  5867. {
  5868. group.replace(NULL, idxL);
  5869. ReleaseRoxieRow(left);
  5870. break;
  5871. }
  5872. }
  5873. }
  5874. }
  5875. }
  5876. }
  5877. }
  5878. void dedupRangeIndirect(unsigned first, unsigned last, void *** index)
  5879. {
  5880. for (unsigned idxL = first; idxL < last; idxL++)
  5881. {
  5882. void * left = *(index[idxL]);
  5883. if (left)
  5884. {
  5885. for (unsigned idxR = first; idxR < last; idxR++)
  5886. {
  5887. void * right = *(index[idxR]);
  5888. if ((idxL != idxR) && right)
  5889. {
  5890. if (helper.matches(left, right))
  5891. {
  5892. if (keepLeft)
  5893. {
  5894. *(index[idxR]) = NULL;
  5895. ReleaseRoxieRow(right);
  5896. }
  5897. else
  5898. {
  5899. *(index[idxL]) = NULL;
  5900. ReleaseRoxieRow(left);
  5901. break;
  5902. }
  5903. }
  5904. }
  5905. }
  5906. }
  5907. }
  5908. }
  5909. bool calcNextDedupAll()
  5910. {
  5911. survivors.kill();
  5912. survivorIndex = 0;
  5913. ConstPointerArray group;
  5914. if (eof || !input->nextGroup(group))
  5915. {
  5916. eof = true;
  5917. return false;
  5918. }
  5919. unsigned max = group.ordinality();
  5920. if (primaryCompare)
  5921. {
  5922. //hard, if not impossible, to hit this code once optimisations in place
  5923. MemoryAttr indexbuff(max*sizeof(void **));
  5924. void *** index = (void ***)indexbuff.bufferBase();
  5925. qsortvecstable(const_cast<void * *>(group.getArray()), max, *primaryCompare, index);
  5926. unsigned first = 0;
  5927. for (unsigned idx = 1; idx < max; idx++)
  5928. {
  5929. if (primaryCompare->docompare(*(index[first]), *(index[idx])) != 0)
  5930. {
  5931. dedupRangeIndirect(first, idx, index);
  5932. first = idx;
  5933. }
  5934. }
  5935. dedupRangeIndirect(first, max, index);
  5936. for(unsigned idx2=0; idx2<max; ++idx2)
  5937. {
  5938. void * cur = *(index[idx2]);
  5939. if(cur)
  5940. survivors.append(cur);
  5941. }
  5942. }
  5943. else
  5944. {
  5945. dedupRange(0, max, group);
  5946. for(unsigned idx=0; idx<max; ++idx)
  5947. {
  5948. const void * cur = group.item(idx);
  5949. if(cur)
  5950. survivors.append(cur);
  5951. }
  5952. }
  5953. return true;
  5954. }
  5955. virtual const void *nextInGroup()
  5956. {
  5957. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  5958. if (first)
  5959. {
  5960. calcNextDedupAll();
  5961. first = false;
  5962. }
  5963. while (survivors.isItem(survivorIndex))
  5964. {
  5965. const void *ret = survivors.item(survivorIndex++);
  5966. if (ret)
  5967. {
  5968. processed++;
  5969. return ret;
  5970. }
  5971. }
  5972. calcNextDedupAll();
  5973. return NULL;
  5974. }
  5975. };
  5976. class CRoxieServerDedupActivityFactory : public CRoxieServerActivityFactory
  5977. {
  5978. bool compareAll;
  5979. bool keepLeft;
  5980. public:
  5981. CRoxieServerDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  5982. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  5983. {
  5984. Owned<IHThorDedupArg> helper = (IHThorDedupArg *) helperFactory();
  5985. compareAll = helper->compareAll();
  5986. keepLeft = helper->keepLeft();
  5987. }
  5988. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  5989. {
  5990. if (compareAll)
  5991. return new CRoxieServerDedupAllActivity(this, _probeManager, keepLeft);
  5992. else if (keepLeft)
  5993. return new CRoxieServerDedupKeepLeftActivity(this, _probeManager);
  5994. else
  5995. return new CRoxieServerDedupKeepRightActivity(this, _probeManager);
  5996. }
  5997. };
  5998. IRoxieServerActivityFactory *createRoxieServerDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  5999. {
  6000. return new CRoxieServerDedupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  6001. }
  6002. //=================================================================================
  6003. class CRoxieServerHashDedupActivity : public CRoxieServerActivity
  6004. {
  6005. bool eof;
  6006. IHThorHashDedupArg &helper;
  6007. class HashDedupElement
  6008. {
  6009. public:
  6010. HashDedupElement(unsigned _hash, const void *_keyRow)
  6011. : hash(_hash), keyRow(_keyRow)
  6012. {
  6013. }
  6014. ~HashDedupElement()
  6015. {
  6016. ReleaseRoxieRow(keyRow);
  6017. }
  6018. inline unsigned queryHash() const
  6019. {
  6020. return hash;
  6021. }
  6022. inline const void *queryRow() const
  6023. {
  6024. return keyRow;
  6025. }
  6026. private:
  6027. unsigned hash;
  6028. const void *keyRow;
  6029. };
  6030. class HashDedupTable : public SuperHashTable
  6031. {
  6032. public:
  6033. HashDedupTable(IHThorHashDedupArg & _helper, unsigned _activityId)
  6034. : helper(_helper),
  6035. activityId(_activityId),
  6036. keySize(helper.queryKeySize())
  6037. {
  6038. }
  6039. virtual ~HashDedupTable() { releaseAll(); }
  6040. virtual unsigned getHashFromElement(const void *et) const
  6041. {
  6042. const HashDedupElement *element = reinterpret_cast<const HashDedupElement *>(et);
  6043. return element->queryHash();
  6044. }
  6045. virtual unsigned getHashFromFindParam(const void *fp) const { throwUnexpected(); }
  6046. virtual const void * getFindParam(const void *et) const { throwUnexpected(); }
  6047. virtual bool matchesElement(const void *et, const void *searchET) const { throwUnexpected(); }
  6048. virtual bool matchesFindParam(const void *et, const void *key, unsigned fphash) const
  6049. {
  6050. const HashDedupElement *element = reinterpret_cast<const HashDedupElement *>(et);
  6051. if (fphash != element->queryHash())
  6052. return false;
  6053. return (helper.queryKeyCompare()->docompare(element->queryRow(), key) == 0);
  6054. }
  6055. virtual void onAdd(void *et) {}
  6056. virtual void onRemove(void *et)
  6057. {
  6058. const HashDedupElement *element = reinterpret_cast<const HashDedupElement *>(et);
  6059. delete element;
  6060. }
  6061. void onCreate(IRoxieSlaveContext *ctx)
  6062. {
  6063. keyRowAllocator.setown(ctx->queryCodeContext()->getRowAllocator(keySize.queryOriginal(), activityId));
  6064. }
  6065. void reset()
  6066. {
  6067. kill();
  6068. }
  6069. bool insert(const void * row)
  6070. {
  6071. unsigned hash = helper.queryHash()->hash(row);
  6072. RtlDynamicRowBuilder keyRowBuilder(keyRowAllocator, true);
  6073. size32_t thisKeySize = helper.recordToKey(keyRowBuilder, row);
  6074. OwnedConstRoxieRow keyRow = keyRowBuilder.finalizeRowClear(thisKeySize);
  6075. if (find(hash, keyRow.get()))
  6076. return false;
  6077. addNew(new HashDedupElement(hash, keyRow.getClear()), hash);
  6078. return true;
  6079. }
  6080. private:
  6081. IHThorHashDedupArg & helper;
  6082. CachedOutputMetaData keySize;
  6083. Owned<IEngineRowAllocator> keyRowAllocator;
  6084. unsigned activityId;
  6085. } table;
  6086. public:
  6087. CRoxieServerHashDedupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6088. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorHashDedupArg &)basehelper), table(helper, activityId)
  6089. {
  6090. eof = false;
  6091. }
  6092. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6093. {
  6094. eof = false;
  6095. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6096. }
  6097. virtual void onCreate(IRoxieSlaveContext *ctx, IHThorArg *_colocalParent)
  6098. {
  6099. CRoxieServerActivity::onCreate(ctx, colocalParent);
  6100. table.onCreate(ctx);
  6101. }
  6102. virtual void reset()
  6103. {
  6104. table.reset();
  6105. eof = false;
  6106. CRoxieServerActivity::reset();
  6107. }
  6108. virtual const void *nextInGroup()
  6109. {
  6110. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  6111. while(!eof)
  6112. {
  6113. const void * next = input->nextInGroup();
  6114. if(!next)
  6115. {
  6116. if (table.count() == 0)
  6117. eof = true;
  6118. table.reset();
  6119. return NULL;
  6120. }
  6121. if(table.insert(next))
  6122. return next;
  6123. else
  6124. ReleaseRoxieRow(next);
  6125. }
  6126. return NULL;
  6127. }
  6128. };
  6129. class CRoxieServerHashDedupActivityFactory : public CRoxieServerActivityFactory
  6130. {
  6131. public:
  6132. CRoxieServerHashDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6133. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  6134. {
  6135. }
  6136. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  6137. {
  6138. return new CRoxieServerHashDedupActivity(this, _probeManager);
  6139. }
  6140. };
  6141. IRoxieServerActivityFactory *createRoxieServerHashDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6142. {
  6143. return new CRoxieServerHashDedupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  6144. }
  6145. //=================================================================================
  6146. class CRoxieServerRollupActivity : public CRoxieServerActivity
  6147. {
  6148. IHThorRollupArg &helper;
  6149. OwnedConstRoxieRow left;
  6150. OwnedConstRoxieRow prev;
  6151. OwnedConstRoxieRow right;
  6152. bool readFirstRow;
  6153. public:
  6154. CRoxieServerRollupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6155. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorRollupArg &)basehelper)
  6156. {
  6157. readFirstRow = false;
  6158. }
  6159. ~CRoxieServerRollupActivity()
  6160. {
  6161. }
  6162. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6163. {
  6164. readFirstRow = false;
  6165. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6166. }
  6167. virtual void reset()
  6168. {
  6169. left.clear();
  6170. prev.clear();
  6171. right.clear();
  6172. CRoxieServerActivity::reset();
  6173. }
  6174. virtual bool needsAllocator() const { return true; }
  6175. virtual const void * nextInGroup()
  6176. {
  6177. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  6178. if (!readFirstRow)
  6179. {
  6180. left.setown(input->nextInGroup());
  6181. prev.set(left);
  6182. readFirstRow = true;
  6183. }
  6184. loop
  6185. {
  6186. right.setown(input->nextInGroup());
  6187. if(!prev || !right || !helper.matches(prev,right))
  6188. {
  6189. const void * ret = left.getClear();
  6190. if(ret)
  6191. processed++;
  6192. left.setown(right.getClear());
  6193. prev.set(left);
  6194. return ret;
  6195. }
  6196. try
  6197. {
  6198. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  6199. unsigned outSize = helper.transform(rowBuilder, left, right);
  6200. if (outSize)
  6201. left.setown(rowBuilder.finalizeRowClear(outSize));
  6202. if (helper.getFlags() & RFrolledismatchleft)
  6203. prev.set(left);
  6204. else
  6205. prev.set(right);
  6206. }
  6207. catch(IException * E)
  6208. {
  6209. throw makeWrappedException(E);
  6210. }
  6211. }
  6212. }
  6213. };
  6214. class CRoxieServerRollupActivityFactory : public CRoxieServerActivityFactory
  6215. {
  6216. public:
  6217. CRoxieServerRollupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6218. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  6219. {
  6220. }
  6221. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  6222. {
  6223. return new CRoxieServerRollupActivity(this, _probeManager);
  6224. }
  6225. };
  6226. IRoxieServerActivityFactory *createRoxieServerRollupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6227. {
  6228. return new CRoxieServerRollupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  6229. }
  6230. //=================================================================================
  6231. class CRoxieServerNormalizeActivity : public CRoxieServerActivity
  6232. {
  6233. IHThorNormalizeArg &helper;
  6234. unsigned numThisRow;
  6235. unsigned curRow;
  6236. const void *buffer;
  6237. unsigned numProcessedLastGroup;
  6238. public:
  6239. CRoxieServerNormalizeActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6240. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorNormalizeArg &)basehelper)
  6241. {
  6242. buffer = NULL;
  6243. numThisRow = 0;
  6244. curRow = 0;
  6245. numProcessedLastGroup = 0;
  6246. }
  6247. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6248. {
  6249. numThisRow = 0;
  6250. curRow = 0;
  6251. numProcessedLastGroup = 0;
  6252. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6253. }
  6254. virtual void reset()
  6255. {
  6256. ReleaseClearRoxieRow(buffer);
  6257. CRoxieServerActivity::reset();
  6258. }
  6259. virtual bool needsAllocator() const { return true; }
  6260. virtual const void * nextInGroup()
  6261. {
  6262. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  6263. loop
  6264. {
  6265. while (curRow == numThisRow)
  6266. {
  6267. if (buffer)
  6268. ReleaseClearRoxieRow(buffer);
  6269. buffer = input->nextInGroup();
  6270. if (!buffer && (processed == numProcessedLastGroup))
  6271. buffer = input->nextInGroup();
  6272. if (!buffer)
  6273. {
  6274. numProcessedLastGroup = processed;
  6275. return NULL;
  6276. }
  6277. curRow = 0;
  6278. numThisRow = helper.numExpandedRows(buffer);
  6279. }
  6280. try
  6281. {
  6282. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  6283. unsigned actualSize = helper.transform(rowBuilder, buffer, ++curRow);
  6284. if (actualSize != 0)
  6285. {
  6286. processed++;
  6287. return rowBuilder.finalizeRowClear(actualSize);
  6288. }
  6289. }
  6290. catch (IException *E)
  6291. {
  6292. throw makeWrappedException(E);
  6293. }
  6294. }
  6295. }
  6296. };
  6297. class CRoxieServerNormalizeActivityFactory : public CRoxieServerActivityFactory
  6298. {
  6299. public:
  6300. CRoxieServerNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6301. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  6302. {
  6303. }
  6304. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  6305. {
  6306. return new CRoxieServerNormalizeActivity(this, _probeManager);
  6307. }
  6308. };
  6309. IRoxieServerActivityFactory *createRoxieServerNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6310. {
  6311. return new CRoxieServerNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  6312. }
  6313. //=================================================================================
  6314. class CRoxieServerNormalizeChildActivity : public CRoxieServerActivity
  6315. {
  6316. IHThorNormalizeChildArg &helper;
  6317. unsigned numThisRow;
  6318. unsigned curRow;
  6319. const void *buffer;
  6320. unsigned numProcessedLastGroup;
  6321. INormalizeChildIterator * cursor;
  6322. const void * curChildRow;
  6323. bool advanceInput()
  6324. {
  6325. loop
  6326. {
  6327. ReleaseClearRoxieRow(buffer);
  6328. buffer = input->nextInGroup();
  6329. if (!buffer && (processed == numProcessedLastGroup))
  6330. buffer = input->nextInGroup();
  6331. if (!buffer)
  6332. {
  6333. numProcessedLastGroup = processed;
  6334. return false;
  6335. }
  6336. curChildRow = cursor->first(buffer);
  6337. if (curChildRow)
  6338. {
  6339. curRow = 0;
  6340. return true;
  6341. }
  6342. }
  6343. }
  6344. public:
  6345. CRoxieServerNormalizeChildActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6346. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorNormalizeChildArg &)basehelper)
  6347. {
  6348. buffer = NULL;
  6349. cursor = NULL;
  6350. numThisRow = 0;
  6351. curRow = 0;
  6352. numProcessedLastGroup = 0;
  6353. curChildRow = NULL;
  6354. }
  6355. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6356. {
  6357. numThisRow = 0;
  6358. curRow = 0;
  6359. numProcessedLastGroup = 0;
  6360. curChildRow = NULL;
  6361. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6362. cursor = helper.queryIterator();
  6363. }
  6364. virtual void stop(bool aborting)
  6365. {
  6366. CRoxieServerActivity::stop(aborting);
  6367. }
  6368. virtual void reset()
  6369. {
  6370. cursor = NULL;
  6371. ReleaseClearRoxieRow(buffer);
  6372. CRoxieServerActivity::reset();
  6373. }
  6374. virtual bool needsAllocator() const { return true; }
  6375. const void *nextInGroup()
  6376. {
  6377. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  6378. loop
  6379. {
  6380. if (!buffer)
  6381. {
  6382. if (!advanceInput())
  6383. return NULL;
  6384. }
  6385. try
  6386. {
  6387. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  6388. size32_t outSize = helper.transform(rowBuilder, buffer, curChildRow, ++curRow);
  6389. curChildRow = cursor->next();
  6390. if (!curChildRow)
  6391. ReleaseClearRoxieRow(buffer);
  6392. if (outSize != 0)
  6393. {
  6394. processed++;
  6395. return rowBuilder.finalizeRowClear(outSize);
  6396. }
  6397. }
  6398. catch (IException *E)
  6399. {
  6400. throw makeWrappedException(E);
  6401. }
  6402. }
  6403. }
  6404. };
  6405. class CRoxieServerNormalizeChildActivityFactory : public CRoxieServerActivityFactory
  6406. {
  6407. public:
  6408. CRoxieServerNormalizeChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6409. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  6410. {
  6411. }
  6412. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  6413. {
  6414. return new CRoxieServerNormalizeChildActivity(this, _probeManager);
  6415. }
  6416. };
  6417. IRoxieServerActivityFactory *createRoxieServerNormalizeChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6418. {
  6419. return new CRoxieServerNormalizeChildActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  6420. }
  6421. //=================================================================================
  6422. class CRoxieServerNormalizeLinkedChildActivity : public CRoxieServerActivity
  6423. {
  6424. IHThorNormalizeLinkedChildArg &helper;
  6425. OwnedConstRoxieRow curParent;
  6426. OwnedConstRoxieRow curChild;
  6427. unsigned numProcessedLastGroup;
  6428. bool advanceInput()
  6429. {
  6430. loop
  6431. {
  6432. curParent.setown(input->nextInGroup());
  6433. if (!curParent && (processed == numProcessedLastGroup))
  6434. curParent.setown(input->nextInGroup());
  6435. if (!curParent)
  6436. {
  6437. numProcessedLastGroup = processed;
  6438. return false;
  6439. }
  6440. curChild.set(helper.first(curParent));
  6441. if (curChild)
  6442. return true;
  6443. }
  6444. }
  6445. public:
  6446. CRoxieServerNormalizeLinkedChildActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6447. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorNormalizeLinkedChildArg &)basehelper)
  6448. {
  6449. numProcessedLastGroup = 0;
  6450. }
  6451. ~CRoxieServerNormalizeLinkedChildActivity()
  6452. {
  6453. }
  6454. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6455. {
  6456. numProcessedLastGroup = 0;
  6457. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6458. }
  6459. virtual void reset()
  6460. {
  6461. curParent.clear();
  6462. curChild.clear();
  6463. CRoxieServerActivity::reset();
  6464. }
  6465. const void *nextInGroup()
  6466. {
  6467. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  6468. loop
  6469. {
  6470. if (!curParent)
  6471. {
  6472. if (!advanceInput())
  6473. return NULL;
  6474. }
  6475. try
  6476. {
  6477. const void *ret = curChild.getClear();
  6478. curChild.set(helper.next());
  6479. if (!curChild)
  6480. curParent.clear();
  6481. if (ret)
  6482. {
  6483. processed++;
  6484. return ret;
  6485. }
  6486. }
  6487. catch (IException *E)
  6488. {
  6489. throw makeWrappedException(E);
  6490. }
  6491. }
  6492. }
  6493. };
  6494. class CRoxieServerNormalizeLinkedChildActivityFactory : public CRoxieServerActivityFactory
  6495. {
  6496. public:
  6497. CRoxieServerNormalizeLinkedChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6498. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  6499. {
  6500. }
  6501. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  6502. {
  6503. return new CRoxieServerNormalizeLinkedChildActivity(this, _probeManager);
  6504. }
  6505. };
  6506. IRoxieServerActivityFactory *createRoxieServerNormalizeLinkedChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6507. {
  6508. return new CRoxieServerNormalizeLinkedChildActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  6509. }
  6510. //=================================================================================
  6511. interface ISortAlgorithm : extends IInterface
  6512. {
  6513. virtual void prepare(IRoxieInput *input) = 0;
  6514. virtual const void *next() = 0;
  6515. virtual void reset() = 0;
  6516. };
  6517. class CQuickSortAlgorithm : implements CInterfaceOf<ISortAlgorithm>
  6518. {
  6519. unsigned curIndex;
  6520. ConstPointerArray sorted;
  6521. ICompare *compare;
  6522. public:
  6523. CQuickSortAlgorithm(ICompare *_compare) : compare(_compare)
  6524. {
  6525. curIndex = 0;
  6526. }
  6527. virtual void prepare(IRoxieInput *input)
  6528. {
  6529. curIndex = 0;
  6530. if (input->nextGroup(sorted))
  6531. qsortvec(const_cast<void * *>(sorted.getArray()), sorted.ordinality(), *compare);
  6532. }
  6533. virtual const void *next()
  6534. {
  6535. if (sorted.isItem(curIndex))
  6536. return sorted.item(curIndex++);
  6537. return NULL;
  6538. }
  6539. virtual void reset()
  6540. {
  6541. while (sorted.isItem(curIndex))
  6542. ReleaseRoxieRow(sorted.item(curIndex++));
  6543. curIndex = 0;
  6544. sorted.kill();
  6545. }
  6546. };
  6547. class CSpillingQuickSortAlgorithm : implements CInterfaceOf<ISortAlgorithm>, implements roxiemem::IBufferedRowCallback
  6548. {
  6549. enum {
  6550. InitialSortElements = 0,
  6551. //The number of rows that can be added without entering a critical section, and therefore also the number
  6552. //of rows that might not get freed when memory gets tight.
  6553. CommitStep=32
  6554. };
  6555. roxiemem::DynamicRoxieOutputRowArray rowsToSort;
  6556. roxiemem::RoxieSimpleInputRowArray sorted;
  6557. ICompare *compare;
  6558. IRoxieSlaveContext * ctx;
  6559. Owned<IDiskMerger> diskMerger;
  6560. Owned<IRowStream> diskReader;
  6561. Owned<IOutputMetaData> rowMeta;
  6562. unsigned activityId;
  6563. public:
  6564. CSpillingQuickSortAlgorithm(ICompare *_compare, IRoxieSlaveContext * _ctx, IOutputMetaData * _rowMeta, unsigned _activityId)
  6565. : rowsToSort(&_ctx->queryRowManager(), InitialSortElements, CommitStep), ctx(_ctx), compare(_compare), rowMeta(_rowMeta), activityId(_activityId)
  6566. {
  6567. ctx->queryRowManager().addRowBuffer(this);
  6568. }
  6569. ~CSpillingQuickSortAlgorithm()
  6570. {
  6571. ctx->queryRowManager().removeRowBuffer(this);
  6572. diskReader.clear();
  6573. }
  6574. virtual void prepare(IRoxieInput *input)
  6575. {
  6576. loop
  6577. {
  6578. const void * next = input->nextInGroup();
  6579. if (!next)
  6580. break;
  6581. if (!rowsToSort.append(next))
  6582. {
  6583. {
  6584. roxiemem::RoxieOutputRowArrayLock block(rowsToSort);
  6585. //We should have been called back to free any committed rows, but occasionally it may not (e.g., if
  6586. //the problem is global memory is exhausted) - in which case force a spill here (but add any pending
  6587. //rows first).
  6588. if (rowsToSort.numCommitted() != 0)
  6589. {
  6590. rowsToSort.flush();
  6591. spillRows();
  6592. }
  6593. //Ensure new rows are written to the head of the array. It needs to be a separate call because
  6594. //spillRows() cannot shift active row pointer since it can be called from any thread
  6595. rowsToSort.flush();
  6596. }
  6597. if (!rowsToSort.append(next))
  6598. {
  6599. ReleaseRoxieRow(next);
  6600. throw MakeStringException(ROXIEMM_MEMORY_LIMIT_EXCEEDED, "Insufficient memory to append sort row");
  6601. }
  6602. }
  6603. }
  6604. rowsToSort.flush();
  6605. roxiemem::RoxieOutputRowArrayLock block(rowsToSort);
  6606. if (diskMerger)
  6607. {
  6608. spillRows();
  6609. rowsToSort.kill();
  6610. diskReader.setown(diskMerger->merge(compare));
  6611. }
  6612. else
  6613. {
  6614. unsigned numRows = rowsToSort.numCommitted();
  6615. if (numRows)
  6616. {
  6617. const void * * rows = rowsToSort.getBlock(numRows);
  6618. //MORE: Should this be parallel? Should that be dependent on whether it is grouped? Should be a hint.
  6619. qsortvec(const_cast<void * *>(rows), numRows, *compare);
  6620. }
  6621. sorted.transferFrom(rowsToSort);
  6622. }
  6623. }
  6624. virtual const void *next()
  6625. {
  6626. if(diskReader)
  6627. return diskReader->nextRow();
  6628. return sorted.dequeue();
  6629. }
  6630. virtual void reset()
  6631. {
  6632. //MORE: This could transfer any row pointer from sorted back to rowsToSort. It would trade
  6633. //fewer heap allocations with not freeing up the memory from large group sorts.
  6634. rowsToSort.clearRows();
  6635. sorted.kill();
  6636. //Disk reader must be cleared before the merger - or the files may still be locked.
  6637. diskReader.clear();
  6638. diskMerger.clear();
  6639. }
  6640. //interface roxiemem::IBufferedRowCallback
  6641. virtual unsigned getPriority() const
  6642. {
  6643. //Spill global sorts before grouped sorts
  6644. if (rowMeta->isGrouped())
  6645. return 20;
  6646. return 10;
  6647. }
  6648. virtual bool freeBufferedRows(bool critical)
  6649. {
  6650. roxiemem::RoxieOutputRowArrayLock block(rowsToSort);
  6651. return spillRows();
  6652. }
  6653. protected:
  6654. bool spillRows()
  6655. {
  6656. unsigned numRows = rowsToSort.numCommitted();
  6657. if (numRows == 0)
  6658. return false;
  6659. const void * * rows = rowsToSort.getBlock(numRows);
  6660. qsortvec(const_cast<void * *>(rows), numRows, *compare);
  6661. Owned<IRowWriter> out = queryMerger()->createWriteBlock();
  6662. for (unsigned i= 0; i < numRows; i++)
  6663. {
  6664. out->putRow(rows[i]);
  6665. }
  6666. rowsToSort.noteSpilled(numRows);
  6667. return true;
  6668. }
  6669. IDiskMerger * queryMerger()
  6670. {
  6671. if (!diskMerger)
  6672. {
  6673. unsigned __int64 seq = (memsize_t)this ^ get_cycles_now();
  6674. StringBuffer spillBasename;
  6675. spillBasename.append(tempDirectory).append(PATHSEPCHAR).appendf("spill_sort_%"I64F"u", seq);
  6676. Owned<IRowLinkCounter> linker = new RoxieRowLinkCounter();
  6677. Owned<IRowInterfaces> rowInterfaces = createRowInterfaces(rowMeta, activityId, ctx->queryCodeContext());
  6678. diskMerger.setown(createDiskMerger(rowInterfaces, linker, spillBasename));
  6679. }
  6680. return diskMerger;
  6681. }
  6682. };
  6683. #define INSERTION_SORT_BLOCKSIZE 1024
  6684. class SortedBlock : public CInterface, implements IInterface
  6685. {
  6686. unsigned sequence;
  6687. const void **rows;
  6688. unsigned length;
  6689. unsigned pos;
  6690. SortedBlock(const SortedBlock &);
  6691. public:
  6692. IMPLEMENT_IINTERFACE;
  6693. SortedBlock(unsigned _sequence, IRowManager *rowManager, unsigned activityId) : sequence(_sequence)
  6694. {
  6695. rows = (const void **) rowManager->allocate(INSERTION_SORT_BLOCKSIZE * sizeof(void *), activityId);
  6696. length = 0;
  6697. pos = 0;
  6698. }
  6699. ~SortedBlock()
  6700. {
  6701. while (pos < length)
  6702. ReleaseRoxieRow(rows[pos++]);
  6703. ReleaseRoxieRow(rows);
  6704. }
  6705. int compareTo(SortedBlock *r, ICompare *compare)
  6706. {
  6707. int rc = compare->docompare(rows[pos], r->rows[r->pos]);
  6708. if (!rc)
  6709. rc = sequence - r->sequence;
  6710. return rc;
  6711. }
  6712. const void *next()
  6713. {
  6714. if (pos < length)
  6715. return rows[pos++];
  6716. else
  6717. return NULL;
  6718. }
  6719. inline bool eof()
  6720. {
  6721. return pos==length;
  6722. }
  6723. bool insert(const void *next, ICompare *_compare )
  6724. {
  6725. unsigned b = length;
  6726. if (b == INSERTION_SORT_BLOCKSIZE)
  6727. return false;
  6728. else if (b < 7)
  6729. {
  6730. while (b)
  6731. {
  6732. if (_compare->docompare(next, rows[b-1]) >= 0)
  6733. break;
  6734. b--;
  6735. }
  6736. if (b != length)
  6737. memmove(&rows[b+1], &rows[b], (length - b) * sizeof(void *));
  6738. rows[b] = next;
  6739. length++;
  6740. return true;
  6741. }
  6742. else
  6743. {
  6744. unsigned int a = 0;
  6745. while ((int)a<b)
  6746. {
  6747. int i = (a+b)/2;
  6748. int rc = _compare->docompare(next, rows[i]);
  6749. if (rc>=0)
  6750. a = i+1;
  6751. else
  6752. b = i;
  6753. }
  6754. if (a != length)
  6755. memmove(&rows[a+1], &rows[a], (length - a) * sizeof(void *));
  6756. rows[a] = next;
  6757. length++;
  6758. return true;
  6759. }
  6760. }
  6761. };
  6762. class CInsertionSortAlgorithm : implements CInterfaceOf<ISortAlgorithm>
  6763. {
  6764. SortedBlock *curBlock;
  6765. unsigned blockNo;
  6766. IArrayOf<SortedBlock> blocks;
  6767. unsigned activityId;
  6768. IRowManager *rowManager;
  6769. ICompare *compare;
  6770. void newBlock()
  6771. {
  6772. blocks.append(*curBlock);
  6773. curBlock = new SortedBlock(blockNo++, rowManager, activityId);
  6774. }
  6775. inline static int doCompare(SortedBlock &l, SortedBlock &r, ICompare *compare)
  6776. {
  6777. return l.compareTo(&r, compare);
  6778. }
  6779. void makeHeap()
  6780. {
  6781. /* Permute blocks to establish the heap property
  6782. For each element p, the children are p*2+1 and p*2+2 (provided these are in range)
  6783. The children of p must both be greater than or equal to p
  6784. The parent of a child c is given by p = (c-1)/2
  6785. */
  6786. unsigned i;
  6787. unsigned n = blocks.length();
  6788. SortedBlock **s = blocks.getArray();
  6789. for (i=1; i<n; i++)
  6790. {
  6791. SortedBlock * r = s[i];
  6792. int c = i; /* child */
  6793. while (c > 0)
  6794. {
  6795. int p = (c-1)/2; /* parent */
  6796. if ( doCompare( blocks.item(c), blocks.item(p), compare ) >= 0 )
  6797. break;
  6798. s[c] = s[p];
  6799. s[p] = r;
  6800. c = p;
  6801. }
  6802. }
  6803. }
  6804. void remakeHeap()
  6805. {
  6806. /* The row associated with block[0] will have changed
  6807. This code restores the heap property
  6808. */
  6809. unsigned p = 0; /* parent */
  6810. unsigned n = blocks.length();
  6811. SortedBlock **s = blocks.getArray();
  6812. while (1)
  6813. {
  6814. unsigned c = p*2 + 1; /* child */
  6815. if ( c >= n )
  6816. break;
  6817. /* Select smaller child */
  6818. if ( c+1 < n && doCompare( blocks.item(c+1), blocks.item(c), compare ) < 0 ) c += 1;
  6819. /* If child is greater or equal than parent then we are done */
  6820. if ( doCompare( blocks.item(c), blocks.item(p), compare ) >= 0 )
  6821. break;
  6822. /* Swap parent and child */
  6823. SortedBlock *r = s[c];
  6824. s[c] = s[p];
  6825. s[p] = r;
  6826. /* child becomes parent */
  6827. p = c;
  6828. }
  6829. }
  6830. public:
  6831. CInsertionSortAlgorithm(ICompare *_compare, IRowManager *_rowManager, unsigned _activityId)
  6832. : compare(_compare)
  6833. {
  6834. rowManager = _rowManager;
  6835. activityId = _activityId;
  6836. curBlock = NULL;
  6837. blockNo = 0;
  6838. }
  6839. virtual void reset()
  6840. {
  6841. blocks.kill();
  6842. delete curBlock;
  6843. curBlock = NULL;
  6844. blockNo = 0;
  6845. }
  6846. virtual void prepare(IRoxieInput *input)
  6847. {
  6848. blockNo = 0;
  6849. curBlock = new SortedBlock(blockNo++, rowManager, activityId);
  6850. loop
  6851. {
  6852. const void *next = input->nextInGroup();
  6853. if (!next)
  6854. break;
  6855. if (!curBlock->insert(next, compare))
  6856. {
  6857. newBlock();
  6858. curBlock->insert(next, compare);
  6859. }
  6860. }
  6861. if (blockNo > 1)
  6862. {
  6863. blocks.append(*curBlock);
  6864. curBlock = NULL;
  6865. makeHeap();
  6866. }
  6867. }
  6868. virtual const void * next()
  6869. {
  6870. const void *ret;
  6871. if (blockNo==1) // single block case..
  6872. {
  6873. ret = curBlock->next();
  6874. }
  6875. else if (blocks.length())
  6876. {
  6877. SortedBlock &top = blocks.item(0);
  6878. ret = top.next();
  6879. if (top.eof())
  6880. blocks.replace(blocks.popGet(), 0);
  6881. remakeHeap();
  6882. }
  6883. else
  6884. ret = NULL;
  6885. return ret;
  6886. }
  6887. };
  6888. class CHeapSortAlgorithm : implements CInterfaceOf<ISortAlgorithm>
  6889. {
  6890. unsigned curIndex;
  6891. ConstPointerArray sorted;
  6892. bool inputAlreadySorted;
  6893. IntArray sequences;
  6894. bool eof;
  6895. ICompare *compare;
  6896. #ifdef _CHECK_HEAPSORT
  6897. void checkHeap() const
  6898. {
  6899. unsigned n = sorted.ordinality();
  6900. if (n)
  6901. {
  6902. ICompare *_compare = compare;
  6903. void **s = sorted.getArray();
  6904. int *sq = sequences.getArray();
  6905. unsigned p;
  6906. #if 0
  6907. CTXLOG("------------------------%d entries-----------------", n);
  6908. for (p = 0; p < n; p++)
  6909. {
  6910. CTXLOG("HEAP %d: %d %.10s", p, sq[p], s[p] ? s[p] : "..");
  6911. }
  6912. #endif
  6913. for (p = 0; p < n; p++)
  6914. {
  6915. unsigned c = p*2+1;
  6916. if (c<n)
  6917. assertex(!s[c] || (docompare(p, c, _compare, s, sq) <= 0));
  6918. c++;
  6919. if (c<n)
  6920. assertex(!s[c] || (docompare(p, c, _compare, s, sq) <= 0));
  6921. }
  6922. }
  6923. }
  6924. #else
  6925. inline void checkHeap() const {}
  6926. #endif
  6927. const void *removeHeap()
  6928. {
  6929. unsigned n = sorted.ordinality();
  6930. if (n)
  6931. {
  6932. const void *ret = sorted.item(0);
  6933. if (n > 1 && ret)
  6934. {
  6935. ICompare *_compare = compare;
  6936. const void **s = sorted.getArray();
  6937. int *sq = sequences.getArray();
  6938. unsigned v = 0; // vacancy
  6939. loop
  6940. {
  6941. unsigned c = 2*v + 1;
  6942. if (c < n)
  6943. {
  6944. unsigned f = c; // favourite to fill it
  6945. c++;
  6946. if (c < n && s[c] && (!s[f] || (docompare(f, c, _compare, s, sq) > 0))) // is the smaller of the children
  6947. f = c;
  6948. sq[v] = sq[f];
  6949. if ((s[v] = s[f]) != NULL)
  6950. v = f;
  6951. else
  6952. break;
  6953. }
  6954. else
  6955. {
  6956. s[v] = NULL;
  6957. break;
  6958. }
  6959. }
  6960. }
  6961. checkHeap();
  6962. return ret;
  6963. }
  6964. else
  6965. return NULL;
  6966. }
  6967. static inline int docompare(unsigned l, unsigned r, ICompare *_compare, const void **s, int *sq)
  6968. {
  6969. int rc = _compare->docompare(s[l], s[r]);
  6970. if (!rc)
  6971. rc = sq[l] - sq[r];
  6972. return rc;
  6973. }
  6974. void insertHeap(const void *next)
  6975. {
  6976. // Upside-down heap sort
  6977. // Maintain a heap where every parent is lower than each of its children
  6978. // Root (at node 0) is lowest record seen, nodes 2n+1, 2n+2 are the children
  6979. // To insert a row, add it at end then keep swapping with parent as long as parent is greater
  6980. // To remove a row, take row 0, then recreate heap by replacing it with smaller of two children and so on down the tree
  6981. // Nice features:
  6982. // 1. Deterministic
  6983. // 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
  6984. // 3. Already sorted case can be spotted at zero cost while reading.
  6985. // 4. If you don't read all the results, you don't have to complete the sort
  6986. // BUT it is NOT stable, so we have to use a parallel array of sequence numbers
  6987. unsigned n = sorted.ordinality();
  6988. sorted.append(next);
  6989. sequences.append(n);
  6990. if (!n)
  6991. return;
  6992. ICompare *_compare = compare;
  6993. const void **s = sorted.getArray();
  6994. if (inputAlreadySorted)
  6995. {
  6996. if (_compare->docompare(next, s[n-1]) >= 0)
  6997. return;
  6998. else
  6999. {
  7000. // MORE - could delay creating sequences until now...
  7001. inputAlreadySorted = false;
  7002. }
  7003. }
  7004. int *sq = sequences.getArray();
  7005. unsigned q = n;
  7006. while (n)
  7007. {
  7008. unsigned parent = (n-1) / 2;
  7009. const void *p = s[parent];
  7010. if (_compare->docompare(p, next) <= 0)
  7011. break;
  7012. s[n] = p;
  7013. sq[n] = sq[parent];
  7014. s[parent] = next;
  7015. sq[parent] = q;
  7016. n = parent;
  7017. }
  7018. }
  7019. public:
  7020. CHeapSortAlgorithm(ICompare *_compare) : compare(_compare)
  7021. {
  7022. inputAlreadySorted = true;
  7023. curIndex = 0;
  7024. eof = false;
  7025. }
  7026. virtual void reset()
  7027. {
  7028. eof = false;
  7029. if (inputAlreadySorted)
  7030. {
  7031. while (sorted.isItem(curIndex))
  7032. ReleaseRoxieRow(sorted.item(curIndex++));
  7033. sorted.kill();
  7034. }
  7035. else
  7036. {
  7037. ReleaseRoxieRowSet(sorted);
  7038. }
  7039. inputAlreadySorted = true;
  7040. sequences.kill();
  7041. }
  7042. virtual void prepare(IRoxieInput *input)
  7043. {
  7044. inputAlreadySorted = true;
  7045. curIndex = 0;
  7046. eof = false;
  7047. assertex(sorted.ordinality()==0);
  7048. const void *next = input->nextInGroup();
  7049. if (!next)
  7050. {
  7051. eof = true;
  7052. return;
  7053. }
  7054. loop
  7055. {
  7056. insertHeap(next);
  7057. next = input->nextInGroup();
  7058. if (!next)
  7059. break;
  7060. }
  7061. checkHeap();
  7062. }
  7063. virtual const void * next()
  7064. {
  7065. if (inputAlreadySorted)
  7066. {
  7067. if (sorted.isItem(curIndex))
  7068. {
  7069. return sorted.item(curIndex++);
  7070. }
  7071. else
  7072. return NULL;
  7073. }
  7074. else
  7075. return removeHeap();
  7076. }
  7077. };
  7078. typedef enum {heapSort, insertionSort, quickSort, spillingQuickSort, unknownSort } RoxieSortAlgorithm;
  7079. class CRoxieServerSortActivity : public CRoxieServerActivity
  7080. {
  7081. protected:
  7082. IHThorSortArg &helper;
  7083. ICompare *compare;
  7084. Owned<ISortAlgorithm> sorter;
  7085. bool readInput;
  7086. RoxieSortAlgorithm sortAlgorithm;
  7087. unsigned sortFlags;
  7088. public:
  7089. CRoxieServerSortActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, RoxieSortAlgorithm _sortAlgorithm, unsigned _sortFlags)
  7090. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorSortArg &)basehelper), sortAlgorithm(_sortAlgorithm), sortFlags(_sortFlags)
  7091. {
  7092. compare = helper.queryCompare();
  7093. readInput = false;
  7094. }
  7095. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  7096. {
  7097. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  7098. switch (sortAlgorithm)
  7099. {
  7100. case heapSort:
  7101. sorter.setown(new CHeapSortAlgorithm(compare));
  7102. break;
  7103. case insertionSort:
  7104. sorter.setown(new CInsertionSortAlgorithm(compare, &ctx->queryRowManager(), activityId));
  7105. break;
  7106. case quickSort:
  7107. sorter.setown(new CQuickSortAlgorithm(compare));
  7108. break;
  7109. case spillingQuickSort:
  7110. sorter.setown(new CSpillingQuickSortAlgorithm(compare, ctx, meta, activityId));
  7111. break;
  7112. case unknownSort:
  7113. sorter.clear(); // create it later....
  7114. break;
  7115. default:
  7116. throwUnexpected();
  7117. break;
  7118. }
  7119. }
  7120. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7121. {
  7122. assertex(!readInput);
  7123. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7124. }
  7125. virtual void reset()
  7126. {
  7127. if (sorter)
  7128. sorter->reset();
  7129. readInput = false;
  7130. CRoxieServerActivity::reset();
  7131. }
  7132. virtual const void * nextInGroup()
  7133. {
  7134. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  7135. if (!readInput)
  7136. {
  7137. if (sortAlgorithm == unknownSort)
  7138. {
  7139. sorter.clear();
  7140. IHThorAlgorithm *sortMethod = static_cast<IHThorAlgorithm *>(helper.selectInterface(TAIalgorithm_1));
  7141. OwnedRoxieString useAlgorithm(sortMethod->getAlgorithm());
  7142. if (useAlgorithm)
  7143. {
  7144. if (stricmp(useAlgorithm, "quicksort")==0)
  7145. {
  7146. if (sortFlags & TAFstable)
  7147. throw MakeStringException(ROXIE_UNKNOWN_ALGORITHM, "Invalid stable sort algorithm %s requested", useAlgorithm.get());
  7148. sorter.setown(new CQuickSortAlgorithm(compare));
  7149. }
  7150. else if (stricmp(useAlgorithm, "heapsort")==0)
  7151. sorter.setown(new CHeapSortAlgorithm(compare));
  7152. else if (stricmp(useAlgorithm, "insertionsort")==0)
  7153. sorter.setown(new CInsertionSortAlgorithm(compare, &ctx->queryRowManager(), activityId));
  7154. else
  7155. {
  7156. WARNLOG(ROXIE_UNKNOWN_ALGORITHM, "Ignoring unsupported sort order algorithm '%s', using default", useAlgorithm.get());
  7157. if (sortFlags & TAFunstable)
  7158. sorter.setown(new CQuickSortAlgorithm(compare));
  7159. else
  7160. sorter.setown(new CHeapSortAlgorithm(compare));
  7161. }
  7162. }
  7163. else
  7164. 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...
  7165. }
  7166. sorter->prepare(input);
  7167. readInput = true;
  7168. }
  7169. const void *ret = sorter->next();
  7170. if (ret)
  7171. processed++;
  7172. else
  7173. {
  7174. sorter->reset();
  7175. readInput = false; // ready for next group
  7176. }
  7177. return ret;
  7178. }
  7179. };
  7180. class CRoxieServerSortActivityFactory : public CRoxieServerActivityFactory
  7181. {
  7182. RoxieSortAlgorithm sortAlgorithm;
  7183. unsigned sortFlags;
  7184. public:
  7185. CRoxieServerSortActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  7186. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  7187. {
  7188. sortAlgorithm = heapSort;
  7189. sortFlags = TAFstable;
  7190. Owned<IHThorSortArg> sortHelper = (IHThorSortArg *) helperFactory();
  7191. IHThorAlgorithm *sortMethod = static_cast<IHThorAlgorithm *>(sortHelper->selectInterface(TAIalgorithm_1));
  7192. if (sortMethod)
  7193. {
  7194. sortFlags = sortMethod->getAlgorithmFlags();
  7195. if (sortFlags & TAFunstable)
  7196. sortAlgorithm = quickSort;
  7197. if (!(sortFlags & TAFconstant))
  7198. sortAlgorithm = unknownSort;
  7199. else
  7200. {
  7201. OwnedRoxieString useAlgorithm(sortMethod->getAlgorithm());
  7202. if (useAlgorithm)
  7203. {
  7204. if (stricmp(useAlgorithm, "quicksort")==0)
  7205. {
  7206. if (sortFlags & TAFstable)
  7207. throw MakeStringException(ROXIE_UNKNOWN_ALGORITHM, "Invalid stable sort algorithm %s requested", useAlgorithm.get());
  7208. sortAlgorithm = quickSort;
  7209. }
  7210. else if (stricmp(useAlgorithm, "spillingquicksort")==0)
  7211. {
  7212. if (sortFlags & TAFstable)
  7213. throw MakeStringException(ROXIE_UNKNOWN_ALGORITHM, "Invalid stable sort algorithm %s requested", useAlgorithm.get());
  7214. sortAlgorithm = spillingQuickSort;
  7215. }
  7216. else if (stricmp(useAlgorithm, "heapsort")==0)
  7217. sortAlgorithm = heapSort; // NOTE - we do allow UNSTABLE('heapsort') in order to facilitate runtime selection
  7218. else if (stricmp(useAlgorithm, "insertionsort")==0)
  7219. sortAlgorithm = insertionSort;
  7220. else
  7221. {
  7222. WARNLOG(ROXIE_UNKNOWN_ALGORITHM, "Ignoring unsupported sort order algorithm '%s', using default", useAlgorithm.get());
  7223. if (sortFlags & TAFunstable)
  7224. sortAlgorithm = quickSort;
  7225. else
  7226. sortAlgorithm = heapSort;
  7227. }
  7228. }
  7229. }
  7230. }
  7231. }
  7232. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  7233. {
  7234. return new CRoxieServerSortActivity(this, _probeManager, sortAlgorithm, sortFlags);
  7235. }
  7236. };
  7237. IRoxieServerActivityFactory *createRoxieServerSortActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  7238. {
  7239. return new CRoxieServerSortActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  7240. }
  7241. //=====================================================================================================
  7242. class CRoxieServerSortedActivity : public CRoxieServerActivity
  7243. {
  7244. IHThorSortedArg &helper;
  7245. ICompare * compare;
  7246. const void *prev;
  7247. IRangeCompare * stepCompare;
  7248. public:
  7249. CRoxieServerSortedActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  7250. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorSortedArg &)basehelper)
  7251. {
  7252. prev = NULL;
  7253. compare = helper.queryCompare();
  7254. stepCompare = NULL;
  7255. }
  7256. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7257. {
  7258. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7259. IInputSteppingMeta * stepMeta = input->querySteppingMeta();
  7260. if (stepMeta)
  7261. stepCompare = stepMeta->queryCompare();
  7262. prev = NULL;
  7263. }
  7264. virtual void reset()
  7265. {
  7266. ReleaseClearRoxieRow(prev);
  7267. CRoxieServerActivity::reset();
  7268. }
  7269. virtual const void * nextInGroup()
  7270. {
  7271. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  7272. const void *ret = input->nextInGroup();
  7273. if (ret && prev && compare->docompare(prev, ret) > 0)
  7274. {
  7275. // MORE - better to give mismatching rows that indexes?
  7276. throw MakeStringException(ROXIE_NOT_SORTED, "SORTED(%u) detected incorrectly sorted rows (row %d, %d))", activityId, processed, processed+1);
  7277. }
  7278. ReleaseRoxieRow(prev);
  7279. prev = ret;
  7280. if (ret)
  7281. {
  7282. LinkRoxieRow(prev);
  7283. processed++;
  7284. }
  7285. return ret;
  7286. }
  7287. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  7288. {
  7289. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  7290. const void *ret = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  7291. if (ret && prev && compare->docompare(prev, ret) > 0)
  7292. {
  7293. // MORE - better to give mismatching rows that indexes?
  7294. throw MakeStringException(ROXIE_NOT_SORTED, "SORTED(%u) detected incorrectly sorted rows (row %d, %d))", activityId, processed, processed+1);
  7295. }
  7296. ReleaseRoxieRow(prev);
  7297. prev = ret;
  7298. if (ret)
  7299. {
  7300. LinkRoxieRow(prev);
  7301. processed++;
  7302. }
  7303. return ret;
  7304. }
  7305. IInputSteppingMeta * querySteppingMeta()
  7306. {
  7307. return input->querySteppingMeta();
  7308. }
  7309. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  7310. {
  7311. return input->gatherConjunctions(collector);
  7312. }
  7313. virtual void resetEOF()
  7314. {
  7315. input->resetEOF();
  7316. }
  7317. };
  7318. class CRoxieServerSortedActivityFactory : public CRoxieServerActivityFactory
  7319. {
  7320. public:
  7321. CRoxieServerSortedActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  7322. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  7323. {
  7324. }
  7325. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  7326. {
  7327. return new CRoxieServerSortedActivity(this, _probeManager);
  7328. }
  7329. };
  7330. IRoxieServerActivityFactory *createRoxieServerSortedActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  7331. {
  7332. return new CRoxieServerSortedActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  7333. }
  7334. //=====================================================================================================
  7335. class CRoxieServerThroughSpillActivity : public CRoxieServerActivity
  7336. {
  7337. /*
  7338. BE VERY CAREFUL - this code is tricky.
  7339. Note that starts and stops (and resets) can occur in strange orders
  7340. The FIRST start OR stop must initialize the activity but only the first START should call the upstream start.
  7341. The last stop should call the upstream stop.
  7342. The first reset should call the upstream reset.
  7343. 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
  7344. not yet had start or stop called - for this to happen init() is called on all outputs on the first start or stop.
  7345. Some outputs may be completely pruned away when used in a GRAPH - these outputs should not receive any start/stop/reset and should be
  7346. ignored in the minIndex calculation
  7347. */
  7348. public:
  7349. IHThorArg &helper;
  7350. unsigned activeOutputs;
  7351. unsigned numOutputs;
  7352. unsigned numOriginalOutputs;
  7353. QueueOf<const void, true> buffer;
  7354. CriticalSection crit;
  7355. CriticalSection crit2;
  7356. unsigned tailIdx;
  7357. unsigned headIdx;
  7358. Owned<IException> error;
  7359. class OutputAdaptor : public CInterface, implements IRoxieInput
  7360. {
  7361. bool eof, eofpending, stopped;
  7362. public:
  7363. CRoxieServerThroughSpillActivity *parent;
  7364. unsigned idx;
  7365. unsigned oid;
  7366. unsigned processed;
  7367. unsigned __int64 totalCycles;
  7368. public:
  7369. IMPLEMENT_IINTERFACE;
  7370. OutputAdaptor()
  7371. {
  7372. parent = NULL;
  7373. oid = 0;
  7374. idx = 0;
  7375. processed = 0;
  7376. totalCycles = 0;
  7377. eofpending = false;
  7378. eof = false;
  7379. stopped = false;
  7380. }
  7381. ~OutputAdaptor()
  7382. {
  7383. if (traceStartStop)
  7384. DBGLOG("%p ~OutputAdaptor %d", this, oid);
  7385. }
  7386. void init()
  7387. {
  7388. if (traceStartStop)
  7389. DBGLOG("%p init Input adaptor %d", this, oid);
  7390. idx = 0;
  7391. processed = 0;
  7392. totalCycles = 0;
  7393. eofpending = false;
  7394. eof = false;
  7395. stopped = false;
  7396. }
  7397. virtual unsigned queryId() const
  7398. {
  7399. return parent->queryId();
  7400. }
  7401. virtual IRoxieServerActivity *queryActivity()
  7402. {
  7403. return parent;
  7404. }
  7405. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  7406. {
  7407. return parent->queryIndexReadActivity();
  7408. }
  7409. virtual unsigned __int64 queryTotalCycles() const
  7410. {
  7411. return totalCycles;
  7412. }
  7413. virtual unsigned __int64 queryLocalCycles() const
  7414. {
  7415. return 0;
  7416. }
  7417. virtual IRoxieInput *queryInput(unsigned idx) const
  7418. {
  7419. return parent->queryInput(idx);
  7420. }
  7421. virtual const void * nextInGroup()
  7422. {
  7423. ActivityTimer t(totalCycles, timeActivities, parent->ctx->queryDebugContext());
  7424. if (eof)
  7425. return NULL;
  7426. const void *ret = parent->readBuffered(idx, oid);
  7427. #ifdef TRACE_SPLIT
  7428. parent->CTXLOG("Adaptor %d got back %p for record %d", oid, ret, idx);
  7429. #endif
  7430. idx++;
  7431. if (ret)
  7432. {
  7433. processed++;
  7434. eofpending = false;
  7435. }
  7436. else if (eofpending)
  7437. eof = true;
  7438. else
  7439. eofpending = true;
  7440. return ret;
  7441. }
  7442. virtual IOutputMetaData * queryOutputMeta() const
  7443. {
  7444. return parent->queryOutputMeta();
  7445. }
  7446. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7447. {
  7448. // NOTE: it is tempting to move the init() of all output adaptors here. However that is not a good idea,
  7449. // since adaptors that have not yet started or stopped (but are going to) still need to have been init()'ed
  7450. // for minIndex to give the correct answers
  7451. // therefore, we call init() on all adaptors on receipt of the first start() or stop()
  7452. if (traceStartStop)
  7453. parent->CTXLOG("%p start Input adaptor %d stopped = %d", this, oid, stopped);
  7454. parent->start(oid, parentExtractSize, parentExtract, paused);
  7455. }
  7456. virtual void stop(bool aborting)
  7457. {
  7458. if (traceStartStop)
  7459. parent->CTXLOG("%p stop Input adaptor %d stopped = %d", this, oid, stopped);
  7460. if (!stopped)
  7461. {
  7462. parent->stop(oid, idx, aborting); // NOTE - may call init()
  7463. stopped = true; // parent code relies on stop being called exactly once per adaptor, so make sure it is!
  7464. idx = (unsigned) -1; // causes minIndex not to save rows for me...
  7465. }
  7466. };
  7467. virtual void reset()
  7468. {
  7469. if (traceStartStop)
  7470. parent->CTXLOG("%p reset Input adaptor %d stopped = %d", this, oid, stopped);
  7471. parent->reset(oid);
  7472. parent->noteProcessed(oid, processed, 0, 0);
  7473. processed = 0;
  7474. idx = 0; // value should not be relevant really but this is the safest...
  7475. stopped = false;
  7476. };
  7477. virtual void resetEOF()
  7478. {
  7479. parent->resetEOF();
  7480. }
  7481. virtual void checkAbort()
  7482. {
  7483. parent->checkAbort();
  7484. }
  7485. } *adaptors;
  7486. bool *used;
  7487. unsigned nextFreeOutput()
  7488. {
  7489. unsigned i = numOutputs;
  7490. while (i)
  7491. {
  7492. i--;
  7493. if (!used[i])
  7494. return i;
  7495. }
  7496. throwUnexpected();
  7497. }
  7498. unsigned minIndex(unsigned exceptOid)
  7499. {
  7500. // MORE - yukky code (and slow). Could keep them heapsorted by idx or something
  7501. // this is trying to determine whethwe any of the adaptors will in the future read a given record
  7502. unsigned minIdx = (unsigned) -1;
  7503. for (unsigned i = 0; i < numOutputs; i++)
  7504. {
  7505. if (i != exceptOid && used[i] && adaptors[i].idx < minIdx)
  7506. minIdx = adaptors[i].idx;
  7507. }
  7508. return minIdx;
  7509. }
  7510. void initOutputs()
  7511. {
  7512. activeOutputs = numOutputs;
  7513. for (unsigned i = 0; i < numOriginalOutputs; i++)
  7514. if (used[i])
  7515. adaptors[i].init();
  7516. state = STATEstarting;
  7517. }
  7518. public:
  7519. CRoxieServerThroughSpillActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  7520. : CRoxieServerActivity(_factory, _probeManager), helper(basehelper), numOutputs(_numOutputs)
  7521. {
  7522. numOriginalOutputs = numOutputs;
  7523. adaptors = new OutputAdaptor[numOutputs];
  7524. used = new bool[numOutputs];
  7525. for (unsigned i = 0; i < numOutputs; i++)
  7526. {
  7527. adaptors[i].parent = this;
  7528. adaptors[i].oid = i;
  7529. used[i] = false;
  7530. }
  7531. tailIdx = 0;
  7532. headIdx = 0;
  7533. activeOutputs = numOutputs;
  7534. }
  7535. ~CRoxieServerThroughSpillActivity()
  7536. {
  7537. delete [] adaptors;
  7538. delete [] used;
  7539. }
  7540. const void *readBuffered(unsigned idx, unsigned oid)
  7541. {
  7542. CriticalBlock b(crit);
  7543. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext()); // NOTE - time spent waiting for crit not included here. Is that right?
  7544. if (idx == headIdx) // test once without getting the crit2 sec
  7545. {
  7546. CriticalUnblock b1(crit);
  7547. CriticalBlock b2(crit2);
  7548. if (error)
  7549. {
  7550. throw error.getLink();
  7551. }
  7552. if (idx == headIdx) // test again now that we have it
  7553. {
  7554. try
  7555. {
  7556. const void *row = input->nextInGroup();
  7557. CriticalBlock b3(crit);
  7558. headIdx++;
  7559. if (activeOutputs==1)
  7560. {
  7561. #ifdef TRACE_SPLIT
  7562. CTXLOG("spill %d optimised return of %p", activityId, row);
  7563. #endif
  7564. return row; // optimization for the case where only one output still active.
  7565. }
  7566. buffer.enqueue(row);
  7567. }
  7568. catch (IException *E)
  7569. {
  7570. #ifdef TRACE_SPLIT
  7571. CTXLOG("spill %d caught exception", activityId);
  7572. #endif
  7573. error.set(E);
  7574. throw;
  7575. }
  7576. catch (...)
  7577. {
  7578. IException *E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught in CRoxieServerThroughSpillActivity::readBuffered");
  7579. error.set(E);
  7580. throw E;
  7581. }
  7582. }
  7583. }
  7584. idx -= tailIdx;
  7585. if (!idx)
  7586. {
  7587. unsigned min = minIndex(oid);
  7588. if (min > tailIdx)
  7589. {
  7590. tailIdx++;
  7591. const void *ret = buffer.dequeue(); // no need to link - last puller
  7592. #ifdef TRACE_SPLIT
  7593. CTXLOG("last puller return of %p", ret);
  7594. #endif
  7595. return ret;
  7596. }
  7597. }
  7598. const void *ret = buffer.item(idx);
  7599. if (ret) LinkRoxieRow(ret);
  7600. #ifdef TRACE_SPLIT
  7601. CTXLOG("standard return of %p", ret);
  7602. #endif
  7603. return ret;
  7604. }
  7605. virtual void start(unsigned oid, unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7606. {
  7607. CriticalBlock b(crit);
  7608. if (error)
  7609. throw error.getLink();
  7610. if (factory)
  7611. factory->noteStarted(oid);
  7612. if (traceStartStop)
  7613. CTXLOG("SPLIT %p: start %d child %d activeOutputs %d numOutputs %d numOriginalOutputs %d state %s", this, activityId, oid, activeOutputs, numOutputs, numOriginalOutputs, queryStateText(state));
  7614. if (state != STATEstarted)
  7615. {
  7616. if (state != STATEstarting)
  7617. initOutputs();
  7618. tailIdx = 0;
  7619. headIdx = 0;
  7620. error.clear();
  7621. try
  7622. {
  7623. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7624. }
  7625. catch (IException *E)
  7626. {
  7627. #ifdef TRACE_SPLIT
  7628. CTXLOG("spill %d caught exception in start", activityId);
  7629. #endif
  7630. error.set(E);
  7631. throw;
  7632. }
  7633. catch (...)
  7634. {
  7635. IException *E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught in CRoxieServerThroughSpillActivity::start");
  7636. error.set(E);
  7637. throw E;
  7638. }
  7639. }
  7640. }
  7641. void stop(unsigned oid, unsigned idx, bool aborting)
  7642. {
  7643. // Note that OutputAdaptor code ensures that stop is not called more than once per adaptor
  7644. CriticalBlock b(crit);
  7645. #ifdef TRACE_STARTSTOP
  7646. if (traceStartStop)
  7647. {
  7648. CTXLOG("SPLIT %p: stop %d child %d activeOutputs %d numOutputs %d numOriginalOutputs %d state %s", this, activityId, oid, activeOutputs, numOutputs, numOriginalOutputs, queryStateText(state));
  7649. if (watchActivityId && watchActivityId==activityId)
  7650. {
  7651. CTXLOG("WATCH: stop %d", activityId);
  7652. }
  7653. }
  7654. #endif
  7655. if (state != STATEstarting && state != STATEstarted)
  7656. initOutputs();
  7657. if (activeOutputs > 1)
  7658. {
  7659. if (tailIdx==idx)
  7660. {
  7661. // Discard all buffered rows that are there purely for this adaptor to read them
  7662. unsigned min = minIndex(oid);
  7663. if (min != (unsigned) -1)
  7664. // what does -1 signify?? No-one wants anything? In which case can't we kill all rows??
  7665. // Should never happen though if there are still some active.
  7666. // there may be a small window where adaptors are blocked on the semaphore...
  7667. {
  7668. #ifdef TRACE_SPLIT
  7669. CTXLOG("%p: Discarding buffered rows from %d to %d for oid %x (%d outputs active)", this, idx, min, oid, activeOutputs);
  7670. #endif
  7671. while (tailIdx < min)
  7672. {
  7673. ReleaseRoxieRow(buffer.dequeue());
  7674. tailIdx++;
  7675. }
  7676. }
  7677. }
  7678. activeOutputs--;
  7679. return;
  7680. }
  7681. #ifdef TRACE_SPLIT
  7682. CTXLOG("%p: All outputs done", this);
  7683. #endif
  7684. activeOutputs = numOutputs;
  7685. CRoxieServerActivity::stop(aborting);
  7686. };
  7687. void reset(unsigned oid)
  7688. {
  7689. if (traceStartStop)
  7690. CTXLOG("SPLIT %p: reset %d child %d activeOutputs %d numOutputs %d numOriginalOutputs %d state %s", this, activityId, oid, activeOutputs, numOutputs, numOriginalOutputs, queryStateText(state));
  7691. activeOutputs = numOutputs;
  7692. while (buffer.ordinality())
  7693. ReleaseRoxieRow(buffer.dequeue());
  7694. error.clear();
  7695. if (state != STATEreset) // make sure input is only reset once
  7696. CRoxieServerActivity::reset();
  7697. };
  7698. virtual unsigned __int64 queryLocalCycles() const
  7699. {
  7700. return 0;
  7701. }
  7702. virtual const void *nextInGroup()
  7703. {
  7704. throwUnexpected(); // Internal logic error - we are not anybody's input
  7705. }
  7706. virtual IOutputMetaData * queryOutputMeta() const
  7707. {
  7708. // if (outputMeta)
  7709. // return outputMeta;
  7710. // else
  7711. return input->queryOutputMeta(); // not always known (e.g. disk write - though Gavin _could_ fill it in)
  7712. }
  7713. virtual IRoxieInput *queryOutput(unsigned idx)
  7714. {
  7715. if (idx==(unsigned)-1)
  7716. idx = nextFreeOutput(); // MORE - what is this used for?
  7717. assertex(idx < numOriginalOutputs);
  7718. assertex(!used[idx]);
  7719. used[idx] = true;
  7720. return &adaptors[idx];
  7721. }
  7722. virtual void resetOutputsUsed()
  7723. {
  7724. numOutputs = 1;
  7725. activeOutputs = 1;
  7726. // MORE RKC->GH should we be clearing the used array here? anywhere?
  7727. }
  7728. virtual void noteOutputUsed()
  7729. {
  7730. assertex(numOutputs < numOriginalOutputs);
  7731. numOutputs++;
  7732. activeOutputs = numOutputs;
  7733. }
  7734. virtual bool isPassThrough()
  7735. {
  7736. return numOutputs==1;
  7737. }
  7738. };
  7739. class CRoxieServerThroughSpillActivityFactory : public CRoxieServerMultiOutputFactory
  7740. {
  7741. public:
  7742. CRoxieServerThroughSpillActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  7743. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  7744. {
  7745. Owned<IHThorSpillArg> helper = (IHThorSpillArg *) helperFactory();
  7746. setNumOutputs(helper->getTempUsageCount() + 1);
  7747. }
  7748. CRoxieServerThroughSpillActivityFactory(IQueryFactory &_queryFactory, HelperFactory *_helperFactory, unsigned _numOutputs)
  7749. : CRoxieServerMultiOutputFactory(0, 0, _queryFactory, _helperFactory, TAKsplit)
  7750. {
  7751. setNumOutputs(_numOutputs);
  7752. }
  7753. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  7754. {
  7755. return new CRoxieServerThroughSpillActivity(this, _probeManager, numOutputs);
  7756. }
  7757. };
  7758. IRoxieServerActivityFactory *createRoxieServerThroughSpillActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  7759. {
  7760. return new CRoxieServerThroughSpillActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  7761. }
  7762. IRoxieServerActivityFactory *createRoxieServerThroughSpillActivityFactory(IQueryFactory &_queryFactory, HelperFactory *_factory, unsigned _numOutputs)
  7763. {
  7764. return new CRoxieServerThroughSpillActivityFactory(_queryFactory, _factory, _numOutputs);
  7765. }
  7766. //----------------------------------------------------------------------------------------------
  7767. class CRoxieServerSplitActivityFactory : public CRoxieServerMultiOutputFactory
  7768. {
  7769. public:
  7770. CRoxieServerSplitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  7771. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  7772. {
  7773. Owned<IHThorSplitArg> helper = (IHThorSplitArg *) helperFactory();
  7774. setNumOutputs(helper->numBranches());
  7775. }
  7776. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  7777. {
  7778. return new CRoxieServerThroughSpillActivity(this, _probeManager, numOutputs);
  7779. }
  7780. };
  7781. IRoxieServerActivityFactory *createRoxieServerSplitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  7782. {
  7783. return new CRoxieServerSplitActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  7784. }
  7785. //=====================================================================================================
  7786. #define PIPE_BUFSIZE 0x8000
  7787. static IException *createPipeFailureException(const char *cmd, unsigned retcode, IPipeProcess *pipe)
  7788. {
  7789. StringBuffer msg;
  7790. if(pipe->hasError())
  7791. {
  7792. try
  7793. {
  7794. char error[512];
  7795. size32_t sz = pipe->readError(sizeof(error), error);
  7796. if(sz && sz!=(size32_t)-1)
  7797. msg.append(", stderr: '").append(sz, error).append("'");
  7798. }
  7799. catch (IException *e)
  7800. {
  7801. EXCLOG(e, "Error reading pipe stderr");
  7802. e->Release();
  7803. }
  7804. }
  7805. return MakeStringException(ROXIE_PIPE_ERROR, "Pipe process %s returned error %u%s", cmd, retcode, msg.str());
  7806. }
  7807. class CRoxieServerPipeReadActivity : public CRoxieServerActivity
  7808. {
  7809. IHThorPipeReadArg &helper;
  7810. Owned<IPipeProcess> pipe;
  7811. StringAttr pipeCommand;
  7812. Owned<IOutputRowDeserializer> rowDeserializer;
  7813. Owned<IReadRowStream> readTransformer;
  7814. bool groupSignalled;
  7815. public:
  7816. CRoxieServerPipeReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  7817. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorPipeReadArg &)basehelper)
  7818. {
  7819. groupSignalled = true;
  7820. }
  7821. virtual bool needsAllocator() const { return true; }
  7822. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  7823. {
  7824. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  7825. rowDeserializer.setown(rowAllocator->createDiskDeserializer(ctx->queryCodeContext()));
  7826. }
  7827. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7828. {
  7829. groupSignalled = true; // i.e. don't start with a NULL row
  7830. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7831. if (!readTransformer)
  7832. {
  7833. OwnedRoxieString xmlIteratorPath(helper.getXmlIteratorPath());
  7834. readTransformer.setown(createReadRowStream(rowAllocator, rowDeserializer, helper.queryXmlTransformer(), helper.queryCsvTransformer(), xmlIteratorPath, helper.getPipeFlags()));
  7835. }
  7836. OwnedRoxieString pipeProgram(helper.getPipeProgram());
  7837. openPipe(pipeProgram);
  7838. }
  7839. virtual void stop(bool aborting)
  7840. {
  7841. CRoxieServerActivity::stop(aborting);
  7842. pipe.clear();
  7843. readTransformer->setStream(NULL);
  7844. }
  7845. virtual const void *nextInGroup()
  7846. {
  7847. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  7848. while (!waitForPipe())
  7849. {
  7850. if (!pipe)
  7851. return NULL;
  7852. if (helper.getPipeFlags() & TPFgroupeachrow)
  7853. {
  7854. if (!groupSignalled)
  7855. {
  7856. groupSignalled = true;
  7857. return NULL;
  7858. }
  7859. }
  7860. }
  7861. const void *ret = readTransformer->next();
  7862. assertex(ret != NULL); // if ret can ever be NULL then we need to recode this logic
  7863. processed++;
  7864. groupSignalled = false;
  7865. return ret;
  7866. }
  7867. protected:
  7868. bool waitForPipe()
  7869. {
  7870. if (!pipe)
  7871. return false; // done
  7872. if (!readTransformer->eos())
  7873. return true;
  7874. verifyPipe();
  7875. return false;
  7876. }
  7877. void openPipe(char const * cmd)
  7878. {
  7879. pipeCommand.setown(cmd);
  7880. pipe.setown(createPipeProcess());
  7881. if(!pipe->run(NULL, cmd, ".", false, true, true, 0x10000))
  7882. throw MakeStringException(ROXIE_PIPE_ERROR, "Could not run pipe process %s", cmd);
  7883. Owned<ISimpleReadStream> pipeReader = pipe->getOutputStream();
  7884. readTransformer->setStream(pipeReader.get());
  7885. }
  7886. void verifyPipe()
  7887. {
  7888. if (pipe)
  7889. {
  7890. unsigned err = pipe->wait();
  7891. if(err && !(helper.getPipeFlags() & TPFnofail))
  7892. {
  7893. throw createPipeFailureException(pipeCommand.get(), err, pipe);
  7894. }
  7895. pipe.clear();
  7896. }
  7897. }
  7898. };
  7899. class CRoxieServerPipeThroughActivity : public CRoxieServerActivity, implements IRecordPullerCallback
  7900. {
  7901. IHThorPipeThroughArg &helper;
  7902. RecordPullerThread puller;
  7903. Owned<IPipeProcess> pipe;
  7904. StringAttr pipeCommand;
  7905. InterruptableSemaphore pipeVerified;
  7906. InterruptableSemaphore pipeOpened;
  7907. CachedOutputMetaData inputMeta;
  7908. Owned<IOutputRowSerializer> rowSerializer;
  7909. Owned<IOutputRowDeserializer> rowDeserializer;
  7910. Owned<IPipeWriteXformHelper> writeTransformer;
  7911. Owned<IReadRowStream> readTransformer;
  7912. bool firstRead;
  7913. bool recreate;
  7914. bool inputExhausted;
  7915. bool groupSignalled;
  7916. public:
  7917. CRoxieServerPipeThroughActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  7918. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorPipeThroughArg &)basehelper), puller(false)
  7919. {
  7920. recreate = helper.recreateEachRow();
  7921. groupSignalled = true;
  7922. firstRead = false;
  7923. inputExhausted = false;
  7924. }
  7925. virtual bool needsAllocator() const { return true; }
  7926. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  7927. {
  7928. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  7929. rowSerializer.setown(inputMeta.createDiskSerializer(ctx->queryCodeContext(), activityId));
  7930. rowDeserializer.setown(rowAllocator->createDiskDeserializer(ctx->queryCodeContext()));
  7931. writeTransformer.setown(createPipeWriteXformHelper(helper.getPipeFlags(), helper.queryXmlOutput(), helper.queryCsvOutput(), rowSerializer));
  7932. }
  7933. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7934. {
  7935. firstRead = true;
  7936. inputExhausted = false;
  7937. groupSignalled = true; // i.e. don't start with a NULL row
  7938. pipeVerified.reinit();
  7939. pipeOpened.reinit();
  7940. writeTransformer->ready();
  7941. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7942. if (!readTransformer)
  7943. {
  7944. OwnedRoxieString xmlIterator(helper.getXmlIteratorPath());
  7945. readTransformer.setown(createReadRowStream(rowAllocator, rowDeserializer, helper.queryXmlTransformer(), helper.queryCsvTransformer(), xmlIterator, helper.getPipeFlags()));
  7946. }
  7947. if(!recreate)
  7948. {
  7949. OwnedRoxieString pipeProgram(helper.getPipeProgram());
  7950. openPipe(pipeProgram);
  7951. }
  7952. puller.start(parentExtractSize, parentExtract, paused, 0, false, ctx); // Pipe does not support preload presently - locks up
  7953. }
  7954. virtual void setInput(unsigned idx, IRoxieInput *_in)
  7955. {
  7956. if (idx)
  7957. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  7958. puller.setInput(this, _in);
  7959. inputMeta.set(_in->queryOutputMeta());
  7960. }
  7961. virtual void stop(bool aborting)
  7962. {
  7963. pipeVerified.interrupt(NULL);
  7964. pipeOpened.interrupt(NULL);
  7965. puller.stop(aborting);
  7966. CRoxieServerActivity::stop(aborting);
  7967. pipe.clear();
  7968. readTransformer->setStream(NULL);
  7969. }
  7970. virtual void reset()
  7971. {
  7972. puller.reset();
  7973. CRoxieServerActivity::reset();
  7974. }
  7975. virtual const void *nextInGroup()
  7976. {
  7977. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  7978. while (!waitForPipe())
  7979. {
  7980. if (!pipe)
  7981. return NULL;
  7982. if (helper.getPipeFlags() & TPFgroupeachrow)
  7983. {
  7984. if (!groupSignalled)
  7985. {
  7986. groupSignalled = true;
  7987. return NULL;
  7988. }
  7989. }
  7990. }
  7991. const void *ret = readTransformer->next();
  7992. assertex(ret != NULL); // if ret can ever be NULL then we need to recode this logic
  7993. processed++;
  7994. groupSignalled = false;
  7995. return ret;
  7996. }
  7997. virtual void processRow(const void *row)
  7998. {
  7999. // called from puller thread
  8000. if(recreate)
  8001. openPipe(helper.getNameFromRow(row));
  8002. writeTransformer->writeTranslatedText(row, pipe);
  8003. ReleaseRoxieRow(row);
  8004. if(recreate)
  8005. {
  8006. closePipe();
  8007. pipeVerified.wait();
  8008. }
  8009. }
  8010. virtual void processDone()
  8011. {
  8012. // called from puller thread
  8013. if(recreate)
  8014. {
  8015. inputExhausted = true;
  8016. pipeOpened.signal();
  8017. }
  8018. else
  8019. {
  8020. closePipe();
  8021. pipeVerified.wait();
  8022. }
  8023. }
  8024. virtual void processEOG()
  8025. {
  8026. }
  8027. void processGroup(const ConstPointerArray &)
  8028. {
  8029. throwUnexpected();
  8030. }
  8031. virtual bool fireException(IException *e)
  8032. {
  8033. pipeOpened.interrupt(LINK(e));
  8034. pipeVerified.interrupt(e);
  8035. return true;
  8036. }
  8037. private:
  8038. bool waitForPipe()
  8039. {
  8040. if (firstRead)
  8041. {
  8042. pipeOpened.wait();
  8043. firstRead = false;
  8044. }
  8045. if (!pipe)
  8046. return false; // done
  8047. if (!readTransformer->eos())
  8048. return true;
  8049. verifyPipe();
  8050. if (recreate && !inputExhausted)
  8051. pipeOpened.wait();
  8052. return false;
  8053. }
  8054. void openPipe(char const * cmd)
  8055. {
  8056. pipeCommand.setown(cmd);
  8057. pipe.setown(createPipeProcess());
  8058. if(!pipe->run(NULL, cmd, ".", true, true, true, 0x10000))
  8059. throw MakeStringException(ROXIE_PIPE_ERROR, "Could not run pipe process %s", cmd);
  8060. writeTransformer->writeHeader(pipe);
  8061. Owned<ISimpleReadStream> pipeReader = pipe->getOutputStream();
  8062. readTransformer->setStream(pipeReader.get());
  8063. pipeOpened.signal();
  8064. }
  8065. void closePipe()
  8066. {
  8067. writeTransformer->writeFooter(pipe);
  8068. pipe->closeInput();
  8069. }
  8070. void verifyPipe()
  8071. {
  8072. if (pipe)
  8073. {
  8074. unsigned err = pipe->wait();
  8075. if(err && !(helper.getPipeFlags() & TPFnofail))
  8076. {
  8077. throw createPipeFailureException(pipeCommand.get(), err, pipe);
  8078. }
  8079. pipe.clear();
  8080. pipeVerified.signal();
  8081. }
  8082. }
  8083. };
  8084. class CRoxieServerPipeWriteActivity : public CRoxieServerInternalSinkActivity
  8085. {
  8086. IHThorPipeWriteArg &helper;
  8087. Owned<IPipeProcess> pipe;
  8088. StringAttr pipeCommand;
  8089. CachedOutputMetaData inputMeta;
  8090. Owned<IOutputRowSerializer> rowSerializer;
  8091. Owned<IPipeWriteXformHelper> writeTransformer;
  8092. bool firstRead;
  8093. bool recreate;
  8094. bool inputExhausted;
  8095. public:
  8096. CRoxieServerPipeWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  8097. : CRoxieServerInternalSinkActivity(_factory, _probeManager, _numOutputs), helper((IHThorPipeWriteArg &)basehelper)
  8098. {
  8099. recreate = helper.recreateEachRow();
  8100. firstRead = false;
  8101. inputExhausted = false;
  8102. }
  8103. virtual bool needsAllocator() const { return true; }
  8104. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  8105. {
  8106. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  8107. inputMeta.set(input->queryOutputMeta());
  8108. rowSerializer.setown(inputMeta.createDiskSerializer(ctx->queryCodeContext(), activityId));
  8109. writeTransformer.setown(createPipeWriteXformHelper(helper.getPipeFlags(), helper.queryXmlOutput(), helper.queryCsvOutput(), rowSerializer));
  8110. }
  8111. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8112. {
  8113. firstRead = true;
  8114. inputExhausted = false;
  8115. writeTransformer->ready();
  8116. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8117. if(!recreate)
  8118. {
  8119. OwnedRoxieString pipeProgram(helper.getPipeProgram());
  8120. openPipe(pipeProgram);
  8121. }
  8122. }
  8123. virtual void stop(bool aborting)
  8124. {
  8125. CRoxieServerActivity::stop(aborting);
  8126. pipe.clear();
  8127. }
  8128. virtual void onExecute()
  8129. {
  8130. loop
  8131. {
  8132. const void *row = input->nextInGroup();
  8133. if (!row)
  8134. {
  8135. row = input->nextInGroup();
  8136. if (!row)
  8137. break;
  8138. }
  8139. processed++;
  8140. if(recreate)
  8141. openPipe(helper.getNameFromRow(row));
  8142. writeTransformer->writeTranslatedText(row, pipe);
  8143. ReleaseRoxieRow(row);
  8144. if(recreate)
  8145. closePipe();
  8146. }
  8147. closePipe();
  8148. }
  8149. private:
  8150. void openPipe(char const * cmd)
  8151. {
  8152. pipeCommand.setown(cmd);
  8153. pipe.setown(createPipeProcess());
  8154. if(!pipe->run(NULL, cmd, ".", true, false, true, 0x10000))
  8155. throw MakeStringException(ROXIE_PIPE_ERROR, "Could not run pipe process %s", cmd);
  8156. writeTransformer->writeHeader(pipe);
  8157. }
  8158. void closePipe()
  8159. {
  8160. writeTransformer->writeFooter(pipe);
  8161. pipe->closeInput();
  8162. unsigned err = pipe->wait();
  8163. if(err && !(helper.getPipeFlags() & TPFnofail))
  8164. {
  8165. throw createPipeFailureException(pipeCommand.get(), err, pipe);
  8166. }
  8167. pipe.clear();
  8168. }
  8169. };
  8170. class CRoxieServerPipeReadActivityFactory : public CRoxieServerActivityFactory
  8171. {
  8172. public:
  8173. CRoxieServerPipeReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8174. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  8175. {
  8176. }
  8177. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8178. {
  8179. return new CRoxieServerPipeReadActivity(this, _probeManager);
  8180. }
  8181. };
  8182. class CRoxieServerPipeThroughActivityFactory : public CRoxieServerActivityFactory
  8183. {
  8184. public:
  8185. CRoxieServerPipeThroughActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8186. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  8187. {
  8188. }
  8189. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8190. {
  8191. return new CRoxieServerPipeThroughActivity(this, _probeManager);
  8192. }
  8193. };
  8194. class CRoxieServerPipeWriteActivityFactory : public CRoxieServerInternalSinkFactory
  8195. {
  8196. public:
  8197. CRoxieServerPipeWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  8198. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot)
  8199. {
  8200. }
  8201. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8202. {
  8203. return new CRoxieServerPipeWriteActivity(this, _probeManager, usageCount);
  8204. }
  8205. };
  8206. IRoxieServerActivityFactory *createRoxieServerPipeReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8207. {
  8208. return new CRoxieServerPipeReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  8209. }
  8210. IRoxieServerActivityFactory *createRoxieServerPipeThroughActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8211. {
  8212. return new CRoxieServerPipeThroughActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  8213. }
  8214. IRoxieServerActivityFactory *createRoxieServerPipeWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  8215. {
  8216. return new CRoxieServerPipeWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot);
  8217. }
  8218. //=====================================================================================================
  8219. class CRoxieServerStreamedIteratorActivity : public CRoxieServerActivity
  8220. {
  8221. IHThorStreamedIteratorArg &helper;
  8222. Owned<IRowStream> rows;
  8223. public:
  8224. CRoxieServerStreamedIteratorActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8225. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorStreamedIteratorArg &)basehelper)
  8226. {
  8227. }
  8228. ~CRoxieServerStreamedIteratorActivity()
  8229. {
  8230. }
  8231. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8232. {
  8233. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8234. rows.setown(helper.createInput());
  8235. }
  8236. virtual void stop(bool aborting)
  8237. {
  8238. if (rows)
  8239. {
  8240. rows->stop();
  8241. rows.clear();
  8242. }
  8243. CRoxieServerActivity::stop(aborting);
  8244. }
  8245. virtual const void *nextInGroup()
  8246. {
  8247. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  8248. assertex(rows != NULL);
  8249. const void * next = rows->nextRow();
  8250. if (next)
  8251. processed++;
  8252. return next;
  8253. }
  8254. };
  8255. class CRoxieServerStreamedIteratorActivityFactory : public CRoxieServerActivityFactory
  8256. {
  8257. public:
  8258. CRoxieServerStreamedIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8259. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  8260. {
  8261. }
  8262. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8263. {
  8264. return new CRoxieServerStreamedIteratorActivity(this, _probeManager);
  8265. }
  8266. };
  8267. IRoxieServerActivityFactory *createRoxieServerStreamedIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8268. {
  8269. return new CRoxieServerStreamedIteratorActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  8270. }
  8271. //=====================================================================================================
  8272. class CRoxieServerFilterActivity : public CRoxieServerLateStartActivity
  8273. {
  8274. IHThorFilterArg &helper;
  8275. bool anyThisGroup;
  8276. IRangeCompare * stepCompare;
  8277. public:
  8278. CRoxieServerFilterActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8279. : CRoxieServerLateStartActivity(_factory, _probeManager), helper((IHThorFilterArg &)basehelper)
  8280. {
  8281. anyThisGroup = false;
  8282. stepCompare = NULL;
  8283. }
  8284. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8285. {
  8286. anyThisGroup = false;
  8287. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  8288. lateStart(parentExtractSize, parentExtract, helper.canMatchAny());
  8289. stepCompare = NULL;
  8290. if (!eof)
  8291. {
  8292. IInputSteppingMeta * stepMeta = input->querySteppingMeta();
  8293. if (stepMeta)
  8294. stepCompare = stepMeta->queryCompare();
  8295. }
  8296. }
  8297. virtual const void * nextInGroup()
  8298. {
  8299. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  8300. if (eof)
  8301. return NULL;
  8302. loop
  8303. {
  8304. const void * ret = input->nextInGroup();
  8305. if (!ret)
  8306. {
  8307. //stop returning two NULLs in a row.
  8308. if (anyThisGroup)
  8309. {
  8310. anyThisGroup = false;
  8311. return NULL;
  8312. }
  8313. ret = input->nextInGroup();
  8314. if (!ret)
  8315. {
  8316. eof = true;
  8317. return NULL; // eof...
  8318. }
  8319. }
  8320. if (helper.isValid(ret))
  8321. {
  8322. anyThisGroup = true;
  8323. processed++;
  8324. return ret;
  8325. }
  8326. ReleaseRoxieRow(ret);
  8327. }
  8328. }
  8329. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  8330. {
  8331. //Could assert that this isn't grouped
  8332. // MORE - will need rethinking once we rethink the nextSteppedGE interface for global smart-stepping.
  8333. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  8334. if (eof)
  8335. return NULL;
  8336. loop
  8337. {
  8338. const void * ret = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  8339. if (!ret)
  8340. {
  8341. eof = true;
  8342. return NULL;
  8343. }
  8344. if (!wasCompleteMatch)
  8345. {
  8346. anyThisGroup = false; // RKC->GH - is this right??
  8347. return ret;
  8348. }
  8349. if (helper.isValid(ret))
  8350. {
  8351. anyThisGroup = true;
  8352. processed++;
  8353. return ret;
  8354. }
  8355. if (!stepExtra.returnMismatches())
  8356. {
  8357. ReleaseRoxieRow(ret);
  8358. return nextInGroup();
  8359. }
  8360. //If asked to return mismatches we are only interested in mismatches that will force the stepped
  8361. //condition to advance
  8362. if (stepCompare->docompare(ret, seek, numFields) != 0)
  8363. {
  8364. wasCompleteMatch = false;
  8365. anyThisGroup = false; // WHY?
  8366. return ret;
  8367. }
  8368. ReleaseRoxieRow(ret);
  8369. }
  8370. }
  8371. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  8372. {
  8373. return input->gatherConjunctions(collector);
  8374. }
  8375. virtual void resetEOF()
  8376. {
  8377. eof = prefiltered;
  8378. anyThisGroup = false;
  8379. input->resetEOF();
  8380. }
  8381. IInputSteppingMeta * querySteppingMeta()
  8382. {
  8383. return input->querySteppingMeta();
  8384. }
  8385. };
  8386. class CRoxieServerFilterActivityFactory : public CRoxieServerActivityFactory
  8387. {
  8388. public:
  8389. CRoxieServerFilterActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8390. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  8391. {
  8392. }
  8393. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8394. {
  8395. return new CRoxieServerFilterActivity(this, _probeManager);
  8396. }
  8397. };
  8398. IRoxieServerActivityFactory *createRoxieServerFilterActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8399. {
  8400. return new CRoxieServerFilterActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  8401. }
  8402. //=====================================================================================================
  8403. class CRoxieServerFilterGroupActivity : public CRoxieServerLateStartActivity
  8404. {
  8405. IHThorFilterGroupArg &helper;
  8406. unsigned curIndex;
  8407. ConstPointerArray gathered;
  8408. IRangeCompare * stepCompare;
  8409. public:
  8410. CRoxieServerFilterGroupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8411. : CRoxieServerLateStartActivity(_factory, _probeManager), helper((IHThorFilterGroupArg &)basehelper)
  8412. {
  8413. curIndex = 0;
  8414. stepCompare = NULL;
  8415. }
  8416. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8417. {
  8418. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  8419. lateStart(parentExtractSize, parentExtract, helper.canMatchAny());//sets eof
  8420. assertex(eof == !helper.canMatchAny());
  8421. curIndex = 0;
  8422. stepCompare = NULL;
  8423. if (!eof)
  8424. {
  8425. IInputSteppingMeta * inputStepping = input->querySteppingMeta();
  8426. if (inputStepping)
  8427. stepCompare = inputStepping->queryCompare();
  8428. }
  8429. }
  8430. virtual void reset()
  8431. {
  8432. releaseGathered();
  8433. CRoxieServerLateStartActivity::reset();
  8434. }
  8435. inline void releaseGathered()
  8436. {
  8437. while (gathered.isItem(curIndex))
  8438. ReleaseRoxieRow(gathered.item(curIndex++));
  8439. gathered.kill();
  8440. }
  8441. virtual const void * nextInGroup()
  8442. {
  8443. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  8444. loop
  8445. {
  8446. if (eof)
  8447. return NULL;
  8448. if (gathered.ordinality())
  8449. {
  8450. if (gathered.isItem(curIndex))
  8451. {
  8452. const void * ret = gathered.item(curIndex++);
  8453. processed++;
  8454. return ret;
  8455. }
  8456. curIndex = 0;
  8457. gathered.kill();
  8458. return NULL;
  8459. }
  8460. const void * ret = input->nextInGroup();
  8461. while (ret)
  8462. {
  8463. gathered.append(ret);
  8464. ret = input->nextInGroup();
  8465. }
  8466. unsigned num = gathered.ordinality();
  8467. if (num != 0)
  8468. {
  8469. if (!helper.isValid(num, (const void * *)gathered.getArray()))
  8470. ReleaseRoxieRowSet(gathered); // read next group
  8471. }
  8472. else
  8473. eof = true;
  8474. }
  8475. }
  8476. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  8477. {
  8478. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  8479. if (eof)
  8480. return NULL;
  8481. if (gathered.ordinality())
  8482. {
  8483. while (gathered.isItem(curIndex))
  8484. {
  8485. const void * ret = gathered.item(curIndex++);
  8486. if (stepCompare->docompare(ret, seek, numFields) >= 0)
  8487. {
  8488. processed++;
  8489. return ret;
  8490. }
  8491. ReleaseRoxieRow(ret);
  8492. }
  8493. curIndex = 0;
  8494. gathered.kill();
  8495. //nextSteppedGE never returns an end of group marker.
  8496. }
  8497. //Not completely sure about this - it could lead the the start of a group being skipped,
  8498. //so the group filter could potentially work on a different group. If so, we'd need to check the
  8499. //next fields were a subset of the grouping fields - more an issue for the group activity.
  8500. //MORE: What do we do with wasCompleteMatch? something like the following????
  8501. #if 0
  8502. loop
  8503. {
  8504. const void * ret;
  8505. if (stepExtra.returnMismatches())
  8506. {
  8507. bool matchedCompletely = true;
  8508. ret = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  8509. if (!wasCompleteMatch)
  8510. return ret;
  8511. }
  8512. else
  8513. ret = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  8514. #endif
  8515. const void * ret = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  8516. while (ret)
  8517. {
  8518. gathered.append(ret);
  8519. ret = input->nextInGroup();
  8520. }
  8521. unsigned num = gathered.ordinality();
  8522. if (num != 0)
  8523. {
  8524. if (!helper.isValid(num, (const void * *)gathered.getArray()))
  8525. ReleaseRoxieRowSet(gathered); // read next group
  8526. }
  8527. else
  8528. eof = true;
  8529. return nextUngrouped(this);
  8530. }
  8531. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  8532. {
  8533. return input->gatherConjunctions(collector);
  8534. }
  8535. virtual void resetEOF()
  8536. {
  8537. eof = false;
  8538. releaseGathered();
  8539. input->resetEOF();
  8540. }
  8541. IInputSteppingMeta * querySteppingMeta()
  8542. {
  8543. return input->querySteppingMeta();
  8544. }
  8545. };
  8546. class CRoxieServerFilterGroupActivityFactory : public CRoxieServerActivityFactory
  8547. {
  8548. public:
  8549. CRoxieServerFilterGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8550. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  8551. {
  8552. }
  8553. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8554. {
  8555. return new CRoxieServerFilterGroupActivity(this, _probeManager);
  8556. }
  8557. };
  8558. IRoxieServerActivityFactory *createRoxieServerFilterGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8559. {
  8560. return new CRoxieServerFilterGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  8561. }
  8562. //=================================================================================
  8563. class CRoxieServerSideEffectActivity : public CRoxieServerActivity
  8564. {
  8565. IHThorSideEffectArg &helper;
  8566. CriticalSection ecrit;
  8567. Owned<IException> exception;
  8568. bool executed;
  8569. public:
  8570. CRoxieServerSideEffectActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8571. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorSideEffectArg &)basehelper)
  8572. {
  8573. executed = false;
  8574. }
  8575. virtual const void * nextInGroup()
  8576. {
  8577. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  8578. CriticalBlock b(ecrit);
  8579. if (exception)
  8580. throw(exception.getLink());
  8581. if (!executed)
  8582. {
  8583. try
  8584. {
  8585. executed = true;
  8586. helper.action();
  8587. }
  8588. catch(IException *E)
  8589. {
  8590. exception.set(E);
  8591. throw;
  8592. }
  8593. }
  8594. return NULL;
  8595. }
  8596. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  8597. {
  8598. CriticalBlock b(ecrit);
  8599. if (exception)
  8600. throw(exception.getLink());
  8601. if (!executed)
  8602. {
  8603. try
  8604. {
  8605. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  8606. executed = true;
  8607. start(parentExtractSize, parentExtract, false);
  8608. helper.action();
  8609. stop(false);
  8610. }
  8611. catch(IException *E)
  8612. {
  8613. ctx->notifyAbort(E);
  8614. stop(true);
  8615. exception.set(E);
  8616. throw;
  8617. }
  8618. }
  8619. }
  8620. virtual void reset()
  8621. {
  8622. executed = false;
  8623. exception.clear();
  8624. CRoxieServerActivity::reset();
  8625. }
  8626. };
  8627. class CRoxieServerSideEffectActivityFactory : public CRoxieServerActivityFactory
  8628. {
  8629. bool isRoot;
  8630. public:
  8631. CRoxieServerSideEffectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  8632. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  8633. {
  8634. }
  8635. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8636. {
  8637. return new CRoxieServerSideEffectActivity(this, _probeManager);
  8638. }
  8639. virtual bool isSink() const
  8640. {
  8641. return isRoot && !meta.queryOriginal();
  8642. }
  8643. };
  8644. IRoxieServerActivityFactory *createRoxieServerSideEffectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  8645. {
  8646. return new CRoxieServerSideEffectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  8647. }
  8648. //=================================================================================
  8649. class CRoxieServerActionActivity : public CRoxieServerInternalSinkActivity
  8650. {
  8651. IHThorActionArg &helper;
  8652. public:
  8653. CRoxieServerActionActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  8654. : CRoxieServerInternalSinkActivity(_factory, _probeManager, _numOutputs), helper((IHThorActionArg &)basehelper)
  8655. {
  8656. }
  8657. virtual void onExecute()
  8658. {
  8659. helper.action();
  8660. }
  8661. };
  8662. class CRoxieServerActionActivityFactory : public CRoxieServerInternalSinkFactory
  8663. {
  8664. public:
  8665. CRoxieServerActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  8666. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot)
  8667. {
  8668. }
  8669. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8670. {
  8671. return new CRoxieServerActionActivity(this, _probeManager, usageCount);
  8672. }
  8673. };
  8674. IRoxieServerActivityFactory *createRoxieServerActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  8675. {
  8676. return new CRoxieServerActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot);
  8677. }
  8678. //=================================================================================
  8679. class CRoxieServerSampleActivity : public CRoxieServerActivity
  8680. {
  8681. IHThorSampleArg &helper;
  8682. unsigned numSamples;
  8683. unsigned numToSkip;
  8684. unsigned whichSample;
  8685. bool anyThisGroup;
  8686. bool eof;
  8687. public:
  8688. CRoxieServerSampleActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8689. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorSampleArg &)basehelper)
  8690. {
  8691. numSamples = 0;
  8692. numToSkip = 0;
  8693. whichSample = 0;
  8694. anyThisGroup = false;
  8695. eof = false;
  8696. }
  8697. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8698. {
  8699. anyThisGroup = false;
  8700. eof = false;
  8701. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8702. numSamples = helper.getProportion();
  8703. whichSample = helper.getSampleNumber();
  8704. numToSkip = (whichSample ? whichSample-1 : 0);
  8705. }
  8706. virtual const void * nextInGroup()
  8707. {
  8708. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  8709. if (eof)
  8710. return NULL;
  8711. loop
  8712. {
  8713. const void * ret = input->nextInGroup();
  8714. if (!ret)
  8715. {
  8716. //this does work with groups - may or may not be useful...
  8717. //reset the sample for each group.... probably best.
  8718. numToSkip = (whichSample ? whichSample-1 : 0);
  8719. if (anyThisGroup)
  8720. {
  8721. anyThisGroup = false;
  8722. return NULL;
  8723. }
  8724. ret = input->nextInGroup();
  8725. if (!ret)
  8726. {
  8727. eof = true;
  8728. return NULL; // eof...
  8729. }
  8730. }
  8731. if (numToSkip == 0)
  8732. {
  8733. anyThisGroup = true;
  8734. numToSkip = numSamples-1;
  8735. processed++;
  8736. return ret;
  8737. }
  8738. numToSkip--;
  8739. ReleaseRoxieRow(ret);
  8740. }
  8741. }
  8742. };
  8743. class CRoxieServerSampleActivityFactory : public CRoxieServerActivityFactory
  8744. {
  8745. public:
  8746. CRoxieServerSampleActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8747. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  8748. {
  8749. }
  8750. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8751. {
  8752. return new CRoxieServerSampleActivity(this, _probeManager);
  8753. }
  8754. };
  8755. IRoxieServerActivityFactory *createRoxieServerSampleActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8756. {
  8757. return new CRoxieServerSampleActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  8758. }
  8759. //=================================================================================
  8760. class CRoxieServerChooseSetsActivity : public CRoxieServerActivity
  8761. {
  8762. IHThorChooseSetsArg &helper;
  8763. unsigned numSets;
  8764. unsigned * setCounts;
  8765. bool done;
  8766. public:
  8767. CRoxieServerChooseSetsActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8768. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorChooseSetsArg &)basehelper)
  8769. {
  8770. setCounts = NULL;
  8771. numSets = 0;
  8772. done = false;
  8773. }
  8774. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8775. {
  8776. done = false;
  8777. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8778. numSets = helper.getNumSets();
  8779. setCounts = new unsigned[numSets];
  8780. memset(setCounts, 0, sizeof(unsigned)*numSets);
  8781. helper.setCounts(setCounts);
  8782. }
  8783. virtual void reset()
  8784. {
  8785. delete [] setCounts;
  8786. setCounts = NULL;
  8787. CRoxieServerActivity::reset();
  8788. }
  8789. virtual const void * nextInGroup()
  8790. {
  8791. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  8792. if (done)
  8793. return NULL;
  8794. loop
  8795. {
  8796. const void * ret = input->nextInGroup();
  8797. if (!ret)
  8798. {
  8799. ret = input->nextInGroup();
  8800. if (!ret)
  8801. {
  8802. done = true;
  8803. return NULL;
  8804. }
  8805. }
  8806. processed++;
  8807. switch (helper.getRecordAction(ret))
  8808. {
  8809. case 2:
  8810. done = true;
  8811. return ret;
  8812. case 1:
  8813. return ret;
  8814. }
  8815. ReleaseRoxieRow(ret);
  8816. }
  8817. }
  8818. };
  8819. class CRoxieServerChooseSetsActivityFactory : public CRoxieServerActivityFactory
  8820. {
  8821. public:
  8822. CRoxieServerChooseSetsActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8823. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  8824. {
  8825. }
  8826. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8827. {
  8828. return new CRoxieServerChooseSetsActivity(this, _probeManager);
  8829. }
  8830. };
  8831. IRoxieServerActivityFactory *createRoxieServerChooseSetsActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8832. {
  8833. return new CRoxieServerChooseSetsActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  8834. }
  8835. //=================================================================================
  8836. class CRoxieServerChooseSetsExActivity : public CRoxieServerActivity
  8837. {
  8838. protected:
  8839. IHThorChooseSetsExArg &helper;
  8840. unsigned numSets;
  8841. unsigned curIndex;
  8842. unsigned * setCounts;
  8843. count_t * limits;
  8844. bool done;
  8845. ConstPointerArray gathered;
  8846. virtual bool includeRow(const void * row) = 0;
  8847. virtual void calculateSelection() = 0;
  8848. public:
  8849. CRoxieServerChooseSetsExActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8850. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorChooseSetsExArg &)basehelper)
  8851. {
  8852. setCounts = NULL;
  8853. limits = NULL;
  8854. done = false;
  8855. curIndex = 0;
  8856. numSets = 0;
  8857. }
  8858. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8859. {
  8860. done = false;
  8861. curIndex = 0;
  8862. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8863. numSets = helper.getNumSets();
  8864. setCounts = new unsigned[numSets];
  8865. memset(setCounts, 0, sizeof(unsigned)*numSets);
  8866. limits = (count_t *)calloc(sizeof(count_t), numSets);
  8867. helper.getLimits(limits);
  8868. }
  8869. virtual void reset()
  8870. {
  8871. delete [] setCounts;
  8872. setCounts = NULL;
  8873. free(limits);
  8874. limits = NULL;
  8875. while (gathered.isItem(curIndex))
  8876. ReleaseRoxieRow(gathered.item(curIndex++));
  8877. gathered.kill();
  8878. CRoxieServerActivity::reset();
  8879. }
  8880. virtual const void * nextInGroup()
  8881. {
  8882. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  8883. if (gathered.ordinality() == 0)
  8884. {
  8885. curIndex = 0;
  8886. if (!input->nextGroup(gathered))
  8887. {
  8888. done = true;
  8889. return NULL;
  8890. }
  8891. ForEachItemIn(idx1, gathered)
  8892. {
  8893. unsigned category = helper.getCategory(gathered.item(idx1));
  8894. if (category)
  8895. setCounts[category-1]++;
  8896. }
  8897. calculateSelection();
  8898. }
  8899. while (gathered.isItem(curIndex))
  8900. {
  8901. const void * row = gathered.item(curIndex);
  8902. gathered.replace(NULL, curIndex);
  8903. curIndex++;
  8904. if (includeRow(row))
  8905. {
  8906. processed++;
  8907. return row;
  8908. }
  8909. ReleaseRoxieRow(row);
  8910. }
  8911. gathered.kill();
  8912. return NULL;
  8913. }
  8914. };
  8915. class CRoxieServerChooseSetsLastActivity : public CRoxieServerChooseSetsExActivity
  8916. {
  8917. unsigned * numToSkip;
  8918. public:
  8919. CRoxieServerChooseSetsLastActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager) : CRoxieServerChooseSetsExActivity(_factory, _probeManager)
  8920. {
  8921. numToSkip = NULL;
  8922. }
  8923. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8924. {
  8925. CRoxieServerChooseSetsExActivity::start(parentExtractSize, parentExtract, paused);
  8926. numToSkip = (unsigned *)calloc(sizeof(unsigned), numSets);
  8927. }
  8928. virtual void reset()
  8929. {
  8930. free(numToSkip);
  8931. numToSkip = NULL;
  8932. CRoxieServerChooseSetsExActivity::reset();
  8933. }
  8934. protected:
  8935. virtual void calculateSelection()
  8936. {
  8937. for (unsigned idx=0; idx < numSets; idx++)
  8938. {
  8939. if (setCounts[idx] < limits[idx])
  8940. numToSkip[idx] = 0;
  8941. else
  8942. numToSkip[idx] = (unsigned)(setCounts[idx] - limits[idx]);
  8943. }
  8944. }
  8945. virtual bool includeRow(const void * row)
  8946. {
  8947. unsigned category = helper.getCategory(row);
  8948. if (category)
  8949. {
  8950. if (numToSkip[category-1] == 0)
  8951. return true;
  8952. numToSkip[category-1]--;
  8953. }
  8954. return false;
  8955. }
  8956. };
  8957. class CRoxieServerChooseSetsEnthActivity : public CRoxieServerChooseSetsExActivity
  8958. {
  8959. count_t * counter;
  8960. public:
  8961. CRoxieServerChooseSetsEnthActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager) : CRoxieServerChooseSetsExActivity(_factory, _probeManager)
  8962. {
  8963. counter = NULL;
  8964. }
  8965. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8966. {
  8967. CRoxieServerChooseSetsExActivity::start(parentExtractSize, parentExtract, paused);
  8968. counter = (count_t *)calloc(sizeof(count_t), numSets);
  8969. }
  8970. virtual void reset()
  8971. {
  8972. free(counter);
  8973. counter = NULL;
  8974. CRoxieServerChooseSetsExActivity::reset();
  8975. }
  8976. protected:
  8977. virtual void calculateSelection()
  8978. {
  8979. }
  8980. virtual bool includeRow(const void * row)
  8981. {
  8982. unsigned category = helper.getCategory(row);
  8983. if (category)
  8984. {
  8985. assertex(category <= numSets);
  8986. counter[category-1] += limits[category-1];
  8987. if(counter[category-1] >= setCounts[category-1])
  8988. {
  8989. counter[category-1] -= setCounts[category-1];
  8990. return true;
  8991. }
  8992. }
  8993. return false;
  8994. }
  8995. };
  8996. class CRoxieServerChooseSetsEnthActivityFactory : public CRoxieServerActivityFactory
  8997. {
  8998. public:
  8999. CRoxieServerChooseSetsEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9000. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  9001. {
  9002. }
  9003. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  9004. {
  9005. return new CRoxieServerChooseSetsEnthActivity(this, _probeManager);
  9006. }
  9007. };
  9008. IRoxieServerActivityFactory *createRoxieServerChooseSetsEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9009. {
  9010. return new CRoxieServerChooseSetsEnthActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  9011. }
  9012. class CRoxieServerChooseSetsLastActivityFactory : public CRoxieServerActivityFactory
  9013. {
  9014. public:
  9015. CRoxieServerChooseSetsLastActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9016. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  9017. {
  9018. }
  9019. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  9020. {
  9021. return new CRoxieServerChooseSetsLastActivity(this, _probeManager);
  9022. }
  9023. };
  9024. IRoxieServerActivityFactory *createRoxieServerChooseSetsLastActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9025. {
  9026. return new CRoxieServerChooseSetsLastActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  9027. }
  9028. //=================================================================================
  9029. class CRoxieServerEnthActivity : public CRoxieServerActivity
  9030. {
  9031. IHThorEnthArg &helper;
  9032. unsigned __int64 numerator;
  9033. unsigned __int64 denominator;
  9034. unsigned __int64 counter;
  9035. bool eof;
  9036. public:
  9037. CRoxieServerEnthActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9038. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorEnthArg &)basehelper)
  9039. {
  9040. eof = false;
  9041. numerator = denominator = counter = 0;
  9042. }
  9043. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9044. {
  9045. eof = false;
  9046. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9047. numerator = helper.getProportionNumerator();
  9048. denominator = helper.getProportionDenominator();
  9049. if(denominator == 0) denominator = 1; //MORE: simplest way to avoid disaster in this case
  9050. counter = (helper.getSampleNumber()-1) * greatestCommonDivisor(numerator, denominator);
  9051. if (counter >= denominator)
  9052. counter %= denominator;
  9053. }
  9054. inline bool wanted()
  9055. {
  9056. counter += numerator;
  9057. if(counter >= denominator)
  9058. {
  9059. counter -= denominator;
  9060. return true;
  9061. }
  9062. return false;
  9063. }
  9064. virtual const void * nextInGroup()
  9065. {
  9066. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  9067. if (eof)
  9068. return NULL;
  9069. const void * ret;
  9070. loop
  9071. {
  9072. ret = input->nextInGroup();
  9073. if(!ret) //end of group
  9074. ret = input->nextInGroup();
  9075. if(!ret) //eof
  9076. {
  9077. eof = true;
  9078. return ret;
  9079. }
  9080. if (wanted())
  9081. return ret;
  9082. ReleaseRoxieRow(ret);
  9083. }
  9084. }
  9085. };
  9086. class CRoxieServerEnthActivityFactory : public CRoxieServerActivityFactory
  9087. {
  9088. public:
  9089. CRoxieServerEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9090. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  9091. {
  9092. }
  9093. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  9094. {
  9095. return new CRoxieServerEnthActivity(this, _probeManager);
  9096. }
  9097. };
  9098. IRoxieServerActivityFactory *createRoxieServerEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9099. {
  9100. return new CRoxieServerEnthActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  9101. }
  9102. //=================================================================================
  9103. class CRoxieServerAggregateActivity : public CRoxieServerActivity
  9104. {
  9105. IHThorAggregateArg &helper;
  9106. bool eof;
  9107. bool isInputGrouped;
  9108. bool abortEarly;
  9109. public:
  9110. CRoxieServerAggregateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9111. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorAggregateArg &)basehelper)
  9112. {
  9113. eof = false;
  9114. isInputGrouped = false;
  9115. abortEarly = false;
  9116. }
  9117. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9118. {
  9119. eof = false;
  9120. isInputGrouped = input->queryOutputMeta()->isGrouped(); // could be done earlier, in setInput?
  9121. abortEarly = !isInputGrouped && (factory->getKind() == TAKexistsaggregate); // ditto
  9122. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9123. }
  9124. virtual bool needsAllocator() const { return true; }
  9125. virtual const void * nextInGroup()
  9126. {
  9127. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  9128. if (eof)
  9129. return NULL;
  9130. const void * next = input->nextInGroup();
  9131. if (!next && isInputGrouped)
  9132. {
  9133. eof = true;
  9134. return NULL;
  9135. }
  9136. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  9137. size32_t finalSize = helper.clearAggregate(rowBuilder);
  9138. if (next)
  9139. {
  9140. finalSize = helper.processFirst(rowBuilder, next);
  9141. ReleaseRoxieRow(next);
  9142. if (!abortEarly)
  9143. {
  9144. loop
  9145. {
  9146. next = input->nextInGroup();
  9147. if (!next)
  9148. break;
  9149. finalSize = helper.processNext(rowBuilder, next);
  9150. ReleaseRoxieRow(next);
  9151. }
  9152. }
  9153. }
  9154. if (!isInputGrouped) // either read all, or aborted early
  9155. eof = true;
  9156. processed++;
  9157. return rowBuilder.finalizeRowClear(finalSize);
  9158. }
  9159. };
  9160. class CRoxieServerAggregateActivityFactory : public CRoxieServerActivityFactory
  9161. {
  9162. public:
  9163. CRoxieServerAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9164. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  9165. {
  9166. }
  9167. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  9168. {
  9169. return new CRoxieServerAggregateActivity(this, _probeManager);
  9170. }
  9171. };
  9172. IRoxieServerActivityFactory *createRoxieServerAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9173. {
  9174. return new CRoxieServerAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  9175. }
  9176. //=================================================================================
  9177. typedef unsigned t_hashPrefix;
  9178. class CRoxieServerHashAggregateActivity : public CRoxieServerActivity
  9179. {
  9180. IHThorHashAggregateArg &helper;
  9181. RowAggregator aggregated;
  9182. bool eof;
  9183. bool gathered;
  9184. bool isGroupedAggregate;
  9185. public:
  9186. CRoxieServerHashAggregateActivity(const IRoxieServerActivityFactory *_factory, bool _isGroupedAggregate, IProbeManager *_probeManager)
  9187. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorHashAggregateArg &)basehelper),
  9188. isGroupedAggregate(_isGroupedAggregate),
  9189. aggregated(helper, helper)
  9190. {
  9191. eof = false;
  9192. gathered = false;
  9193. }
  9194. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9195. {
  9196. eof = false;
  9197. gathered = false;
  9198. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9199. }
  9200. virtual void reset()
  9201. {
  9202. aggregated.reset();
  9203. CRoxieServerActivity::reset();
  9204. }
  9205. virtual bool needsAllocator() const { return true; }
  9206. virtual const void * nextInGroup()
  9207. {
  9208. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  9209. if (eof)
  9210. return NULL;
  9211. if (!gathered)
  9212. {
  9213. aggregated.start(rowAllocator);
  9214. bool eog = true;
  9215. loop
  9216. {
  9217. const void * next = input->nextInGroup();
  9218. if (!next)
  9219. {
  9220. if (isGroupedAggregate)
  9221. {
  9222. if (eog)
  9223. eof = true;
  9224. break;
  9225. }
  9226. next = input->nextInGroup();
  9227. if (!next)
  9228. break;
  9229. }
  9230. eog = false;
  9231. aggregated.addRow(next);
  9232. ReleaseRoxieRow(next);
  9233. }
  9234. gathered = true;
  9235. }
  9236. Owned<AggregateRowBuilder> next = aggregated.nextResult();
  9237. if (next)
  9238. {
  9239. processed++;
  9240. return next->finalizeRowClear();
  9241. }
  9242. if (!isGroupedAggregate)
  9243. eof = true;
  9244. aggregated.reset();
  9245. gathered = false;
  9246. return NULL;
  9247. }
  9248. };
  9249. class CRoxieServerHashAggregateActivityFactory : public CRoxieServerActivityFactory
  9250. {
  9251. public:
  9252. CRoxieServerHashAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9253. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  9254. {
  9255. isGroupedAggregate = _graphNode.getPropBool("att[@name='grouped']/@value");
  9256. }
  9257. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  9258. {
  9259. return new CRoxieServerHashAggregateActivity(this, isGroupedAggregate, _probeManager);
  9260. }
  9261. protected:
  9262. bool isGroupedAggregate;
  9263. };
  9264. IRoxieServerActivityFactory *createRoxieServerHashAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9265. {
  9266. return new CRoxieServerHashAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9267. }
  9268. //=================================================================================
  9269. class CRoxieServerDegroupActivity : public CRoxieServerActivity
  9270. {
  9271. IHThorDegroupArg &helper;
  9272. bool eof;
  9273. public:
  9274. CRoxieServerDegroupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9275. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorDegroupArg &)basehelper)
  9276. {
  9277. eof = false;
  9278. }
  9279. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9280. {
  9281. eof = false;
  9282. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9283. }
  9284. virtual const void * nextInGroup()
  9285. {
  9286. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  9287. if (eof)
  9288. return NULL;
  9289. const void * ret = input->nextInGroup();
  9290. if (!ret)
  9291. ret = input->nextInGroup();
  9292. if (ret)
  9293. processed++;
  9294. else
  9295. eof = true;
  9296. return ret;
  9297. }
  9298. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  9299. {
  9300. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  9301. if (eof)
  9302. return NULL;
  9303. const void * ret = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  9304. if (ret)
  9305. processed++;
  9306. else
  9307. eof = true;
  9308. return ret;
  9309. }
  9310. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  9311. {
  9312. return input->gatherConjunctions(collector);
  9313. }
  9314. virtual void resetEOF()
  9315. {
  9316. eof = false;
  9317. input->resetEOF();
  9318. }
  9319. IInputSteppingMeta * querySteppingMeta()
  9320. {
  9321. return input->querySteppingMeta();
  9322. }
  9323. };
  9324. class CRoxieServerDegroupActivityFactory : public CRoxieServerActivityFactory
  9325. {
  9326. public:
  9327. CRoxieServerDegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9328. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  9329. {
  9330. }
  9331. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  9332. {
  9333. return new CRoxieServerDegroupActivity(this, _probeManager);
  9334. }
  9335. };
  9336. IRoxieServerActivityFactory *createRoxieServerDegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9337. {
  9338. return new CRoxieServerDegroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  9339. }
  9340. //=================================================================================
  9341. class CRoxieServerSpillReadActivity : public CRoxieServerActivity
  9342. {
  9343. IHThorDiskReadArg &helper;
  9344. bool needTransform;
  9345. bool eof;
  9346. bool anyThisGroup;
  9347. unsigned __int64 rowLimit;
  9348. unsigned __int64 choosenLimit;
  9349. public:
  9350. CRoxieServerSpillReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9351. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorDiskReadArg &)basehelper)
  9352. {
  9353. needTransform = helper.needTransform();
  9354. rowLimit = (unsigned __int64) -1;
  9355. choosenLimit = 0;
  9356. eof = false;
  9357. anyThisGroup = false;
  9358. }
  9359. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9360. {
  9361. anyThisGroup = false;
  9362. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9363. if (helper.canMatchAny())
  9364. eof = false;
  9365. else
  9366. eof = true;
  9367. choosenLimit = helper.getChooseNLimit();
  9368. rowLimit = helper.getRowLimit();
  9369. helper.setCallback(NULL); // members should not be called - change if they are
  9370. }
  9371. virtual bool needsAllocator() const { return true; }
  9372. virtual const void * nextInGroup()
  9373. {
  9374. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  9375. if (eof)
  9376. return NULL;
  9377. if (processed==choosenLimit)
  9378. {
  9379. eof = true;
  9380. return NULL;
  9381. }
  9382. if (needTransform)
  9383. {
  9384. loop
  9385. {
  9386. const void *in = input->nextInGroup();
  9387. if (!in)
  9388. {
  9389. if (anyThisGroup)
  9390. {
  9391. anyThisGroup = false;
  9392. return NULL;
  9393. }
  9394. in = input->nextInGroup();
  9395. if (!in)
  9396. {
  9397. eof = true;
  9398. return NULL; // eof...
  9399. }
  9400. }
  9401. unsigned outSize;
  9402. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  9403. try
  9404. {
  9405. outSize = helper.transform(rowBuilder, in);
  9406. ReleaseRoxieRow(in);
  9407. }
  9408. catch (IException *E)
  9409. {
  9410. throw makeWrappedException(E);
  9411. }
  9412. if (outSize)
  9413. {
  9414. anyThisGroup = true;
  9415. processed++;
  9416. if (processed==rowLimit)
  9417. {
  9418. if (traceLevel > 4)
  9419. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  9420. helper.onLimitExceeded();
  9421. }
  9422. return rowBuilder.finalizeRowClear(outSize);
  9423. }
  9424. }
  9425. }
  9426. else
  9427. {
  9428. const void *ret = input->nextInGroup();
  9429. if (ret)
  9430. {
  9431. processed++;
  9432. if (processed==rowLimit)
  9433. {
  9434. if (traceLevel > 4)
  9435. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  9436. ReleaseClearRoxieRow(ret);
  9437. helper.onLimitExceeded(); // should not return
  9438. throwUnexpected();
  9439. }
  9440. }
  9441. return ret;
  9442. }
  9443. }
  9444. };
  9445. class CRoxieServerSpillReadActivityFactory : public CRoxieServerActivityFactory
  9446. {
  9447. public:
  9448. CRoxieServerSpillReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9449. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  9450. {
  9451. }
  9452. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  9453. {
  9454. return new CRoxieServerSpillReadActivity(this, _probeManager);
  9455. }
  9456. virtual void addDependency(unsigned source, ThorActivityKind sourceKind, unsigned sourceIdx, int controlId, const char *edgeId)
  9457. {
  9458. if (sourceKind==TAKspill || sourceKind==TAKdiskwrite) // Bit of a hack - codegen probably should differentiate
  9459. setInput(0, source, sourceIdx);
  9460. else
  9461. CRoxieServerActivityFactory::addDependency(source, kind, sourceIdx, controlId, edgeId);
  9462. }
  9463. };
  9464. IRoxieServerActivityFactory *createRoxieServerSpillReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9465. {
  9466. return new CRoxieServerSpillReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  9467. }
  9468. //=================================================================================
  9469. class CRoxieServerSpillWriteActivity : public CRoxieServerActivity
  9470. {
  9471. public:
  9472. CRoxieServerSpillWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9473. : CRoxieServerActivity(_factory, _probeManager)
  9474. {
  9475. }
  9476. ~CRoxieServerSpillWriteActivity()
  9477. {
  9478. }
  9479. virtual const void *nextInGroup()
  9480. {
  9481. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  9482. return input->nextInGroup();
  9483. }
  9484. };
  9485. //==================================================================================
  9486. class CRoxieServerDiskWriteActivity : public CRoxieServerInternalSinkActivity, implements IRoxiePublishCallback
  9487. {
  9488. protected:
  9489. Owned<IExtRowWriter> outSeq;
  9490. Owned<IOutputRowSerializer> rowSerializer;
  9491. Linked<IFileIOStream> diskout;
  9492. bool blockcompressed;
  9493. bool extend;
  9494. bool overwrite;
  9495. bool encrypted;
  9496. bool grouped;
  9497. IHThorDiskWriteArg &helper;
  9498. StringBuffer lfn; // logical filename
  9499. CachedOutputMetaData diskmeta;
  9500. Owned<IRoxieWriteHandler> writer;
  9501. bool tallycrc;
  9502. unsigned __int64 uncompressedBytesWritten;
  9503. CRC32 crc;
  9504. void updateWorkUnitResult(unsigned __int64 reccount)
  9505. {
  9506. assertex(writer);
  9507. // MORE - a lot of this is common with hthor
  9508. 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
  9509. {
  9510. WorkunitUpdate wu = ctx->updateWorkUnit();
  9511. if (wu)
  9512. {
  9513. unsigned flags = helper.getFlags();
  9514. WUFileKind fileKind;
  9515. if (TDXtemporary & flags)
  9516. fileKind = WUFileTemporary;
  9517. else if(TDXjobtemp & flags)
  9518. fileKind = WUFileJobOwned;
  9519. else if(TDWowned & flags)
  9520. fileKind = WUFileOwned;
  9521. else
  9522. fileKind = WUFileStandard;
  9523. StringArray clusters;
  9524. writer->getClusters(clusters);
  9525. wu->addFile(lfn.str(), &clusters, helper.getTempUsageCount(), fileKind, NULL);
  9526. if (!(flags & TDXtemporary) && helper.getSequence() >= 0)
  9527. {
  9528. Owned<IWUResult> result = wu->updateResultBySequence(helper.getSequence());
  9529. if (result)
  9530. {
  9531. result->setResultTotalRowCount(reccount);
  9532. result->setResultStatus(ResultStatusCalculated);
  9533. if (helper.getFlags() & TDWresult)
  9534. result->setResultFilename(lfn.str());
  9535. else
  9536. result->setResultLogicalName(lfn.str());
  9537. }
  9538. }
  9539. }
  9540. }
  9541. }
  9542. void resolve()
  9543. {
  9544. OwnedRoxieString rawLogicalName = helper.getFileName();
  9545. assertex(rawLogicalName);
  9546. assertex((helper.getFlags() & TDXtemporary) == 0);
  9547. StringArray clusters;
  9548. unsigned clusterIdx = 0;
  9549. while(true)
  9550. {
  9551. OwnedRoxieString cluster(helper.getCluster(clusterIdx));
  9552. if(!cluster)
  9553. break;
  9554. clusters.append(cluster);
  9555. clusterIdx++;
  9556. }
  9557. if (clusters.length())
  9558. {
  9559. if (extend)
  9560. throw MakeStringException(0, "Cannot combine EXTEND and CLUSTER flags on disk write of file %s", rawLogicalName.get());
  9561. }
  9562. else
  9563. {
  9564. if (roxieName.length())
  9565. clusters.append(roxieName.str());
  9566. else
  9567. clusters.append(".");
  9568. }
  9569. writer.setown(ctx->createLFN(rawLogicalName, overwrite, extend, clusters)); // MORE - if there's a workunit, use if for scope.
  9570. // MORE - need to check somewhere that single part if it's an existing file or an external one...
  9571. }
  9572. public:
  9573. CRoxieServerDiskWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9574. : CRoxieServerInternalSinkActivity(_factory, _probeManager, 0), helper((IHThorDiskWriteArg &)basehelper)
  9575. {
  9576. extend = ((helper.getFlags() & TDWextend) != 0);
  9577. overwrite = ((helper.getFlags() & TDWoverwrite) != 0);
  9578. grouped = false; // don't think we need to support it...
  9579. diskmeta.set(helper.queryDiskRecordSize());
  9580. blockcompressed = (((helper.getFlags() & TDWnewcompress) != 0) || (((helper.getFlags() & TDXcompress) != 0) && (diskmeta.getFixedSize() >= MIN_ROWCOMPRESS_RECSIZE))); //always use new compression
  9581. encrypted = false; // set later
  9582. tallycrc = true;
  9583. uncompressedBytesWritten = 0;
  9584. }
  9585. ~CRoxieServerDiskWriteActivity()
  9586. {
  9587. }
  9588. virtual bool needsAllocator() const
  9589. {
  9590. return true;
  9591. }
  9592. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9593. {
  9594. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9595. resolve();
  9596. Owned<IFileIO> io;
  9597. void *ekey;
  9598. size32_t ekeylen;
  9599. helper.getEncryptKey(ekeylen, ekey);
  9600. Owned<ICompressor> ecomp;
  9601. if (ekeylen!=0)
  9602. {
  9603. ecomp.setown(createAESCompressor256(ekeylen,ekey));
  9604. memset(ekey,0,ekeylen);
  9605. rtlFree(ekey);
  9606. encrypted = true;
  9607. blockcompressed = true;
  9608. }
  9609. if (blockcompressed)
  9610. io.setown(createCompressedFileWriter(writer->queryFile(), (diskmeta.isFixedSize() ? diskmeta.getFixedSize() : 0), extend, true, ecomp));
  9611. else
  9612. io.setown(writer->queryFile()->open(extend ? IFOwrite : IFOcreate));
  9613. if (!io)
  9614. throw MakeStringException(errno, "Failed to create%s file %s for writing", (encrypted ? " encrypted" : (blockcompressed ? " compressed" : "")), writer->queryFile()->queryFilename());
  9615. diskout.setown(createBufferedIOStream(io));
  9616. if (extend)
  9617. diskout->seek(0, IFSend);
  9618. tallycrc = !factory->queryQueryFactory().getDebugValueBool("skipFileFormatCrcCheck", false) && !(helper.getFlags() & TDRnocrccheck) && !blockcompressed;
  9619. Owned<IRowInterfaces> rowIf = createRowInterfaces(input->queryOutputMeta(), activityId, ctx->queryCodeContext());
  9620. rowSerializer.set(rowIf->queryRowSerializer());
  9621. unsigned rwFlags = rw_autoflush;
  9622. if(grouped)
  9623. rwFlags |= rw_grouped;
  9624. if(tallycrc)
  9625. rwFlags |= rw_crc;
  9626. if(!factory->queryQueryFactory().getDebugValueBool("skipFileFormatCrcCheck", false) && !(helper.getFlags() & TDRnocrccheck))
  9627. rwFlags |= rw_crc;
  9628. outSeq.setown(createRowWriter(diskout, rowIf, rwFlags));
  9629. }
  9630. virtual void stop(bool aborting)
  9631. {
  9632. if (aborting)
  9633. {
  9634. if (writer)
  9635. writer->finish(false, this);
  9636. }
  9637. else
  9638. {
  9639. outSeq->flush(&crc);
  9640. updateWorkUnitResult(processed);
  9641. uncompressedBytesWritten = outSeq->getPosition();
  9642. writer->finish(true, this);
  9643. }
  9644. writer.clear();
  9645. CRoxieServerActivity::stop(aborting);
  9646. }
  9647. virtual void reset()
  9648. {
  9649. CRoxieServerActivity::reset();
  9650. diskout.clear();
  9651. outSeq.clear();
  9652. writer.clear();
  9653. uncompressedBytesWritten = 0;
  9654. crc.reset();
  9655. }
  9656. virtual void onExecute()
  9657. {
  9658. loop
  9659. {
  9660. const void *nextrec = input->nextInGroup();
  9661. if (!nextrec)
  9662. {
  9663. nextrec = input->nextInGroup();
  9664. if (!nextrec)
  9665. break;
  9666. }
  9667. processed++;
  9668. outSeq->putRow(nextrec);
  9669. }
  9670. }
  9671. virtual void setFileProperties(IFileDescriptor *desc) const
  9672. {
  9673. IPropertyTree &partProps = desc->queryPart(0)->queryProperties(); //properties of the first file part.
  9674. IPropertyTree &fileProps = desc->queryProperties(); // properties of the logical file
  9675. if (blockcompressed)
  9676. {
  9677. // caller has already set @size from file size...
  9678. fileProps.setPropBool("@blockCompressed", true);
  9679. fileProps.setPropInt64("@compressedSize", partProps.getPropInt64("@size", 0));
  9680. partProps.setPropInt64("@compressedSize", partProps.getPropInt64("@size", 0));
  9681. fileProps.setPropInt64("@size", uncompressedBytesWritten);
  9682. partProps.setPropInt64("@size", uncompressedBytesWritten);
  9683. }
  9684. else if (tallycrc)
  9685. partProps.setPropInt64("@fileCrc", crc.get());
  9686. if (encrypted)
  9687. fileProps.setPropBool("@encrypted", true);
  9688. fileProps.setPropInt64("@recordCount", processed);
  9689. unsigned flags = helper.getFlags();
  9690. if (flags & TDWpersist)
  9691. fileProps.setPropBool("@persistent", true);
  9692. if (grouped)
  9693. fileProps.setPropBool("@grouped", true);
  9694. if (flags & (TDWowned|TDXjobtemp|TDXtemporary))
  9695. fileProps.setPropBool("@owned", true);
  9696. if (flags & TDWresult)
  9697. fileProps.setPropBool("@result", true);
  9698. IConstWorkUnit *workUnit = ctx->queryWorkUnit();
  9699. if (workUnit)
  9700. {
  9701. SCMStringBuffer owner, wuid, job;
  9702. fileProps.setProp("@owner", workUnit->getUser(owner).str());
  9703. fileProps.setProp("@workunit", workUnit->getWuid(wuid).str());
  9704. fileProps.setProp("@job", workUnit->getJobName(job).str());
  9705. }
  9706. if (flags & TDWexpires)
  9707. setExpiryTime(fileProps, helper.getExpiryDays());
  9708. if (flags & TDWupdate)
  9709. {
  9710. unsigned eclCRC;
  9711. unsigned __int64 totalCRC;
  9712. helper.getUpdateCRCs(eclCRC, totalCRC);
  9713. fileProps.setPropInt("@eclCRC", eclCRC);
  9714. fileProps.setPropInt64("@totalCRC", totalCRC);
  9715. }
  9716. fileProps.setPropInt("@formatCrc", helper.getFormatCrc());
  9717. IRecordSize * inputMeta = input->queryOutputMeta();
  9718. if ((inputMeta->isFixedSize()) && !isOutputTransformed())
  9719. fileProps.setPropInt("@recordSize", inputMeta->getFixedSize() + (grouped ? 1 : 0));
  9720. const char *recordECL = helper.queryRecordECL();
  9721. if (recordECL && *recordECL)
  9722. fileProps.setProp("ECL", recordECL);
  9723. fileProps.setProp("@kind", "flat"); // default, derivitives may override
  9724. }
  9725. virtual IUserDescriptor *queryUserDescriptor() const
  9726. {
  9727. IConstWorkUnit *workUnit = ctx->queryWorkUnit();
  9728. if (workUnit)
  9729. return workUnit->queryUserDescriptor();
  9730. else
  9731. return NULL;
  9732. }
  9733. virtual bool isOutputTransformed() const { return false; }
  9734. };
  9735. //=================================================================================
  9736. class CRoxieServerCsvWriteActivity : public CRoxieServerDiskWriteActivity
  9737. {
  9738. IHThorCsvWriteArg &csvHelper;
  9739. CSVOutputStream csvOutput;
  9740. public:
  9741. CRoxieServerCsvWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9742. : CRoxieServerDiskWriteActivity(_factory, _probeManager), csvHelper(static_cast<IHThorCsvWriteArg &>(helper))
  9743. {
  9744. csvOutput.init(csvHelper.queryCsvParameters(), false);
  9745. }
  9746. virtual void onExecute()
  9747. {
  9748. OwnedRoxieString header(csvHelper.queryCsvParameters()->getHeader());
  9749. if (header)
  9750. {
  9751. csvOutput.beginLine();
  9752. csvOutput.writeHeaderLn(strlen(header), header);
  9753. diskout->write(csvOutput.length(), csvOutput.str());
  9754. }
  9755. loop
  9756. {
  9757. const void *nextrec = input->nextInGroup();
  9758. if (!nextrec)
  9759. {
  9760. nextrec = input->nextInGroup();
  9761. if (!nextrec)
  9762. break;
  9763. }
  9764. processed++;
  9765. csvOutput.beginLine();
  9766. csvHelper.writeRow((const byte *)nextrec, &csvOutput);
  9767. csvOutput.endLine();
  9768. diskout->write(csvOutput.length(), csvOutput.str());
  9769. ReleaseRoxieRow(nextrec);
  9770. }
  9771. OwnedRoxieString footer(csvHelper.queryCsvParameters()->getFooter());
  9772. if (footer)
  9773. {
  9774. csvOutput.beginLine();
  9775. csvOutput.writeHeaderLn(strlen(footer), footer);
  9776. diskout->write(csvOutput.length(), csvOutput.str());
  9777. }
  9778. }
  9779. virtual void setFileProperties(IFileDescriptor *desc) const
  9780. {
  9781. CRoxieServerDiskWriteActivity::setFileProperties(desc);
  9782. IPropertyTree &props = desc->queryProperties();
  9783. props.setProp("@format","utf8n");
  9784. ICsvParameters *csvParameters = csvHelper.queryCsvParameters();
  9785. StringBuffer separator;
  9786. OwnedRoxieString rs(csvParameters->getSeparator(0));
  9787. const char *s = rs;
  9788. while (s && *s)
  9789. {
  9790. if (',' == *s)
  9791. separator.append("\\,");
  9792. else
  9793. separator.append(*s);
  9794. ++s;
  9795. }
  9796. props.setProp("@csvSeparate", separator.str());
  9797. props.setProp("@csvQuote", rs.setown(csvParameters->getQuote(0)));
  9798. props.setProp("@csvTerminate", rs.setown(csvParameters->getTerminator(0)));
  9799. props.setProp("@csvEscape", rs.setown(csvParameters->getEscape(0)));
  9800. props.setProp("@kind", "csv");
  9801. }
  9802. virtual bool isOutputTransformed() const { return true; }
  9803. };
  9804. class CRoxieServerXmlWriteActivity : public CRoxieServerDiskWriteActivity
  9805. {
  9806. IHThorXmlWriteArg &xmlHelper;
  9807. StringAttr rowTag;
  9808. public:
  9809. CRoxieServerXmlWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9810. : CRoxieServerDiskWriteActivity(_factory, _probeManager), xmlHelper(static_cast<IHThorXmlWriteArg &>(helper))
  9811. {
  9812. }
  9813. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9814. {
  9815. CRoxieServerDiskWriteActivity::start(parentExtractSize, parentExtract, paused);
  9816. OwnedRoxieString xmlpath(xmlHelper.getXmlIteratorPath());
  9817. if (!xmlpath)
  9818. rowTag.set("Row");
  9819. else
  9820. {
  9821. const char *path = xmlpath;
  9822. if (*path == '/') path++;
  9823. if (strchr(path, '/')) UNIMPLEMENTED; // more what do we do with /mydata/row
  9824. rowTag.set(path);
  9825. }
  9826. }
  9827. virtual void onExecute()
  9828. {
  9829. OwnedRoxieString suppliedHeader(xmlHelper.getHeader());
  9830. const char *header = suppliedHeader;
  9831. if (!header) header = "<Dataset>\n";
  9832. diskout->write(strlen(header), header);
  9833. CommonXmlWriter xmlOutput(xmlHelper.getXmlFlags());
  9834. loop
  9835. {
  9836. OwnedConstRoxieRow nextrec = input->nextInGroup();
  9837. if (!nextrec)
  9838. {
  9839. nextrec.setown(input->nextInGroup());
  9840. if (!nextrec)
  9841. break;
  9842. }
  9843. processed++;
  9844. xmlOutput.clear().outputBeginNested(rowTag, false);
  9845. xmlHelper.toXML((const byte *)nextrec.get(), xmlOutput);
  9846. xmlOutput.outputEndNested(rowTag);
  9847. diskout->write(xmlOutput.length(), xmlOutput.str());
  9848. }
  9849. OwnedRoxieString suppliedFooter(xmlHelper.getFooter());
  9850. const char * footer = suppliedFooter;
  9851. if (!footer) footer = "</Dataset>\n";
  9852. diskout->write(strlen(footer), footer);
  9853. }
  9854. virtual void reset()
  9855. {
  9856. CRoxieServerDiskWriteActivity::reset();
  9857. rowTag.clear();
  9858. }
  9859. virtual void setFileProperties(IFileDescriptor *desc) const
  9860. {
  9861. CRoxieServerDiskWriteActivity::setFileProperties(desc);
  9862. desc->queryProperties().setProp("@format","utf8n");
  9863. desc->queryProperties().setProp("@rowTag",rowTag.get());
  9864. desc->queryProperties().setProp("@kind", "xml");
  9865. }
  9866. virtual bool isOutputTransformed() const { return true; }
  9867. };
  9868. class CRoxieServerDiskWriteActivityFactory : public CRoxieServerMultiOutputFactory
  9869. {
  9870. bool isRoot;
  9871. bool isTemp;
  9872. public:
  9873. CRoxieServerDiskWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  9874. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  9875. {
  9876. Owned<IHThorDiskWriteArg> helper = (IHThorDiskWriteArg *) helperFactory();
  9877. isTemp = (helper->getFlags() & TDXtemporary) != 0;
  9878. setNumOutputs(helper->getTempUsageCount());
  9879. if (_kind!=TAKdiskwrite)
  9880. assertex(numOutputs == 0);
  9881. }
  9882. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  9883. {
  9884. switch (numOutputs)
  9885. {
  9886. case 0:
  9887. switch (kind)
  9888. {
  9889. case TAKdiskwrite: return new CRoxieServerDiskWriteActivity(this, _probeManager);
  9890. case TAKcsvwrite: return new CRoxieServerCsvWriteActivity(this, _probeManager);
  9891. case TAKxmlwrite: return new CRoxieServerXmlWriteActivity(this, _probeManager);
  9892. };
  9893. throwUnexpected();
  9894. case 1:
  9895. return new CRoxieServerSpillWriteActivity(this, _probeManager);
  9896. default:
  9897. return new CRoxieServerThroughSpillActivity(this, _probeManager, numOutputs);
  9898. }
  9899. }
  9900. virtual bool isSink() const
  9901. {
  9902. return numOutputs == 0 && !isTemp; // MORE - check with Gavin if this is right if not a temp but reread in same job...
  9903. }
  9904. };
  9905. IRoxieServerActivityFactory *createRoxieServerDiskWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  9906. {
  9907. return new CRoxieServerDiskWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  9908. }
  9909. //=================================================================================
  9910. class CRoxieServerIndexWriteActivity : public CRoxieServerInternalSinkActivity, implements IRoxiePublishCallback
  9911. {
  9912. IHThorIndexWriteArg &helper;
  9913. bool overwrite;
  9914. Owned<ClusterWriteHandler> clusterHandler;
  9915. Owned<IRoxieWriteHandler> writer;
  9916. unsigned __int64 reccount;
  9917. unsigned int fileCrc;
  9918. StringBuffer filename;
  9919. void updateWorkUnitResult()
  9920. {
  9921. 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
  9922. {
  9923. WorkunitUpdate wu = ctx->updateWorkUnit();
  9924. if (wu)
  9925. {
  9926. if (!(helper.getFlags() & TDXtemporary) && helper.getSequence() >= 0)
  9927. {
  9928. Owned<IWUResult> result = wu->updateResultBySequence(helper.getSequence());
  9929. if (result)
  9930. {
  9931. result->setResultTotalRowCount(reccount);
  9932. result->setResultStatus(ResultStatusCalculated);
  9933. result->setResultLogicalName(filename.str());
  9934. }
  9935. }
  9936. if(clusterHandler)
  9937. clusterHandler->finish(writer->queryFile());
  9938. }
  9939. CTXLOG("Created roxie index file %s", filename.str());
  9940. }
  9941. }
  9942. virtual void resolve()
  9943. {
  9944. StringArray clusters;
  9945. unsigned clusterIdx = 0;
  9946. while(true)
  9947. {
  9948. OwnedRoxieString cluster(helper.getCluster(clusterIdx));
  9949. if(!cluster)
  9950. break;
  9951. clusters.append(cluster);
  9952. clusterIdx++;
  9953. }
  9954. if (roxieName.length())
  9955. clusters.append(roxieName.str());
  9956. else
  9957. clusters.append(".");
  9958. OwnedRoxieString fname(helper.getFileName());
  9959. writer.setown(ctx->createLFN(fname, overwrite, false, clusters)); // MORE - if there's a workunit, use if for scope.
  9960. filename.set(writer->queryFile()->queryFilename());
  9961. if (writer->queryFile()->exists())
  9962. {
  9963. if (overwrite)
  9964. {
  9965. CTXLOG("Removing existing %s from DFS",filename.str());
  9966. writer->queryFile()->remove();
  9967. }
  9968. else
  9969. throw MakeStringException(99, "Cannot write index file %s, file already exists (missing OVERWRITE attribute?)", filename.str());
  9970. }
  9971. }
  9972. void buildUserMetadata(Owned<IPropertyTree> & metadata)
  9973. {
  9974. size32_t nameLen;
  9975. char * nameBuff;
  9976. size32_t valueLen;
  9977. char * valueBuff;
  9978. unsigned idx = 0;
  9979. while(helper.getIndexMeta(nameLen, nameBuff, valueLen, valueBuff, idx++))
  9980. {
  9981. StringBuffer name(nameLen, nameBuff);
  9982. StringBuffer value(valueLen, valueBuff);
  9983. if(*nameBuff == '_' && strcmp(name, "_nodeSize") != 0)
  9984. {
  9985. OwnedRoxieString fname(helper.getFileName());
  9986. throw MakeStringException(0, "Invalid name %s in user metadata for index %s (names beginning with underscore are reserved)", name.str(), fname.get());
  9987. }
  9988. if(!validateXMLTag(name.str()))
  9989. {
  9990. OwnedRoxieString fname(helper.getFileName());
  9991. throw MakeStringException(0, "Invalid name %s in user metadata for index %s (not legal XML element name)", name.str(), fname.get());
  9992. }
  9993. if(!metadata)
  9994. metadata.setown(createPTree("metadata"));
  9995. metadata->setProp(name.str(), value.str());
  9996. }
  9997. }
  9998. void buildLayoutMetadata(Owned<IPropertyTree> & metadata)
  9999. {
  10000. if(!metadata)
  10001. metadata.setown(createPTree("metadata"));
  10002. metadata->setProp("_record_ECL", helper.queryRecordECL());
  10003. void * layoutMetaBuff;
  10004. size32_t layoutMetaSize;
  10005. if(helper.getIndexLayout(layoutMetaSize, layoutMetaBuff))
  10006. {
  10007. metadata->setPropBin("_record_layout", layoutMetaSize, layoutMetaBuff);
  10008. rtlFree(layoutMetaBuff);
  10009. }
  10010. }
  10011. public:
  10012. CRoxieServerIndexWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  10013. : CRoxieServerInternalSinkActivity(_factory, _probeManager, 0), helper(static_cast<IHThorIndexWriteArg &>(basehelper))
  10014. {
  10015. overwrite = ((helper.getFlags() & TIWoverwrite) != 0);
  10016. reccount = 0;
  10017. }
  10018. ~CRoxieServerIndexWriteActivity()
  10019. {
  10020. }
  10021. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10022. {
  10023. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  10024. resolve();
  10025. }
  10026. virtual void onExecute()
  10027. {
  10028. bool isVariable = helper.queryDiskRecordSize()->isVariableSize();
  10029. size32_t maxDiskRecordSize;
  10030. if (isVariable)
  10031. maxDiskRecordSize = 0x8000;
  10032. else
  10033. {
  10034. maxDiskRecordSize = helper.queryDiskRecordSize()->getFixedSize();
  10035. if (maxDiskRecordSize > 0x8000)
  10036. throw MakeStringException(99, "Index minimum record length (%d) exceeds 32k internal limit", maxDiskRecordSize);
  10037. }
  10038. OwnedMalloc<char> rowBuffer(maxDiskRecordSize, true);
  10039. unsigned __int64 fileSize = 0;
  10040. fileCrc = -1;
  10041. OwnedRoxieString dsName(helper.getFileName());
  10042. if (dsName.get())
  10043. {
  10044. Owned<const IResolvedFile> dsFileInfo = resolveLFN(dsName, false);
  10045. if (dsFileInfo)
  10046. {
  10047. fileSize = dsFileInfo->getFileSize();
  10048. }
  10049. }
  10050. {
  10051. Owned<IFileIO> io;
  10052. try
  10053. {
  10054. io.setown(writer->queryFile()->open(IFOcreate));
  10055. }
  10056. catch(IException * e)
  10057. {
  10058. e->Release();
  10059. clearKeyStoreCache(false);
  10060. io.setown(writer->queryFile()->open(IFOcreate));
  10061. }
  10062. if(!io)
  10063. throw MakeStringException(errno, "Failed to create file %s for writing", filename.str());
  10064. Owned<IFileIOStream> out = createIOStream(io);
  10065. unsigned flags = COL_PREFIX | HTREE_FULLSORT_KEY;
  10066. if (helper.getFlags() & TIWrowcompress)
  10067. flags |= HTREE_COMPRESSED_KEY|HTREE_QUICK_COMPRESSED_KEY;
  10068. else if (!(helper.getFlags() & TIWnolzwcompress))
  10069. flags |= HTREE_COMPRESSED_KEY;
  10070. if (isVariable)
  10071. flags |= HTREE_VARSIZE;
  10072. Owned<IPropertyTree> metadata;
  10073. buildUserMetadata(metadata);
  10074. buildLayoutMetadata(metadata);
  10075. unsigned nodeSize = metadata ? metadata->getPropInt("_nodeSize", NODESIZE) : NODESIZE;
  10076. Owned<IKeyBuilder> builder = createKeyBuilder(out, flags, maxDiskRecordSize, fileSize, nodeSize, helper.getKeyedSize(), 0);
  10077. class BcWrapper : implements IBlobCreator
  10078. {
  10079. IKeyBuilder *builder;
  10080. public:
  10081. BcWrapper(IKeyBuilder *_builder) : builder(_builder) {}
  10082. virtual unsigned __int64 createBlob(size32_t size, const void * ptr)
  10083. {
  10084. return builder->createBlob(size, (const char *) ptr);
  10085. }
  10086. } bc(builder);
  10087. // Loop thru the results
  10088. loop
  10089. {
  10090. OwnedConstRoxieRow nextrec(input->nextInGroup());
  10091. if (!nextrec)
  10092. {
  10093. nextrec.setown(input->nextInGroup());
  10094. if (!nextrec)
  10095. break;
  10096. }
  10097. try
  10098. {
  10099. unsigned __int64 fpos;
  10100. RtlStaticRowBuilder rowBuilder(rowBuffer, maxDiskRecordSize);
  10101. size32_t thisSize = helper.transform(rowBuilder, nextrec, &bc, fpos);
  10102. builder->processKeyData(rowBuffer, fpos, thisSize);
  10103. }
  10104. catch(IException * e)
  10105. {
  10106. throw makeWrappedException(e);
  10107. }
  10108. reccount++;
  10109. }
  10110. if(metadata)
  10111. builder->finish(metadata,&fileCrc);
  10112. else
  10113. builder->finish(&fileCrc);
  10114. }
  10115. }
  10116. virtual void stop(bool aborting)
  10117. {
  10118. if (writer)
  10119. {
  10120. if (!aborting)
  10121. updateWorkUnitResult();
  10122. writer->finish(!aborting, this);
  10123. writer.clear();
  10124. }
  10125. CRoxieServerActivity::stop(aborting);
  10126. }
  10127. virtual void reset()
  10128. {
  10129. CRoxieServerActivity::reset();
  10130. writer.clear();
  10131. }
  10132. //interface IRoxiePublishCallback
  10133. virtual void setFileProperties(IFileDescriptor *desc) const
  10134. {
  10135. IPropertyTree &partProps = desc->queryPart(0)->queryProperties(); //properties of the first file part.
  10136. IPropertyTree &fileProps = desc->queryProperties(); // properties of the logical file
  10137. // Now publish to name services
  10138. StringBuffer dir,base;
  10139. offset_t indexFileSize = writer->queryFile()->size();
  10140. if(clusterHandler)
  10141. clusterHandler->splitPhysicalFilename(dir, base);
  10142. else
  10143. splitFilename(filename.str(), &dir, &dir, &base, &base);
  10144. desc->setDefaultDir(dir.str());
  10145. //properties of the first file part.
  10146. Owned<IPropertyTree> attrs;
  10147. if(clusterHandler)
  10148. attrs.setown(createPTree("Part")); // clusterHandler is going to set attributes
  10149. else
  10150. {
  10151. // add cluster
  10152. StringBuffer mygroupname;
  10153. desc->setNumParts(1);
  10154. desc->setPartMask(base.str());
  10155. attrs.set(&desc->queryPart(0)->queryProperties());
  10156. }
  10157. attrs->setPropInt64("@size", indexFileSize);
  10158. CDateTime createTime, modifiedTime, accessedTime;
  10159. writer->queryFile()->getTime(&createTime, &modifiedTime, &accessedTime);
  10160. // round file time down to nearest sec. Nanosec accurancy is not preserved elsewhere and can lead to mismatch later.
  10161. unsigned hour, min, sec, nanosec;
  10162. modifiedTime.getTime(hour, min, sec, nanosec);
  10163. modifiedTime.setTime(hour, min, sec, 0);
  10164. StringBuffer timestr;
  10165. modifiedTime.getString(timestr);
  10166. if(timestr.length())
  10167. attrs->setProp("@modified", timestr.str());
  10168. if(clusterHandler)
  10169. clusterHandler->setDescriptorParts(desc, base.str(), attrs);
  10170. // properties of the logical file
  10171. IPropertyTree & properties = desc->queryProperties();
  10172. properties.setProp("@kind", "key");
  10173. properties.setPropInt64("@size", indexFileSize);
  10174. properties.setPropInt64("@recordCount", reccount);
  10175. SCMStringBuffer info;
  10176. WorkunitUpdate workUnit = ctx->updateWorkUnit();
  10177. if (workUnit)
  10178. {
  10179. properties.setProp("@owner", workUnit->getUser(info).str());
  10180. info.clear();
  10181. properties.setProp("@workunit", workUnit->getWuid(info).str());
  10182. info.clear();
  10183. properties.setProp("@job", workUnit->getJobName(info).str());
  10184. }
  10185. char const * rececl = helper.queryRecordECL();
  10186. if(rececl && *rececl)
  10187. properties.setProp("ECL", rececl);
  10188. if (helper.getFlags() & TIWexpires)
  10189. setExpiryTime(properties, helper.getExpiryDays());
  10190. if (helper.getFlags() & TIWupdate)
  10191. {
  10192. unsigned eclCRC;
  10193. unsigned __int64 totalCRC;
  10194. helper.getUpdateCRCs(eclCRC, totalCRC);
  10195. properties.setPropInt("@eclCRC", eclCRC);
  10196. properties.setPropInt64("@totalCRC", totalCRC);
  10197. }
  10198. properties.setPropInt("@fileCrc", fileCrc);
  10199. properties.setPropInt("@formatCrc", helper.getFormatCrc());
  10200. void * layoutMetaBuff;
  10201. size32_t layoutMetaSize;
  10202. if(helper.getIndexLayout(layoutMetaSize, layoutMetaBuff))
  10203. {
  10204. properties.setPropBin("_record_layout", layoutMetaSize, layoutMetaBuff);
  10205. rtlFree(layoutMetaBuff);
  10206. }
  10207. }
  10208. IUserDescriptor *queryUserDescriptor() const
  10209. {
  10210. IConstWorkUnit *workUnit = ctx->queryWorkUnit();
  10211. if (workUnit)
  10212. return workUnit->queryUserDescriptor();
  10213. else
  10214. return NULL;
  10215. }
  10216. };
  10217. //=================================================================================
  10218. class CRoxieServerIndexWriteActivityFactory : public CRoxieServerMultiOutputFactory
  10219. {
  10220. public:
  10221. CRoxieServerIndexWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  10222. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  10223. {
  10224. setNumOutputs(0);
  10225. }
  10226. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  10227. {
  10228. return new CRoxieServerIndexWriteActivity(this, _probeManager);
  10229. }
  10230. virtual bool isSink() const
  10231. {
  10232. return true;
  10233. }
  10234. };
  10235. IRoxieServerActivityFactory *createRoxieServerIndexWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  10236. {
  10237. return new CRoxieServerIndexWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  10238. }
  10239. //=================================================================================
  10240. static inline void getLimitType(unsigned flags, bool & limitFail, bool & limitOnFail)
  10241. {
  10242. if((flags & JFmatchAbortLimitSkips) != 0)
  10243. {
  10244. limitFail = false;
  10245. limitOnFail = false;
  10246. }
  10247. else
  10248. {
  10249. limitOnFail = ((flags & JFonfail) != 0);
  10250. limitFail = !limitOnFail;
  10251. }
  10252. }
  10253. class CRoxieServerJoinActivity : public CRoxieServerTwoInputActivity
  10254. {
  10255. enum { JSfill, JSfillleft, JSfillright, JScollate, JScompare, JSleftonly, JSrightonly } state;
  10256. IHThorJoinArg &helper;
  10257. ICompare * collate;
  10258. ICompare * collateupper;
  10259. ThorActivityKind activityKind;
  10260. bool leftOuterJoin;
  10261. bool rightOuterJoin;
  10262. bool exclude;
  10263. bool limitFail;
  10264. bool limitOnFail;
  10265. unsigned keepLimit;
  10266. unsigned joinLimit;
  10267. unsigned atmostLimit;
  10268. unsigned abortLimit;
  10269. unsigned atmostsTriggered;
  10270. bool betweenjoin;
  10271. OwnedRowArray right;
  10272. const void * left;
  10273. const void * pendingRight;
  10274. unsigned rightIndex;
  10275. BoolArray matchedRight;
  10276. bool matchedLeft;
  10277. Owned<IException> failingLimit;
  10278. ConstPointerArray filteredRight;
  10279. Owned<IRHLimitedCompareHelper> limitedhelper;
  10280. OwnedConstRoxieRow defaultLeft;
  10281. OwnedConstRoxieRow defaultRight;
  10282. Owned<IEngineRowAllocator> defaultLeftAllocator;
  10283. Owned<IEngineRowAllocator> defaultRightAllocator;
  10284. bool cloneLeft;
  10285. void createDefaultLeft()
  10286. {
  10287. if (!defaultLeft)
  10288. {
  10289. if (!defaultLeftAllocator)
  10290. defaultLeftAllocator.setown(ctx->queryCodeContext()->getRowAllocator(input->queryOutputMeta(), activityId));
  10291. RtlDynamicRowBuilder rowBuilder(defaultLeftAllocator);
  10292. size32_t thisSize = helper.createDefaultLeft(rowBuilder);
  10293. defaultLeft.setown(rowBuilder.finalizeRowClear(thisSize));
  10294. }
  10295. }
  10296. void createDefaultRight()
  10297. {
  10298. if (!defaultRight)
  10299. {
  10300. if (!defaultRightAllocator)
  10301. defaultRightAllocator.setown(ctx->queryCodeContext()->getRowAllocator(input1->queryOutputMeta(), activityId));
  10302. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  10303. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  10304. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  10305. }
  10306. }
  10307. public:
  10308. CRoxieServerJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  10309. : CRoxieServerTwoInputActivity(_factory, _probeManager), helper((IHThorJoinArg &)basehelper)
  10310. {
  10311. // MORE - some of this should be done in factory
  10312. unsigned joinFlags = helper.getJoinFlags();
  10313. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  10314. rightOuterJoin = (joinFlags & JFrightouter) != 0;
  10315. exclude = (joinFlags & JFexclude) != 0;
  10316. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  10317. getLimitType(joinFlags, limitFail, limitOnFail);
  10318. if (joinFlags & JFslidingmatch)
  10319. {
  10320. betweenjoin = true;
  10321. collate = helper.queryCompareLeftRightLower();
  10322. collateupper = helper.queryCompareLeftRightUpper();
  10323. }
  10324. else
  10325. {
  10326. betweenjoin = false;
  10327. collate = collateupper = helper.queryCompareLeftRight();
  10328. }
  10329. rightIndex = 0;
  10330. state = JSfill;
  10331. matchedLeft = false;
  10332. joinLimit = 0;
  10333. keepLimit = 0; // wait until ctx available
  10334. atmostLimit = 0; // wait until ctx available
  10335. abortLimit = 0; // wait until ctx available
  10336. atmostsTriggered = 0;
  10337. assertex((joinFlags & (JFfirst | JFfirstleft | JFfirstright)) == 0);
  10338. left = NULL;
  10339. pendingRight = NULL;
  10340. activityKind = _factory->getKind();
  10341. }
  10342. virtual bool needsAllocator() const { return true; }
  10343. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10344. {
  10345. left = NULL;
  10346. rightIndex = 0;
  10347. state = JSfill;
  10348. matchedLeft = false;
  10349. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  10350. keepLimit = helper.getKeepLimit();
  10351. if (keepLimit == 0)
  10352. keepLimit = (unsigned)-1;
  10353. atmostsTriggered = 0;
  10354. atmostLimit = helper.getJoinLimit();
  10355. if(atmostLimit == 0)
  10356. atmostLimit = (unsigned)-1;
  10357. else
  10358. assertex(!rightOuterJoin && !betweenjoin);
  10359. abortLimit = helper.getMatchAbortLimit();
  10360. if (abortLimit == 0)
  10361. abortLimit = (unsigned)-1;
  10362. if (rightOuterJoin)
  10363. createDefaultLeft();
  10364. if ((leftOuterJoin && (activityKind==TAKjoin || activityKind==TAKjoinlight || activityKind==TAKdenormalizegroup)) || limitOnFail)
  10365. createDefaultRight();
  10366. if ((helper.getJoinFlags() & JFlimitedprefixjoin) && helper.getJoinLimit())
  10367. { //limited match join (s[1..n])
  10368. limitedhelper.setown(createRHLimitedCompareHelper());
  10369. limitedhelper->init( helper.getJoinLimit(), input1, collate, helper.queryPrefixCompare() );
  10370. }
  10371. }
  10372. virtual void reset()
  10373. {
  10374. if (atmostsTriggered)
  10375. noteStatistic(STATS_ATMOST, atmostsTriggered, 1);
  10376. right.clear();
  10377. ReleaseClearRoxieRow(left);
  10378. ReleaseClearRoxieRow(pendingRight);
  10379. defaultRight.clear();
  10380. defaultLeft.clear();
  10381. CRoxieServerTwoInputActivity::reset();
  10382. }
  10383. virtual void setInput(unsigned idx, IRoxieInput *_in)
  10384. {
  10385. switch(idx)
  10386. {
  10387. case 0:
  10388. if ((helper.getJoinFlags() & JFparallel) != 0)
  10389. {
  10390. puller.setown(new CRoxieServerReadAheadInput(0)); // MORE - cant ask context for parallelJoinPreload as context is not yet set up.
  10391. puller->setInput(0, _in);
  10392. _in = puller;
  10393. }
  10394. input = _in;
  10395. break;
  10396. case 1:
  10397. input1 = _in;
  10398. break;
  10399. default:
  10400. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  10401. }
  10402. }
  10403. virtual IRoxieInput *queryOutput(unsigned idx)
  10404. {
  10405. if (idx==(unsigned)-1)
  10406. idx = 0;
  10407. return idx ? NULL : this;
  10408. }
  10409. void fillLeft()
  10410. {
  10411. matchedLeft = false;
  10412. left = input->nextInGroup();
  10413. if (!left)
  10414. left = input->nextInGroup();
  10415. if(betweenjoin && left && pendingRight && (collate->docompare(left, pendingRight) >= 0))
  10416. fillRight();
  10417. if (limitedhelper && 0==rightIndex)
  10418. {
  10419. rightIndex = 0;
  10420. right.clear();
  10421. matchedRight.kill();
  10422. if (left)
  10423. {
  10424. limitedhelper->getGroup(right,left);
  10425. ForEachItemIn(idx, right)
  10426. matchedRight.append(false);
  10427. }
  10428. }
  10429. }
  10430. void fillRight()
  10431. {
  10432. if (limitedhelper)
  10433. return;
  10434. failingLimit.clear();
  10435. if(betweenjoin && left)
  10436. {
  10437. aindex_t start = 0;
  10438. while(right.isItem(start) && (collateupper->docompare(left, right.item(start)) > 0))
  10439. start++;
  10440. if(start>0)
  10441. right.clearPart(0, start);
  10442. }
  10443. else
  10444. right.clear();
  10445. rightIndex = 0;
  10446. unsigned groupCount = 0;
  10447. const void * next;
  10448. while(true)
  10449. {
  10450. if(pendingRight)
  10451. {
  10452. next = pendingRight;
  10453. pendingRight = NULL;
  10454. }
  10455. else
  10456. {
  10457. next = input1->nextInGroup();
  10458. }
  10459. if(!rightOuterJoin && next && (!left || (collateupper->docompare(left, next) > 0))) // if right is less than left, and not right outer, can skip group
  10460. {
  10461. while(next)
  10462. {
  10463. ReleaseClearRoxieRow(next);
  10464. next = input1->nextInGroup();
  10465. }
  10466. continue;
  10467. }
  10468. while(next)
  10469. {
  10470. if(groupCount==abortLimit)
  10471. {
  10472. if(limitFail)
  10473. failLimit();
  10474. if (ctx->queryDebugContext())
  10475. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  10476. if(limitOnFail)
  10477. {
  10478. assertex(!failingLimit);
  10479. try
  10480. {
  10481. failLimit();
  10482. }
  10483. catch(IException * except)
  10484. {
  10485. failingLimit.setown(except);
  10486. }
  10487. assertex(failingLimit != NULL);
  10488. }
  10489. right.append(next);
  10490. do
  10491. {
  10492. next = input1->nextInGroup();
  10493. ReleaseRoxieRow(next);
  10494. } while(next);
  10495. break;
  10496. }
  10497. else if(groupCount==atmostLimit)
  10498. {
  10499. atmostsTriggered++;
  10500. right.clear();
  10501. groupCount = 0;
  10502. while(next)
  10503. {
  10504. ReleaseRoxieRow(next);
  10505. next = input1->nextInGroup();
  10506. }
  10507. }
  10508. else
  10509. {
  10510. right.append(next);
  10511. groupCount++;
  10512. }
  10513. next = input1->nextInGroup();
  10514. }
  10515. // 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
  10516. if(betweenjoin && left)
  10517. {
  10518. pendingRight = input1->nextInGroup();
  10519. if(!pendingRight || (collate->docompare(left, pendingRight) < 0))
  10520. break;
  10521. }
  10522. else
  10523. break;
  10524. }
  10525. matchedRight.kill();
  10526. ForEachItemIn(idx, right)
  10527. matchedRight.append(false);
  10528. }
  10529. const void * joinRecords(const void * curLeft, const void * curRight)
  10530. {
  10531. if (cloneLeft)
  10532. {
  10533. LinkRoxieRow(curLeft);
  10534. return curLeft;
  10535. }
  10536. try
  10537. {
  10538. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  10539. size32_t thisSize = helper.transform(rowBuilder, curLeft, curRight);
  10540. if (thisSize)
  10541. return rowBuilder.finalizeRowClear(thisSize);
  10542. else
  10543. return NULL;
  10544. }
  10545. catch (IException *E)
  10546. {
  10547. throw makeWrappedException(E);
  10548. }
  10549. }
  10550. const void * denormalizeRecords(const void * curLeft, ConstPointerArray & rows)
  10551. {
  10552. try
  10553. {
  10554. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  10555. unsigned numRows = rows.ordinality();
  10556. const void * right = numRows ? rows.item(0) : defaultRight.get();
  10557. size32_t thisSize = helper.transform(rowBuilder, curLeft, right, numRows, (const void * *)rows.getArray());
  10558. if (thisSize)
  10559. return rowBuilder.finalizeRowClear(thisSize);
  10560. else
  10561. return NULL;
  10562. }
  10563. catch (IException *E)
  10564. {
  10565. throw makeWrappedException(E);
  10566. }
  10567. }
  10568. const void * joinException(const void * curLeft, IException * except)
  10569. {
  10570. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  10571. size32_t thisSize = helper.onFailTransform(rowBuilder, curLeft, defaultRight, except);
  10572. return rowBuilder.finalizeRowClear(thisSize);
  10573. }
  10574. void failLimit()
  10575. {
  10576. helper.onMatchAbortLimitExceeded();
  10577. CommonXmlWriter xmlwrite(0);
  10578. if (input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  10579. {
  10580. input->queryOutputMeta()->toXML((byte *) left, xmlwrite);
  10581. }
  10582. throw MakeStringException(ROXIE_TOO_MANY_RESULTS, "More than %d match candidates in join %d for row %s", abortLimit, queryId(), xmlwrite.str());
  10583. }
  10584. virtual const void * nextInGroup()
  10585. {
  10586. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  10587. loop
  10588. {
  10589. switch (state)
  10590. {
  10591. case JSfill:
  10592. fillLeft();
  10593. state = JSfillright;
  10594. break;
  10595. case JSfillright:
  10596. fillRight();
  10597. state = JScollate;
  10598. break;
  10599. case JSfillleft:
  10600. fillLeft();
  10601. state = JScollate;
  10602. break;
  10603. case JScollate:
  10604. if (right.ordinality() == 0)
  10605. {
  10606. if (left == NULL)
  10607. return NULL;
  10608. state = JSleftonly;
  10609. }
  10610. else
  10611. {
  10612. if (!left)
  10613. state = JSrightonly;
  10614. else
  10615. {
  10616. int diff;
  10617. if(betweenjoin)
  10618. diff = ((collate->docompare(left, right.item(0)) < 0) ? -1 : ((collateupper->docompare(left, right.item(right.ordinality()-1)) > 0) ? +1 : 0));
  10619. else
  10620. diff = collate->docompare(left, right.item(0));
  10621. bool limitExceeded = right.ordinality()>abortLimit;
  10622. if (diff == 0)
  10623. {
  10624. if (limitExceeded)
  10625. {
  10626. const void * ret = NULL;
  10627. if(failingLimit)
  10628. ret = joinException(left, failingLimit);
  10629. ReleaseRoxieRow(left);
  10630. left = NULL;
  10631. state = JSfillleft;
  10632. ForEachItemIn(idx, right)
  10633. matchedRight.replace(true, idx);
  10634. if(ret)
  10635. {
  10636. processed++;
  10637. return ret;
  10638. }
  10639. }
  10640. else
  10641. {
  10642. state = JScompare;
  10643. joinLimit = keepLimit;
  10644. }
  10645. }
  10646. else if (diff < 0)
  10647. state = JSleftonly;
  10648. else if (limitExceeded)
  10649. {
  10650. // MORE - Roxie code seems to think there should be a destroyRowset(right) here....
  10651. state = JSfillright;
  10652. }
  10653. else
  10654. state = JSrightonly;
  10655. }
  10656. }
  10657. break;
  10658. case JSrightonly:
  10659. if (rightOuterJoin)
  10660. {
  10661. switch (activityKind)
  10662. {
  10663. case TAKjoin:
  10664. {
  10665. while (right.isItem(rightIndex))
  10666. {
  10667. if (!matchedRight.item(rightIndex))
  10668. {
  10669. const void * rhs = right.item(rightIndex++);
  10670. const void *ret = joinRecords(defaultLeft, rhs);
  10671. if (ret)
  10672. {
  10673. processed++;
  10674. return ret;
  10675. }
  10676. }
  10677. rightIndex++;
  10678. }
  10679. break;
  10680. }
  10681. //Probably excessive to implement the following, but possibly useful
  10682. case TAKdenormalize:
  10683. {
  10684. OwnedConstRoxieRow newLeft;
  10685. newLeft.set(defaultLeft);
  10686. unsigned rowSize = 0;
  10687. unsigned leftCount = 0;
  10688. while (right.isItem(rightIndex))
  10689. {
  10690. if (!matchedRight.item(rightIndex))
  10691. {
  10692. const void * rhs = right.item(rightIndex);
  10693. try
  10694. {
  10695. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  10696. unsigned thisSize = helper.transform(rowBuilder, newLeft, rhs, ++leftCount);
  10697. if (thisSize)
  10698. {
  10699. rowSize = thisSize;
  10700. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  10701. }
  10702. }
  10703. catch (IException *E)
  10704. {
  10705. throw makeWrappedException(E);
  10706. }
  10707. }
  10708. rightIndex++;
  10709. }
  10710. state = JSfillright;
  10711. if (rowSize)
  10712. {
  10713. processed++;
  10714. return newLeft.getClear();
  10715. }
  10716. break;
  10717. }
  10718. case TAKdenormalizegroup:
  10719. {
  10720. filteredRight.kill();
  10721. while (right.isItem(rightIndex))
  10722. {
  10723. if (!matchedRight.item(rightIndex))
  10724. filteredRight.append(right.item(rightIndex));
  10725. rightIndex++;
  10726. }
  10727. state = JSfillright;
  10728. if (filteredRight.ordinality())
  10729. {
  10730. const void * ret = denormalizeRecords(defaultLeft, filteredRight);
  10731. filteredRight.kill();
  10732. if (ret)
  10733. {
  10734. processed++;
  10735. return ret;
  10736. }
  10737. }
  10738. break;
  10739. }
  10740. }
  10741. }
  10742. state = JSfillright;
  10743. break;
  10744. case JSleftonly:
  10745. {
  10746. const void * ret = NULL;
  10747. if (!matchedLeft && leftOuterJoin)
  10748. {
  10749. switch (activityKind)
  10750. {
  10751. case TAKjoin:
  10752. ret = joinRecords(left, defaultRight);
  10753. break;
  10754. case TAKdenormalize:
  10755. ret = left;
  10756. left = NULL;
  10757. break;
  10758. case TAKdenormalizegroup:
  10759. filteredRight.kill();
  10760. ret = denormalizeRecords(left, filteredRight);
  10761. break;
  10762. }
  10763. }
  10764. ReleaseRoxieRow(left);
  10765. left = NULL;
  10766. state = JSfillleft;
  10767. if (ret)
  10768. {
  10769. processed++;
  10770. return ret;
  10771. }
  10772. break;
  10773. }
  10774. case JScompare:
  10775. if (joinLimit != 0)
  10776. {
  10777. switch (activityKind)
  10778. {
  10779. case TAKjoin:
  10780. {
  10781. while (right.isItem(rightIndex))
  10782. {
  10783. const void * rhs = right.item(rightIndex++);
  10784. if (helper.match(left, rhs))
  10785. {
  10786. matchedRight.replace(true, rightIndex-1);
  10787. matchedLeft = true;
  10788. if (!exclude)
  10789. {
  10790. const void *ret = joinRecords(left, rhs);
  10791. if (ret)
  10792. {
  10793. processed++;
  10794. joinLimit--;
  10795. return ret;
  10796. }
  10797. }
  10798. }
  10799. }
  10800. break;
  10801. }
  10802. case TAKdenormalize:
  10803. {
  10804. OwnedConstRoxieRow newLeft;
  10805. newLeft.set(left);
  10806. unsigned rowSize = 0;
  10807. unsigned leftCount = 0;
  10808. while (right.isItem(rightIndex) && joinLimit)
  10809. {
  10810. try
  10811. {
  10812. const void * rhs = right.item(rightIndex++);
  10813. if (helper.match(left, rhs))
  10814. {
  10815. matchedRight.replace(true, rightIndex-1);
  10816. matchedLeft = true;
  10817. if (!exclude)
  10818. {
  10819. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  10820. unsigned thisSize = helper.transform(rowBuilder, newLeft, rhs, ++leftCount);
  10821. if (thisSize)
  10822. {
  10823. rowSize = thisSize;
  10824. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  10825. joinLimit--;
  10826. }
  10827. }
  10828. }
  10829. }
  10830. catch (IException *E)
  10831. {
  10832. throw makeWrappedException(E);
  10833. }
  10834. }
  10835. state = JSleftonly;
  10836. rightIndex = 0;
  10837. if (rowSize)
  10838. {
  10839. processed++;
  10840. return newLeft.getClear();
  10841. }
  10842. break;
  10843. }
  10844. case TAKdenormalizegroup:
  10845. {
  10846. filteredRight.kill();
  10847. while (right.isItem(rightIndex))
  10848. {
  10849. const void * rhs = right.item(rightIndex++);
  10850. if (helper.match(left, rhs))
  10851. {
  10852. matchedRight.replace(true, rightIndex-1);
  10853. filteredRight.append(rhs);
  10854. matchedLeft = true;
  10855. if (filteredRight.ordinality()==joinLimit)
  10856. break;
  10857. }
  10858. }
  10859. state = JSleftonly;
  10860. rightIndex = 0;
  10861. if (!exclude && filteredRight.ordinality())
  10862. {
  10863. const void * ret = denormalizeRecords(left, filteredRight);
  10864. filteredRight.kill();
  10865. if (ret)
  10866. {
  10867. processed++;
  10868. return ret;
  10869. }
  10870. }
  10871. break;
  10872. }
  10873. }
  10874. }
  10875. state = JSleftonly;
  10876. rightIndex = 0;
  10877. break;
  10878. }
  10879. }
  10880. }
  10881. };
  10882. class CRoxieServerJoinActivityFactory : public CRoxieServerActivityFactory
  10883. {
  10884. unsigned input2;
  10885. unsigned input2idx;
  10886. public:
  10887. CRoxieServerJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  10888. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  10889. {
  10890. input2 = 0;
  10891. input2idx = 0;
  10892. }
  10893. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  10894. {
  10895. return new CRoxieServerJoinActivity(this, _probeManager);
  10896. }
  10897. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  10898. {
  10899. if (idx==1)
  10900. {
  10901. input2 = source;
  10902. input2idx = sourceidx;
  10903. }
  10904. else
  10905. CRoxieServerActivityFactory::setInput(idx, source, sourceidx);
  10906. }
  10907. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  10908. {
  10909. switch (idx)
  10910. {
  10911. case 1:
  10912. sourceidx = input2idx;
  10913. return input2;
  10914. case 0:
  10915. return CRoxieServerActivityFactory::getInput(idx, sourceidx);
  10916. default:
  10917. return (unsigned) -1;
  10918. }
  10919. }
  10920. virtual unsigned numInputs() const { return 2; }
  10921. };
  10922. IRoxieServerActivityFactory *createRoxieServerJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  10923. {
  10924. return new CRoxieServerJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  10925. }
  10926. //=================================================================================
  10927. #define CONCAT_READAHEAD 1000
  10928. MAKEPointerArray(RecordPullerThread, RecordPullerArray);
  10929. class CRoxieServerThreadedConcatActivity : public CRoxieServerActivity, implements IRecordPullerCallback
  10930. {
  10931. QueueOf<const void, true> buffer;
  10932. InterruptableSemaphore ready;
  10933. InterruptableSemaphore space;
  10934. CriticalSection crit;
  10935. unsigned eofs;
  10936. RecordPullerArray pullers;
  10937. unsigned numInputs;
  10938. public:
  10939. CRoxieServerThreadedConcatActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _grouped, unsigned _numInputs)
  10940. : CRoxieServerActivity(_factory, _probeManager)
  10941. {
  10942. eofs = 0;
  10943. numInputs = _numInputs;
  10944. for (unsigned i = 0; i < numInputs; i++)
  10945. pullers.append(*new RecordPullerThread(_grouped));
  10946. }
  10947. ~CRoxieServerThreadedConcatActivity()
  10948. {
  10949. ForEachItemIn(idx, pullers)
  10950. delete &pullers.item(idx);
  10951. }
  10952. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10953. {
  10954. space.reinit(CONCAT_READAHEAD);
  10955. ready.reinit();
  10956. eofs = 0;
  10957. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  10958. ForEachItemIn(idx, pullers)
  10959. {
  10960. pullers.item(idx).start(parentExtractSize, parentExtract, paused, ctx->concatPreload(), false, ctx);
  10961. // NOTE - it is ok to start the thread running while parts of the subgraph are still being started, since everything
  10962. // in the part of the subgraph that the thread uses has been started.
  10963. // Note that splitters are supposed to cope with being used when only some outputs have been started.
  10964. }
  10965. }
  10966. virtual void stop(bool aborting)
  10967. {
  10968. space.interrupt();
  10969. ready.interrupt();
  10970. ForEachItemIn(idx, pullers)
  10971. pullers.item(idx).stop(aborting);
  10972. CRoxieServerActivity::stop(aborting);
  10973. }
  10974. virtual unsigned __int64 queryLocalCycles() const
  10975. {
  10976. return 0;
  10977. }
  10978. virtual IRoxieInput *queryInput(unsigned idx) const
  10979. {
  10980. if (pullers.isItem(idx))
  10981. return pullers.item(idx).queryInput();
  10982. else
  10983. return NULL;
  10984. }
  10985. virtual void reset()
  10986. {
  10987. CRoxieServerActivity::reset();
  10988. ForEachItemIn(idx, pullers)
  10989. pullers.item(idx).reset();
  10990. ForEachItemIn(idx1, buffer)
  10991. ReleaseRoxieRow(buffer.item(idx1));
  10992. buffer.clear();
  10993. }
  10994. virtual void setInput(unsigned idx, IRoxieInput *_in)
  10995. {
  10996. if (pullers.isItem(idx))
  10997. pullers.item(idx).setInput(this, _in);
  10998. else
  10999. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  11000. }
  11001. virtual const void * nextInGroup()
  11002. {
  11003. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  11004. loop
  11005. {
  11006. {
  11007. CriticalBlock b(crit);
  11008. if (eofs==numInputs && !buffer.ordinality())
  11009. return NULL; // eof
  11010. }
  11011. ready.wait();
  11012. const void *ret;
  11013. {
  11014. CriticalBlock b(crit);
  11015. ret = buffer.dequeue();
  11016. }
  11017. if (ret)
  11018. processed++;
  11019. space.signal();
  11020. return ret;
  11021. }
  11022. }
  11023. virtual bool fireException(IException *e)
  11024. {
  11025. // called from puller thread on failure
  11026. ready.interrupt(LINK(e));
  11027. space.interrupt(e);
  11028. return true;
  11029. }
  11030. virtual void processRow(const void *row)
  11031. {
  11032. {
  11033. CriticalBlock b(crit);
  11034. buffer.enqueue(row);
  11035. }
  11036. ready.signal();
  11037. space.wait();
  11038. }
  11039. virtual void processGroup(const ConstPointerArray &rows)
  11040. {
  11041. // NOTE - a bit bizzare in that it waits for the space AFTER using it.
  11042. // But the space semaphore is only there to stop infinite readahead. And otherwise it would deadlock
  11043. // if group was larger than max(space)
  11044. {
  11045. CriticalBlock b(crit);
  11046. ForEachItemIn(idx, rows)
  11047. buffer.enqueue(rows.item(idx));
  11048. buffer.enqueue(NULL);
  11049. }
  11050. for (unsigned i2 = 0; i2 <= rows.length(); i2++) // note - does 1 extra for the null
  11051. {
  11052. ready.signal();
  11053. space.wait();
  11054. }
  11055. }
  11056. virtual void processEOG()
  11057. {
  11058. // Used when output is not grouped - just ignore
  11059. }
  11060. virtual void processDone()
  11061. {
  11062. CriticalBlock b(crit);
  11063. eofs++;
  11064. if (eofs == numInputs)
  11065. ready.signal();
  11066. }
  11067. };
  11068. class CRoxieServerOrderedConcatActivity : public CRoxieServerActivity
  11069. {
  11070. IRoxieInput *curInput;
  11071. bool eogSeen;
  11072. bool anyThisGroup;
  11073. bool grouped;
  11074. unsigned numInputs;
  11075. unsigned inputIdx;
  11076. IRoxieInput **inputArray;
  11077. public:
  11078. CRoxieServerOrderedConcatActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _grouped, unsigned _numInputs)
  11079. : CRoxieServerActivity(_factory, _probeManager)
  11080. {
  11081. eogSeen = false;
  11082. anyThisGroup = false;
  11083. grouped = _grouped;
  11084. numInputs = _numInputs;
  11085. inputIdx = 0;
  11086. inputArray = new IRoxieInput*[numInputs];
  11087. for (unsigned i = 0; i < numInputs; i++)
  11088. inputArray[i] = NULL;
  11089. }
  11090. ~CRoxieServerOrderedConcatActivity()
  11091. {
  11092. delete [] inputArray;
  11093. }
  11094. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11095. {
  11096. inputIdx = 0;
  11097. curInput = inputArray[inputIdx];
  11098. eogSeen = false;
  11099. anyThisGroup = false;
  11100. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  11101. for (unsigned i = 0; i < numInputs; i++)
  11102. inputArray[i]->start(parentExtractSize, parentExtract, paused);
  11103. }
  11104. virtual void stop(bool aborting)
  11105. {
  11106. for (unsigned i = 0; i < numInputs; i++)
  11107. inputArray[i]->stop(aborting);
  11108. CRoxieServerActivity::stop(aborting);
  11109. }
  11110. virtual unsigned __int64 queryLocalCycles() const
  11111. {
  11112. return 0;
  11113. }
  11114. virtual IRoxieInput *queryInput(unsigned idx) const
  11115. {
  11116. if (idx < numInputs)
  11117. return inputArray[idx];
  11118. else
  11119. return NULL;
  11120. }
  11121. virtual void reset()
  11122. {
  11123. CRoxieServerActivity::reset();
  11124. for (unsigned i = 0; i < numInputs; i++)
  11125. inputArray[i]->reset();
  11126. }
  11127. virtual void setInput(unsigned idx, IRoxieInput *_in)
  11128. {
  11129. inputArray[idx] = _in;
  11130. }
  11131. virtual const void * nextInGroup()
  11132. {
  11133. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  11134. if (!curInput)
  11135. return NULL; // eof
  11136. const void * next = curInput->nextInGroup();
  11137. if (next)
  11138. {
  11139. anyThisGroup = true;
  11140. eogSeen = false;
  11141. processed++;
  11142. return next;
  11143. }
  11144. else if (!eogSeen)
  11145. {
  11146. eogSeen = true;
  11147. if (grouped)
  11148. {
  11149. if (anyThisGroup)
  11150. {
  11151. anyThisGroup = false;
  11152. return NULL;
  11153. }
  11154. else
  11155. return nextInGroup();
  11156. }
  11157. else
  11158. return nextInGroup();
  11159. }
  11160. else if (inputIdx < numInputs-1)
  11161. {
  11162. inputIdx++;
  11163. curInput = inputArray[inputIdx];
  11164. eogSeen = false;
  11165. return nextInGroup();
  11166. }
  11167. else
  11168. {
  11169. curInput = NULL;
  11170. return NULL;
  11171. }
  11172. }
  11173. };
  11174. class CRoxieServerConcatActivityFactory : public CRoxieServerMultiInputFactory
  11175. {
  11176. bool ordered;
  11177. bool grouped;
  11178. public:
  11179. CRoxieServerConcatActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11180. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  11181. {
  11182. Owned <IHThorFunnelArg> helper = (IHThorFunnelArg *) helperFactory();
  11183. ordered = helper->isOrdered();
  11184. grouped = helper->queryOutputMeta()->isGrouped();
  11185. }
  11186. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  11187. {
  11188. if (ordered || (_probeManager && _probeManager->queryDebugManager()))
  11189. return new CRoxieServerOrderedConcatActivity(this, _probeManager, grouped, numInputs());
  11190. else
  11191. return new CRoxieServerThreadedConcatActivity(this, _probeManager, grouped, numInputs());
  11192. }
  11193. };
  11194. IRoxieServerActivityFactory *createRoxieServerConcatActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11195. {
  11196. return new CRoxieServerConcatActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  11197. }
  11198. //=================================================================================
  11199. class CRoxieServerNonEmptyActivity : public CRoxieServerMultiInputBaseActivity
  11200. {
  11201. IRoxieInput * selectedInput;
  11202. unsigned savedParentExtractSize;
  11203. const byte * savedParentExtract;
  11204. bool foundInput;
  11205. public:
  11206. CRoxieServerNonEmptyActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  11207. : CRoxieServerMultiInputBaseActivity(_factory, _probeManager, _numInputs)
  11208. {
  11209. foundInput = false;
  11210. selectedInput = NULL;
  11211. savedParentExtractSize = 0;;
  11212. savedParentExtract = NULL;
  11213. }
  11214. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11215. {
  11216. //Don't start the inputs yet so we can short-circuit...
  11217. CRoxieServerMultiInputBaseActivity::start(parentExtractSize, parentExtract, paused);
  11218. savedParentExtractSize = parentExtractSize;
  11219. savedParentExtract = parentExtract;
  11220. }
  11221. virtual void stop(bool aborting)
  11222. {
  11223. if (foundInput)
  11224. {
  11225. if (selectedInput)
  11226. selectedInput->stop(aborting);
  11227. }
  11228. else
  11229. {
  11230. for (unsigned i = 0; i < numInputs; i++)
  11231. inputArray[i]->stop(aborting);
  11232. }
  11233. CRoxieServerMultiInputBaseActivity::stop(aborting);
  11234. }
  11235. virtual void reset()
  11236. {
  11237. CRoxieServerMultiInputBaseActivity::reset();
  11238. foundInput = false;
  11239. selectedInput = NULL;
  11240. }
  11241. virtual unsigned __int64 queryLocalCycles() const
  11242. {
  11243. return 0; // Can't easily calcuate anything reliable but local processing is negligible
  11244. }
  11245. virtual const void * nextInGroup()
  11246. {
  11247. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  11248. if (!foundInput)
  11249. {
  11250. foundInput = true;
  11251. //If we get an exception in this loop then stop() will stop any started inputs
  11252. for (unsigned i=0; i < numInputs; i++)
  11253. {
  11254. selectedInput = inputArray[i];
  11255. selectedInput->start(savedParentExtractSize, savedParentExtract, false);
  11256. const void * next = selectedInput->nextInGroup();
  11257. if (next)
  11258. {
  11259. //Found a row so stop remaining
  11260. for (unsigned j=i+1; j < numInputs; j++)
  11261. inputArray[j]->stop(false);
  11262. processed++;
  11263. return next;
  11264. }
  11265. selectedInput->stop(false);
  11266. }
  11267. selectedInput = NULL;
  11268. return NULL;
  11269. }
  11270. if (!selectedInput)
  11271. return NULL;
  11272. const void * next = selectedInput->nextInGroup();
  11273. if (next)
  11274. processed++;
  11275. return next;
  11276. }
  11277. };
  11278. class CRoxieServerNonEmptyActivityFactory : public CRoxieServerMultiInputFactory
  11279. {
  11280. public:
  11281. CRoxieServerNonEmptyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11282. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  11283. {
  11284. }
  11285. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  11286. {
  11287. return new CRoxieServerNonEmptyActivity(this, _probeManager, numInputs());
  11288. }
  11289. };
  11290. IRoxieServerActivityFactory *createRoxieServerNonEmptyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11291. {
  11292. return new CRoxieServerNonEmptyActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  11293. }
  11294. //=================================================================================
  11295. class CRoxieServerMergeActivity : public CRoxieServerActivity
  11296. {
  11297. IHThorMergeArg &helper;
  11298. unsigned *mergeheap;
  11299. unsigned activeInputs;
  11300. unsigned numInputs;
  11301. IRoxieInput **inputArray;
  11302. const void **pending;
  11303. bool first;
  11304. ICompare *compare;
  11305. bool dedup;
  11306. void permute()
  11307. {
  11308. assertex(activeInputs == 0);
  11309. for(unsigned i = 0; i < numInputs; i++)
  11310. if(pullInput(i))
  11311. mergeheap[activeInputs++] = i;
  11312. // the tree structure: element p has children p*2+1 and p*2+2, or element c has parent (unsigned)(c-1)/2
  11313. // the heap property: no element should be smaller than its parent
  11314. // the dedup variant: if(dedup), the top of the heap should also not be equal to either child
  11315. // 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
  11316. if (activeInputs >= 2)
  11317. for(unsigned p = (activeInputs-2)/2; p > 0; --p)
  11318. siftDown(p);
  11319. if(dedup)
  11320. siftDownDedupTop();
  11321. else
  11322. siftDown(0);
  11323. }
  11324. void readNext()
  11325. {
  11326. if(!pullInput(mergeheap[0]))
  11327. if(!promote(0))
  11328. return;
  11329. // we have changed the element at the top of the heap, so need to sift it down to maintain the heap property
  11330. if(dedup)
  11331. siftDownDedupTop();
  11332. else
  11333. siftDown(0);
  11334. }
  11335. bool pullInput(unsigned i)
  11336. {
  11337. const void *next = inputArray[i]->nextInGroup();
  11338. if (!next)
  11339. next = inputArray[i]->nextInGroup();
  11340. pending[i] = next;
  11341. return (next != NULL);
  11342. }
  11343. bool promote(unsigned p)
  11344. {
  11345. activeInputs--;
  11346. if(activeInputs == p)
  11347. return false;
  11348. mergeheap[p] = mergeheap[activeInputs];
  11349. return true;
  11350. }
  11351. bool siftDown(unsigned p)
  11352. {
  11353. // assumimg that all descendents of p form a heap, sift p down to its correct position, and so include it in the heap
  11354. bool nochange = true;
  11355. while(1)
  11356. {
  11357. unsigned c = p*2 + 1;
  11358. if(c >= activeInputs)
  11359. return nochange;
  11360. if(c+1 < activeInputs)
  11361. {
  11362. int childcmp = BuffCompare(c+1, c);
  11363. if((childcmp < 0) || ((childcmp == 0) && (mergeheap[c+1] < mergeheap[c])))
  11364. ++c;
  11365. }
  11366. int cmp = BuffCompare(c, p);
  11367. if((cmp > 0) || ((cmp == 0) && (mergeheap[c] > mergeheap[p])))
  11368. return nochange;
  11369. nochange = false;
  11370. unsigned r = mergeheap[c];
  11371. mergeheap[c] = mergeheap[p];
  11372. mergeheap[p] = r;
  11373. p = c;
  11374. }
  11375. }
  11376. void siftDownDedupTop()
  11377. {
  11378. // same as siftDown(0), except that it also ensures that the top of the heap is not equal to either of its children
  11379. if(activeInputs < 2)
  11380. return;
  11381. unsigned c = 1;
  11382. int childcmp = 1;
  11383. if(activeInputs >= 3)
  11384. {
  11385. childcmp = BuffCompare(2, 1);
  11386. if(childcmp < 0)
  11387. c = 2;
  11388. }
  11389. int cmp = BuffCompare(c, 0);
  11390. if(cmp > 0)
  11391. return;
  11392. // the following loop ensures the correct property holds on the smaller branch, and that childcmp==0 iff the top matches the other branch
  11393. while(cmp <= 0)
  11394. {
  11395. if(cmp == 0)
  11396. {
  11397. if(mergeheap[c] < mergeheap[0])
  11398. {
  11399. unsigned r = mergeheap[c];
  11400. mergeheap[c] = mergeheap[0];
  11401. mergeheap[0] = r;
  11402. }
  11403. ReleaseClearRoxieRow(pending[mergeheap[c]]);
  11404. if(!pullInput(mergeheap[c]))
  11405. if(!promote(c))
  11406. break;
  11407. siftDown(c);
  11408. }
  11409. else
  11410. {
  11411. unsigned r = mergeheap[c];
  11412. mergeheap[c] = mergeheap[0];
  11413. mergeheap[0] = r;
  11414. if(siftDown(c))
  11415. break;
  11416. }
  11417. cmp = BuffCompare(c, 0);
  11418. }
  11419. // the following loop ensures the uniqueness property holds on the other branch too
  11420. c = 3-c;
  11421. if(activeInputs <= c)
  11422. return;
  11423. while(childcmp == 0)
  11424. {
  11425. if(mergeheap[c] < mergeheap[0])
  11426. {
  11427. unsigned r = mergeheap[c];
  11428. mergeheap[c] = mergeheap[0];
  11429. mergeheap[0] = r;
  11430. }
  11431. ReleaseClearRoxieRow(pending[mergeheap[c]]);
  11432. if(!pullInput(mergeheap[c]))
  11433. if(!promote(c))
  11434. break;
  11435. siftDown(c);
  11436. childcmp = BuffCompare(c, 0);
  11437. }
  11438. }
  11439. inline int BuffCompare(unsigned a, unsigned b)
  11440. {
  11441. return compare->docompare(pending[mergeheap[a]], pending[mergeheap[b]]);
  11442. }
  11443. public:
  11444. CRoxieServerMergeActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  11445. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorMergeArg &)basehelper), numInputs(_numInputs)
  11446. {
  11447. activeInputs = 0;
  11448. first = true;
  11449. mergeheap = new unsigned[numInputs];
  11450. inputArray = new IRoxieInput*[numInputs];
  11451. pending = new const void *[numInputs];
  11452. compare = helper.queryCompare();
  11453. dedup = helper.dedup();
  11454. for (unsigned i = 0; i < numInputs; i++)
  11455. {
  11456. inputArray[i] = NULL;
  11457. pending[i] = NULL;
  11458. }
  11459. }
  11460. ~CRoxieServerMergeActivity()
  11461. {
  11462. delete [] mergeheap;
  11463. delete [] inputArray;
  11464. delete [] pending;
  11465. }
  11466. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11467. {
  11468. activeInputs = 0;
  11469. first = true;
  11470. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  11471. for (unsigned i = 0; i < numInputs; i++)
  11472. {
  11473. inputArray[i]->start(parentExtractSize, parentExtract, paused);
  11474. }
  11475. }
  11476. virtual void stop(bool aborting)
  11477. {
  11478. for (unsigned i = 0; i < numInputs; i++)
  11479. {
  11480. inputArray[i]->stop(aborting);
  11481. }
  11482. CRoxieServerActivity::stop(aborting);
  11483. }
  11484. virtual void reset()
  11485. {
  11486. for (unsigned i = 0; i < numInputs; i++)
  11487. {
  11488. ReleaseClearRoxieRow(pending[i]);
  11489. inputArray[i]->reset();
  11490. }
  11491. CRoxieServerActivity::reset();
  11492. }
  11493. virtual void setInput(unsigned idx, IRoxieInput *_in)
  11494. {
  11495. inputArray[idx] = _in;
  11496. }
  11497. virtual const void * nextInGroup()
  11498. {
  11499. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  11500. if (first)
  11501. {
  11502. permute();
  11503. first = false;
  11504. }
  11505. if (activeInputs)
  11506. {
  11507. const void *next = pending[mergeheap[0]];
  11508. readNext();
  11509. if (next)
  11510. processed++;
  11511. return next;
  11512. }
  11513. else
  11514. return NULL;
  11515. }
  11516. };
  11517. class CRoxieServerMergeActivityFactory : public CRoxieServerMultiInputFactory
  11518. {
  11519. public:
  11520. CRoxieServerMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11521. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  11522. {
  11523. }
  11524. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  11525. {
  11526. return new CRoxieServerMergeActivity(this, _probeManager, numInputs());
  11527. }
  11528. };
  11529. IRoxieServerActivityFactory *createRoxieServerMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11530. {
  11531. return new CRoxieServerMergeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  11532. }
  11533. //=================================================================================
  11534. class CRoxieServerRegroupActivity : public CRoxieServerMultiInputActivity
  11535. {
  11536. IHThorRegroupArg &helper;
  11537. unsigned inputIndex;
  11538. bool eof;
  11539. unsigned __int64 numProcessedLastGroup;
  11540. public:
  11541. CRoxieServerRegroupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  11542. : CRoxieServerMultiInputActivity(_factory, _probeManager, _numInputs), helper((IHThorRegroupArg &)basehelper)
  11543. {
  11544. inputIndex = 0;
  11545. eof = false;
  11546. numProcessedLastGroup = 0;
  11547. }
  11548. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11549. {
  11550. inputIndex = 0;
  11551. eof = false;
  11552. numProcessedLastGroup = processed;
  11553. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  11554. }
  11555. const void * nextFromInputs()
  11556. {
  11557. unsigned initialInput = inputIndex;
  11558. while (inputIndex < numInputs)
  11559. {
  11560. const void * next = inputArray[inputIndex]->nextInGroup();
  11561. if (next)
  11562. {
  11563. if ((inputIndex != initialInput) && (inputIndex != initialInput+1))
  11564. {
  11565. ReleaseRoxieRow(next);
  11566. throw MakeStringException(ROXIE_MISMATCH_GROUP_ERROR, "Mismatched groups supplied to Regroup (%d)", factory->queryId());
  11567. }
  11568. return next;
  11569. }
  11570. inputIndex++;
  11571. }
  11572. if ((initialInput != 0) && (initialInput+1 != numInputs))
  11573. throw MakeStringException(ROXIE_MISMATCH_GROUP_ERROR, "Mismatched groups supplied to Regroup (%d)", factory->queryId());
  11574. inputIndex = 0;
  11575. return NULL;
  11576. }
  11577. virtual const void * nextInGroup()
  11578. {
  11579. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  11580. if (eof)
  11581. return NULL;
  11582. const void * ret = nextFromInputs();
  11583. if (ret)
  11584. {
  11585. processed++;
  11586. return ret;
  11587. }
  11588. if (numProcessedLastGroup != processed)
  11589. {
  11590. numProcessedLastGroup = processed;
  11591. return NULL;
  11592. }
  11593. eof = true;
  11594. return NULL;
  11595. }
  11596. #if 0
  11597. virtual void setInput(unsigned idx, IRoxieInput *_in)
  11598. {
  11599. //MORE: RKC: Do we want to do this i) always ii) conditionally iii) never
  11600. if (idx)
  11601. {
  11602. puller.setown(new CRoxieServerReadAheadInput(0)); // MORE - cant ask context for parallelJoinPreload as context is not yet set up.
  11603. puller->setInput(0, _in);
  11604. CRoxieServerMultiInputActivity::setInput(idx, puller);
  11605. }
  11606. else
  11607. CRoxieServerMultiInputActivity::setInput(idx, _in);
  11608. }
  11609. #endif
  11610. };
  11611. class CRoxieServerRegroupActivityFactory : public CRoxieServerMultiInputFactory
  11612. {
  11613. public:
  11614. CRoxieServerRegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11615. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  11616. {
  11617. }
  11618. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  11619. {
  11620. return new CRoxieServerRegroupActivity(this, _probeManager, numInputs());
  11621. }
  11622. };
  11623. IRoxieServerActivityFactory *createRoxieServerRegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11624. {
  11625. return new CRoxieServerRegroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  11626. }
  11627. //=================================================================================
  11628. class CRoxieServerCombineActivity : public CRoxieServerMultiInputActivity
  11629. {
  11630. IHThorCombineArg &helper;
  11631. unsigned __int64 numProcessedLastGroup;
  11632. public:
  11633. CRoxieServerCombineActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  11634. : CRoxieServerMultiInputActivity(_factory, _probeManager, _numInputs), helper((IHThorCombineArg &)basehelper)
  11635. {
  11636. numProcessedLastGroup = 0;
  11637. }
  11638. ~CRoxieServerCombineActivity()
  11639. {
  11640. }
  11641. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11642. {
  11643. numProcessedLastGroup = processed;
  11644. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  11645. }
  11646. void nextInputs(ConstPointerArray & out)
  11647. {
  11648. for (unsigned i=0; i < numInputs; i++)
  11649. {
  11650. const void * next = inputArray[i]->nextInGroup();
  11651. if (next)
  11652. out.append(next);
  11653. }
  11654. }
  11655. virtual bool needsAllocator() const { return true; }
  11656. virtual const void * nextInGroup()
  11657. {
  11658. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  11659. loop
  11660. {
  11661. ConstPointerArray group;
  11662. nextInputs(group);
  11663. if ((group.ordinality() == 0) && (numProcessedLastGroup == processed))
  11664. nextInputs(group);
  11665. if (group.ordinality() == 0)
  11666. {
  11667. numProcessedLastGroup = processed;
  11668. return NULL;
  11669. }
  11670. else if (group.ordinality() != numInputs)
  11671. {
  11672. ReleaseRoxieRowSet(group);
  11673. throw MakeStringException(ROXIE_MISMATCH_GROUP_ERROR, "Mismatched group input for Combine Activity(%d)", factory->queryId());
  11674. }
  11675. try
  11676. {
  11677. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11678. size32_t outSize = helper.transform(rowBuilder, group.ordinality(), group.getArray());
  11679. ReleaseRoxieRowSet(group);
  11680. if (outSize)
  11681. {
  11682. processed++;
  11683. return rowBuilder.finalizeRowClear(outSize);
  11684. }
  11685. }
  11686. catch (IException *E)
  11687. {
  11688. ReleaseRoxieRowSet(group);
  11689. throw makeWrappedException(E);
  11690. }
  11691. }
  11692. }
  11693. };
  11694. class CRoxieServerCombineActivityFactory : public CRoxieServerMultiInputFactory
  11695. {
  11696. public:
  11697. CRoxieServerCombineActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11698. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  11699. {
  11700. }
  11701. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  11702. {
  11703. return new CRoxieServerCombineActivity(this, _probeManager, numInputs());
  11704. }
  11705. };
  11706. IRoxieServerActivityFactory *createRoxieServerCombineActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11707. {
  11708. return new CRoxieServerCombineActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  11709. }
  11710. //=================================================================================
  11711. class CRoxieServerCombineGroupActivity : public CRoxieServerTwoInputActivity
  11712. {
  11713. IHThorCombineGroupArg &helper;
  11714. unsigned __int64 numProcessedLastGroup;
  11715. public:
  11716. CRoxieServerCombineGroupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  11717. : CRoxieServerTwoInputActivity(_factory, _probeManager), helper((IHThorCombineGroupArg &)basehelper)
  11718. {
  11719. numProcessedLastGroup = 0;
  11720. }
  11721. ~CRoxieServerCombineGroupActivity()
  11722. {
  11723. }
  11724. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11725. {
  11726. numProcessedLastGroup = processed;
  11727. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  11728. }
  11729. virtual void setInput(unsigned idx, IRoxieInput *_in)
  11730. {
  11731. switch(idx)
  11732. {
  11733. case 0:
  11734. #if 0
  11735. //MORE: RKC: Do we want to do this i) always ii) conditionally iii) never
  11736. puller.setown(new CRoxieServerReadAheadInput(0)); // MORE - cant ask context for parallelJoinPreload as context is not yet set up.
  11737. puller->setInput(0, _in);
  11738. _in = puller;
  11739. #endif
  11740. input = _in;
  11741. break;
  11742. case 1:
  11743. input1 = _in;
  11744. break;
  11745. default:
  11746. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  11747. }
  11748. }
  11749. virtual IRoxieInput *queryOutput(unsigned idx)
  11750. {
  11751. if (idx==(unsigned)-1)
  11752. idx = 0;
  11753. return idx ? NULL : this;
  11754. }
  11755. virtual bool needsAllocator() const { return true; }
  11756. virtual const void * nextInGroup()
  11757. {
  11758. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  11759. loop
  11760. {
  11761. const void * left = input->nextInGroup();
  11762. if (!left && (numProcessedLastGroup == processed))
  11763. left = input->nextInGroup();
  11764. if (!left)
  11765. {
  11766. if (numProcessedLastGroup == processed)
  11767. {
  11768. const void * nextRight = input1->nextInGroup();
  11769. if (nextRight)
  11770. {
  11771. ReleaseRoxieRow(nextRight);
  11772. throw MakeStringException(ROXIE_MISSING_GROUP_ERROR, "Missing LEFT record for Combine Group (%d)", factory->queryId());
  11773. }
  11774. }
  11775. else
  11776. numProcessedLastGroup = processed;
  11777. return NULL;
  11778. }
  11779. ConstPointerArray group;
  11780. loop
  11781. {
  11782. const void * in = input1->nextInGroup();
  11783. if (!in)
  11784. break;
  11785. group.append(in);
  11786. }
  11787. if (group.ordinality() == 0)
  11788. {
  11789. ReleaseRoxieRow(left);
  11790. ReleaseRoxieRowSet(group);
  11791. throw MakeStringException(ROXIE_MISSING_GROUP_ERROR, "Missing RIGHT group for Combine Group (%d)", factory->queryId());
  11792. }
  11793. try
  11794. {
  11795. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11796. size32_t outSize = helper.transform(rowBuilder, left, group.ordinality(), (const void * *)group.getArray());
  11797. ReleaseRoxieRow(left);
  11798. ReleaseRoxieRowSet(group);
  11799. if (outSize)
  11800. {
  11801. processed++;
  11802. return rowBuilder.finalizeRowClear(outSize);
  11803. }
  11804. }
  11805. catch (IException *E)
  11806. {
  11807. ReleaseRoxieRow(left);
  11808. ReleaseRoxieRowSet(group);
  11809. throw makeWrappedException(E);
  11810. }
  11811. }
  11812. }
  11813. };
  11814. class CRoxieServerCombineGroupActivityFactory : public CRoxieServerActivityFactory
  11815. {
  11816. unsigned input2;
  11817. unsigned input2idx;
  11818. public:
  11819. CRoxieServerCombineGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11820. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  11821. {
  11822. input2 = 0;
  11823. input2idx = 0;
  11824. }
  11825. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  11826. {
  11827. return new CRoxieServerCombineGroupActivity(this, _probeManager);
  11828. }
  11829. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  11830. {
  11831. if (idx==1)
  11832. {
  11833. input2 = source;
  11834. input2idx = sourceidx;
  11835. }
  11836. else
  11837. CRoxieServerActivityFactory::setInput(idx, source, sourceidx);
  11838. }
  11839. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  11840. {
  11841. switch (idx)
  11842. {
  11843. case 1:
  11844. sourceidx = input2idx;
  11845. return input2;
  11846. case 0:
  11847. return CRoxieServerActivityFactory::getInput(idx, sourceidx);
  11848. default:
  11849. return (unsigned) -1;
  11850. }
  11851. }
  11852. virtual unsigned numInputs() const { return 2; }
  11853. };
  11854. IRoxieServerActivityFactory *createRoxieServerCombineGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11855. {
  11856. return new CRoxieServerCombineGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  11857. }
  11858. //=================================================================================
  11859. class CRoxieServerRollupGroupActivity : public CRoxieServerActivity
  11860. {
  11861. IHThorRollupGroupArg &helper;
  11862. bool eof;
  11863. public:
  11864. CRoxieServerRollupGroupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  11865. : CRoxieServerActivity(_factory, _probeManager),
  11866. helper((IHThorRollupGroupArg &)basehelper)
  11867. {
  11868. eof = false;
  11869. }
  11870. ~CRoxieServerRollupGroupActivity()
  11871. {
  11872. }
  11873. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11874. {
  11875. eof = false;
  11876. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  11877. }
  11878. virtual bool needsAllocator() const { return true; }
  11879. virtual const void * nextInGroup()
  11880. {
  11881. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  11882. if (eof)
  11883. return NULL;
  11884. loop
  11885. {
  11886. ConstPointerArray group;
  11887. loop
  11888. {
  11889. const void * in = input->nextInGroup();
  11890. if (!in)
  11891. break;
  11892. group.append(in);
  11893. }
  11894. if (group.ordinality() == 0)
  11895. {
  11896. eof = true;
  11897. return NULL;
  11898. }
  11899. try
  11900. {
  11901. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11902. size32_t outSize = helper.transform(rowBuilder, group.ordinality(), (const void * *)group.getArray());
  11903. ReleaseRoxieRowSet(group);
  11904. if (outSize)
  11905. {
  11906. processed++;
  11907. return rowBuilder.finalizeRowClear(outSize);
  11908. }
  11909. }
  11910. catch (IException * E)
  11911. {
  11912. ReleaseRoxieRowSet(group);
  11913. throw makeWrappedException(E);
  11914. }
  11915. }
  11916. }
  11917. };
  11918. class CRoxieServerRollupGroupActivityFactory : public CRoxieServerActivityFactory
  11919. {
  11920. public:
  11921. CRoxieServerRollupGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11922. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  11923. {
  11924. }
  11925. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  11926. {
  11927. return new CRoxieServerRollupGroupActivity(this, _probeManager);
  11928. }
  11929. };
  11930. IRoxieServerActivityFactory *createRoxieServerRollupGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11931. {
  11932. return new CRoxieServerRollupGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  11933. }
  11934. //=================================================================================
  11935. class CRoxieServerFilterProjectActivity : public CRoxieServerLateStartActivity
  11936. {
  11937. IHThorFilterProjectArg &helper;
  11938. unsigned numProcessedLastGroup;
  11939. unsigned __int64 recordCount;
  11940. public:
  11941. CRoxieServerFilterProjectActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  11942. : CRoxieServerLateStartActivity(_factory, _probeManager), helper((IHThorFilterProjectArg &)basehelper)
  11943. {
  11944. numProcessedLastGroup = 0;
  11945. recordCount = 0;
  11946. }
  11947. ~CRoxieServerFilterProjectActivity()
  11948. {
  11949. }
  11950. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11951. {
  11952. numProcessedLastGroup = 0;
  11953. recordCount = 0;
  11954. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  11955. lateStart(parentExtractSize, parentExtract, helper.canMatchAny()); //sets eof
  11956. }
  11957. virtual bool needsAllocator() const { return true; }
  11958. virtual const void * nextInGroup()
  11959. {
  11960. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  11961. if (eof)
  11962. return NULL;
  11963. loop
  11964. {
  11965. const void * in = input->nextInGroup();
  11966. if (!in)
  11967. {
  11968. recordCount = 0;
  11969. if (numProcessedLastGroup == processed)
  11970. in = input->nextInGroup();
  11971. if (!in)
  11972. {
  11973. numProcessedLastGroup = processed;
  11974. return NULL;
  11975. }
  11976. }
  11977. try
  11978. {
  11979. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11980. size32_t outSize = helper.transform(rowBuilder, in, ++recordCount);
  11981. ReleaseRoxieRow(in);
  11982. if (outSize)
  11983. {
  11984. processed++;
  11985. return rowBuilder.finalizeRowClear(outSize);
  11986. }
  11987. }
  11988. catch (IException *E)
  11989. {
  11990. throw makeWrappedException(E);
  11991. }
  11992. }
  11993. }
  11994. };
  11995. class CRoxieServerFilterProjectActivityFactory : public CRoxieServerActivityFactory
  11996. {
  11997. public:
  11998. CRoxieServerFilterProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11999. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  12000. {
  12001. }
  12002. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  12003. {
  12004. return new CRoxieServerFilterProjectActivity(this, _probeManager);
  12005. }
  12006. };
  12007. IRoxieServerActivityFactory *createRoxieServerFilterProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  12008. {
  12009. return new CRoxieServerFilterProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  12010. }
  12011. //=================================================================================
  12012. class CRoxieServerProjectActivity : public CRoxieServerActivity
  12013. {
  12014. unsigned numProcessedLastGroup;
  12015. bool count;
  12016. unsigned __int64 recordCount;
  12017. public:
  12018. CRoxieServerProjectActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _count)
  12019. : CRoxieServerActivity(_factory, _probeManager),
  12020. count(_count)
  12021. {
  12022. numProcessedLastGroup = 0;
  12023. recordCount = 0;
  12024. }
  12025. ~CRoxieServerProjectActivity()
  12026. {
  12027. }
  12028. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12029. {
  12030. numProcessedLastGroup = 0;
  12031. recordCount = 0;
  12032. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  12033. }
  12034. virtual bool needsAllocator() const { return true; }
  12035. virtual const void * nextInGroup()
  12036. {
  12037. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  12038. loop
  12039. {
  12040. OwnedConstRoxieRow in = input->nextInGroup();
  12041. if (!in)
  12042. {
  12043. recordCount = 0;
  12044. if (numProcessedLastGroup == processed)
  12045. in.setown(input->nextInGroup());
  12046. if (!in)
  12047. {
  12048. numProcessedLastGroup = processed;
  12049. return NULL;
  12050. }
  12051. }
  12052. try
  12053. {
  12054. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12055. size32_t outSize;
  12056. if (count)
  12057. outSize = ((IHThorCountProjectArg &) basehelper).transform(rowBuilder, in, ++recordCount);
  12058. else
  12059. outSize = ((IHThorProjectArg &) basehelper).transform(rowBuilder, in);
  12060. if (outSize)
  12061. {
  12062. processed++;
  12063. return rowBuilder.finalizeRowClear(outSize);
  12064. }
  12065. }
  12066. catch (IException *E)
  12067. {
  12068. throw makeWrappedException(E);
  12069. }
  12070. }
  12071. }
  12072. };
  12073. class CRoxieServerProjectActivityFactory : public CRoxieServerActivityFactory
  12074. {
  12075. protected:
  12076. bool count;
  12077. public:
  12078. CRoxieServerProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  12079. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  12080. {
  12081. count = (_kind==TAKcountproject || _kind==TAKprefetchcountproject);
  12082. }
  12083. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  12084. {
  12085. return new CRoxieServerProjectActivity(this, _probeManager, count);
  12086. }
  12087. };
  12088. IRoxieServerActivityFactory *createRoxieServerProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  12089. {
  12090. return new CRoxieServerProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  12091. }
  12092. //=================================================================================
  12093. class CRoxieServerPrefetchProjectActivity : public CRoxieServerActivity, implements IRecordPullerCallback
  12094. {
  12095. unsigned numProcessedLastGroup;
  12096. bool count;
  12097. bool eof;
  12098. bool allPulled;
  12099. bool isThreaded;
  12100. unsigned preload;
  12101. unsigned __int64 recordCount;
  12102. IHThorPrefetchProjectArg &helper;
  12103. RecordPullerThread puller;
  12104. InterruptableSemaphore ready;
  12105. InterruptableSemaphore space;
  12106. class PrefetchInfo : public CInterface
  12107. {
  12108. public:
  12109. inline PrefetchInfo(IHThorPrefetchProjectArg &helper, const void *_in, unsigned __int64 _recordCount)
  12110. {
  12111. if (helper.preTransform(extract, _in, _recordCount))
  12112. {
  12113. in.setown(_in);
  12114. recordCount = _recordCount;
  12115. }
  12116. else
  12117. ReleaseRoxieRow(_in);
  12118. }
  12119. OwnedConstRoxieRow in;
  12120. unsigned __int64 recordCount;
  12121. rtlRowBuilder extract;
  12122. };
  12123. QueueOf<PrefetchInfo, true> pulled;
  12124. CriticalSection pulledCrit;
  12125. public:
  12126. CRoxieServerPrefetchProjectActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _count)
  12127. : CRoxieServerActivity(_factory, _probeManager),
  12128. helper((IHThorPrefetchProjectArg &) basehelper),
  12129. puller(false),
  12130. count(_count)
  12131. {
  12132. numProcessedLastGroup = 0;
  12133. recordCount = 0;
  12134. eof = false;
  12135. allPulled = false;
  12136. isThreaded = (helper.getFlags() & PPFparallel) != 0;
  12137. preload = 0;
  12138. }
  12139. ~CRoxieServerPrefetchProjectActivity()
  12140. {
  12141. while (pulled.ordinality())
  12142. ::Release(pulled.dequeue());
  12143. }
  12144. virtual void setInput(unsigned idx, IRoxieInput *_in)
  12145. {
  12146. if (idx)
  12147. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  12148. puller.setInput(this, _in);
  12149. }
  12150. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12151. {
  12152. numProcessedLastGroup = 0;
  12153. recordCount = 0;
  12154. eof = false;
  12155. allPulled = false;
  12156. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  12157. preload = helper.getLookahead();
  12158. if (!preload)
  12159. preload = ctx->prefetchProjectPreload();
  12160. space.reinit(preload);
  12161. ready.reinit();
  12162. puller.start(parentExtractSize, parentExtract, paused, preload, !isThreaded, ctx);
  12163. }
  12164. virtual void stop(bool aborting)
  12165. {
  12166. space.interrupt();
  12167. ready.interrupt();
  12168. CRoxieServerActivity::stop(aborting);
  12169. puller.stop(aborting);
  12170. }
  12171. virtual void reset()
  12172. {
  12173. CRoxieServerActivity::reset();
  12174. puller.reset();
  12175. allPulled = false;
  12176. while (pulled.ordinality())
  12177. ::Release(pulled.dequeue());
  12178. }
  12179. virtual PrefetchInfo *readNextRecord()
  12180. {
  12181. if (!isThreaded)
  12182. {
  12183. if (!allPulled) // This looks like it's thread unsafe but we are inside the if(!isThreaded) so should be ok
  12184. puller.pullRecords(1);
  12185. }
  12186. else
  12187. ready.wait();
  12188. CriticalBlock b(pulledCrit);
  12189. PrefetchInfo *ret = pulled.ordinality() ? pulled.dequeue() : NULL;
  12190. space.signal();
  12191. return ret;
  12192. }
  12193. virtual bool needsAllocator() const { return true; }
  12194. virtual const void * nextInGroup()
  12195. {
  12196. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  12197. if (eof)
  12198. return NULL;
  12199. loop
  12200. {
  12201. Owned<PrefetchInfo> in = readNextRecord();
  12202. if (!in)
  12203. {
  12204. recordCount = 0;
  12205. if (numProcessedLastGroup == processed)
  12206. in.setown(readNextRecord());
  12207. if (!in)
  12208. {
  12209. numProcessedLastGroup = processed;
  12210. eof = true;
  12211. return NULL;
  12212. }
  12213. }
  12214. try
  12215. {
  12216. if (in->in)
  12217. {
  12218. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12219. size32_t outSize;
  12220. IThorChildGraph *child = helper.queryChild();
  12221. Owned<IEclGraphResults> results;
  12222. if (child)
  12223. results.setown(child->evaluate(in->extract.size(), in->extract.getbytes()));
  12224. outSize = helper.transform(rowBuilder, in->in, results, in->recordCount);
  12225. if (outSize)
  12226. {
  12227. processed++;
  12228. return rowBuilder.finalizeRowClear(outSize);
  12229. }
  12230. }
  12231. }
  12232. catch (IException *E)
  12233. {
  12234. throw makeWrappedException(E);
  12235. }
  12236. }
  12237. }
  12238. // interface IExceptionHandler
  12239. virtual bool fireException(IException *e)
  12240. {
  12241. // called from puller thread on failure
  12242. ready.interrupt(LINK(e));
  12243. space.interrupt(e);
  12244. return true;
  12245. }
  12246. // interface IRecordPullerCallback
  12247. virtual void processRow(const void *row)
  12248. {
  12249. {
  12250. CriticalBlock b(pulledCrit);
  12251. pulled.enqueue(new PrefetchInfo(helper, row, ++recordCount));
  12252. }
  12253. if (isThreaded)
  12254. {
  12255. ready.signal();
  12256. space.wait();
  12257. }
  12258. }
  12259. virtual void processEOG()
  12260. {
  12261. {
  12262. CriticalBlock b(pulledCrit);
  12263. pulled.enqueue(NULL);
  12264. }
  12265. if (isThreaded)
  12266. {
  12267. ready.signal();
  12268. space.wait();
  12269. }
  12270. }
  12271. virtual void processGroup(const ConstPointerArray &rows)
  12272. {
  12273. throwUnexpected();
  12274. }
  12275. virtual void processDone()
  12276. {
  12277. CriticalBlock b(pulledCrit);
  12278. allPulled = true;
  12279. if (isThreaded)
  12280. ready.signal();
  12281. }
  12282. };
  12283. class CRoxieServerPrefetchProjectActivityFactory : public CRoxieServerProjectActivityFactory
  12284. {
  12285. public:
  12286. CRoxieServerPrefetchProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  12287. : CRoxieServerProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  12288. {
  12289. }
  12290. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  12291. {
  12292. return new CRoxieServerPrefetchProjectActivity(this, _probeManager, count);
  12293. }
  12294. };
  12295. extern IRoxieServerActivityFactory *createRoxieServerPrefetchProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  12296. {
  12297. return new CRoxieServerPrefetchProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  12298. }
  12299. //=================================================================================
  12300. class CPointerArrayRoxieInput : public CPseudoRoxieInput
  12301. {
  12302. public:
  12303. CPointerArrayRoxieInput()
  12304. {
  12305. rowset = NULL;
  12306. rowcount = 0;
  12307. curRow = 0;
  12308. }
  12309. void init(size32_t _rowcount, byte **_rowset)
  12310. {
  12311. rowset = _rowset;
  12312. rowcount = _rowcount;
  12313. curRow = 0;
  12314. }
  12315. virtual const void * nextInGroup()
  12316. {
  12317. if (curRow < rowcount)
  12318. {
  12319. const void * ret = rowset[curRow];
  12320. if (ret)
  12321. LinkRoxieRow(ret);
  12322. curRow++;
  12323. return ret;
  12324. }
  12325. return NULL;
  12326. }
  12327. protected:
  12328. byte **rowset;
  12329. size32_t rowcount;
  12330. size32_t curRow;
  12331. };
  12332. class CRoxieServerLoopActivity : public CRoxieServerActivity
  12333. {
  12334. protected:
  12335. IHThorLoopArg &helper;
  12336. ThorActivityKind activityKind;
  12337. unsigned maxIterations;
  12338. bool finishedLooping;
  12339. unsigned flags;
  12340. bool eof;
  12341. rtlRowBuilder loopExtractBuilder;
  12342. unsigned loopGraphId;
  12343. Linked<IOutputMetaData> counterMeta;
  12344. public:
  12345. CRoxieServerLoopActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _loopGraphId, IOutputMetaData * _counterMeta)
  12346. : CRoxieServerActivity(_factory, _probeManager),
  12347. helper((IHThorLoopArg &)basehelper), loopGraphId(_loopGraphId), counterMeta(_counterMeta)
  12348. {
  12349. eof = false;
  12350. finishedLooping = false;
  12351. activityKind = factory->getKind();
  12352. flags = helper.getFlags();
  12353. maxIterations = 0;
  12354. }
  12355. virtual bool needsAllocator() const { return true; }
  12356. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12357. {
  12358. eof = false;
  12359. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  12360. int iterations = (int) helper.numIterations();
  12361. maxIterations = (iterations >= 0) ? iterations : 0;
  12362. finishedLooping = ((activityKind == TAKloopcount) && (maxIterations == 0));
  12363. if ((flags & IHThorLoopArg::LFnewloopagain) && !helper.loopFirstTime())
  12364. finishedLooping = true;
  12365. loopExtractBuilder.clear();
  12366. helper.createParentExtract(loopExtractBuilder); // could possibly delay this until execution actually happens
  12367. }
  12368. virtual void stop(bool aborting)
  12369. {
  12370. CRoxieServerActivity::stop(aborting);
  12371. loopExtractBuilder.clear();
  12372. }
  12373. void createCounterResult(IRoxieServerChildGraph * graph, unsigned counter)
  12374. {
  12375. if (flags & IHThorLoopArg::LFcounter)
  12376. {
  12377. void * counterRow = ctx->queryRowManager().allocate(sizeof(thor_loop_counter_t), activityId);
  12378. *((thor_loop_counter_t *)counterRow) = counter;
  12379. RtlLinkedDatasetBuilder builder(rowAllocator);
  12380. builder.appendOwn(counterRow);
  12381. Owned<CGraphResult> counterResult = new CGraphResult(builder.getcount(), builder.linkrows());
  12382. graph->setInputResult(2, counterResult);
  12383. }
  12384. }
  12385. };
  12386. //=================================================================================
  12387. class CRoxieServerSequentialLoopActivity : public CRoxieServerLoopActivity
  12388. {
  12389. Owned<IActivityGraph> loopQuery;
  12390. Owned<IRoxieServerChildGraph> loopGraph;
  12391. IRoxieInput * curInput;
  12392. RtlLinkedDatasetBuilder *loopInputBuilder;
  12393. CPointerArrayRoxieInput arrayInput;
  12394. Linked<IRoxieInput> resultInput;
  12395. unsigned loopCounter;
  12396. public:
  12397. CRoxieServerSequentialLoopActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _loopGraphId, IOutputMetaData * _counterMeta)
  12398. : CRoxieServerLoopActivity(_factory, _probeManager, _loopGraphId, _counterMeta)
  12399. {
  12400. curInput = NULL;
  12401. loopCounter = 0;
  12402. loopInputBuilder = NULL;
  12403. }
  12404. virtual bool needsAllocator() const { return true; }
  12405. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  12406. {
  12407. CRoxieServerLoopActivity::onCreate(_ctx, _colocalParent);
  12408. loopQuery.set(_ctx->queryChildGraph(loopGraphId));
  12409. }
  12410. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12411. {
  12412. curInput = input;
  12413. loopCounter = 1;
  12414. CRoxieServerLoopActivity::start(parentExtractSize, parentExtract, paused);
  12415. //MORE: Not sure about this, should IRoxieServerChildGraph be combined with IActivityGraph?
  12416. loopGraph.set(loopQuery->queryLoopGraph());
  12417. loopInputBuilder = new RtlLinkedDatasetBuilder(rowAllocator);
  12418. }
  12419. virtual void stop(bool aborting)
  12420. {
  12421. delete loopInputBuilder;
  12422. loopInputBuilder = NULL;
  12423. CRoxieServerLoopActivity::stop(aborting);
  12424. }
  12425. virtual const void * nextInGroup()
  12426. {
  12427. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  12428. if (eof)
  12429. return NULL;
  12430. unsigned emptyIterations = 0;
  12431. loop
  12432. {
  12433. loop
  12434. {
  12435. const void * ret = curInput->nextInGroup();
  12436. if (!ret)
  12437. {
  12438. ret = curInput->nextInGroup(); // more cope with groups somehow....
  12439. if (!ret)
  12440. {
  12441. if (finishedLooping)
  12442. {
  12443. eof = true;
  12444. return NULL;
  12445. }
  12446. break;
  12447. }
  12448. }
  12449. if (finishedLooping ||
  12450. ((flags & IHThorLoopArg::LFfiltered) && !helper.sendToLoop(loopCounter, ret)))
  12451. {
  12452. processed++;
  12453. return ret;
  12454. }
  12455. loopInputBuilder->appendOwn(ret);
  12456. }
  12457. switch (activityKind)
  12458. {
  12459. case TAKloopdataset:
  12460. {
  12461. if (!(flags & IHThorLoopArg::LFnewloopagain))
  12462. {
  12463. if (!helper.loopAgain(loopCounter, loopInputBuilder->getcount(), (const void**) loopInputBuilder->queryrows()))
  12464. {
  12465. if (loopInputBuilder->getcount() == 0)
  12466. {
  12467. eof = true;
  12468. return NULL;
  12469. }
  12470. arrayInput.init(loopInputBuilder->getcount(), loopInputBuilder->linkrows());
  12471. // MORE - should builder be cleared here?
  12472. curInput = &arrayInput;
  12473. finishedLooping = true;
  12474. continue; // back to the input loop again
  12475. }
  12476. }
  12477. break;
  12478. }
  12479. case TAKlooprow:
  12480. if (!loopInputBuilder->getcount())
  12481. {
  12482. finishedLooping = true;
  12483. eof = true;
  12484. return NULL;
  12485. }
  12486. break;
  12487. }
  12488. if (loopInputBuilder->getcount())
  12489. emptyIterations = 0;
  12490. else
  12491. {
  12492. //note: any outputs which didn't go around the loop again, would return the record, reinitializing emptyIterations
  12493. emptyIterations++;
  12494. if (emptyIterations > maxEmptyLoopIterations)
  12495. throw MakeStringException(ROXIE_TOO_MANY_EMPTY_LOOP, "Executed LOOP with empty input and output %u times", emptyIterations);
  12496. if (emptyIterations % 32 == 0)
  12497. CTXLOG("Executing LOOP with empty input and output %u times", emptyIterations);
  12498. }
  12499. checkAbort();
  12500. try
  12501. {
  12502. Owned<IRoxieGraphResults> results = executeIteration(loopExtractBuilder.size(), loopExtractBuilder.getbytes(), loopCounter);
  12503. resultInput.setown(results->createIterator(0));
  12504. if (flags & IHThorLoopArg::LFnewloopagain)
  12505. {
  12506. Owned<IRoxieInput> againResult = results->createIterator(helper.loopAgainResult());
  12507. OwnedConstRoxieRow row = againResult->nextInGroup();
  12508. assertex(row);
  12509. //Result is a row which contains a single boolean field.
  12510. if (!((const bool *)row.get())[0])
  12511. finishedLooping = true;
  12512. }
  12513. }
  12514. catch (IException *E)
  12515. {
  12516. throw makeWrappedException(E);
  12517. }
  12518. curInput = resultInput.get();
  12519. loopCounter++;
  12520. if ((activityKind == TAKloopcount) && (loopCounter > maxIterations))
  12521. finishedLooping = true;
  12522. }
  12523. }
  12524. IRoxieGraphResults * executeIteration(unsigned parentExtractSize, const byte *parentExtract, unsigned counter)
  12525. {
  12526. try
  12527. {
  12528. loopGraph->beforeExecute();
  12529. Owned<IGraphResult> inputRowsResult = new CGraphResult(loopInputBuilder->getcount(), loopInputBuilder->linkrows());
  12530. loopInputBuilder->clear();
  12531. loopGraph->setInputResult(1, inputRowsResult);
  12532. createCounterResult(loopGraph, counter);
  12533. Owned<IRoxieGraphResults> ret = loopGraph->execute(parentExtractSize, parentExtract);
  12534. loopGraph->afterExecute();
  12535. return ret.getClear();
  12536. }
  12537. catch (...)
  12538. {
  12539. CTXLOG("Exception thrown in loop body - cleaning up");
  12540. loopGraph->afterExecute();
  12541. throw;
  12542. }
  12543. }
  12544. };
  12545. //=================================================================================
  12546. typedef SafeQueueOf<const void, true> SafeRowQueue;
  12547. class CRowQueuePseudoInput : public CPseudoRoxieInput
  12548. {
  12549. public:
  12550. CRowQueuePseudoInput(SafeRowQueue & _input) :
  12551. input(_input)
  12552. {
  12553. eof = false;
  12554. }
  12555. virtual const void * nextInGroup()
  12556. {
  12557. if (eof)
  12558. return NULL;
  12559. const void * ret = input.dequeue();
  12560. if (!ret)
  12561. eof = true;
  12562. return ret;
  12563. }
  12564. protected:
  12565. SafeRowQueue & input;
  12566. bool eof;
  12567. };
  12568. class CRoxieServerParallelLoopActivity;
  12569. class LoopFilterPseudoInput : public CIndirectRoxieInput
  12570. {
  12571. public:
  12572. LoopFilterPseudoInput(CRoxieServerParallelLoopActivity * _activity, IRoxieInput * _input, unsigned _counter) :
  12573. CIndirectRoxieInput(_input), activity(_activity), counter(_counter)
  12574. {
  12575. }
  12576. virtual const void * nextInGroup();
  12577. protected:
  12578. CRoxieServerParallelLoopActivity * activity;
  12579. unsigned counter;
  12580. };
  12581. class LoopExecutorThread : public RestartableThread
  12582. {
  12583. protected:
  12584. Owned<IRoxieInput> safeInput;
  12585. CRoxieServerParallelLoopActivity * activity;
  12586. bool eof;
  12587. CriticalSection crit;
  12588. unsigned flags;
  12589. SafeRowQueue tempResults[2];
  12590. unsigned savedParentExtractSize;
  12591. const byte * savedParentExtract;
  12592. IArrayOf<IActivityGraph> cachedGraphs;
  12593. IRoxieSlaveContext *ctx;
  12594. public:
  12595. LoopExecutorThread()
  12596. : RestartableThread("LoopExecutorThread")
  12597. {
  12598. activity = NULL;
  12599. eof = false;
  12600. flags = 0;
  12601. ctx = NULL;
  12602. savedParentExtract = NULL;
  12603. savedParentExtractSize = 0;
  12604. }
  12605. virtual IRoxieInput *queryInput(unsigned idx) const
  12606. {
  12607. return safeInput->queryInput(idx);
  12608. }
  12609. void setInput(CRoxieServerParallelLoopActivity * _activity, IRoxieInput *_input, unsigned _flags)
  12610. {
  12611. activity = _activity;
  12612. flags = _flags;
  12613. // 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.
  12614. safeInput.setown(new CSafeRoxieInput(_input));
  12615. }
  12616. IRoxieInput *queryInput() const
  12617. {
  12618. return safeInput;
  12619. }
  12620. void onCreate(IRoxieSlaveContext * _ctx);
  12621. void start(unsigned parentExtractSize, const byte *parentExtract, bool paused);
  12622. void stop(bool aborting);
  12623. void reset();
  12624. virtual int run();
  12625. protected:
  12626. void executeLoop();
  12627. void executeLoopInstance(unsigned counter, unsigned numIterations, IRoxieInput * input, SafeRowQueue * spillOutput);
  12628. IRoxieInput * createLoopIterationGraph(unsigned i, IRoxieInput * input, unsigned counter);
  12629. };
  12630. class CRoxieServerParallelLoopActivity : public CRoxieServerLoopActivity
  12631. {
  12632. friend class LoopFilterPseudoInput;
  12633. friend class LoopExecutorThread;
  12634. QueueOf<const void, true> ready;
  12635. CriticalSection helperCS;
  12636. CriticalSection cs;
  12637. size32_t sizeNumParallel;
  12638. rtlDataAttr listNumParallel;
  12639. unsigned defaultNumParallel;
  12640. LoopExecutorThread executor;
  12641. IProbeManager* probeManager;
  12642. CriticalSection canAccess;
  12643. CriticalSection scrit;
  12644. InterruptableSemaphore readySpace;
  12645. InterruptableSemaphore recordsReady;
  12646. protected:
  12647. bool includeInLoop(unsigned counter, const void * row)
  12648. {
  12649. CriticalBlock b(helperCS);
  12650. return helper.sendToLoop(counter, row);
  12651. }
  12652. public:
  12653. CRoxieServerParallelLoopActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _loopGraphId, IOutputMetaData * _counterMeta)
  12654. : CRoxieServerLoopActivity(_factory, _probeManager, _loopGraphId, _counterMeta),
  12655. readySpace(parallelLoopFlowLimit)
  12656. {
  12657. probeManager = _probeManager;
  12658. defaultNumParallel = 0;
  12659. }
  12660. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  12661. {
  12662. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  12663. executor.onCreate(_ctx);
  12664. }
  12665. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12666. {
  12667. CriticalBlock b(scrit); // can stop while still starting, if unlucky...
  12668. readySpace.reinit(parallelLoopFlowLimit);
  12669. recordsReady.reinit();
  12670. CRoxieServerLoopActivity::start(parentExtractSize, parentExtract, paused);
  12671. defaultNumParallel = helper.defaultParallelIterations();
  12672. if (!defaultNumParallel)
  12673. defaultNumParallel = DEFAULT_PARALLEL_LOOP_THREADS;
  12674. helper.numParallelIterations(sizeNumParallel, listNumParallel.refdata());
  12675. //MORE: If numIterations <= number of parallel iterations[1],
  12676. //then we don't need to create a separate thread to do the processing, and the results will also avoid
  12677. //being transferred via a queue
  12678. executor.start(parentExtractSize, parentExtract, paused);
  12679. }
  12680. virtual void setInput(unsigned idx, IRoxieInput *_in)
  12681. {
  12682. if (idx)
  12683. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  12684. executor.setInput(this, _in, flags);
  12685. }
  12686. virtual void stop(bool aborting)
  12687. {
  12688. CriticalBlock b(scrit); // can stop while still starting, if unlucky...
  12689. readySpace.interrupt();
  12690. recordsReady.interrupt();
  12691. executor.join(); // MORE - may not be needed given stop/reset split
  12692. CRoxieServerLoopActivity::stop(aborting);
  12693. }
  12694. virtual void reset()
  12695. {
  12696. while (ready.ordinality())
  12697. ReleaseRoxieRow(ready.dequeue());
  12698. executor.reset();
  12699. CRoxieServerActivity::reset();
  12700. }
  12701. virtual const void * nextInGroup()
  12702. {
  12703. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  12704. loop
  12705. {
  12706. if (eof)
  12707. return NULL;
  12708. recordsReady.wait();
  12709. CriticalBlock procedure(canAccess);
  12710. if (ready.ordinality())
  12711. {
  12712. const void *result = ready.dequeue();
  12713. readySpace.signal();
  12714. if (result)
  12715. processed++;
  12716. return result;
  12717. }
  12718. else
  12719. eof = true;
  12720. }
  12721. }
  12722. unsigned getNumParallel(unsigned iter)
  12723. {
  12724. if (iter * sizeof(unsigned) >= sizeNumParallel)
  12725. return defaultNumParallel;
  12726. return ((unsigned *)listNumParallel.getdata())[iter];
  12727. }
  12728. inline void enqueueResult(const void * row)
  12729. {
  12730. try
  12731. {
  12732. while(!readySpace.wait(1000))
  12733. {
  12734. CTXLOG("Blocked waiting for space in loop %p activity id: %d output queue: %d records in queue", this, queryId(), ready.ordinality());
  12735. }
  12736. }
  12737. catch (...)
  12738. {
  12739. ReleaseRoxieRow(row);
  12740. throw;
  12741. }
  12742. CriticalBlock b2(canAccess);
  12743. ready.enqueue(row);
  12744. recordsReady.signal();
  12745. }
  12746. inline void finishResults()
  12747. {
  12748. recordsReady.signal();
  12749. }
  12750. virtual bool fireException(IException *e)
  12751. {
  12752. readySpace.interrupt(LINK(e));
  12753. recordsReady.interrupt(e);
  12754. return true;
  12755. }
  12756. IActivityGraph * createChildGraphInstance()
  12757. {
  12758. return factory->createChildGraph(ctx, &helper, loopGraphId, this, probeManager, *this);
  12759. }
  12760. IActivityGraph * queryChildGraph()
  12761. {
  12762. return ctx->queryChildGraph(loopGraphId);
  12763. }
  12764. };
  12765. //=================================================================================
  12766. const void * LoopFilterPseudoInput::nextInGroup()
  12767. {
  12768. loop
  12769. {
  12770. const void * next = input->nextInGroup();
  12771. if (!next || activity->includeInLoop(counter, next))
  12772. return next;
  12773. activity->enqueueResult(next);
  12774. }
  12775. }
  12776. void LoopExecutorThread::onCreate(IRoxieSlaveContext * _ctx)
  12777. {
  12778. //Initialise the cached graph list with the child instance that will always be created. Other iterations will be created on demand.
  12779. ctx = _ctx;
  12780. cachedGraphs.append(*LINK(activity->queryChildGraph()));
  12781. }
  12782. void LoopExecutorThread::start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12783. {
  12784. savedParentExtractSize = parentExtractSize;
  12785. savedParentExtract = parentExtract;
  12786. eof = false;
  12787. StringBuffer logPrefix("[");
  12788. ctx->getLogPrefix(logPrefix).append("] ");
  12789. RestartableThread::start(logPrefix);
  12790. }
  12791. int LoopExecutorThread::run()
  12792. {
  12793. try
  12794. {
  12795. executeLoop();
  12796. }
  12797. catch (IException *e)
  12798. {
  12799. activity->fireException(e);
  12800. }
  12801. catch (...)
  12802. {
  12803. activity->fireException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unexpected exception caught in LoopExecutorThread::run"));
  12804. }
  12805. return 0;
  12806. }
  12807. void LoopExecutorThread::stop(bool aborting)
  12808. {
  12809. safeInput->stop(aborting);
  12810. RestartableThread::join();
  12811. }
  12812. void LoopExecutorThread::reset()
  12813. {
  12814. safeInput->reset();
  12815. }
  12816. void LoopExecutorThread::executeLoop()
  12817. {
  12818. unsigned iterations = 0;
  12819. unsigned counter = 0;
  12820. unsigned outputIndex = 0;
  12821. //Note, activities don't link inputs, so need to be careful that special inputs remain linked while the activity is executing.
  12822. loop
  12823. {
  12824. if (activity->activityKind == TAKloopcount)
  12825. {
  12826. if (counter == activity->maxIterations)
  12827. break;
  12828. }
  12829. else
  12830. {
  12831. //This condition isn't quite right because it needs to be whether the filtered
  12832. //input is empty. May be ok if we include that in the semantics,
  12833. if (tempResults[1-outputIndex].ordinality() == 0)
  12834. break;
  12835. }
  12836. unsigned numParallel = activity->getNumParallel(iterations);
  12837. Linked<IRoxieInput> curInput;
  12838. if (iterations == 0)
  12839. curInput.set(safeInput);
  12840. else
  12841. {
  12842. SafeRowQueue & inputQueue = tempResults[1-outputIndex];
  12843. inputQueue.enqueue(NULL);
  12844. curInput.setown(new CRowQueuePseudoInput(inputQueue));
  12845. }
  12846. SafeRowQueue * curOutput = NULL;
  12847. if (counter+numParallel > activity->maxIterations)
  12848. numParallel = activity->maxIterations - counter;
  12849. else if (counter+numParallel < activity->maxIterations)
  12850. curOutput = &tempResults[outputIndex];
  12851. executeLoopInstance(counter, numParallel, curInput, curOutput);
  12852. outputIndex = 1-outputIndex;
  12853. counter += numParallel;
  12854. iterations++;
  12855. }
  12856. //Check for TAKlooprow, where end of loop couldn't be determined ahead of time
  12857. SafeRowQueue & inputQueue = tempResults[1-outputIndex];
  12858. while (inputQueue.ordinality())
  12859. {
  12860. const void * next = inputQueue.dequeue();
  12861. activity->enqueueResult(next);
  12862. }
  12863. activity->finishResults();
  12864. }
  12865. void LoopExecutorThread::executeLoopInstance(unsigned counter, unsigned numIterations, IRoxieInput * input, SafeRowQueue * spillOutput)
  12866. {
  12867. IArrayOf<IRoxieInput> savedInputs; // activities don't link their inputs, so this list keeps filters alive.
  12868. Linked<IRoxieInput> curInput = input;
  12869. unsigned i;
  12870. for (i= 0; i != numIterations; i++)
  12871. {
  12872. unsigned thisCounter = counter+i+1;
  12873. IRoxieInput * filtered = curInput;
  12874. if (flags & IHThorLoopArg::LFfiltered)
  12875. {
  12876. filtered = new LoopFilterPseudoInput(activity, curInput, thisCounter);
  12877. savedInputs.append(*filtered);
  12878. }
  12879. //graph is kept, so new curInput will be guaranteed to exist
  12880. curInput.setown(createLoopIterationGraph(i, filtered, thisCounter));
  12881. }
  12882. try
  12883. {
  12884. curInput->start(savedParentExtractSize, savedParentExtract, false);
  12885. if (spillOutput)
  12886. {
  12887. loop
  12888. {
  12889. const void * next = curInput->nextInGroup();
  12890. if (!next)
  12891. break;
  12892. spillOutput->enqueue(next);
  12893. }
  12894. }
  12895. else
  12896. {
  12897. loop
  12898. {
  12899. const void * next = curInput->nextInGroup();
  12900. if (!next)
  12901. break;
  12902. activity->enqueueResult(next);
  12903. }
  12904. }
  12905. }
  12906. catch (IException *E)
  12907. {
  12908. ctx->notifyAbort(E);
  12909. for (i= 0; i != numIterations; i++)
  12910. {
  12911. cachedGraphs.item(i).queryLoopGraph()->afterExecute();
  12912. }
  12913. curInput->stop(true);
  12914. curInput->reset();
  12915. throw;
  12916. }
  12917. for (i= 0; i != numIterations; i++)
  12918. {
  12919. cachedGraphs.item(i).queryLoopGraph()->afterExecute();
  12920. }
  12921. curInput->stop(false);
  12922. curInput->reset();
  12923. }
  12924. IRoxieInput * LoopExecutorThread::createLoopIterationGraph(unsigned i, IRoxieInput * input, unsigned counter)
  12925. {
  12926. if (!cachedGraphs.isItem(i))
  12927. cachedGraphs.append(*activity->createChildGraphInstance());
  12928. Linked<IRoxieServerChildGraph> loopGraph = cachedGraphs.item(i).queryLoopGraph();
  12929. loopGraph->beforeExecute();
  12930. if (!loopGraph->querySetInputResult(1, input))
  12931. throwUnexpected(); // a loop which doesn't use the value from the previous iteration. Should probably handle even if daft.
  12932. activity->createCounterResult(loopGraph, counter);
  12933. return loopGraph->selectOutput(0);
  12934. }
  12935. //=================================================================================
  12936. class CCounterRowMetaData : public CInterface, implements IOutputMetaData
  12937. {
  12938. public:
  12939. IMPLEMENT_IINTERFACE
  12940. virtual size32_t getRecordSize(const void *) { return sizeof(thor_loop_counter_t); }
  12941. virtual size32_t getMinRecordSize() const { return sizeof(thor_loop_counter_t); }
  12942. virtual size32_t getFixedSize() const { return sizeof(thor_loop_counter_t); }
  12943. virtual void toXML(const byte * self, IXmlWriter & out) { }
  12944. virtual unsigned getVersion() const { return OUTPUTMETADATA_VERSION; }
  12945. virtual unsigned getMetaFlags() { return 0; }
  12946. virtual void destruct(byte * self) {}
  12947. virtual IOutputRowSerializer * createDiskSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  12948. virtual IOutputRowDeserializer * createDiskDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  12949. virtual ISourceRowPrefetcher * createDiskPrefetcher(ICodeContext * ctx, unsigned activityId) { return NULL; }
  12950. virtual IOutputMetaData * querySerializedDiskMeta() { return this; }
  12951. virtual IOutputRowSerializer * createInternalSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  12952. virtual IOutputRowDeserializer * createInternalDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  12953. virtual void walkIndirectMembers(const byte * self, IIndirectMemberVisitor & visitor) {}
  12954. };
  12955. class CRoxieServerLoopActivityFactory : public CRoxieServerActivityFactory
  12956. {
  12957. unsigned loopGraphId;
  12958. unsigned flags;
  12959. Linked<IOutputMetaData> counterMeta;
  12960. public:
  12961. CRoxieServerLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _loopGraphId)
  12962. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), loopGraphId(_loopGraphId)
  12963. {
  12964. Owned<IHThorLoopArg> helper = (IHThorLoopArg *) helperFactory();
  12965. flags = helper->getFlags();
  12966. counterMeta.setown(new CCounterRowMetaData);
  12967. }
  12968. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  12969. {
  12970. if (flags & IHThorLoopArg::LFparallel)
  12971. return new CRoxieServerParallelLoopActivity(this, _probeManager, loopGraphId, counterMeta);
  12972. else
  12973. return new CRoxieServerSequentialLoopActivity(this, _probeManager, loopGraphId, counterMeta);
  12974. }
  12975. };
  12976. IRoxieServerActivityFactory *createRoxieServerLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _loopGraphId)
  12977. {
  12978. return new CRoxieServerLoopActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _loopGraphId);
  12979. }
  12980. //=================================================================================
  12981. class CRoxieServerGraphLoopActivity : public CRoxieServerActivity
  12982. {
  12983. protected:
  12984. IHThorGraphLoopArg &helper;
  12985. unsigned maxIterations;
  12986. unsigned flags;
  12987. rtlRowBuilder GraphExtractBuilder;
  12988. unsigned loopGraphId;
  12989. Linked<IOutputMetaData> counterMeta;
  12990. public:
  12991. CRoxieServerGraphLoopActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _GraphGraphId, IOutputMetaData * _counterMeta)
  12992. : CRoxieServerActivity(_factory, _probeManager),
  12993. helper((IHThorGraphLoopArg &)basehelper), loopGraphId(_GraphGraphId), counterMeta(_counterMeta)
  12994. {
  12995. flags = helper.getFlags();
  12996. maxIterations = 0;
  12997. }
  12998. virtual bool needsAllocator() const { return true; }
  12999. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13000. {
  13001. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  13002. int iterations = (int) helper.numIterations();
  13003. maxIterations = (iterations >= 0) ? iterations : 0;
  13004. if (maxIterations > maxGraphLoopIterations)
  13005. throw MakeStringException(ROXIE_TOO_MANY_GRAPH_LOOP, "Attempt to execute graph %u times", maxIterations);
  13006. if (maxIterations != 0)
  13007. {
  13008. GraphExtractBuilder.clear();
  13009. helper.createParentExtract(GraphExtractBuilder);
  13010. }
  13011. }
  13012. virtual void stop(bool aborting)
  13013. {
  13014. CRoxieServerActivity::stop(aborting);
  13015. GraphExtractBuilder.clear();
  13016. }
  13017. void createCounterResult(IRoxieServerChildGraph * graph, unsigned counter)
  13018. {
  13019. if (flags & IHThorGraphLoopArg::GLFcounter)
  13020. {
  13021. void * counterRow = ctx->queryRowManager().allocate(sizeof(thor_loop_counter_t), activityId);
  13022. *((thor_loop_counter_t *)counterRow) = counter;
  13023. RtlLinkedDatasetBuilder builder(rowAllocator);
  13024. builder.appendOwn(counterRow);
  13025. Owned<CGraphResult> counterResult = new CGraphResult(builder.getcount(), builder.linkrows());
  13026. graph->setInputResult(0, counterResult);
  13027. }
  13028. }
  13029. };
  13030. //=================================================================================
  13031. class CRoxieServerSequentialGraphLoopActivity : public CRoxieServerGraphLoopActivity
  13032. {
  13033. Owned<IActivityGraph> GraphQuery;
  13034. Owned<IRoxieServerChildGraph> loopGraph;
  13035. Linked<IRoxieInput> resultInput;
  13036. bool evaluated;
  13037. public:
  13038. CRoxieServerSequentialGraphLoopActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _GraphGraphId, IOutputMetaData * _counterMeta)
  13039. : CRoxieServerGraphLoopActivity(_factory, _probeManager, _GraphGraphId, _counterMeta)
  13040. {
  13041. evaluated = false;
  13042. }
  13043. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  13044. {
  13045. CRoxieServerGraphLoopActivity::onCreate(_ctx, _colocalParent);
  13046. GraphQuery.set(_ctx->queryChildGraph(loopGraphId));
  13047. }
  13048. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13049. {
  13050. CRoxieServerGraphLoopActivity::start(parentExtractSize, parentExtract, paused);
  13051. //MORE: Not sure about this, should IRoxieServerChildGraph be combined with IActivityGraph?
  13052. loopGraph.set(GraphQuery->queryLoopGraph());
  13053. evaluated = false;
  13054. }
  13055. virtual void stop(bool aborting)
  13056. {
  13057. if (loopGraph)
  13058. loopGraph->clearGraphLoopResults();
  13059. CRoxieServerGraphLoopActivity::stop(aborting);
  13060. }
  13061. virtual const void * nextInGroup()
  13062. {
  13063. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  13064. if (!evaluated)
  13065. {
  13066. executeEntireGraph();
  13067. evaluated = true;
  13068. }
  13069. const void * ret = resultInput->nextInGroup();
  13070. if (ret)
  13071. processed++;
  13072. return ret;
  13073. }
  13074. void executeIteration(unsigned parentExtractSize, const byte *parentExtract, unsigned counter)
  13075. {
  13076. try
  13077. {
  13078. loopGraph->beforeExecute();
  13079. createCounterResult(loopGraph, counter);
  13080. loopGraph->executeGraphLoop(parentExtractSize, parentExtract);
  13081. loopGraph->afterExecute();
  13082. }
  13083. catch (...)
  13084. {
  13085. CTXLOG("Exception thrown in graph body - cleaning up");
  13086. loopGraph->afterExecute();
  13087. throw;
  13088. }
  13089. }
  13090. void createInitialGraphInput()
  13091. {
  13092. loopGraph->clearGraphLoopResults();
  13093. RtlLinkedDatasetBuilder builder(rowAllocator);
  13094. input->readAll(builder);
  13095. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  13096. loopGraph->setGraphLoopResult(0, result);
  13097. }
  13098. void executeEntireGraph()
  13099. {
  13100. createInitialGraphInput();
  13101. for (unsigned loopCounter=1; loopCounter <= maxIterations; loopCounter++)
  13102. {
  13103. executeIteration(GraphExtractBuilder.size(), GraphExtractBuilder.getbytes(), loopCounter);
  13104. }
  13105. resultInput.setown(loopGraph->getGraphLoopResult(maxIterations));
  13106. }
  13107. };
  13108. //=================================================================================
  13109. struct GraphOutputSplitterArg : public ccdserver_hqlhelper::CThorSplitArg
  13110. {
  13111. public:
  13112. virtual unsigned numBranches()
  13113. {
  13114. return 0;
  13115. }
  13116. virtual IOutputMetaData * queryOutputMeta()
  13117. {
  13118. return NULL;// get it from the parent..
  13119. }
  13120. };
  13121. extern "C" IHThorArg * createGraphOutputSplitter() { return new GraphOutputSplitterArg; }
  13122. class CGraphIterationInfo : public CInterface
  13123. {
  13124. private:
  13125. Owned<IRoxieServerActivityFactory> factory; // Note - before sourceAct, so destroyed last
  13126. unsigned sourceIdx;
  13127. Linked<IRoxieServerActivity> sourceAct;
  13128. Linked<IRoxieInput> sourceInput;
  13129. unsigned numUses;
  13130. unsigned iteration;
  13131. public:
  13132. CGraphIterationInfo(IRoxieServerActivity * _sourceAct, IRoxieInput *_input, unsigned _sourceIdx, unsigned _iteration)
  13133. : sourceAct(_sourceAct), sourceInput(_input), sourceIdx(_sourceIdx), iteration(_iteration)
  13134. {
  13135. numUses = 0;
  13136. }
  13137. inline void noteUsed()
  13138. {
  13139. numUses++;
  13140. }
  13141. void createSplitter(IRoxieSlaveContext *ctx, IProbeManager *probeManager)
  13142. {
  13143. if (numUses > 1)
  13144. {
  13145. factory.setown(createRoxieServerThroughSpillActivityFactory(sourceAct->queryFactory()->queryQueryFactory(), createGraphOutputSplitter, numUses));
  13146. IRoxieServerActivity *splitter = factory->createActivity(NULL);
  13147. splitter->onCreate(ctx, NULL);
  13148. IRoxieInput *input = sourceAct->queryOutput(sourceIdx);
  13149. if (probeManager)
  13150. {
  13151. IInputBase * inputBase = probeManager->createProbe(static_cast<IInputBase*>(input), sourceAct, splitter, sourceIdx, 0, iteration);
  13152. input = static_cast<IRoxieInput*>(inputBase);
  13153. // MORE - shouldn't this be added to probes?
  13154. }
  13155. sourceAct.setown(splitter);
  13156. sourceAct->setInput(0, input);
  13157. sourceIdx = 0;
  13158. sourceInput.clear();
  13159. }
  13160. }
  13161. IRoxieInput *connectOutput(IProbeManager *probeManager, IArrayOf<IRoxieInput> &probes, IRoxieServerActivity *targetAct, unsigned targetIdx)
  13162. {
  13163. // MORE - not really necessary to create splitters in separate pass, is it?
  13164. if (factory) // we created a splitter....
  13165. sourceInput.set(sourceAct->queryOutput(sourceIdx));
  13166. IRoxieInput *ret = sourceInput;
  13167. if (probeManager)
  13168. {
  13169. IInputBase *inputBase = probeManager->createProbe(ret, sourceAct, targetAct, sourceIdx, targetIdx, iteration);
  13170. ret = static_cast<IRoxieInput *>(inputBase);
  13171. probes.append(*LINK(ret));
  13172. }
  13173. if (factory) // we created a splitter....
  13174. sourceIdx++;
  13175. return ret;
  13176. }
  13177. };
  13178. class CRoxieServerParallelGraphLoopActivity : public CRoxieServerGraphLoopActivity, implements IRoxieServerLoopResultProcessor
  13179. {
  13180. Owned<IActivityGraph> childGraph;
  13181. IRoxieInput * resultInput;
  13182. CIArrayOf<CGraphIterationInfo> outputs;
  13183. IArrayOf<IRoxieServerChildGraph> iterationGraphs;
  13184. Owned<CExtractMapperInput> inputExtractMapper;
  13185. IProbeManager *probeManager;
  13186. unsigned createLoopCounter;
  13187. IArrayOf<IRoxieInput> probes;
  13188. public:
  13189. CRoxieServerParallelGraphLoopActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _GraphGraphId, IOutputMetaData * _counterMeta)
  13190. : CRoxieServerGraphLoopActivity(_factory, _probeManager, _GraphGraphId, _counterMeta), probeManager(_probeManager)
  13191. {
  13192. inputExtractMapper.setown(new CExtractMapperInput);
  13193. resultInput = NULL;
  13194. createLoopCounter = 0;
  13195. }
  13196. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  13197. {
  13198. CRoxieServerGraphLoopActivity::onCreate(_ctx, _colocalParent);
  13199. childGraph.set(_ctx->queryChildGraph(loopGraphId));
  13200. }
  13201. virtual void setInput(unsigned idx, IRoxieInput *_in)
  13202. {
  13203. //Input needs to be handled very carefully.....
  13204. //We don't want to call onStart on the input unless it is actually used, so don't use the base CRoxieServerActivity implementation.
  13205. //This activity's input needs to be started with (parentExtractSize, parentExtract), but the elements in the graph need to be started with the
  13206. //GraphExtractBuilder parent extract. So we need to wrap the input in a pseudo-input (inputExtractMapper) that passes through a different
  13207. //parentExtract. Something very similar will be needed for query library calls with streaming inputs when they are implemented.
  13208. assertex(idx == 0);
  13209. inputExtractMapper->setInput(_in);
  13210. }
  13211. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13212. {
  13213. CRoxieServerGraphLoopActivity::start(parentExtractSize, parentExtract, paused); // initialises GraphExtractBuilder
  13214. inputExtractMapper->setParentExtract(parentExtractSize, parentExtract);
  13215. createExpandedGraph(GraphExtractBuilder.size(), GraphExtractBuilder.getbytes(), probeManager);
  13216. resultInput->start(GraphExtractBuilder.size(), GraphExtractBuilder.getbytes(), paused);
  13217. }
  13218. virtual void stop(bool aborting)
  13219. {
  13220. if (resultInput)
  13221. resultInput->stop(aborting);
  13222. CRoxieServerGraphLoopActivity::stop(aborting);
  13223. }
  13224. virtual void reset()
  13225. {
  13226. if (resultInput)
  13227. resultInput->reset();
  13228. resultInput = NULL;
  13229. iterationGraphs.kill();
  13230. outputs.kill();
  13231. if (probeManager)
  13232. {
  13233. probeManager->deleteGraph(NULL, (IArrayOf<IInputBase>*)&probes);
  13234. probes.kill();
  13235. }
  13236. CRoxieServerGraphLoopActivity::reset();
  13237. }
  13238. virtual const void * nextInGroup()
  13239. {
  13240. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  13241. const void * ret = resultInput->nextInGroup();
  13242. if (ret)
  13243. processed++;
  13244. return ret;
  13245. }
  13246. void createExpandedGraph(unsigned parentExtractSize, const byte *parentExtract, IProbeManager *probeManager)
  13247. {
  13248. //result(0) is the input to the graph.
  13249. resultInput = inputExtractMapper;
  13250. outputs.append(* new CGraphIterationInfo(resultInput->queryActivity(), resultInput, 0, 1));
  13251. for (createLoopCounter=1; createLoopCounter <= maxIterations; createLoopCounter++)
  13252. {
  13253. IRoxieServerChildGraph * graph = childGraph->createGraphLoopInstance(createLoopCounter, parentExtractSize, parentExtract, *this);
  13254. graph->beforeExecute();
  13255. iterationGraphs.append(*graph);
  13256. graph->gatherIterationUsage(*this);
  13257. CGraphIterationInfo *iteration = graph->selectGraphLoopOutput();
  13258. outputs.append(*iteration);
  13259. }
  13260. createLoopCounter = 0;
  13261. createSplitters(probeManager);
  13262. ForEachItemIn(i2, iterationGraphs)
  13263. iterationGraphs.item(i2).associateIterationOutputs(*this);
  13264. resultInput = outputs.tos().connectOutput(probeManager, probes, this, 0);
  13265. }
  13266. void createSplitters(IProbeManager *probeManager)
  13267. {
  13268. ForEachItemIn(i, outputs)
  13269. {
  13270. CGraphIterationInfo & next = outputs.item(i);
  13271. next.createSplitter(ctx, probeManager);
  13272. }
  13273. }
  13274. //IRoxieServerLoopResultProcessor
  13275. virtual void noteUseIteration(unsigned _whichIteration)
  13276. {
  13277. int whichIteration = (int) _whichIteration; // May go negative - API is unsigned for historical reasons
  13278. if (whichIteration >= 0)
  13279. {
  13280. if (!outputs.isItem(whichIteration))
  13281. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Error reading graph result %d from iteration %d", whichIteration, createLoopCounter);
  13282. outputs.item(whichIteration).noteUsed();
  13283. }
  13284. }
  13285. virtual IRoxieInput * connectIterationOutput(unsigned whichIteration, IProbeManager *probeManager, IArrayOf<IRoxieInput> &probes, IRoxieServerActivity *targetAct, unsigned targetIdx)
  13286. {
  13287. if (outputs.isItem(whichIteration))
  13288. {
  13289. CGraphIterationInfo & next = outputs.item(whichIteration);
  13290. return next.connectOutput(probeManager, probes, targetAct, targetIdx);
  13291. }
  13292. return NULL;
  13293. }
  13294. };
  13295. //=================================================================================
  13296. class CRoxieServerGraphLoopActivityFactory : public CRoxieServerActivityFactory
  13297. {
  13298. unsigned loopGraphId;
  13299. unsigned flags;
  13300. Linked<IOutputMetaData> counterMeta;
  13301. public:
  13302. CRoxieServerGraphLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _loopGraphId)
  13303. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), loopGraphId(_loopGraphId)
  13304. {
  13305. Owned<IHThorGraphLoopArg> helper = (IHThorGraphLoopArg *) helperFactory();
  13306. flags = helper->getFlags();
  13307. counterMeta.setown(new CCounterRowMetaData);
  13308. }
  13309. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  13310. {
  13311. if (kind == TAKparallelgraphloop)
  13312. return new CRoxieServerParallelGraphLoopActivity(this, _probeManager, loopGraphId, counterMeta);
  13313. else
  13314. return new CRoxieServerSequentialGraphLoopActivity(this, _probeManager, loopGraphId, counterMeta);
  13315. }
  13316. };
  13317. IRoxieServerActivityFactory *createRoxieServerGraphLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _loopGraphId)
  13318. {
  13319. return new CRoxieServerGraphLoopActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _loopGraphId);
  13320. }
  13321. //=====================================================================================================
  13322. class CRoxieServerLibraryCallActivity : public CRoxieServerActivity
  13323. {
  13324. class OutputAdaptor : public CExtractMapperInput
  13325. {
  13326. bool stopped;
  13327. public:
  13328. CRoxieServerLibraryCallActivity *parent;
  13329. unsigned oid;
  13330. unsigned processed;
  13331. public:
  13332. IMPLEMENT_IINTERFACE;
  13333. OutputAdaptor() : CExtractMapperInput(NULL)
  13334. {
  13335. parent = NULL;
  13336. oid = 0;
  13337. init();
  13338. }
  13339. void init()
  13340. {
  13341. processed = 0;
  13342. stopped = false;
  13343. }
  13344. virtual unsigned queryId() const
  13345. {
  13346. return parent->queryId();
  13347. }
  13348. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13349. {
  13350. parent->start(oid, parentExtractSize, parentExtract, paused);
  13351. CExtractMapperInput::start(parentExtractSize, parentExtract, paused);
  13352. }
  13353. virtual void stop(bool aborting)
  13354. {
  13355. if (!stopped)
  13356. {
  13357. stopped = true;
  13358. parent->stop(oid, aborting); // parent code relies on stop being called exactly once per adaptor, so make sure it is!
  13359. CExtractMapperInput::stop(aborting);
  13360. }
  13361. };
  13362. virtual void reset()
  13363. {
  13364. parent->reset(oid, processed);
  13365. CExtractMapperInput::reset();
  13366. init();
  13367. };
  13368. virtual void checkAbort()
  13369. {
  13370. parent->checkAbort();
  13371. }
  13372. };
  13373. IHThorLibraryCallArg &helper;
  13374. unsigned numInputs;
  13375. unsigned numOutputs;
  13376. unsigned numActiveOutputs;
  13377. bool started;
  13378. OutputAdaptor* outputAdaptors;
  13379. CExtractMapperInput * * inputAdaptors;
  13380. bool * inputUsed;
  13381. bool * outputUsed;
  13382. Owned<IException> error;
  13383. CriticalSection crit;
  13384. rtlRowBuilder libraryExtractBuilder;
  13385. Owned<IActivityGraph> libraryGraph;
  13386. const LibraryCallFactoryExtra & extra;
  13387. public:
  13388. CRoxieServerLibraryCallActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs, unsigned _numOutputs, const LibraryCallFactoryExtra & _extra)
  13389. : CRoxieServerActivity(_factory, _probeManager),
  13390. helper((IHThorLibraryCallArg &)basehelper), extra(_extra)
  13391. {
  13392. numInputs = _numInputs;
  13393. numOutputs = _numOutputs;
  13394. numActiveOutputs = numOutputs;
  13395. inputAdaptors = new CExtractMapperInput*[numInputs];
  13396. inputUsed = new bool[numInputs];
  13397. for (unsigned i1 = 0; i1 < numInputs; i1++)
  13398. {
  13399. inputAdaptors[i1] = new CExtractMapperInput;
  13400. inputUsed[i1] = false;
  13401. }
  13402. outputAdaptors = new OutputAdaptor[numOutputs];
  13403. outputUsed = new bool[numOutputs];
  13404. for (unsigned i2 = 0; i2 < numOutputs; i2++)
  13405. {
  13406. outputAdaptors[i2].parent = this;
  13407. outputAdaptors[i2].oid = i2;
  13408. outputUsed[i2] = false;
  13409. }
  13410. started = false;
  13411. }
  13412. ~CRoxieServerLibraryCallActivity()
  13413. {
  13414. for (unsigned i1 = 0; i1 < numInputs; i1++)
  13415. ::Release(inputAdaptors[i1]);
  13416. delete [] inputAdaptors;
  13417. delete [] inputUsed;
  13418. delete [] outputAdaptors;
  13419. delete [] outputUsed;
  13420. }
  13421. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  13422. {
  13423. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  13424. libraryGraph.setown(_ctx->getLibraryGraph(extra, this));
  13425. libraryGraph->onCreate(_ctx, _colocalParent);
  13426. //Now map the inputs and outputs to the adapters
  13427. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  13428. for (unsigned i1=0; i1<numInputs; i1++)
  13429. inputUsed[i1] = graph->querySetInputResult(i1, inputAdaptors[i1]);
  13430. for (unsigned i2=0; i2<numOutputs; i2++)
  13431. {
  13432. unsigned outputIndex = extra.outputs.item(i2);
  13433. Owned<IRoxieInput> output = graph->selectOutput(numInputs+outputIndex);
  13434. outputAdaptors[i2].setInput(output);
  13435. }
  13436. }
  13437. virtual void start(unsigned oid, unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13438. {
  13439. CriticalBlock b(crit);
  13440. if (error)
  13441. throw error.getLink();
  13442. if (factory)
  13443. factory->noteStarted(oid);
  13444. if (!started)
  13445. {
  13446. // even though it is not complete, we don't want to run this again if it fails.
  13447. started = true;
  13448. //see notes on splitter above
  13449. try
  13450. {
  13451. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  13452. }
  13453. catch (IException *E)
  13454. {
  13455. #ifdef TRACE_SPLIT
  13456. CTXLOG("spill %d caught exception in start", activityId);
  13457. #endif
  13458. error.set(E);
  13459. throw;
  13460. }
  13461. catch (...)
  13462. {
  13463. IException *E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught in CRoxieServerLibraryCallActivity::start");
  13464. error.set(E);
  13465. throw E;
  13466. }
  13467. //recreate the parent extract, and use it to reinitialize the graphs...
  13468. libraryExtractBuilder.clear();
  13469. helper.createParentExtract(libraryExtractBuilder);
  13470. // 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
  13471. // some inputs before we see start on others.
  13472. for (unsigned i1 = 0; i1 < numInputs; i1++)
  13473. {
  13474. if (inputUsed[i1])
  13475. inputAdaptors[i1]->setParentExtract(parentExtractSize, parentExtract);
  13476. else
  13477. inputAdaptors[i1]->stop(false);
  13478. }
  13479. for (unsigned i2 = 0; i2 < numOutputs; i2++)
  13480. outputAdaptors[i2].setParentExtract(libraryExtractBuilder.size(), libraryExtractBuilder.getbytes());
  13481. //call stop on all the unused inputs.
  13482. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  13483. graph->beforeExecute();
  13484. ForEachItemIn(i3, extra.unusedOutputs)
  13485. {
  13486. Owned<IRoxieInput> output = graph->selectOutput(numInputs+extra.unusedOutputs.item(i3));
  13487. output->stop(false);
  13488. }
  13489. }
  13490. }
  13491. virtual void stop(unsigned oid, bool aborting)
  13492. {
  13493. CriticalBlock b(crit);
  13494. if (--numActiveOutputs == 0)
  13495. {
  13496. //call stop on all the unused inputs.
  13497. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  13498. graph->beforeExecute();
  13499. ForEachItemIn(i3, extra.unusedOutputs)
  13500. {
  13501. Owned<IRoxieInput> output = graph->selectOutput(numInputs+extra.unusedOutputs.item(i3));
  13502. output->stop(false);
  13503. }
  13504. CRoxieServerActivity::stop(aborting);
  13505. }
  13506. }
  13507. void reset(unsigned oid, unsigned _processed)
  13508. {
  13509. noteProcessed(oid, _processed, 0, 0);
  13510. started = false;
  13511. error.clear();
  13512. numActiveOutputs = numOutputs;
  13513. if (state != STATEreset) // make sure input is only reset once
  13514. {
  13515. CRoxieServerActivity::reset();
  13516. libraryGraph->reset();
  13517. //Call reset on all unused outputs from the graph - no one else will.
  13518. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  13519. ForEachItemIn(i3, extra.unusedOutputs)
  13520. {
  13521. Owned<IRoxieInput> output = graph->selectOutput(numInputs+extra.unusedOutputs.item(i3));
  13522. output->reset();
  13523. }
  13524. }
  13525. };
  13526. virtual void setInput(unsigned idx, IRoxieInput *_in)
  13527. {
  13528. inputAdaptors[idx]->setInput(_in);
  13529. }
  13530. public:
  13531. virtual const void *nextInGroup()
  13532. {
  13533. throwUnexpected(); // Internal logic error - we are not anybody's input
  13534. }
  13535. virtual IOutputMetaData * queryOutputMeta() const
  13536. {
  13537. throwUnexpected(); // should be called on outputs instead
  13538. }
  13539. virtual IRoxieInput *queryOutput(unsigned idx)
  13540. {
  13541. assertex(idx!=(unsigned)-1);
  13542. assertex(!outputUsed[idx]);
  13543. outputUsed[idx] = true;
  13544. return &outputAdaptors[idx];
  13545. }
  13546. };
  13547. void LibraryCallFactoryExtra::set(const LibraryCallFactoryExtra & _other)
  13548. {
  13549. ForEachItemIn(i1, _other.outputs)
  13550. outputs.append(_other.outputs.item(i1));
  13551. ForEachItemIn(i2, _other.unusedOutputs)
  13552. unusedOutputs.append(_other.unusedOutputs.item(i2));
  13553. maxOutputs = _other.maxOutputs;
  13554. graphid = _other.graphid;
  13555. libraryName.set(_other.libraryName);
  13556. interfaceHash = _other.interfaceHash;
  13557. embedded = _other.embedded;
  13558. }
  13559. void LibraryCallFactoryExtra::calcUnused()
  13560. {
  13561. for (unsigned i=0; i < maxOutputs; i++)
  13562. if (!outputs.contains(i))
  13563. unusedOutputs.append(i);
  13564. }
  13565. class CRoxieServerLibraryCallActivityFactory : public CRoxieServerMultiOutputFactory
  13566. {
  13567. private:
  13568. CRoxieServerMultiInputInfo inputs;
  13569. LibraryCallFactoryExtra extra;
  13570. public:
  13571. CRoxieServerLibraryCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, LibraryCallFactoryExtra & _extra)
  13572. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  13573. {
  13574. extra.set(_extra);
  13575. extra.calcUnused();
  13576. setNumOutputs(extra.outputs.ordinality());
  13577. }
  13578. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  13579. {
  13580. return new CRoxieServerLibraryCallActivity(this, _probeManager, numInputs(), numOutputs, extra);
  13581. }
  13582. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  13583. {
  13584. inputs.set(idx, source, sourceidx);
  13585. }
  13586. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  13587. {
  13588. return inputs.get(idx, sourceidx);
  13589. }
  13590. virtual unsigned numInputs() const { return inputs.ordinality(); }
  13591. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  13592. {
  13593. addXrefLibraryInfo(reply, extra.libraryName);
  13594. }
  13595. };
  13596. IRoxieServerActivityFactory *createRoxieServerLibraryCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, LibraryCallFactoryExtra & _extra)
  13597. {
  13598. return new CRoxieServerLibraryCallActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _extra);
  13599. }
  13600. //=====================================================================================================
  13601. class CRoxieServerNWayInputActivity : public CRoxieServerActivity
  13602. {
  13603. IHThorNWayInputArg & helper;
  13604. IRoxieInput ** inputs;
  13605. PointerArrayOf<IRoxieInput> selectedInputs;
  13606. unsigned numInputs;
  13607. public:
  13608. CRoxieServerNWayInputActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  13609. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorNWayInputArg &)basehelper), numInputs(_numInputs)
  13610. {
  13611. inputs = new IRoxieInput*[numInputs];
  13612. for (unsigned i = 0; i < numInputs; i++)
  13613. inputs[i] = NULL;
  13614. }
  13615. ~CRoxieServerNWayInputActivity()
  13616. {
  13617. delete [] inputs;
  13618. }
  13619. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13620. {
  13621. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  13622. bool selectionIsAll;
  13623. size32_t selectionLen;
  13624. rtlDataAttr selection;
  13625. helper.getInputSelection(selectionIsAll, selectionLen, selection.refdata());
  13626. selectedInputs.kill();
  13627. if (selectionIsAll)
  13628. {
  13629. for (unsigned i=0; i < numInputs; i++)
  13630. selectedInputs.append(inputs[i]);
  13631. }
  13632. else
  13633. {
  13634. const size32_t * selections = (const size32_t *)selection.getdata();
  13635. unsigned max = selectionLen/sizeof(size32_t);
  13636. for (unsigned i = 0; i < max; i++)
  13637. {
  13638. unsigned nextIndex = selections[i];
  13639. //Check there are no duplicates..... Assumes there are a fairly small number of inputs, so n^2 search is ok.
  13640. for (unsigned j=i+1; j < max; j++)
  13641. {
  13642. if (nextIndex == selections[j])
  13643. throw MakeStringException(ROXIE_NWAY_INPUT_ERROR, "Selection list for nway input can not contain duplicates");
  13644. }
  13645. if (nextIndex > numInputs)
  13646. throw MakeStringException(ROXIE_NWAY_INPUT_ERROR, "Index %d in RANGE selection list is out of range", nextIndex);
  13647. selectedInputs.append(inputs[nextIndex-1]);
  13648. }
  13649. }
  13650. ForEachItemIn(i2, selectedInputs)
  13651. selectedInputs.item(i2)->start(parentExtractSize, parentExtract, paused);
  13652. }
  13653. virtual void stop(bool aborting)
  13654. {
  13655. ForEachItemIn(i2, selectedInputs)
  13656. selectedInputs.item(i2)->stop(aborting);
  13657. CRoxieServerActivity::stop(aborting);
  13658. }
  13659. virtual unsigned __int64 queryLocalCycles() const
  13660. {
  13661. __int64 localCycles = totalCycles;
  13662. ForEachItemIn(i, selectedInputs)
  13663. {
  13664. localCycles -= selectedInputs.item(i)->queryTotalCycles();
  13665. }
  13666. if (localCycles < 0)
  13667. localCycles = 0;
  13668. return localCycles;
  13669. }
  13670. virtual IRoxieInput *queryInput(unsigned idx) const
  13671. {
  13672. if (selectedInputs.isItem(idx))
  13673. return selectedInputs.item(idx);
  13674. else
  13675. return NULL;
  13676. }
  13677. virtual void reset()
  13678. {
  13679. ForEachItemIn(i, selectedInputs)
  13680. selectedInputs.item(i)->reset();
  13681. selectedInputs.kill();
  13682. CRoxieServerActivity::reset();
  13683. }
  13684. virtual void setInput(unsigned idx, IRoxieInput *_in)
  13685. {
  13686. assertex(idx < numInputs);
  13687. inputs[idx] = _in;
  13688. }
  13689. virtual const void * nextInGroup()
  13690. {
  13691. throwUnexpected();
  13692. }
  13693. virtual unsigned numConcreteOutputs() const
  13694. {
  13695. return selectedInputs.ordinality();
  13696. }
  13697. virtual IRoxieInput * queryConcreteInput(unsigned idx)
  13698. {
  13699. if (selectedInputs.isItem(idx))
  13700. return selectedInputs.item(idx);
  13701. return NULL;
  13702. }
  13703. };
  13704. class CRoxieServerNWayInputActivityFactory : public CRoxieServerMultiInputFactory
  13705. {
  13706. // bool ordered;
  13707. public:
  13708. CRoxieServerNWayInputActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  13709. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  13710. {
  13711. }
  13712. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  13713. {
  13714. return new CRoxieServerNWayInputActivity(this, _probeManager, numInputs());
  13715. }
  13716. };
  13717. IRoxieServerActivityFactory *createRoxieServerNWayInputActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  13718. {
  13719. return new CRoxieServerNWayInputActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  13720. }
  13721. //=====================================================================================================
  13722. class CRoxieServerNWayGraphLoopResultReadActivity : public CRoxieServerActivity
  13723. {
  13724. IHThorNWayGraphLoopResultReadArg & helper;
  13725. CIArrayOf<CRoxieServerActivity> resultReaders;
  13726. PointerArrayOf<IRoxieInput> inputs;
  13727. unsigned graphId;
  13728. bool grouped;
  13729. bool selectionIsAll;
  13730. size32_t selectionLen;
  13731. rtlDataAttr selection;
  13732. public:
  13733. CRoxieServerNWayGraphLoopResultReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId)
  13734. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorNWayGraphLoopResultReadArg &)basehelper)
  13735. {
  13736. grouped = helper.isGrouped();
  13737. graphId = _graphId;
  13738. selectionIsAll = false;
  13739. }
  13740. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13741. {
  13742. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  13743. if (inputs.ordinality() == 0)
  13744. {
  13745. initInputSelection();
  13746. unsigned max = selectionLen / sizeof(size32_t);
  13747. const size32_t * selections = (const size32_t *)selection.getdata();
  13748. IProbeManager * probeManager = NULL; // MORE!!
  13749. for (unsigned i = 0; i < max; i++)
  13750. {
  13751. CRoxieServerActivity * resultInput = new CRoxieServerInternalGraphLoopResultReadActivity(factory, probeManager, graphId, selections[i]);
  13752. resultReaders.append(*resultInput);
  13753. inputs.append(resultInput->queryOutput(0));
  13754. resultInput->onCreate(ctx, colocalParent);
  13755. resultInput->start(parentExtractSize, parentExtract, paused);
  13756. }
  13757. }
  13758. else
  13759. {
  13760. ForEachItemIn(i, inputs)
  13761. inputs.item(i)->start(parentExtractSize, parentExtract, paused);
  13762. }
  13763. }
  13764. virtual void stop(bool aborting)
  13765. {
  13766. ForEachItemIn(i, inputs)
  13767. inputs.item(i)->stop(aborting);
  13768. CRoxieServerActivity::stop(aborting);
  13769. }
  13770. virtual void reset()
  13771. {
  13772. ForEachItemIn(i, inputs)
  13773. inputs.item(i)->reset();
  13774. inputs.kill();
  13775. resultReaders.kill();
  13776. CRoxieServerActivity::reset();
  13777. }
  13778. virtual void setInput(unsigned idx, IRoxieInput *_in)
  13779. {
  13780. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for nway graph result read");
  13781. }
  13782. virtual const void * nextInGroup()
  13783. {
  13784. throwUnexpected();
  13785. }
  13786. virtual unsigned numConcreteOutputs() const
  13787. {
  13788. return inputs.ordinality();
  13789. }
  13790. virtual IRoxieInput * queryConcreteInput(unsigned idx)
  13791. {
  13792. if (inputs.isItem(idx))
  13793. return inputs.item(idx);
  13794. return NULL;
  13795. }
  13796. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract)
  13797. {
  13798. ensureCreated();
  13799. basehelper.onStart(parentExtract, NULL);
  13800. initInputSelection();
  13801. unsigned max = selectionLen / sizeof(size32_t);
  13802. const size32_t * selections = (const size32_t *)selection.getdata();
  13803. for (unsigned i = 0; i < max; i++)
  13804. processor.noteUseIteration(selections[i]);
  13805. }
  13806. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract, IProbeManager *probeManager, IArrayOf<IRoxieInput> &probes)
  13807. {
  13808. //selection etc. already initialised from the gratherIterationUsage() call.
  13809. unsigned max = selectionLen / sizeof(size32_t);
  13810. const size32_t * selections = (const size32_t *)selection.getdata();
  13811. for (unsigned i = 0; i < max; i++)
  13812. inputs.append(processor.connectIterationOutput(selections[i], probeManager, probes, this, i));
  13813. }
  13814. protected:
  13815. void initInputSelection()
  13816. {
  13817. helper.getInputSelection(selectionIsAll, selectionLen, selection.refdata());
  13818. if (selectionIsAll)
  13819. throw MakeStringException(ROXIE_NWAY_INPUT_ERROR, "ALL not yet supported for NWay graph inputs");
  13820. }
  13821. };
  13822. class CRoxieServerNWayGraphLoopResultReadActivityFactory : public CRoxieServerActivityFactory
  13823. {
  13824. unsigned graphId;
  13825. public:
  13826. CRoxieServerNWayGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _graphId)
  13827. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), graphId(_graphId)
  13828. {
  13829. }
  13830. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  13831. {
  13832. return new CRoxieServerNWayGraphLoopResultReadActivity(this, _probeManager, graphId);
  13833. }
  13834. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  13835. {
  13836. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for NWay GraphLoopResultRead activity");
  13837. }
  13838. };
  13839. IRoxieServerActivityFactory *createRoxieServerNWayGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned graphId)
  13840. {
  13841. return new CRoxieServerNWayGraphLoopResultReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, graphId);
  13842. }
  13843. //=================================================================================
  13844. class RoxieSteppedInput : public CInterface, implements ISteppedInput
  13845. {
  13846. public:
  13847. RoxieSteppedInput(IRoxieInput * _input) { input = _input; }
  13848. IMPLEMENT_IINTERFACE
  13849. protected:
  13850. virtual const void * nextInputRow()
  13851. {
  13852. #ifdef TRACE_SEEK_REQUESTS
  13853. IRoxieContextLogger * logger = input->queryActivity();
  13854. const void * ret = doNextInputRow();
  13855. {
  13856. CommonXmlWriter xmlwrite(XWFtrim|XWFopt|XWFnoindent);
  13857. if (!ret)
  13858. xmlwrite.outputBool(true,"eof");
  13859. else if (input->queryOutputMeta()->hasXML())
  13860. input->queryOutputMeta()->toXML((byte *) ret, xmlwrite);
  13861. logger->CTXLOG("next() returns (%s)", xmlwrite.str());
  13862. }
  13863. return ret;
  13864. #else
  13865. return doNextInputRow();
  13866. #endif
  13867. }
  13868. virtual const void * nextInputRowGE(const void * seek, unsigned numFields, bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  13869. {
  13870. #ifdef TRACE_SEEK_REQUESTS
  13871. IRoxieContextLogger * logger = input->queryActivity();
  13872. {
  13873. CommonXmlWriter xmlwrite(XWFtrim|XWFopt|XWFnoindent);
  13874. if (input->queryOutputMeta()->hasXML())
  13875. input->queryOutputMeta()->toXML((byte *) seek, xmlwrite);
  13876. logger->CTXLOG("nextInputRowGE(%d, %s%s%s, %s) seek(%s)",
  13877. numFields,
  13878. stepExtra.readAheadManyResults() ? "readahead " : "",
  13879. stepExtra.returnMismatches() ? "mismatch" : "exact",
  13880. stepExtra.onlyReturnFirstSeekMatch() ? " single-match" : "",
  13881. stepExtra.queryExtraSeeks() ? "multi-seek":"",
  13882. xmlwrite.str());
  13883. }
  13884. const void * ret = doNextInputRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  13885. {
  13886. CommonXmlWriter xmlwrite(XWFtrim|XWFopt|XWFnoindent);
  13887. if (!ret)
  13888. xmlwrite.outputBool(true,"eof");
  13889. else if (input->queryOutputMeta()->hasXML())
  13890. input->queryOutputMeta()->toXML((byte *) ret, xmlwrite);
  13891. logger->CTXLOG("nextInputRowGE(%d, %s%s%s, %s) result(%s)",
  13892. numFields,
  13893. stepExtra.readAheadManyResults() ? "readahead " : "",
  13894. stepExtra.returnMismatches() ? "mismatch" : "exact",
  13895. stepExtra.onlyReturnFirstSeekMatch() ? " single-match" : "",
  13896. stepExtra.queryExtraSeeks() ? "multi-seek":"",
  13897. xmlwrite.str());
  13898. }
  13899. return ret;
  13900. #else
  13901. return doNextInputRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  13902. #endif
  13903. }
  13904. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  13905. {
  13906. return input->gatherConjunctions(collector);
  13907. }
  13908. virtual void resetEOF()
  13909. {
  13910. input->resetEOF();
  13911. }
  13912. virtual IInputSteppingMeta * queryInputSteppingMeta()
  13913. {
  13914. return input->querySteppingMeta();
  13915. }
  13916. inline const void * doNextInputRow()
  13917. {
  13918. const void * ret = input->nextInGroup();
  13919. if (!ret)
  13920. ret = input->nextInGroup();
  13921. return ret;
  13922. }
  13923. inline const void * doNextInputRowGE(const void * seek, unsigned numFields, bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  13924. {
  13925. assertex(wasCompleteMatch);
  13926. return input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  13927. }
  13928. protected:
  13929. IRoxieInput * input;
  13930. };
  13931. //=================================================================================
  13932. class CRoxieServerNaryActivity : public CRoxieServerMultiInputActivity
  13933. {
  13934. public:
  13935. CRoxieServerNaryActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  13936. : CRoxieServerMultiInputActivity(_factory, _probeManager, _numInputs)
  13937. {
  13938. }
  13939. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13940. {
  13941. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  13942. for (unsigned i=0; i < numInputs; i++)
  13943. {
  13944. IRoxieInput * cur = inputArray[i];
  13945. unsigned numRealInputs = cur->numConcreteOutputs();
  13946. for (unsigned j = 0; j < numRealInputs; j++)
  13947. {
  13948. IRoxieInput * curReal = cur->queryConcreteInput(j);
  13949. expandedInputs.append(curReal);
  13950. }
  13951. }
  13952. }
  13953. virtual void reset()
  13954. {
  13955. expandedInputs.kill();
  13956. CRoxieServerMultiInputActivity::reset();
  13957. }
  13958. protected:
  13959. PointerArrayOf<IRoxieInput> expandedInputs;
  13960. };
  13961. //=================================================================================
  13962. class CRoxieStreamMerger : public CStreamMerger
  13963. {
  13964. public:
  13965. CRoxieStreamMerger() : CStreamMerger(true) {}
  13966. void initInputs(unsigned _numInputs, IRoxieInput ** _inputArray)
  13967. {
  13968. CStreamMerger::initInputs(_numInputs);
  13969. inputArray = _inputArray;
  13970. }
  13971. virtual bool pullInput(unsigned i, const void * seek, unsigned numFields, const SmartStepExtra * stepExtra)
  13972. {
  13973. const void * next;
  13974. bool matches = true;
  13975. if (seek)
  13976. next = inputArray[i]->nextSteppedGE(seek, numFields, matches, *stepExtra);
  13977. else
  13978. next = nextUngrouped(inputArray[i]);
  13979. pending[i] = next;
  13980. pendingMatches[i] = matches;
  13981. return (next != NULL);
  13982. }
  13983. virtual void releaseRow(const void * row)
  13984. {
  13985. ReleaseRoxieRow(row);
  13986. }
  13987. protected:
  13988. IRoxieInput **inputArray;
  13989. };
  13990. class CRoxieServerNWayMergeActivity : public CRoxieServerNaryActivity
  13991. {
  13992. public:
  13993. CRoxieServerNWayMergeActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  13994. : CRoxieServerNaryActivity(_factory, _probeManager, _numInputs),
  13995. helper((IHThorNWayMergeArg &)basehelper)
  13996. {
  13997. initializedMeta = false;
  13998. }
  13999. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14000. {
  14001. CRoxieServerNaryActivity::start(parentExtractSize, parentExtract, paused);
  14002. merger.init(helper.queryCompare(), helper.dedup(), helper.querySteppingMeta()->queryCompare());
  14003. merger.initInputs(expandedInputs.length(), expandedInputs.getArray());
  14004. }
  14005. virtual void stop(bool aborting)
  14006. {
  14007. merger.done();
  14008. CRoxieServerNaryActivity::stop(aborting);
  14009. }
  14010. virtual void reset()
  14011. {
  14012. merger.cleanup();
  14013. CRoxieServerNaryActivity::reset();
  14014. initializedMeta = false;
  14015. }
  14016. virtual const void * nextInGroup()
  14017. {
  14018. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  14019. const void * next = merger.nextRow();
  14020. if (next)
  14021. processed++;
  14022. return next;
  14023. }
  14024. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  14025. {
  14026. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  14027. const void * next = merger.nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  14028. if (next)
  14029. processed++;
  14030. return next;
  14031. }
  14032. virtual IInputSteppingMeta * querySteppingMeta()
  14033. {
  14034. if (expandedInputs.ordinality() == 0)
  14035. return NULL;
  14036. if (!initializedMeta)
  14037. {
  14038. meta.init(helper.querySteppingMeta(), false);
  14039. ForEachItemIn(i, expandedInputs)
  14040. {
  14041. if (meta.getNumFields() == 0)
  14042. break;
  14043. IInputSteppingMeta * inputMeta = expandedInputs.item(i)->querySteppingMeta();
  14044. meta.intersect(inputMeta);
  14045. }
  14046. initializedMeta = true;
  14047. }
  14048. if (meta.getNumFields() == 0)
  14049. return NULL;
  14050. return &meta;
  14051. }
  14052. protected:
  14053. IHThorNWayMergeArg &helper;
  14054. CRoxieStreamMerger merger;
  14055. CSteppingMeta meta;
  14056. bool initializedMeta;
  14057. };
  14058. class CRoxieServerNWayMergeActivityFactory : public CRoxieServerMultiInputFactory
  14059. {
  14060. public:
  14061. CRoxieServerNWayMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14062. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  14063. {
  14064. }
  14065. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14066. {
  14067. return new CRoxieServerNWayMergeActivity(this, _probeManager, numInputs());
  14068. }
  14069. };
  14070. IRoxieServerActivityFactory *createRoxieServerNWayMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14071. {
  14072. return new CRoxieServerNWayMergeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  14073. }
  14074. //=================================================================================
  14075. class CRoxieServerNWayMergeJoinActivity : public CRoxieServerNaryActivity
  14076. {
  14077. public:
  14078. CRoxieServerNWayMergeJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs, CMergeJoinProcessor & _processor)
  14079. : CRoxieServerNaryActivity(_factory, _probeManager, _numInputs),processor(_processor),
  14080. helper((IHThorNWayMergeJoinArg &)basehelper)
  14081. {
  14082. }
  14083. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14084. {
  14085. CRoxieServerNaryActivity::start(parentExtractSize, parentExtract, paused);
  14086. ForEachItemIn(i1, expandedInputs)
  14087. {
  14088. IRoxieInput * cur = expandedInputs.item(i1);
  14089. Owned<RoxieSteppedInput> stepInput = new RoxieSteppedInput(cur);
  14090. processor.addInput(stepInput);
  14091. }
  14092. ICodeContext * codectx = ctx->queryCodeContext();
  14093. Owned<IEngineRowAllocator> inputAllocator = codectx->getRowAllocator(helper.queryInputMeta(), activityId);
  14094. Owned<IEngineRowAllocator> outputAllocator = codectx->getRowAllocator(helper.queryOutputMeta(), activityId);
  14095. processor.beforeProcessing(inputAllocator, outputAllocator);
  14096. }
  14097. virtual void stop(bool aborting)
  14098. {
  14099. processor.afterProcessing();
  14100. CRoxieServerNaryActivity::stop(aborting);
  14101. }
  14102. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  14103. {
  14104. return processor.gatherConjunctions(collector);
  14105. }
  14106. virtual void resetEOF()
  14107. {
  14108. processor.queryResetEOF();
  14109. }
  14110. virtual const void * nextInGroup()
  14111. {
  14112. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  14113. const void * next = processor.nextInGroup();
  14114. if (next)
  14115. processed++;
  14116. return next;
  14117. }
  14118. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  14119. {
  14120. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  14121. const void * next = processor.nextGE(seek, numFields, wasCompleteMatch, stepExtra);
  14122. if (next)
  14123. processed++;
  14124. return next;
  14125. }
  14126. virtual IInputSteppingMeta * querySteppingMeta()
  14127. {
  14128. return processor.queryInputSteppingMeta();
  14129. }
  14130. protected:
  14131. IHThorNWayMergeJoinArg & helper;
  14132. CMergeJoinProcessor & processor;
  14133. };
  14134. class CRoxieServerAndMergeJoinActivity : public CRoxieServerNWayMergeJoinActivity
  14135. {
  14136. public:
  14137. CRoxieServerAndMergeJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14138. : CRoxieServerNWayMergeJoinActivity(_factory, _probeManager, _numInputs, andProcessor), andProcessor(helper)
  14139. {
  14140. }
  14141. protected:
  14142. CAndMergeJoinProcessor andProcessor;
  14143. };
  14144. class CRoxieServerAndLeftMergeJoinActivity : public CRoxieServerNWayMergeJoinActivity
  14145. {
  14146. public:
  14147. CRoxieServerAndLeftMergeJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14148. : CRoxieServerNWayMergeJoinActivity(_factory, _probeManager, _numInputs, andLeftProcessor), andLeftProcessor(helper)
  14149. {
  14150. }
  14151. protected:
  14152. CAndLeftMergeJoinProcessor andLeftProcessor;
  14153. };
  14154. class CRoxieServerMofNMergeJoinActivity : public CRoxieServerNWayMergeJoinActivity
  14155. {
  14156. public:
  14157. CRoxieServerMofNMergeJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14158. : CRoxieServerNWayMergeJoinActivity(_factory, _probeManager, _numInputs, mofnProcessor), mofnProcessor(helper)
  14159. {
  14160. }
  14161. protected:
  14162. CMofNMergeJoinProcessor mofnProcessor;
  14163. };
  14164. class CRoxieServerProximityJoinActivity : public CRoxieServerNWayMergeJoinActivity
  14165. {
  14166. public:
  14167. CRoxieServerProximityJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14168. : CRoxieServerNWayMergeJoinActivity(_factory, _probeManager, _numInputs, proximityProcessor), proximityProcessor(helper)
  14169. {
  14170. }
  14171. protected:
  14172. CProximityJoinProcessor proximityProcessor;
  14173. };
  14174. class CRoxieServerNWayMergeJoinActivityFactory : public CRoxieServerMultiInputFactory
  14175. {
  14176. unsigned flags;
  14177. public:
  14178. CRoxieServerNWayMergeJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14179. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  14180. {
  14181. Owned<IHThorNWayMergeJoinArg> helper = (IHThorNWayMergeJoinArg *) helperFactory();
  14182. flags = helper->getJoinFlags();
  14183. }
  14184. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14185. {
  14186. if (flags & IHThorNWayMergeJoinArg::MJFhasrange)
  14187. return new CRoxieServerProximityJoinActivity(this, _probeManager, numInputs());
  14188. switch (flags & IHThorNWayMergeJoinArg::MJFkindmask)
  14189. {
  14190. case IHThorNWayMergeJoinArg::MJFinner:
  14191. return new CRoxieServerAndMergeJoinActivity(this, _probeManager, numInputs());
  14192. case IHThorNWayMergeJoinArg::MJFleftonly:
  14193. case IHThorNWayMergeJoinArg::MJFleftouter:
  14194. return new CRoxieServerAndLeftMergeJoinActivity(this, _probeManager, numInputs());
  14195. case IHThorNWayMergeJoinArg::MJFmofn:
  14196. return new CRoxieServerMofNMergeJoinActivity(this, _probeManager, numInputs());
  14197. default:
  14198. throwUnexpected();
  14199. }
  14200. }
  14201. };
  14202. IRoxieServerActivityFactory *createRoxieServerNWayMergeJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14203. {
  14204. return new CRoxieServerNWayMergeJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  14205. }
  14206. //=================================================================================
  14207. class CRoxieServerNWaySelectActivity : public CRoxieServerMultiInputActivity
  14208. {
  14209. IHThorNWaySelectArg &helper;
  14210. public:
  14211. CRoxieServerNWaySelectActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14212. : CRoxieServerMultiInputActivity(_factory, _probeManager, _numInputs),
  14213. helper((IHThorNWaySelectArg &)basehelper)
  14214. {
  14215. }
  14216. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14217. {
  14218. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  14219. unsigned whichInput = helper.getInputIndex();
  14220. selectedInput = NULL;
  14221. if (whichInput--)
  14222. {
  14223. for (unsigned i=0; i < numInputs; i++)
  14224. {
  14225. IRoxieInput * cur = inputArray[i];
  14226. unsigned numRealInputs = cur->numConcreteOutputs();
  14227. if (whichInput < numRealInputs)
  14228. {
  14229. selectedInput = cur->queryConcreteInput(whichInput);
  14230. break;
  14231. }
  14232. whichInput -= numRealInputs;
  14233. }
  14234. }
  14235. }
  14236. virtual void reset()
  14237. {
  14238. selectedInput = NULL;
  14239. CRoxieServerMultiInputActivity::reset();
  14240. }
  14241. const void * nextInGroup()
  14242. {
  14243. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  14244. if (!selectedInput)
  14245. return NULL;
  14246. return selectedInput->nextInGroup();
  14247. }
  14248. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  14249. {
  14250. if (!selectedInput)
  14251. return false;
  14252. return selectedInput->gatherConjunctions(collector);
  14253. }
  14254. virtual void resetEOF()
  14255. {
  14256. if (selectedInput)
  14257. selectedInput->resetEOF();
  14258. }
  14259. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  14260. {
  14261. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  14262. if (!selectedInput)
  14263. return NULL;
  14264. return selectedInput->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  14265. }
  14266. IInputSteppingMeta * querySteppingMeta()
  14267. {
  14268. if (selectedInput)
  14269. return selectedInput->querySteppingMeta();
  14270. return NULL;
  14271. }
  14272. protected:
  14273. IRoxieInput * selectedInput;
  14274. };
  14275. class CRoxieServerNWaySelectActivityFactory : public CRoxieServerMultiInputFactory
  14276. {
  14277. public:
  14278. CRoxieServerNWaySelectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14279. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  14280. {
  14281. }
  14282. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14283. {
  14284. return new CRoxieServerNWaySelectActivity(this, _probeManager, numInputs());
  14285. }
  14286. };
  14287. IRoxieServerActivityFactory *createRoxieServerNWaySelectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14288. {
  14289. return new CRoxieServerNWaySelectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  14290. }
  14291. //=================================================================================
  14292. class CRoxieServerRemoteActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler
  14293. {
  14294. protected:
  14295. IHThorRemoteArg &helper;
  14296. CRemoteResultAdaptor remote;
  14297. public:
  14298. CRoxieServerRemoteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteID)
  14299. : CRoxieServerActivity(_factory, _probeManager),
  14300. helper((IHThorRemoteArg &)basehelper),
  14301. remote(_remoteID, meta.queryOriginal(), helper, *this, false, false) // MORE - if they need it stable we'll have to think!
  14302. {
  14303. }
  14304. virtual const IResolvedFile *queryVarFileInfo() const
  14305. {
  14306. return NULL;
  14307. }
  14308. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  14309. {
  14310. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  14311. remote.onCreate(this, this, _ctx, _colocalParent);
  14312. }
  14313. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14314. {
  14315. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14316. remote.onStart(parentExtractSize, parentExtract);
  14317. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  14318. unsigned fileNo = 0; // MORE - superfiles require us to do this per file part... maybe (needs thought)
  14319. remote.getMem(0, fileNo, 0); // the cached context is all we need to send
  14320. remote.flush();
  14321. remote.senddone();
  14322. }
  14323. virtual void setInput(unsigned idx, IRoxieInput *_in)
  14324. {
  14325. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  14326. }
  14327. virtual IRoxieInput *queryOutput(unsigned idx)
  14328. {
  14329. if (idx==(unsigned)-1)
  14330. idx = 0;
  14331. return idx ? NULL: &remote;
  14332. }
  14333. virtual void reset()
  14334. {
  14335. processed = remote.processed;
  14336. remote.processed = 0;
  14337. CRoxieServerActivity::reset();
  14338. }
  14339. virtual void onLimitExceeded(bool isKeyed)
  14340. {
  14341. if (traceLevel > 4)
  14342. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  14343. helper.onLimitExceeded();
  14344. }
  14345. virtual const void *createLimitFailRow(bool isKeyed)
  14346. {
  14347. UNIMPLEMENTED; // MORE - is there an ONFAIL for a limit folded into a remote?
  14348. }
  14349. virtual const void *nextInGroup()
  14350. {
  14351. throwUnexpected(); // I am nobody's input
  14352. }
  14353. };
  14354. class CRoxieServerRemoteActivityFactory : public CRoxieServerActivityFactory
  14355. {
  14356. public:
  14357. RemoteActivityId remoteId;
  14358. bool isRoot;
  14359. CRoxieServerRemoteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, bool _isRoot)
  14360. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), remoteId(_remoteId), isRoot(_isRoot)
  14361. {
  14362. }
  14363. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14364. {
  14365. return new CRoxieServerRemoteActivity(this, _probeManager, remoteId);
  14366. }
  14367. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  14368. {
  14369. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  14370. }
  14371. virtual bool isSink() const
  14372. {
  14373. //I don't think the action version of this is implemented - but this would be the code
  14374. return isRoot && !meta.queryOriginal();
  14375. }
  14376. };
  14377. IRoxieServerActivityFactory *createRoxieServerRemoteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, bool _isRoot)
  14378. {
  14379. return new CRoxieServerRemoteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _isRoot);
  14380. }
  14381. //=================================================================================
  14382. class CRoxieServerIterateActivity : public CRoxieServerActivity
  14383. {
  14384. IHThorIterateArg &helper;
  14385. OwnedConstRoxieRow defaultRecord;
  14386. OwnedConstRoxieRow left;
  14387. OwnedConstRoxieRow right;
  14388. unsigned counter;
  14389. public:
  14390. CRoxieServerIterateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  14391. : CRoxieServerActivity(_factory, _probeManager),
  14392. helper((IHThorIterateArg &)basehelper)
  14393. {
  14394. counter = 0;
  14395. }
  14396. virtual bool needsAllocator() const { return true; }
  14397. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14398. {
  14399. counter = 0;
  14400. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14401. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  14402. size32_t thisSize = helper.createDefault(rowBuilder);
  14403. defaultRecord.setown(rowBuilder.finalizeRowClear(thisSize));
  14404. }
  14405. virtual void reset()
  14406. {
  14407. defaultRecord.clear();
  14408. right.clear();
  14409. left.clear();
  14410. CRoxieServerActivity::reset();
  14411. }
  14412. virtual const void * nextInGroup()
  14413. {
  14414. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  14415. loop
  14416. {
  14417. right.setown(input->nextInGroup());
  14418. if (!right)
  14419. {
  14420. bool skippedGroup = (left == NULL) && (counter > 0); //we have just skipped entire group, but shouldn't output a double null
  14421. left.clear();
  14422. counter = 0;
  14423. if (skippedGroup) continue;
  14424. return NULL;
  14425. }
  14426. try
  14427. {
  14428. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  14429. unsigned outSize = helper.transform(rowBuilder, left ? left : defaultRecord, right, ++counter);
  14430. if (outSize)
  14431. {
  14432. left.setown(rowBuilder.finalizeRowClear(outSize));
  14433. processed++;
  14434. return left.getLink();
  14435. }
  14436. }
  14437. catch (IException *E)
  14438. {
  14439. throw makeWrappedException(E);
  14440. }
  14441. }
  14442. }
  14443. };
  14444. class CRoxieServerIterateActivityFactory : public CRoxieServerActivityFactory
  14445. {
  14446. public:
  14447. CRoxieServerIterateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14448. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  14449. {
  14450. }
  14451. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14452. {
  14453. return new CRoxieServerIterateActivity(this, _probeManager);
  14454. }
  14455. };
  14456. IRoxieServerActivityFactory *createRoxieServerIterateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14457. {
  14458. return new CRoxieServerIterateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  14459. }
  14460. //=================================================================================
  14461. class CRoxieServerProcessActivity : public CRoxieServerActivity
  14462. {
  14463. IHThorProcessArg &helper;
  14464. OwnedConstRoxieRow curRight;
  14465. OwnedConstRoxieRow initialRight;
  14466. unsigned counter;
  14467. Owned<IEngineRowAllocator> rightRowAllocator;
  14468. public:
  14469. CRoxieServerProcessActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  14470. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorProcessArg &)basehelper)
  14471. {
  14472. counter = 0;
  14473. }
  14474. virtual bool needsAllocator() const { return true; }
  14475. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  14476. {
  14477. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  14478. rightRowAllocator.setown(ctx->queryCodeContext()->getRowAllocator(QUERYINTERFACE(helper.queryRightRecordSize(), IOutputMetaData), activityId));
  14479. }
  14480. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14481. {
  14482. counter = 0;
  14483. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14484. RtlDynamicRowBuilder rowBuilder(rightRowAllocator);
  14485. size32_t thisSize = helper.createInitialRight(rowBuilder);
  14486. initialRight.setown(rowBuilder.finalizeRowClear(thisSize));
  14487. curRight.set(initialRight);
  14488. }
  14489. virtual const void * nextInGroup()
  14490. {
  14491. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  14492. try
  14493. {
  14494. loop
  14495. {
  14496. const void * in = input->nextInGroup();
  14497. if (!in)
  14498. {
  14499. bool eog = (curRight != initialRight); // processed any records?
  14500. counter = 0;
  14501. curRight.set(initialRight);
  14502. if (eog)
  14503. return NULL;
  14504. in = input->nextInGroup();
  14505. if (!in)
  14506. return NULL;
  14507. }
  14508. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  14509. RtlDynamicRowBuilder rightRowBuilder(rightRowAllocator);
  14510. size32_t outSize = helper.transform(rowBuilder, rightRowBuilder, in, curRight, ++counter);
  14511. ReleaseRoxieRow(in);
  14512. if (outSize)
  14513. {
  14514. //MORE: This should be returned...
  14515. size32_t rightSize = rightRowAllocator->queryOutputMeta()->getRecordSize(rightRowBuilder.getSelf());
  14516. curRight.setown(rightRowBuilder.finalizeRowClear(rightSize));
  14517. processed++;
  14518. return rowBuilder.finalizeRowClear(outSize);
  14519. }
  14520. }
  14521. }
  14522. catch (IException *E)
  14523. {
  14524. throw makeWrappedException(E);
  14525. }
  14526. }
  14527. };
  14528. class CRoxieServerProcessActivityFactory : public CRoxieServerActivityFactory
  14529. {
  14530. public:
  14531. CRoxieServerProcessActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14532. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  14533. {
  14534. }
  14535. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14536. {
  14537. return new CRoxieServerProcessActivity(this, _probeManager);
  14538. }
  14539. };
  14540. IRoxieServerActivityFactory *createRoxieServerProcessActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14541. {
  14542. return new CRoxieServerProcessActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  14543. }
  14544. //=================================================================================
  14545. class CRoxieServerGroupActivity : public CRoxieServerActivity
  14546. {
  14547. IHThorGroupArg &helper;
  14548. bool endPending;
  14549. bool eof;
  14550. bool first;
  14551. const void *next;
  14552. public:
  14553. CRoxieServerGroupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  14554. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorGroupArg &)basehelper)
  14555. {
  14556. next = NULL;
  14557. endPending = false;
  14558. eof = false;
  14559. first = true;
  14560. }
  14561. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14562. {
  14563. endPending = false;
  14564. eof = false;
  14565. first = true;
  14566. assertex(next == NULL);
  14567. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14568. }
  14569. virtual void reset()
  14570. {
  14571. ReleaseClearRoxieRow(next);
  14572. CRoxieServerActivity::reset();
  14573. }
  14574. virtual const void * nextInGroup()
  14575. {
  14576. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  14577. if (first)
  14578. {
  14579. next = input->nextInGroup();
  14580. first = false;
  14581. }
  14582. if (eof || endPending)
  14583. {
  14584. endPending = false;
  14585. return NULL;
  14586. }
  14587. const void * prev = next;
  14588. next = input->nextInGroup();
  14589. if (!next)
  14590. next = input->nextInGroup();
  14591. if (next)
  14592. {
  14593. assertex(prev);
  14594. if (!helper.isSameGroup(prev, next))
  14595. endPending = true;
  14596. }
  14597. else
  14598. eof = true;
  14599. if (prev)
  14600. processed++;
  14601. return prev;
  14602. }
  14603. };
  14604. class CRoxieServerGroupActivityFactory : public CRoxieServerActivityFactory
  14605. {
  14606. public:
  14607. CRoxieServerGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14608. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  14609. {
  14610. }
  14611. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14612. {
  14613. return new CRoxieServerGroupActivity(this, _probeManager);
  14614. }
  14615. };
  14616. IRoxieServerActivityFactory *createRoxieServerGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14617. {
  14618. return new CRoxieServerGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  14619. }
  14620. //=================================================================================
  14621. class CRoxieServerFirstNActivity : public CRoxieServerLateStartActivity
  14622. {
  14623. unsigned __int64 limit;
  14624. unsigned __int64 skip;
  14625. unsigned doneThisGroup;
  14626. IHThorFirstNArg &helper;
  14627. public:
  14628. CRoxieServerFirstNActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  14629. : CRoxieServerLateStartActivity(_factory, _probeManager), helper((IHThorFirstNArg &)basehelper)
  14630. {
  14631. doneThisGroup = 0;
  14632. limit = 0;
  14633. skip = 0;
  14634. }
  14635. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14636. {
  14637. doneThisGroup = 0;
  14638. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  14639. limit = helper.getLimit();
  14640. skip = helper.numToSkip();
  14641. lateStart(parentExtractSize, parentExtract, limit > 0);
  14642. if (limit + skip >= limit)
  14643. limit += skip;
  14644. }
  14645. const void * nextInGroup()
  14646. {
  14647. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  14648. if (eof)
  14649. return NULL;
  14650. const void *ret;
  14651. loop
  14652. {
  14653. ret = input->nextInGroup();
  14654. if (!ret)
  14655. {
  14656. if (meta.isGrouped())
  14657. {
  14658. if (doneThisGroup > skip)
  14659. {
  14660. doneThisGroup = 0;
  14661. return NULL;
  14662. }
  14663. doneThisGroup = 0;
  14664. }
  14665. ret = input->nextInGroup();
  14666. if (!ret)
  14667. {
  14668. eof = true;
  14669. return NULL;
  14670. }
  14671. }
  14672. doneThisGroup++;
  14673. if (doneThisGroup > skip)
  14674. break;
  14675. ReleaseRoxieRow(ret);
  14676. }
  14677. if (doneThisGroup <= limit)
  14678. {
  14679. processed++;
  14680. return ret;
  14681. }
  14682. ReleaseRoxieRow(ret);
  14683. if (meta.isGrouped())
  14684. {
  14685. while ((ret = input->nextInGroup()) != NULL)
  14686. ReleaseRoxieRow(ret);
  14687. doneThisGroup = 0;
  14688. }
  14689. else
  14690. eof = true;
  14691. return NULL;
  14692. }
  14693. };
  14694. class CRoxieServerFirstNActivityFactory : public CRoxieServerActivityFactory
  14695. {
  14696. public:
  14697. CRoxieServerFirstNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14698. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  14699. {
  14700. }
  14701. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14702. {
  14703. return new CRoxieServerFirstNActivity(this, _probeManager);
  14704. }
  14705. };
  14706. IRoxieServerActivityFactory *createRoxieServerFirstNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14707. {
  14708. return new CRoxieServerFirstNActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  14709. }
  14710. //=================================================================================
  14711. class CRoxieServerSelectNActivity : public CRoxieServerActivity
  14712. {
  14713. bool done;
  14714. IHThorSelectNArg &helper;
  14715. public:
  14716. CRoxieServerSelectNActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  14717. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorSelectNArg &)basehelper)
  14718. {
  14719. done = false;
  14720. }
  14721. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14722. {
  14723. done = false;
  14724. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14725. }
  14726. const void *defaultRow()
  14727. {
  14728. if (!rowAllocator)
  14729. createRowAllocator(); // We delay as often not needed...
  14730. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  14731. size32_t thisSize = helper.createDefault(rowBuilder);
  14732. return rowBuilder.finalizeRowClear(thisSize);
  14733. }
  14734. virtual const void * nextInGroup()
  14735. {
  14736. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  14737. if (done)
  14738. return NULL;
  14739. done = true;
  14740. processed++; // always going to return a row!
  14741. unsigned __int64 index = helper.getRowToSelect();
  14742. while (--index)
  14743. {
  14744. const void * next = input->nextInGroup();
  14745. if (!next)
  14746. next = input->nextInGroup();
  14747. if (!next)
  14748. return defaultRow();
  14749. ReleaseRoxieRow(next);
  14750. }
  14751. const void * next = input->nextInGroup();
  14752. if (!next)
  14753. next = input->nextInGroup();
  14754. if (!next)
  14755. next = defaultRow();
  14756. return next;
  14757. }
  14758. };
  14759. class CRoxieServerSelectNActivityFactory : public CRoxieServerActivityFactory
  14760. {
  14761. public:
  14762. CRoxieServerSelectNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14763. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  14764. {
  14765. }
  14766. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14767. {
  14768. return new CRoxieServerSelectNActivity(this, _probeManager);
  14769. }
  14770. };
  14771. IRoxieServerActivityFactory *createRoxieServerSelectNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14772. {
  14773. return new CRoxieServerSelectNActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  14774. }
  14775. //=================================================================================
  14776. class CRoxieServerSelfJoinActivity : public CRoxieServerActivity
  14777. {
  14778. IHThorJoinArg &helper;
  14779. ICompare *collate;
  14780. OwnedRowArray group;
  14781. bool matchedLeft;
  14782. BoolArray matchedRight;
  14783. bool eof;
  14784. bool first;
  14785. unsigned leftIndex;
  14786. unsigned rightIndex;
  14787. unsigned rightOuterIndex;
  14788. unsigned joinLimit;
  14789. unsigned atmostLimit;
  14790. unsigned atmostsTriggered;
  14791. unsigned abortLimit;
  14792. unsigned keepLimit;
  14793. bool leftOuterJoin;
  14794. bool rightOuterJoin;
  14795. bool exclude;
  14796. bool limitFail;
  14797. bool limitOnFail;
  14798. bool cloneLeft;
  14799. OwnedConstRoxieRow defaultLeft;
  14800. OwnedConstRoxieRow defaultRight;
  14801. OwnedConstRoxieRow lhs;
  14802. Owned<IException> failingLimit;
  14803. bool failingOuterAtmost;
  14804. Owned<IEngineRowAllocator> defaultAllocator;
  14805. Owned<IRHLimitedCompareHelper> limitedhelper;
  14806. Owned<CRHDualCache> dualcache;
  14807. IInputBase *dualCacheInput;
  14808. bool fillGroup()
  14809. {
  14810. group.clear();
  14811. matchedLeft = false;
  14812. matchedRight.kill();
  14813. failingOuterAtmost = false;
  14814. const void * next;
  14815. unsigned groupCount = 0;
  14816. while((next = input->nextInGroup()) != NULL)
  14817. {
  14818. if(groupCount==abortLimit)
  14819. {
  14820. if(limitFail)
  14821. failLimit(next);
  14822. if (ctx->queryDebugContext())
  14823. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  14824. if(limitOnFail)
  14825. {
  14826. assertex(!failingLimit);
  14827. try
  14828. {
  14829. failLimit(next);
  14830. }
  14831. catch(IException * except)
  14832. {
  14833. failingLimit.setown(except);
  14834. }
  14835. assertex(failingLimit != NULL);
  14836. group.append(next);
  14837. groupCount++;
  14838. break;
  14839. }
  14840. group.clear();
  14841. groupCount = 0;
  14842. while(next)
  14843. {
  14844. ReleaseRoxieRow(next);
  14845. next = input->nextInGroup();
  14846. }
  14847. }
  14848. else if(groupCount==atmostLimit)
  14849. {
  14850. atmostsTriggered++;
  14851. if(leftOuterJoin)
  14852. {
  14853. group.append(next);
  14854. groupCount++;
  14855. failingOuterAtmost = true;
  14856. break;
  14857. }
  14858. else
  14859. {
  14860. group.clear();
  14861. groupCount = 0;
  14862. while (next)
  14863. {
  14864. ReleaseRoxieRow(next);
  14865. next = input->nextInGroup();
  14866. }
  14867. }
  14868. }
  14869. else
  14870. {
  14871. group.append(next);
  14872. groupCount++;
  14873. }
  14874. }
  14875. if(group.ordinality()==0)
  14876. {
  14877. eof = true;
  14878. return false;
  14879. }
  14880. leftIndex = 0;
  14881. rightIndex = 0;
  14882. rightOuterIndex = 0;
  14883. joinLimit = keepLimit;
  14884. ForEachItemIn(idx, group)
  14885. matchedRight.append(false);
  14886. return true;
  14887. }
  14888. void failLimit(const void * next)
  14889. {
  14890. helper.onMatchAbortLimitExceeded();
  14891. CommonXmlWriter xmlwrite(XWFtrim|XWFopt );
  14892. if (!ctx->isBlind() && input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  14893. {
  14894. input->queryOutputMeta()->toXML((byte *) next, xmlwrite);
  14895. }
  14896. throw MakeStringException(ROXIE_TOO_MANY_RESULTS, "More than %d match candidates in self-join %d for row %s", abortLimit, queryId(), xmlwrite.str());
  14897. }
  14898. virtual bool needsAllocator() const { return true; }
  14899. const void *joinRecords(const void * curLeft, const void * curRight, IException * except = NULL)
  14900. {
  14901. try
  14902. {
  14903. if (cloneLeft && !except)
  14904. {
  14905. LinkRoxieRow(curLeft);
  14906. return curLeft;
  14907. }
  14908. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  14909. size32_t outsize = except ? helper.onFailTransform(rowBuilder, curLeft, curRight, except) : helper.transform(rowBuilder, curLeft, curRight);
  14910. if (outsize)
  14911. return rowBuilder.finalizeRowClear(outsize);
  14912. else
  14913. return NULL;
  14914. }
  14915. catch (IException *E)
  14916. {
  14917. throw makeWrappedException(E);
  14918. }
  14919. }
  14920. void createDefaultLeft()
  14921. {
  14922. if (!defaultLeft)
  14923. {
  14924. if (!defaultAllocator)
  14925. defaultAllocator.setown(ctx->queryCodeContext()->getRowAllocator(input->queryOutputMeta(), activityId));
  14926. RtlDynamicRowBuilder rowBuilder(defaultAllocator);
  14927. size32_t thisSize = helper.createDefaultLeft(rowBuilder);
  14928. defaultLeft.setown(rowBuilder.finalizeRowClear(thisSize));
  14929. }
  14930. }
  14931. void createDefaultRight()
  14932. {
  14933. if (!defaultRight)
  14934. {
  14935. if (!defaultAllocator)
  14936. defaultAllocator.setown(ctx->queryCodeContext()->getRowAllocator(input->queryOutputMeta(), activityId));
  14937. RtlDynamicRowBuilder rowBuilder(defaultAllocator);
  14938. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  14939. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  14940. }
  14941. }
  14942. public:
  14943. CRoxieServerSelfJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  14944. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorJoinArg &)basehelper)
  14945. {
  14946. collate = helper.queryCompareLeftRight();
  14947. eof = false;
  14948. first = true;
  14949. keepLimit = 0;
  14950. atmostLimit = 0;
  14951. atmostsTriggered = 0;
  14952. unsigned joinFlags = helper.getJoinFlags();
  14953. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  14954. rightOuterJoin = (joinFlags & JFrightouter) != 0;
  14955. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  14956. exclude = (joinFlags & JFexclude) != 0;
  14957. abortLimit = 0;
  14958. joinLimit = 0;
  14959. assertex((joinFlags & (JFfirst | JFfirstleft | JFfirstright)) == 0); // no longer supported
  14960. getLimitType(joinFlags, limitFail, limitOnFail);
  14961. if((joinFlags & JFslidingmatch) != 0)
  14962. throw MakeStringException(ROXIE_UNIMPLEMENTED_ERROR, "Internal Error: Sliding self join not supported");
  14963. failingOuterAtmost = false;
  14964. matchedLeft = false;
  14965. leftIndex = 0;
  14966. rightIndex = 0;
  14967. rightOuterIndex = 0;
  14968. dualCacheInput = NULL;
  14969. }
  14970. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14971. {
  14972. eof = false;
  14973. first = true;
  14974. failingLimit.clear();
  14975. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14976. keepLimit = helper.getKeepLimit();
  14977. if(keepLimit == 0)
  14978. keepLimit = (unsigned)-1;
  14979. atmostsTriggered = 0;
  14980. atmostLimit = helper.getJoinLimit();
  14981. if(atmostLimit == 0)
  14982. atmostLimit = (unsigned)-1;
  14983. else
  14984. assertex(!rightOuterJoin);
  14985. abortLimit = helper.getMatchAbortLimit();
  14986. if (abortLimit == 0)
  14987. abortLimit = (unsigned)-1;
  14988. if (rightOuterJoin)
  14989. createDefaultLeft();
  14990. if (leftOuterJoin || limitOnFail)
  14991. createDefaultRight();
  14992. if ((helper.getJoinFlags() & JFlimitedprefixjoin) && helper.getJoinLimit())
  14993. { //limited match join (s[1..n])
  14994. dualcache.setown(new CRHDualCache());
  14995. dualcache->init(CRoxieServerActivity::input);
  14996. dualCacheInput = dualcache->queryOut1();
  14997. failingOuterAtmost = false;
  14998. matchedLeft = false;
  14999. leftIndex = 0;
  15000. rightOuterIndex = 0;
  15001. limitedhelper.setown(createRHLimitedCompareHelper());
  15002. limitedhelper->init( helper.getJoinLimit(), dualcache->queryOut2(), collate, helper.queryPrefixCompare() );
  15003. }
  15004. }
  15005. virtual void reset()
  15006. {
  15007. if (atmostsTriggered)
  15008. noteStatistic(STATS_ATMOST, atmostsTriggered, 1);
  15009. group.clear();
  15010. CRoxieServerActivity::reset();
  15011. defaultLeft.clear();
  15012. defaultRight.clear();
  15013. }
  15014. virtual const void * nextInGroup()
  15015. {
  15016. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  15017. if (limitedhelper)
  15018. {
  15019. while(!eof) //limited match join
  15020. {
  15021. if (!group.isItem(rightIndex))
  15022. {
  15023. lhs.setown(dualCacheInput->nextInGroup());
  15024. if (lhs)
  15025. {
  15026. rightIndex = 0;
  15027. group.clear();
  15028. limitedhelper->getGroup(group,lhs);
  15029. }
  15030. else
  15031. {
  15032. eof = true;
  15033. }
  15034. }
  15035. if (group.isItem(rightIndex))
  15036. {
  15037. const void * rhs = group.item(rightIndex++);
  15038. if(helper.match(lhs, rhs))
  15039. {
  15040. const void * ret = joinRecords(lhs, rhs);
  15041. return ret;
  15042. }
  15043. }
  15044. }
  15045. return NULL;
  15046. }
  15047. else
  15048. {
  15049. if (first)
  15050. {
  15051. first = false;
  15052. fillGroup();
  15053. }
  15054. while(!eof)
  15055. {
  15056. if(failingOuterAtmost)
  15057. while(group.isItem(leftIndex))
  15058. {
  15059. const void * ret = joinRecords(group.item(leftIndex++), defaultRight);
  15060. if(ret)
  15061. {
  15062. processed++;
  15063. return ret;
  15064. }
  15065. }
  15066. if((joinLimit == 0) || !group.isItem(rightIndex))
  15067. {
  15068. if(leftOuterJoin && !matchedLeft && !failingLimit)
  15069. {
  15070. const void * ret = joinRecords(group.item(leftIndex), defaultRight);
  15071. if(ret)
  15072. {
  15073. matchedLeft = true;
  15074. processed++;
  15075. return ret;
  15076. }
  15077. }
  15078. leftIndex++;
  15079. matchedLeft = false;
  15080. rightIndex = 0;
  15081. joinLimit = keepLimit;
  15082. }
  15083. if(!group.isItem(leftIndex))
  15084. {
  15085. if(failingLimit || failingOuterAtmost)
  15086. {
  15087. const void * lhs;
  15088. while((lhs = input->nextInGroup()) != NULL) // dualCache never active here
  15089. {
  15090. const void * ret = joinRecords(lhs, defaultRight, failingLimit);
  15091. ReleaseRoxieRow(lhs);
  15092. if(ret)
  15093. {
  15094. processed++;
  15095. return ret;
  15096. }
  15097. }
  15098. failingLimit.clear();
  15099. }
  15100. if(rightOuterJoin && !failingLimit)
  15101. while(group.isItem(rightOuterIndex))
  15102. if(!matchedRight.item(rightOuterIndex++))
  15103. {
  15104. const void * ret = joinRecords(defaultLeft, group.item(rightOuterIndex-1));
  15105. if(ret)
  15106. {
  15107. processed++;
  15108. return ret;
  15109. }
  15110. }
  15111. if(!fillGroup())
  15112. return NULL;
  15113. continue;
  15114. }
  15115. const void * lhs = group.item(leftIndex);
  15116. if(failingLimit)
  15117. {
  15118. leftIndex++;
  15119. const void * ret = joinRecords(lhs, defaultRight, failingLimit);
  15120. if(ret)
  15121. {
  15122. processed++;
  15123. return ret;
  15124. }
  15125. }
  15126. else
  15127. {
  15128. const void * rhs = group.item(rightIndex++);
  15129. if(helper.match(lhs, rhs))
  15130. {
  15131. matchedLeft = true;
  15132. matchedRight.replace(true, rightIndex-1);
  15133. if(!exclude)
  15134. {
  15135. const void * ret = joinRecords(lhs, rhs);
  15136. if(ret)
  15137. {
  15138. processed++;
  15139. joinLimit--;
  15140. return ret;
  15141. }
  15142. }
  15143. }
  15144. }
  15145. }
  15146. return NULL;
  15147. }
  15148. }
  15149. };
  15150. class CRoxieServerSelfJoinActivityFactory : public CRoxieServerActivityFactory
  15151. {
  15152. public:
  15153. CRoxieServerSelfJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  15154. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  15155. {
  15156. }
  15157. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  15158. {
  15159. return new CRoxieServerSelfJoinActivity(this, _probeManager);
  15160. }
  15161. };
  15162. IRoxieServerActivityFactory *createRoxieServerSelfJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  15163. {
  15164. return new CRoxieServerSelfJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  15165. }
  15166. //=====================================================================================================
  15167. class CRoxieServerLookupJoinActivity : public CRoxieServerTwoInputActivity
  15168. {
  15169. private:
  15170. class LookupTable : public CInterface
  15171. {
  15172. public:
  15173. LookupTable(unsigned _size, ICompare * _leftRightCompare, ICompare * _rightCompare, IHash * _leftHash, IHash * _rightHash, bool _dedupOnAdd)
  15174. : leftRightCompare(_leftRightCompare), rightCompare(_rightCompare), leftHash(_leftHash), rightHash(_rightHash), dedupOnAdd(_dedupOnAdd)
  15175. {
  15176. unsigned minsize = (4*_size)/3;
  15177. size = 2;
  15178. while((minsize >>= 1) > 0)
  15179. size <<= 1;
  15180. mask = size - 1;
  15181. table = (const void * *)calloc(size, sizeof(void *));
  15182. findex = BadIndex;
  15183. }
  15184. ~LookupTable()
  15185. {
  15186. unsigned i;
  15187. for(i=0; i<size; i++)
  15188. ReleaseRoxieRow(table[i]);
  15189. free(table);
  15190. }
  15191. void add(const void * right)
  15192. {
  15193. findex = BadIndex;
  15194. unsigned start = rightHash->hash(right) & mask;
  15195. unsigned index = start;
  15196. while(table[index])
  15197. {
  15198. if(dedupOnAdd && (rightCompare->docompare(table[index], right) == 0))
  15199. {
  15200. ReleaseRoxieRow(right);
  15201. return;
  15202. }
  15203. index++;
  15204. if(index==size)
  15205. index = 0;
  15206. if(index==start)
  15207. throwUnexpected(); //table is full, should never happen
  15208. }
  15209. table[index] = right;
  15210. }
  15211. const void *find(const void * left) const
  15212. {
  15213. fstart = leftHash->hash(left) & mask;
  15214. findex = fstart;
  15215. return doFind(left);
  15216. }
  15217. const void *findNext(const void * left) const
  15218. {
  15219. if(findex == BadIndex)
  15220. return NULL;
  15221. advance();
  15222. return doFind(left);
  15223. }
  15224. void advance() const
  15225. {
  15226. findex++;
  15227. if(findex==size)
  15228. findex = 0;
  15229. if(findex==fstart)
  15230. throw MakeStringException(ROXIE_JOIN_ERROR, "Internal error hthor lookup join activity (hash table full on lookup)");
  15231. }
  15232. const void *doFind(const void * left) const
  15233. {
  15234. while(table[findex])
  15235. {
  15236. if(leftRightCompare->docompare(left, table[findex]) == 0)
  15237. return table[findex];
  15238. advance();
  15239. }
  15240. findex = BadIndex;
  15241. return NULL;
  15242. }
  15243. private:
  15244. ICompare * leftRightCompare;
  15245. ICompare * rightCompare;
  15246. IHash * leftHash;
  15247. IHash * rightHash;
  15248. unsigned size;
  15249. unsigned mask;
  15250. const void * * table;
  15251. bool dedupOnAdd;
  15252. unsigned mutable fstart;
  15253. unsigned mutable findex;
  15254. static unsigned const BadIndex;
  15255. };
  15256. IHThorHashJoinArg &helper;
  15257. bool leftOuterJoin;
  15258. bool exclude;
  15259. bool eog;
  15260. bool many;
  15261. bool dedupRHS;
  15262. bool matchedGroup;
  15263. const void *left;
  15264. OwnedConstRoxieRow defaultRight;
  15265. Owned<LookupTable> table;
  15266. unsigned keepLimit;
  15267. unsigned atmostLimit;
  15268. unsigned atmostsTriggered;
  15269. unsigned limitLimit;
  15270. bool limitFail;
  15271. bool limitOnFail;
  15272. bool hasGroupLimit;
  15273. bool isSmartJoin;
  15274. unsigned keepCount;
  15275. bool gotMatch;
  15276. bool cloneLeft;
  15277. ConstPointerArray rightGroup;
  15278. aindex_t rightGroupIndex;
  15279. Owned<IException> failingLimit;
  15280. ConstPointerArray filteredRight;
  15281. ThorActivityKind activityKind;
  15282. Owned<IEngineRowAllocator> defaultRightAllocator;
  15283. void createDefaultRight()
  15284. {
  15285. if (!defaultRight)
  15286. {
  15287. if (!defaultRightAllocator)
  15288. defaultRightAllocator.setown(ctx->queryCodeContext()->getRowAllocator(input1->queryOutputMeta(), activityId));
  15289. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  15290. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  15291. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  15292. }
  15293. }
  15294. public:
  15295. CRoxieServerLookupJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  15296. : CRoxieServerTwoInputActivity(_factory, _probeManager), helper((IHThorHashJoinArg &)basehelper)
  15297. {
  15298. unsigned joinFlags = helper.getJoinFlags();
  15299. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  15300. assertex((joinFlags & JFrightouter) == 0);
  15301. exclude = (joinFlags & JFexclude) != 0;
  15302. many = (joinFlags & JFmanylookup) != 0;
  15303. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  15304. dedupRHS = (joinFlags & (JFmanylookup | JFmatchrequired | JFtransformMaySkip)) == 0; // optimisation: can implicitly dedup RHS unless is many lookup, or match required, or transform may skip
  15305. left = NULL;
  15306. activityKind = factory->getKind();
  15307. eog = false;
  15308. matchedGroup = false;
  15309. gotMatch = false;
  15310. keepLimit = 0;
  15311. keepCount = 0;
  15312. atmostLimit = 0;
  15313. atmostsTriggered = 0;
  15314. limitLimit = 0;
  15315. hasGroupLimit = false;
  15316. isSmartJoin = (joinFlags & JFsmart) != 0;
  15317. getLimitType(joinFlags, limitFail, limitOnFail);
  15318. }
  15319. void loadRight()
  15320. {
  15321. ConstPointerArray rightset;
  15322. unsigned i = 0;
  15323. try
  15324. {
  15325. const void * next;
  15326. while(true)
  15327. {
  15328. next = input1->nextInGroup();
  15329. if(!next)
  15330. next = input1->nextInGroup();
  15331. if(!next)
  15332. break;
  15333. rightset.append(next);
  15334. }
  15335. unsigned rightord = rightset.ordinality();
  15336. table.setown(new LookupTable(rightord, helper.queryCompareLeftRight(), helper.queryCompareRight(), helper.queryHashLeft(), helper.queryHashRight(), dedupRHS));
  15337. for(i=0; i<rightord; i++)
  15338. table->add(rightset.item(i));
  15339. }
  15340. catch (...)
  15341. {
  15342. unsigned rightord = rightset.ordinality();
  15343. for ( ; i<rightord; i++)
  15344. ReleaseRoxieRow(rightset.item(i));
  15345. throw;
  15346. }
  15347. };
  15348. virtual void reset()
  15349. {
  15350. if (atmostsTriggered)
  15351. noteStatistic(STATS_ATMOST, atmostsTriggered, 1);
  15352. CRoxieServerTwoInputActivity::reset();
  15353. ReleaseClearRoxieRow(left);
  15354. defaultRight.clear();
  15355. table.clear();
  15356. }
  15357. virtual bool needsAllocator() const { return true; }
  15358. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15359. {
  15360. eog = false;
  15361. matchedGroup = false;
  15362. left = NULL;
  15363. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  15364. keepLimit = helper.getKeepLimit();
  15365. if(keepLimit==0) keepLimit = static_cast<unsigned>(-1);
  15366. atmostsTriggered = 0;
  15367. atmostLimit = helper.getJoinLimit();
  15368. limitLimit = helper.getMatchAbortLimit();
  15369. hasGroupLimit = ((atmostLimit > 0) || (limitLimit > 0));
  15370. if(atmostLimit==0) atmostLimit = static_cast<unsigned>(-1);
  15371. if(limitLimit==0) limitLimit = static_cast<unsigned>(-1);
  15372. getLimitType(helper.getJoinFlags(), limitFail, limitOnFail);
  15373. switch (activityKind)
  15374. {
  15375. case TAKlookupjoin:
  15376. case TAKlookupdenormalizegroup:
  15377. case TAKsmartjoin:
  15378. case TAKsmartdenormalizegroup:
  15379. if (leftOuterJoin)
  15380. createDefaultRight();
  15381. break;
  15382. }
  15383. if (limitOnFail)
  15384. createDefaultRight();
  15385. }
  15386. virtual void setInput(unsigned idx, IRoxieInput *_in)
  15387. {
  15388. if (idx==1)
  15389. input1 = _in;
  15390. else
  15391. {
  15392. if ((helper.getJoinFlags() & JFparallel) != 0)
  15393. {
  15394. puller.setown(new CRoxieServerReadAheadInput(0)); // MORE - cant ask context for parallelJoinPreload as context is not yet set up.
  15395. puller->setInput(0, _in);
  15396. _in = puller;
  15397. }
  15398. CRoxieServerActivity::setInput(idx, _in);
  15399. }
  15400. }
  15401. virtual const void * nextInGroup()
  15402. {
  15403. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  15404. if(!table)
  15405. loadRight();
  15406. switch (activityKind)
  15407. {
  15408. case TAKlookupjoin:
  15409. case TAKsmartjoin:
  15410. return nextInGroupJoin();
  15411. case TAKlookupdenormalize:
  15412. case TAKlookupdenormalizegroup:
  15413. case TAKsmartdenormalize:
  15414. case TAKsmartdenormalizegroup:
  15415. return nextInGroupDenormalize();
  15416. }
  15417. throwUnexpected();
  15418. }
  15419. private:
  15420. const void * nextInGroupJoin()
  15421. {
  15422. if(!table)
  15423. loadRight();
  15424. while(true)
  15425. {
  15426. const void * right = NULL;
  15427. if(!left)
  15428. {
  15429. left = input->nextInGroup();
  15430. keepCount = keepLimit;
  15431. if(!left)
  15432. {
  15433. if (isSmartJoin)
  15434. left = input->nextInGroup();
  15435. if (!left)
  15436. {
  15437. if(matchedGroup || eog)
  15438. {
  15439. matchedGroup = false;
  15440. eog = true;
  15441. return NULL;
  15442. }
  15443. eog = true;
  15444. continue;
  15445. }
  15446. }
  15447. eog = false;
  15448. gotMatch = false;
  15449. right = getRightFirst();
  15450. }
  15451. else
  15452. right = getRightNext();
  15453. const void * ret = NULL;
  15454. if(failingLimit)
  15455. {
  15456. ret = joinException(left, failingLimit);
  15457. }
  15458. else
  15459. {
  15460. while(right)
  15461. {
  15462. if(helper.match(left, right))
  15463. {
  15464. gotMatch = true;
  15465. if(exclude)
  15466. break;
  15467. ret = joinRecords(left, right);
  15468. if(ret)
  15469. break;
  15470. }
  15471. right = getRightNext();
  15472. ret = NULL;
  15473. }
  15474. if(leftOuterJoin && !gotMatch)
  15475. {
  15476. ret = joinRecords(left, defaultRight);
  15477. gotMatch = true;
  15478. }
  15479. }
  15480. if(ret)
  15481. {
  15482. matchedGroup = true;
  15483. processed++;
  15484. if(!many || (--keepCount == 0) || failingLimit)
  15485. {
  15486. ReleaseClearRoxieRow(left);
  15487. failingLimit.clear();
  15488. }
  15489. return ret;
  15490. }
  15491. ReleaseClearRoxieRow(left);
  15492. }
  15493. }
  15494. const void * nextInGroupDenormalize()
  15495. {
  15496. while(true)
  15497. {
  15498. left = input->nextInGroup();
  15499. if(!left)
  15500. {
  15501. if (!matchedGroup || isSmartJoin)
  15502. left = input->nextInGroup();
  15503. if (!left)
  15504. {
  15505. matchedGroup = false;
  15506. return NULL;
  15507. }
  15508. }
  15509. gotMatch = false;
  15510. const void * right = getRightFirst();
  15511. const void * ret = NULL;
  15512. if (failingLimit)
  15513. ret = joinException(left, failingLimit);
  15514. else if (activityKind == TAKlookupdenormalize || activityKind == TAKsmartdenormalize)
  15515. {
  15516. OwnedConstRoxieRow newLeft;
  15517. newLeft.set(left);
  15518. unsigned rowSize = 0;
  15519. unsigned leftCount = 0;
  15520. keepCount = keepLimit;
  15521. while (right)
  15522. {
  15523. try
  15524. {
  15525. if (helper.match(left, right))
  15526. {
  15527. gotMatch = true;
  15528. if (exclude)
  15529. break;
  15530. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15531. unsigned thisSize = helper.transform(rowBuilder, newLeft, right, ++leftCount);
  15532. if (thisSize)
  15533. {
  15534. rowSize = thisSize;
  15535. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  15536. }
  15537. if(!many || (--keepCount == 0))
  15538. break;
  15539. }
  15540. right = getRightNext();
  15541. }
  15542. catch (IException *E)
  15543. {
  15544. throw makeWrappedException(E);
  15545. }
  15546. }
  15547. if (rowSize)
  15548. ret = newLeft.getClear();
  15549. else if (leftOuterJoin && !gotMatch)
  15550. {
  15551. ret = left;
  15552. left = NULL;
  15553. }
  15554. }
  15555. else
  15556. {
  15557. filteredRight.kill();
  15558. keepCount = keepLimit;
  15559. while (right)
  15560. {
  15561. if (helper.match(left, right))
  15562. {
  15563. gotMatch = true;
  15564. if(exclude)
  15565. break;
  15566. filteredRight.append(right);
  15567. if(!many || (--keepCount == 0))
  15568. break;
  15569. }
  15570. right = getRightNext();
  15571. }
  15572. if((filteredRight.ordinality() > 0) || (leftOuterJoin && !gotMatch))
  15573. ret = denormalizeRecords(left, filteredRight);
  15574. filteredRight.kill();
  15575. }
  15576. ReleaseRoxieRow(left);
  15577. left = NULL;
  15578. failingLimit.clear();
  15579. if(ret)
  15580. {
  15581. matchedGroup = true;
  15582. processed++;
  15583. return ret;
  15584. }
  15585. }
  15586. }
  15587. const void * joinRecords(const void * left, const void * right)
  15588. {
  15589. if (cloneLeft)
  15590. {
  15591. LinkRoxieRow(left);
  15592. return left;
  15593. }
  15594. try
  15595. {
  15596. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15597. unsigned outSize = helper.transform(rowBuilder, left, right);
  15598. if (outSize)
  15599. return rowBuilder.finalizeRowClear(outSize);
  15600. else
  15601. return NULL;
  15602. }
  15603. catch (IException *E)
  15604. {
  15605. throw makeWrappedException(E);
  15606. }
  15607. }
  15608. const void * joinException(const void * left, IException * except)
  15609. {
  15610. try
  15611. {
  15612. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15613. unsigned outSize = helper.onFailTransform(rowBuilder, left, defaultRight, except);
  15614. if (outSize)
  15615. return rowBuilder.finalizeRowClear(outSize);
  15616. else
  15617. return NULL;
  15618. }
  15619. catch (IException *E)
  15620. {
  15621. throw makeWrappedException(E);
  15622. }
  15623. }
  15624. const void * denormalizeRecords(const void * left, ConstPointerArray & rows)
  15625. {
  15626. try
  15627. {
  15628. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15629. unsigned numRows = rows.ordinality();
  15630. const void * right = numRows ? rows.item(0) : defaultRight.get();
  15631. unsigned outSize = helper.transform(rowBuilder, left, right, numRows, (const void * *)rows.getArray());
  15632. if (outSize)
  15633. return rowBuilder.finalizeRowClear(outSize);
  15634. else
  15635. return NULL;
  15636. }
  15637. catch (IException *E)
  15638. {
  15639. throw makeWrappedException(E);
  15640. }
  15641. }
  15642. const void * getRightFirst() { if(hasGroupLimit) return fillRightGroup(); else return table->find(left); }
  15643. const void * getRightNext() { if(hasGroupLimit) return readRightGroup(); else return table->findNext(left); }
  15644. const void * readRightGroup() { if(rightGroup.isItem(rightGroupIndex)) return rightGroup.item(rightGroupIndex++); else return NULL; }
  15645. const void *fillRightGroup()
  15646. {
  15647. rightGroup.kill();
  15648. for(const void * right = table->find(left); right; right = table->findNext(left))
  15649. {
  15650. rightGroup.append(right);
  15651. if(rightGroup.ordinality() > limitLimit)
  15652. {
  15653. if(limitFail)
  15654. failLimit();
  15655. gotMatch = true;
  15656. if (ctx->queryDebugContext())
  15657. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  15658. if(limitOnFail)
  15659. {
  15660. assertex(!failingLimit);
  15661. try
  15662. {
  15663. failLimit();
  15664. }
  15665. catch(IException * e)
  15666. {
  15667. failingLimit.setown(e);
  15668. }
  15669. assertex(failingLimit != NULL);
  15670. }
  15671. else
  15672. {
  15673. rightGroup.kill();
  15674. }
  15675. break;
  15676. }
  15677. if(rightGroup.ordinality() > atmostLimit)
  15678. {
  15679. atmostsTriggered++;
  15680. rightGroup.kill();
  15681. break;
  15682. }
  15683. }
  15684. rightGroupIndex = 0;
  15685. return readRightGroup();
  15686. }
  15687. void failLimit()
  15688. {
  15689. helper.onMatchAbortLimitExceeded();
  15690. CommonXmlWriter xmlwrite(XWFtrim|XWFopt );
  15691. if(!ctx->isBlind() && input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  15692. {
  15693. input->queryOutputMeta()->toXML(static_cast<const unsigned char *>(left), xmlwrite);
  15694. }
  15695. throw MakeStringException(ROXIE_TOO_MANY_RESULTS, "More than %u match candidates in join %d for row %s", limitLimit, queryId(), xmlwrite.str());
  15696. }
  15697. };
  15698. unsigned const CRoxieServerLookupJoinActivity::LookupTable::BadIndex(static_cast<unsigned>(-1));
  15699. class CRoxieServerLookupJoinActivityFactory : public CRoxieServerJoinActivityFactory
  15700. {
  15701. public:
  15702. CRoxieServerLookupJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  15703. : CRoxieServerJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  15704. {
  15705. Owned<IHThorHashJoinArg> helper = (IHThorHashJoinArg *) helperFactory();
  15706. if((helper->getJoinFlags() & (JFfirst | JFfirstleft | JFfirstright | JFslidingmatch)) != 0)
  15707. throw MakeStringException(ROXIE_INVALID_FLAGS, "Invalid flags for lookup join activity"); // code generator should never create such an activity
  15708. }
  15709. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  15710. {
  15711. return new CRoxieServerLookupJoinActivity(this, _probeManager);
  15712. }
  15713. };
  15714. IRoxieServerActivityFactory *createRoxieServerLookupJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  15715. {
  15716. return new CRoxieServerLookupJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  15717. }
  15718. //=====================================================================================================
  15719. class CRoxieServerAllJoinActivity : public CRoxieServerTwoInputActivity
  15720. {
  15721. private:
  15722. IHThorAllJoinArg &helper;
  15723. bool leftOuterJoin;
  15724. bool rightOuterJoin;
  15725. bool exclude;
  15726. OwnedConstRoxieRow defaultRight;
  15727. OwnedConstRoxieRow defaultLeft;
  15728. Owned<IEngineRowAllocator> defaultRightAllocator;
  15729. Owned<IEngineRowAllocator> defaultLeftAllocator;
  15730. const void *left;
  15731. unsigned countForLeft;
  15732. ConstPointerArray rightset;
  15733. BoolArray matchedRight; // MORE - could use a bitset...
  15734. unsigned keepLimit;
  15735. bool started;
  15736. bool eog;
  15737. bool eos;
  15738. bool matchedLeft;
  15739. bool matchedGroup;
  15740. bool leftIsGrouped;
  15741. bool cloneLeft;
  15742. unsigned rightIndex;
  15743. unsigned rightOrdinality;
  15744. ThorActivityKind activityKind;
  15745. ConstPointerArray filteredRight;
  15746. void createDefaultLeft()
  15747. {
  15748. if (!defaultLeft)
  15749. {
  15750. if (!defaultLeftAllocator)
  15751. defaultLeftAllocator.setown(ctx->queryCodeContext()->getRowAllocator(input->queryOutputMeta(), activityId));
  15752. RtlDynamicRowBuilder rowBuilder(defaultLeftAllocator);
  15753. size32_t thisSize = helper.createDefaultLeft(rowBuilder);
  15754. defaultLeft.setown(rowBuilder.finalizeRowClear(thisSize));
  15755. }
  15756. }
  15757. void createDefaultRight()
  15758. {
  15759. if (!defaultRight)
  15760. {
  15761. if (!defaultRightAllocator)
  15762. defaultRightAllocator.setown(ctx->queryCodeContext()->getRowAllocator(input1->queryOutputMeta(), activityId));
  15763. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  15764. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  15765. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  15766. }
  15767. }
  15768. public:
  15769. CRoxieServerAllJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  15770. : CRoxieServerTwoInputActivity(_factory, _probeManager), helper((IHThorAllJoinArg &)basehelper)
  15771. {
  15772. unsigned joinFlags = helper.getJoinFlags();
  15773. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  15774. rightOuterJoin = (joinFlags & JFrightouter) != 0;
  15775. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  15776. keepLimit = (unsigned) -1;
  15777. exclude = (joinFlags & JFexclude) != 0;
  15778. left = NULL;
  15779. started = true;
  15780. eog = false;
  15781. eos = false;
  15782. matchedLeft = false;
  15783. matchedGroup = false;
  15784. activityKind = factory->getKind();
  15785. rightIndex = 0;
  15786. rightOrdinality = 0;
  15787. leftIsGrouped = false;
  15788. countForLeft = 0;
  15789. }
  15790. virtual void reset()
  15791. {
  15792. defaultRight.clear();
  15793. defaultLeft.clear();
  15794. ReleaseRoxieRowSet(rightset);
  15795. matchedRight.kill();
  15796. CRoxieServerTwoInputActivity::reset();
  15797. }
  15798. virtual bool needsAllocator() const { return true; }
  15799. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15800. {
  15801. eog = false;
  15802. eos = false;
  15803. matchedLeft = false;
  15804. matchedGroup = false;
  15805. started = false;
  15806. left = NULL;
  15807. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  15808. keepLimit = helper.getKeepLimit();
  15809. if(keepLimit==0)
  15810. keepLimit = (unsigned) -1;
  15811. countForLeft = keepLimit;
  15812. leftIsGrouped = input->queryOutputMeta()->isGrouped();
  15813. if((activityKind==TAKalljoin || activityKind==TAKalldenormalizegroup) && leftOuterJoin)
  15814. createDefaultRight();
  15815. if(rightOuterJoin)
  15816. createDefaultLeft();
  15817. }
  15818. void loadRight()
  15819. {
  15820. const void * next;
  15821. while(true)
  15822. {
  15823. next = input1->nextInGroup();
  15824. if(!next)
  15825. next = input1->nextInGroup();
  15826. if(!next)
  15827. break;
  15828. rightset.append(next);
  15829. matchedRight.append(false);
  15830. }
  15831. rightIndex = 0;
  15832. rightOrdinality = rightset.ordinality();
  15833. }
  15834. virtual void setInput(unsigned idx, IRoxieInput *_in)
  15835. {
  15836. if (idx==1)
  15837. input1 = _in;
  15838. else
  15839. {
  15840. if ((helper.getJoinFlags() & JFparallel) != 0)
  15841. {
  15842. puller.setown(new CRoxieServerReadAheadInput(0)); // MORE - cant ask context for parallelJoinPreload as context is not yet set up.
  15843. puller->setInput(0, _in);
  15844. _in = puller;
  15845. }
  15846. CRoxieServerActivity::setInput(idx, _in);
  15847. }
  15848. }
  15849. const void * joinRecords(const void * left, const void * right)
  15850. {
  15851. // MORE - could share some code with lookup join
  15852. if (cloneLeft)
  15853. {
  15854. LinkRoxieRow(left);
  15855. return left;
  15856. }
  15857. try
  15858. {
  15859. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15860. unsigned outSize = helper.transform(rowBuilder, left, right);
  15861. if (outSize)
  15862. return rowBuilder.finalizeRowClear(outSize);
  15863. else
  15864. return NULL;
  15865. }
  15866. catch (IException *E)
  15867. {
  15868. throw makeWrappedException(E);
  15869. }
  15870. }
  15871. const void * denormalizeRecords(const void * curLeft, ConstPointerArray & rows)
  15872. {
  15873. try
  15874. {
  15875. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15876. unsigned numRows = rows.ordinality();
  15877. const void * right = numRows ? rows.item(0) : defaultRight.get();
  15878. unsigned outSize = helper.transform(rowBuilder, curLeft, right, numRows, rows.getArray());
  15879. if (outSize)
  15880. return rowBuilder.finalizeRowClear(outSize);
  15881. else
  15882. return NULL;
  15883. }
  15884. catch (IException *E)
  15885. {
  15886. throw makeWrappedException(E);
  15887. }
  15888. }
  15889. virtual const void *nextInGroup()
  15890. {
  15891. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  15892. if(!started)
  15893. {
  15894. started = true;
  15895. left = input->nextInGroup();
  15896. matchedLeft = false;
  15897. countForLeft = keepLimit;
  15898. if(left == NULL)
  15899. {
  15900. eos = true;
  15901. return NULL;
  15902. }
  15903. loadRight();
  15904. }
  15905. const void * ret;
  15906. const void * right;
  15907. if(eos)
  15908. return NULL;
  15909. while(true)
  15910. {
  15911. ret = NULL;
  15912. if((rightIndex == rightOrdinality) || (countForLeft==0))
  15913. {
  15914. if(leftOuterJoin && left && !matchedLeft)
  15915. {
  15916. switch(activityKind)
  15917. {
  15918. case TAKalljoin:
  15919. ret = joinRecords(left, defaultRight);
  15920. break;
  15921. case TAKalldenormalize:
  15922. ret = left;
  15923. left = NULL;
  15924. break;
  15925. case TAKalldenormalizegroup:
  15926. filteredRight.kill();
  15927. ret = denormalizeRecords(left, filteredRight);
  15928. break;
  15929. default:
  15930. throwUnexpected();
  15931. }
  15932. }
  15933. rightIndex = 0;
  15934. ReleaseRoxieRow(left);
  15935. left = NULL;
  15936. if(ret)
  15937. {
  15938. matchedGroup = true;
  15939. processed++;
  15940. return ret;
  15941. }
  15942. }
  15943. if(!left)
  15944. {
  15945. left = input->nextInGroup();
  15946. matchedLeft = false;
  15947. countForLeft = keepLimit;
  15948. }
  15949. if(!left)
  15950. {
  15951. if(eog)
  15952. {
  15953. eos = true;
  15954. matchedGroup = false;
  15955. return NULL;
  15956. }
  15957. eog = true;
  15958. if (matchedGroup && leftIsGrouped)
  15959. {
  15960. matchedGroup = false;
  15961. return NULL;
  15962. }
  15963. matchedGroup = false;
  15964. continue;
  15965. }
  15966. eog = false;
  15967. switch(activityKind)
  15968. {
  15969. case TAKalljoin:
  15970. while(rightIndex < rightOrdinality)
  15971. {
  15972. right = rightset.item(rightIndex);
  15973. if(helper.match(left, right))
  15974. {
  15975. matchedLeft = true;
  15976. matchedRight.replace(true, rightIndex);
  15977. if(!exclude)
  15978. ret = joinRecords(left, right);
  15979. }
  15980. rightIndex++;
  15981. if(ret)
  15982. {
  15983. countForLeft--;
  15984. matchedGroup = true;
  15985. processed++;
  15986. return ret;
  15987. }
  15988. }
  15989. break;
  15990. case TAKalldenormalize:
  15991. {
  15992. OwnedConstRoxieRow newLeft;
  15993. newLeft.set(left);
  15994. unsigned rowSize = 0;
  15995. unsigned leftCount = 0;
  15996. while((rightIndex < rightOrdinality) && countForLeft)
  15997. {
  15998. right = rightset.item(rightIndex);
  15999. if(helper.match(left, right))
  16000. {
  16001. matchedLeft = true;
  16002. matchedRight.replace(true, rightIndex);
  16003. if(!exclude)
  16004. {
  16005. try
  16006. {
  16007. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16008. unsigned thisSize = helper.transform(rowBuilder, newLeft, right, ++leftCount);
  16009. if(thisSize)
  16010. {
  16011. rowSize = thisSize;
  16012. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  16013. --countForLeft;
  16014. }
  16015. }
  16016. catch (IException *e)
  16017. {
  16018. throw makeWrappedException(e);
  16019. }
  16020. }
  16021. }
  16022. rightIndex++;
  16023. }
  16024. if(rowSize)
  16025. {
  16026. processed++;
  16027. return newLeft.getClear();
  16028. }
  16029. }
  16030. break;
  16031. case TAKalldenormalizegroup:
  16032. filteredRight.kill();
  16033. while((rightIndex < rightOrdinality) && countForLeft)
  16034. {
  16035. right = rightset.item(rightIndex);
  16036. if(helper.match(left, right))
  16037. {
  16038. matchedLeft = true;
  16039. matchedRight.replace(true, rightIndex);
  16040. filteredRight.append(right);
  16041. --countForLeft;
  16042. }
  16043. ++rightIndex;
  16044. }
  16045. if(!exclude && filteredRight.ordinality())
  16046. {
  16047. ret = denormalizeRecords(left, filteredRight);
  16048. filteredRight.kill();
  16049. if(ret)
  16050. {
  16051. processed++;
  16052. return ret;
  16053. }
  16054. }
  16055. break;
  16056. default:
  16057. throwUnexpected();
  16058. }
  16059. }
  16060. }
  16061. };
  16062. class CRoxieServerAllJoinActivityFactory : public CRoxieServerJoinActivityFactory
  16063. {
  16064. public:
  16065. CRoxieServerAllJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16066. : CRoxieServerJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  16067. {
  16068. Owned<IHThorAllJoinArg> helper = (IHThorAllJoinArg *) helperFactory();
  16069. if((helper->getJoinFlags() & (JFfirst | JFfirstleft | JFfirstright)) != 0)
  16070. throw MakeStringException(ROXIE_INVALID_FLAGS, "Invalid flags for join all activity"); // code generator should never create such an activity
  16071. }
  16072. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  16073. {
  16074. return new CRoxieServerAllJoinActivity(this, _probeManager);
  16075. }
  16076. };
  16077. IRoxieServerActivityFactory *createRoxieServerAllJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16078. {
  16079. return new CRoxieServerAllJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  16080. }
  16081. //=====================================================================================================
  16082. class CRoxieServerTopNActivity : public CRoxieServerLateStartActivity
  16083. {
  16084. unsigned limit;
  16085. bool hasBest;
  16086. bool eoi;
  16087. const void **sorted;
  16088. unsigned sortedCount;
  16089. unsigned curIndex;
  16090. IHThorTopNArg &helper;
  16091. ICompare &compare;
  16092. public:
  16093. CRoxieServerTopNActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  16094. : CRoxieServerLateStartActivity(_factory, _probeManager), helper((IHThorTopNArg &)basehelper), compare(*helper.queryCompare())
  16095. {
  16096. sorted = NULL;
  16097. sortedCount = 0;
  16098. curIndex = 0;
  16099. limit = 0;
  16100. eoi = false;
  16101. hasBest = false;
  16102. }
  16103. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16104. {
  16105. assertex(sorted == NULL);
  16106. sortedCount = 0;
  16107. curIndex = 0;
  16108. eoi = false;
  16109. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  16110. limit = (unsigned) helper.getLimit();
  16111. hasBest = helper.hasBest();
  16112. lateStart(parentExtractSize, parentExtract, limit > 0);
  16113. // MORE - should we use an expanding array instead?
  16114. if (limit > 0)
  16115. sorted = (const void **) ctx->queryRowManager().allocate((limit+1) * sizeof(const void *), activityId);
  16116. }
  16117. virtual void reset()
  16118. {
  16119. if (sorted)
  16120. {
  16121. while(curIndex < sortedCount)
  16122. ReleaseRoxieRow(sorted[curIndex++]);
  16123. ReleaseRoxieRow(sorted);
  16124. }
  16125. sorted = NULL;
  16126. CRoxieServerLateStartActivity::reset();
  16127. }
  16128. bool abortEarly()
  16129. {
  16130. if (hasBest && (sortedCount == limit))
  16131. {
  16132. int compare = helper.compareBest(sorted[sortedCount-1]);
  16133. if (compare == 0)
  16134. {
  16135. if (meta.isGrouped())
  16136. {
  16137. //MORE: This would be more efficient if we had a away of skipping to the end of the incoming group.
  16138. const void * next;
  16139. while ((next = input->nextInGroup()) != NULL)
  16140. ReleaseRoxieRow(next);
  16141. }
  16142. else
  16143. eoi = true;
  16144. return true;
  16145. }
  16146. //This only checks the lowest element - we could check all elements inserted, but it would increase the number of compares
  16147. if (compare < 0)
  16148. throw MakeStringException(ROXIE_TOPN_ROW_ERROR, "TOPN: row found that exceeds the best value");
  16149. }
  16150. return false;
  16151. }
  16152. void getSorted()
  16153. {
  16154. curIndex = 0;
  16155. sortedCount = 0;
  16156. if(eoi)
  16157. return;
  16158. const void * next;
  16159. while ((next = input->nextInGroup()) != NULL)
  16160. {
  16161. if (sortedCount < limit)
  16162. {
  16163. binary_vec_insert_stable(next, sorted, sortedCount, compare);
  16164. sortedCount++;
  16165. if(abortEarly())
  16166. return;
  16167. }
  16168. else
  16169. {
  16170. if(limit && compare.docompare(sorted[sortedCount-1], next) > 0) // MORE - if stability is an issue, need to consider whether this should be > or >=
  16171. {
  16172. binary_vec_insert_stable(next, sorted, sortedCount, compare); // MORE - not sure this is stable!
  16173. ReleaseRoxieRow(sorted[sortedCount]);
  16174. if(abortEarly())
  16175. return;
  16176. }
  16177. else
  16178. {
  16179. ReleaseRoxieRow(next); // do not bother with insertion sort if we know next will fall off the end
  16180. }
  16181. }
  16182. }
  16183. }
  16184. virtual const void * nextInGroup()
  16185. {
  16186. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  16187. if (eof)
  16188. return NULL;
  16189. if (curIndex >= sortedCount)
  16190. {
  16191. bool eog = sortedCount != 0;
  16192. getSorted();
  16193. if(sortedCount == 0)
  16194. {
  16195. eof = true;
  16196. return NULL;
  16197. }
  16198. if (eog)
  16199. return NULL;
  16200. }
  16201. processed++;
  16202. return sorted[curIndex++];
  16203. }
  16204. };
  16205. class CRoxieServerTopNActivityFactory : public CRoxieServerActivityFactory
  16206. {
  16207. public:
  16208. CRoxieServerTopNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16209. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  16210. {
  16211. }
  16212. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  16213. {
  16214. return new CRoxieServerTopNActivity(this, _probeManager);
  16215. }
  16216. };
  16217. IRoxieServerActivityFactory *createRoxieServerTopNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16218. {
  16219. return new CRoxieServerTopNActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  16220. }
  16221. //=================================================================================
  16222. class CRoxieServerLimitActivity : public CRoxieServerActivity
  16223. {
  16224. protected:
  16225. unsigned __int64 rowLimit;
  16226. IHThorLimitArg &helper;
  16227. public:
  16228. CRoxieServerLimitActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  16229. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorLimitArg &)basehelper)
  16230. {
  16231. rowLimit = 0;
  16232. }
  16233. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16234. {
  16235. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  16236. rowLimit = helper.getRowLimit(); // could conceivably depend on context so should not compute any earlier than this
  16237. }
  16238. virtual const void *nextInGroup()
  16239. {
  16240. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  16241. const void * ret = input->nextInGroup();
  16242. if (ret)
  16243. {
  16244. processed++;
  16245. if (processed > rowLimit)
  16246. {
  16247. ReleaseRoxieRow(ret);
  16248. if (traceLevel > 4)
  16249. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  16250. helper.onLimitExceeded();
  16251. }
  16252. }
  16253. return ret;
  16254. }
  16255. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  16256. {
  16257. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  16258. const void * ret = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  16259. if (ret)
  16260. {
  16261. if (wasCompleteMatch)
  16262. processed++;
  16263. if (processed > rowLimit)
  16264. {
  16265. ReleaseRoxieRow(ret);
  16266. if (traceLevel > 4)
  16267. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  16268. helper.onLimitExceeded();
  16269. }
  16270. }
  16271. return ret;
  16272. }
  16273. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  16274. {
  16275. return input->gatherConjunctions(collector);
  16276. }
  16277. virtual void resetEOF()
  16278. {
  16279. //Do not reset the rowLimit
  16280. input->resetEOF();
  16281. }
  16282. IInputSteppingMeta * querySteppingMeta()
  16283. {
  16284. return input->querySteppingMeta();
  16285. }
  16286. };
  16287. class CRoxieServerLimitActivityFactory : public CRoxieServerActivityFactory
  16288. {
  16289. public:
  16290. CRoxieServerLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16291. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  16292. {
  16293. }
  16294. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  16295. {
  16296. return new CRoxieServerLimitActivity(this, _probeManager);
  16297. }
  16298. };
  16299. IRoxieServerActivityFactory *createRoxieServerLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16300. {
  16301. return new CRoxieServerLimitActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  16302. }
  16303. //=====================================================================================================
  16304. class CRoxieServerSkipLimitActivity : public CRoxieServerLimitActivity
  16305. {
  16306. ConstPointerArray buff;
  16307. bool started;
  16308. unsigned index;
  16309. IHThorLimitTransformExtra * transformExtra;
  16310. public:
  16311. CRoxieServerSkipLimitActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _onFail)
  16312. : CRoxieServerLimitActivity(_factory, _probeManager)
  16313. {
  16314. transformExtra = NULL;
  16315. started = false;
  16316. index = 0;
  16317. if (_onFail)
  16318. transformExtra = static_cast<IHThorLimitTransformExtra *>(helper.selectInterface(TAIlimittransformextra_1));
  16319. }
  16320. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16321. {
  16322. started = false;
  16323. index = 0;
  16324. CRoxieServerLimitActivity::start(parentExtractSize, parentExtract, paused);
  16325. }
  16326. virtual void reset()
  16327. {
  16328. while (buff.isItem(index))
  16329. ReleaseRoxieRow(buff.item(index++));
  16330. buff.kill();
  16331. started = false;
  16332. CRoxieServerLimitActivity::reset();
  16333. }
  16334. virtual const void *nextInGroup()
  16335. {
  16336. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  16337. if (!started)
  16338. pullInput();
  16339. if (buff.isItem(index))
  16340. {
  16341. const void * next = buff.item(index++);
  16342. if(next)
  16343. processed++;
  16344. return next;
  16345. }
  16346. return NULL;
  16347. }
  16348. protected:
  16349. void pullInput()
  16350. {
  16351. unsigned count = 0;
  16352. loop
  16353. {
  16354. const void * next = input->nextInGroup();
  16355. if (next == NULL)
  16356. {
  16357. next = input->nextInGroup();
  16358. if(next == NULL)
  16359. break;
  16360. buff.append(NULL);
  16361. }
  16362. count++;
  16363. if (count > rowLimit)
  16364. {
  16365. ReleaseRoxieRow(next);
  16366. ReleaseRoxieRowSet(buff);
  16367. if (ctx->queryDebugContext())
  16368. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  16369. if (transformExtra)
  16370. {
  16371. createRowAllocator();
  16372. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16373. size32_t outSize = transformExtra->transformOnLimitExceeded(rowBuilder);
  16374. if (outSize)
  16375. buff.append(rowBuilder.finalizeRowClear(outSize));
  16376. }
  16377. break;
  16378. }
  16379. buff.append(next);
  16380. }
  16381. started = true;
  16382. }
  16383. };
  16384. class CRoxieServerSkipLimitActivityFactory : public CRoxieServerActivityFactory
  16385. {
  16386. public:
  16387. CRoxieServerSkipLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16388. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  16389. {
  16390. }
  16391. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  16392. {
  16393. return new CRoxieServerSkipLimitActivity(this, _probeManager, kind==TAKcreaterowlimit);
  16394. }
  16395. };
  16396. IRoxieServerActivityFactory *createRoxieServerSkipLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16397. {
  16398. return new CRoxieServerSkipLimitActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  16399. }
  16400. //=================================================================================
  16401. class CRoxieServerCatchActivity : public CRoxieServerActivity
  16402. {
  16403. IHThorCatchArg &helper;
  16404. public:
  16405. CRoxieServerCatchActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  16406. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorCatchArg &)basehelper)
  16407. {
  16408. }
  16409. virtual const void *nextInGroup()
  16410. {
  16411. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  16412. try
  16413. {
  16414. const void *ret = input->nextInGroup();
  16415. if (ret)
  16416. processed++;
  16417. return ret;
  16418. }
  16419. catch (IException *E)
  16420. {
  16421. E->Release();
  16422. helper.onExceptionCaught();
  16423. }
  16424. catch (...)
  16425. {
  16426. helper.onExceptionCaught();
  16427. }
  16428. throwUnexpected(); // onExceptionCaught should have thrown something
  16429. }
  16430. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  16431. {
  16432. try
  16433. {
  16434. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  16435. const void * ret = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  16436. if (ret && wasCompleteMatch)
  16437. processed++;
  16438. return ret;
  16439. }
  16440. catch (IException *E)
  16441. {
  16442. E->Release();
  16443. helper.onExceptionCaught();
  16444. }
  16445. catch (...)
  16446. {
  16447. helper.onExceptionCaught();
  16448. }
  16449. throwUnexpected(); // onExceptionCaught should have thrown something
  16450. }
  16451. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  16452. {
  16453. return input->gatherConjunctions(collector);
  16454. }
  16455. virtual void resetEOF()
  16456. {
  16457. input->resetEOF(); // MORE - why not in base class?
  16458. }
  16459. IInputSteppingMeta * querySteppingMeta()
  16460. {
  16461. return input->querySteppingMeta();
  16462. }
  16463. };
  16464. class CRoxieServerSkipCatchActivity : public CRoxieServerActivity
  16465. {
  16466. ConstPointerArray buff;
  16467. bool started;
  16468. unsigned index;
  16469. IHThorCatchArg &helper;
  16470. bool createRow;
  16471. public:
  16472. CRoxieServerSkipCatchActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _createRow)
  16473. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorCatchArg &)basehelper), createRow(_createRow)
  16474. {
  16475. started = false;
  16476. index = 0;
  16477. }
  16478. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16479. {
  16480. started = false;
  16481. index = 0;
  16482. try
  16483. {
  16484. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  16485. }
  16486. catch (IException *E)
  16487. {
  16488. onException(E);
  16489. started = true;
  16490. }
  16491. catch (...)
  16492. {
  16493. onException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught"));
  16494. started = true;
  16495. }
  16496. }
  16497. virtual void reset()
  16498. {
  16499. while (buff.isItem(index))
  16500. ReleaseRoxieRow(buff.item(index++));
  16501. buff.kill();
  16502. started = false;
  16503. CRoxieServerActivity::reset();
  16504. }
  16505. virtual const void *nextInGroup()
  16506. {
  16507. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  16508. if (!started)
  16509. pullInput();
  16510. if (buff.isItem(index))
  16511. {
  16512. const void * next = buff.item(index++);
  16513. if(next)
  16514. processed++;
  16515. return next;
  16516. }
  16517. return NULL;
  16518. }
  16519. protected:
  16520. void onException(IException *E)
  16521. {
  16522. input->stop(true);
  16523. ReleaseRoxieRowSet(buff);
  16524. if (createRow)
  16525. {
  16526. createRowAllocator();
  16527. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16528. size32_t outSize = helper.transformOnExceptionCaught(rowBuilder, E);
  16529. if (outSize)
  16530. buff.append(rowBuilder.finalizeRowClear(outSize));
  16531. }
  16532. E->Release();
  16533. }
  16534. void pullInput()
  16535. {
  16536. try
  16537. {
  16538. bool EOGseen = false;
  16539. loop
  16540. {
  16541. const void * next = input->nextInGroup();
  16542. buff.append(next);
  16543. if (next == NULL)
  16544. {
  16545. if (EOGseen)
  16546. break;
  16547. EOGseen = true;
  16548. }
  16549. else
  16550. EOGseen = false;
  16551. }
  16552. }
  16553. catch (IException *E)
  16554. {
  16555. onException(E);
  16556. }
  16557. catch (...)
  16558. {
  16559. onException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught"));
  16560. }
  16561. started = true;
  16562. }
  16563. };
  16564. class CRoxieServerCatchActivityFactory : public CRoxieServerActivityFactory
  16565. {
  16566. public:
  16567. CRoxieServerCatchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16568. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  16569. {
  16570. }
  16571. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  16572. {
  16573. switch (kind)
  16574. {
  16575. case TAKcatch:
  16576. return new CRoxieServerCatchActivity(this, _probeManager);
  16577. case TAKskipcatch:
  16578. return new CRoxieServerSkipCatchActivity(this, _probeManager, false);
  16579. case TAKcreaterowcatch:
  16580. return new CRoxieServerSkipCatchActivity(this, _probeManager, true);
  16581. default:
  16582. throwUnexpected();
  16583. }
  16584. }
  16585. };
  16586. IRoxieServerActivityFactory *createRoxieServerCatchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16587. {
  16588. return new CRoxieServerCatchActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  16589. }
  16590. //=================================================================================
  16591. class CRoxieServerCaseActivity : public CRoxieServerActivity
  16592. {
  16593. IHThorCaseArg &helper;
  16594. IRoxieInput **inputs;
  16595. unsigned cond;
  16596. bool unusedStopped;
  16597. IRoxieInput *in;
  16598. unsigned numInputs;
  16599. public:
  16600. CRoxieServerCaseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  16601. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorCaseArg &)basehelper), numInputs(_numInputs)
  16602. {
  16603. unusedStopped = false;
  16604. cond = 0;
  16605. inputs = new IRoxieInput*[numInputs];
  16606. for (unsigned i = 0; i < numInputs; i++)
  16607. inputs[i] = NULL;
  16608. in = NULL;
  16609. }
  16610. ~CRoxieServerCaseActivity()
  16611. {
  16612. delete [] inputs;
  16613. }
  16614. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16615. {
  16616. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  16617. cond = helper.getBranch();
  16618. //CHOOSE defaults to the last argument if out of range.
  16619. if (cond >= numInputs)
  16620. cond = numInputs - 1;
  16621. inputs[cond]->start(parentExtractSize, parentExtract, paused);
  16622. for (unsigned idx = 0; idx < numInputs; idx++)
  16623. {
  16624. if (idx!=cond)
  16625. inputs[idx]->stop(false); // Note: stopping unused branches early helps us avoid buffering splits too long.
  16626. }
  16627. in = inputs[cond];
  16628. unusedStopped = true;
  16629. }
  16630. virtual void stop(bool aborting)
  16631. {
  16632. for (unsigned idx = 0; idx < numInputs; idx++)
  16633. {
  16634. if (idx==cond || !unusedStopped)
  16635. inputs[idx]->stop(aborting);
  16636. }
  16637. CRoxieServerActivity::stop(aborting);
  16638. }
  16639. virtual void reset()
  16640. {
  16641. for (unsigned idx = 0; idx < numInputs; idx++)
  16642. {
  16643. inputs[idx]->reset();
  16644. }
  16645. unusedStopped = false;
  16646. in = NULL;
  16647. CRoxieServerActivity::reset();
  16648. }
  16649. virtual void setInput(unsigned idx, IRoxieInput *_in)
  16650. {
  16651. assertex(idx < numInputs);
  16652. inputs[idx] = _in;
  16653. }
  16654. virtual const void *nextInGroup()
  16655. {
  16656. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  16657. if (in)
  16658. {
  16659. const void *ret = in->nextInGroup();
  16660. if (ret)
  16661. processed++;
  16662. return ret;
  16663. }
  16664. return NULL;
  16665. }
  16666. };
  16667. class CRoxieServerCaseActivityFactory : public CRoxieServerMultiInputFactory
  16668. {
  16669. bool graphInvariant;
  16670. public:
  16671. CRoxieServerCaseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _graphInvariant)
  16672. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  16673. {
  16674. graphInvariant = _graphInvariant;
  16675. }
  16676. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  16677. {
  16678. return new CRoxieServerCaseActivity(this, _probeManager, numInputs());
  16679. }
  16680. virtual bool isGraphInvariant() const
  16681. {
  16682. return graphInvariant;
  16683. }
  16684. };
  16685. IRoxieServerActivityFactory *createRoxieServerCaseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _graphInvariant)
  16686. {
  16687. return new CRoxieServerCaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphInvariant);
  16688. }
  16689. //=================================================================================
  16690. class CRoxieServerIfActivity : public CRoxieServerActivity
  16691. {
  16692. IHThorIfArg &helper;
  16693. IRoxieInput *inputTrue;
  16694. IRoxieInput *inputFalse;
  16695. bool cond;
  16696. bool unusedStopped;
  16697. public:
  16698. CRoxieServerIfActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  16699. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorIfArg &)basehelper)
  16700. {
  16701. inputFalse = NULL;
  16702. inputTrue = NULL;
  16703. unusedStopped = false;
  16704. cond = false;
  16705. }
  16706. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16707. {
  16708. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  16709. cond = helper.getCondition();
  16710. if (cond)
  16711. {
  16712. inputTrue->start(parentExtractSize, parentExtract, paused);
  16713. if (inputFalse)
  16714. inputFalse->stop(false); // Note: stopping unused branches early helps us avoid buffering splits too long.
  16715. }
  16716. else
  16717. {
  16718. if (inputFalse)
  16719. inputFalse->start(parentExtractSize, parentExtract, paused);
  16720. inputTrue->stop(false);
  16721. }
  16722. unusedStopped = true;
  16723. }
  16724. virtual void stop(bool aborting)
  16725. {
  16726. if (!unusedStopped || cond)
  16727. inputTrue->stop(aborting);
  16728. if (inputFalse && (!unusedStopped || !cond))
  16729. inputFalse->stop(aborting);
  16730. CRoxieServerActivity::stop(aborting);
  16731. }
  16732. virtual unsigned __int64 queryLocalCycles() const
  16733. {
  16734. __int64 localCycles = totalCycles;
  16735. localCycles -= inputTrue->queryTotalCycles();
  16736. if (inputFalse)
  16737. localCycles -= inputFalse->queryTotalCycles();
  16738. if (localCycles < 0)
  16739. localCycles = 0;
  16740. return localCycles;
  16741. }
  16742. virtual IRoxieInput *queryInput(unsigned idx) const
  16743. {
  16744. switch (idx)
  16745. {
  16746. case 0:
  16747. return inputTrue;
  16748. case 1:
  16749. return inputFalse;
  16750. default:
  16751. return NULL;
  16752. }
  16753. }
  16754. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  16755. {
  16756. IRoxieInput *in = cond ? inputTrue : inputFalse;
  16757. if (in)
  16758. return in->queryIndexReadActivity();
  16759. return NULL;
  16760. }
  16761. virtual void reset()
  16762. {
  16763. CRoxieServerActivity::reset();
  16764. inputTrue->reset();
  16765. if (inputFalse)
  16766. inputFalse->reset();
  16767. unusedStopped = false;
  16768. }
  16769. virtual void setInput(unsigned idx, IRoxieInput *_in)
  16770. {
  16771. if (idx==1)
  16772. inputFalse = _in;
  16773. else
  16774. {
  16775. assertex(!idx);
  16776. inputTrue = _in;
  16777. }
  16778. }
  16779. virtual const void *nextInGroup()
  16780. {
  16781. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  16782. IRoxieInput *in = cond ? inputTrue : inputFalse;
  16783. if (in)
  16784. {
  16785. const void * ret;
  16786. if ((ret = in->nextInGroup()) != NULL)
  16787. processed++;
  16788. return ret;
  16789. }
  16790. return NULL;
  16791. }
  16792. };
  16793. class CRoxieServerIfActivityFactory : public CRoxieServerActivityFactory
  16794. {
  16795. unsigned input2;
  16796. unsigned input2idx;
  16797. bool graphInvariant;
  16798. public:
  16799. CRoxieServerIfActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _graphInvariant)
  16800. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  16801. {
  16802. graphInvariant = _graphInvariant;
  16803. input2 = (unsigned)-1;
  16804. input2idx = (unsigned)-1;
  16805. }
  16806. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  16807. {
  16808. return new CRoxieServerIfActivity(this, _probeManager);
  16809. }
  16810. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  16811. {
  16812. if (idx==1)
  16813. {
  16814. input2 = source;
  16815. input2idx = sourceidx;
  16816. }
  16817. else
  16818. CRoxieServerActivityFactory::setInput(idx, source, sourceidx);
  16819. }
  16820. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  16821. {
  16822. switch (idx)
  16823. {
  16824. case 1:
  16825. sourceidx = input2idx;
  16826. return input2;
  16827. case 0:
  16828. return CRoxieServerActivityFactory::getInput(idx, sourceidx);
  16829. default:
  16830. return (unsigned) -1;
  16831. }
  16832. }
  16833. virtual unsigned numInputs() const { return (input2 == (unsigned)-1) ? 1 : 2; }
  16834. virtual bool isGraphInvariant() const
  16835. {
  16836. return graphInvariant;
  16837. }
  16838. };
  16839. IRoxieServerActivityFactory *createRoxieServerIfActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _graphInvariant)
  16840. {
  16841. return new CRoxieServerIfActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphInvariant);
  16842. }
  16843. //=================================================================================
  16844. class CRoxieServerActionBaseActivity : public CRoxieServerActivity
  16845. {
  16846. CriticalSection ecrit;
  16847. Owned<IException> exception;
  16848. bool executed;
  16849. public:
  16850. CRoxieServerActionBaseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  16851. : CRoxieServerActivity(_factory, _probeManager)
  16852. {
  16853. executed = false;
  16854. }
  16855. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract) = 0;
  16856. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  16857. {
  16858. CriticalBlock b(ecrit);
  16859. if (exception)
  16860. throw(exception.getLink());
  16861. if (!executed)
  16862. {
  16863. try
  16864. {
  16865. executed = true;
  16866. start(parentExtractSize, parentExtract, false);
  16867. doExecuteAction(parentExtractSize, parentExtract);
  16868. stop(false);
  16869. }
  16870. catch (IException * E)
  16871. {
  16872. ctx->notifyAbort(E);
  16873. stop(true);
  16874. exception.set(E);
  16875. throw;
  16876. }
  16877. }
  16878. }
  16879. virtual void reset()
  16880. {
  16881. executed = false;
  16882. exception.clear();
  16883. CRoxieServerActivity::reset();
  16884. }
  16885. virtual unsigned __int64 queryLocalCycles() const
  16886. {
  16887. return totalCycles;
  16888. }
  16889. virtual const void *nextInGroup()
  16890. {
  16891. throwUnexpected(); // I am nobody's input
  16892. }
  16893. virtual IRoxieInput *queryInput(unsigned idx) const
  16894. {
  16895. throwUnexpected(); // I am nobody's input
  16896. }
  16897. };
  16898. class CRoxieServerIfActionActivity : public CRoxieServerActionBaseActivity
  16899. {
  16900. IHThorIfArg &helper;
  16901. public:
  16902. CRoxieServerIfActionActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  16903. : CRoxieServerActionBaseActivity(_factory, _probeManager), helper((IHThorIfArg &)basehelper)
  16904. {
  16905. }
  16906. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  16907. {
  16908. bool cond;
  16909. {
  16910. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  16911. cond = helper.getCondition();
  16912. }
  16913. stopDependencies(parentExtractSize, parentExtract, cond ? 2 : 1);
  16914. executeDependencies(parentExtractSize, parentExtract, cond ? 1 : 2);
  16915. }
  16916. };
  16917. class CRoxieServerIfActionActivityFactory : public CRoxieServerActivityFactory
  16918. {
  16919. bool isRoot;
  16920. public:
  16921. CRoxieServerIfActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  16922. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  16923. {
  16924. }
  16925. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  16926. {
  16927. return new CRoxieServerIfActionActivity(this, _probeManager);
  16928. }
  16929. virtual bool isSink() const
  16930. {
  16931. return isRoot;
  16932. }
  16933. };
  16934. IRoxieServerActivityFactory *createRoxieServerIfActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  16935. {
  16936. return new CRoxieServerIfActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  16937. }
  16938. //=================================================================================
  16939. class CRoxieServerParallelActionActivity : public CRoxieServerActionBaseActivity
  16940. {
  16941. public:
  16942. CRoxieServerParallelActionActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  16943. : CRoxieServerActionBaseActivity(_factory, _probeManager)
  16944. {
  16945. }
  16946. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  16947. {
  16948. #ifdef PARALLEL_EXECUTE
  16949. CParallelActivityExecutor afor(dependencies, parentExtractSize, parentExtract);
  16950. afor.For(dependencies.ordinality(), dependencies.ordinality(), true);
  16951. #else
  16952. ForEachItemIn(idx, dependencies)
  16953. {
  16954. dependencies.item(idx).execute(parentExtractSize, parentExtract);
  16955. }
  16956. #endif
  16957. }
  16958. };
  16959. class CRoxieServerParallelActionActivityFactory : public CRoxieServerActivityFactory
  16960. {
  16961. bool isRoot;
  16962. public:
  16963. CRoxieServerParallelActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  16964. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  16965. {
  16966. assertex(!isRoot); // non-internal should be expanded out..
  16967. }
  16968. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  16969. {
  16970. return new CRoxieServerParallelActionActivity(this, _probeManager);
  16971. }
  16972. virtual bool isSink() const
  16973. {
  16974. return isRoot;
  16975. }
  16976. };
  16977. IRoxieServerActivityFactory *createRoxieServerParallelActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  16978. {
  16979. return new CRoxieServerParallelActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  16980. }
  16981. //=================================================================================
  16982. class CRoxieServerSequentialActionActivity : public CRoxieServerActionBaseActivity
  16983. {
  16984. IHThorSequentialArg &helper;
  16985. public:
  16986. CRoxieServerSequentialActionActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  16987. : CRoxieServerActionBaseActivity(_factory, _probeManager), helper((IHThorSequentialArg &)basehelper)
  16988. {
  16989. }
  16990. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  16991. {
  16992. unsigned numBranches = helper.numBranches();
  16993. for (unsigned branch=1; branch <= numBranches; branch++)
  16994. executeDependencies(parentExtractSize, parentExtract, branch);
  16995. }
  16996. };
  16997. class CRoxieServerSequentialActionActivityFactory : public CRoxieServerActivityFactory
  16998. {
  16999. bool isRoot;
  17000. public:
  17001. CRoxieServerSequentialActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  17002. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  17003. {
  17004. }
  17005. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  17006. {
  17007. return new CRoxieServerSequentialActionActivity(this, _probeManager);
  17008. }
  17009. virtual bool isSink() const
  17010. {
  17011. return isRoot;
  17012. }
  17013. };
  17014. IRoxieServerActivityFactory *createRoxieServerSequentialActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  17015. {
  17016. return new CRoxieServerSequentialActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  17017. }
  17018. //=================================================================================
  17019. class CRoxieServerWhenActivity : public CRoxieServerActivity
  17020. {
  17021. public:
  17022. CRoxieServerWhenActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17023. : CRoxieServerActivity(_factory, _probeManager)
  17024. {
  17025. savedExtractSize = 0;
  17026. savedExtract = NULL;
  17027. }
  17028. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17029. {
  17030. savedExtractSize = parentExtractSize;
  17031. savedExtract = parentExtract;
  17032. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  17033. executeDependencies(parentExtractSize, parentExtract, WhenParallelId); // MORE: This should probably be done in parallel!
  17034. }
  17035. virtual void stop(bool aborting)
  17036. {
  17037. if (state != STATEstopped)
  17038. {
  17039. stopDependencies(savedExtractSize, savedExtract, aborting ? WhenSuccessId : WhenFailureId); // These ones don't get executed
  17040. executeDependencies(savedExtractSize, savedExtract, aborting ? WhenFailureId : WhenSuccessId); // These ones do
  17041. }
  17042. CRoxieServerActivity::stop(aborting);
  17043. }
  17044. virtual const void *nextInGroup()
  17045. {
  17046. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext()); // bit of a waste of time....
  17047. return input->nextInGroup();
  17048. }
  17049. protected:
  17050. unsigned savedExtractSize;
  17051. const byte *savedExtract;
  17052. };
  17053. class CRoxieServerWhenActivityFactory : public CRoxieServerActivityFactory
  17054. {
  17055. public:
  17056. CRoxieServerWhenActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  17057. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  17058. {
  17059. }
  17060. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  17061. {
  17062. return new CRoxieServerWhenActivity(this, _probeManager);
  17063. }
  17064. };
  17065. extern IRoxieServerActivityFactory *createRoxieServerWhenActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  17066. {
  17067. return new CRoxieServerWhenActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  17068. }
  17069. //=================================================================================
  17070. class CRoxieServerWhenActionActivity : public CRoxieServerActionBaseActivity
  17071. {
  17072. public:
  17073. CRoxieServerWhenActionActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17074. : CRoxieServerActionBaseActivity(_factory, _probeManager)
  17075. {
  17076. savedExtractSize = 0;
  17077. savedExtract = NULL;
  17078. }
  17079. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17080. {
  17081. savedExtractSize = parentExtractSize;
  17082. savedExtract = parentExtract;
  17083. CRoxieServerActionBaseActivity::start(parentExtractSize, parentExtract, paused);
  17084. executeDependencies(parentExtractSize, parentExtract, WhenParallelId); // MORE: This should probably be done in parallel!
  17085. }
  17086. virtual void stop(bool aborting)
  17087. {
  17088. if (state != STATEstopped)
  17089. {
  17090. stopDependencies(savedExtractSize, savedExtract, aborting ? WhenSuccessId : WhenFailureId); // these are NOT going to execute
  17091. executeDependencies(savedExtractSize, savedExtract, aborting ? WhenFailureId : WhenSuccessId);
  17092. }
  17093. CRoxieServerActionBaseActivity::stop(aborting);
  17094. }
  17095. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  17096. {
  17097. executeDependencies(parentExtractSize, parentExtract, 1);
  17098. }
  17099. protected:
  17100. unsigned savedExtractSize;
  17101. const byte *savedExtract;
  17102. };
  17103. class CRoxieServerWhenActionActivityFactory : public CRoxieServerActivityFactory
  17104. {
  17105. public:
  17106. CRoxieServerWhenActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  17107. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  17108. {
  17109. }
  17110. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  17111. {
  17112. return new CRoxieServerWhenActionActivity(this, _probeManager);
  17113. }
  17114. virtual bool isSink() const
  17115. {
  17116. return isRoot;
  17117. }
  17118. private:
  17119. bool isRoot;
  17120. };
  17121. extern IRoxieServerActivityFactory *createRoxieServerWhenActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  17122. {
  17123. return new CRoxieServerWhenActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  17124. }
  17125. //=================================================================================
  17126. class CRoxieServerParseActivity : public CRoxieServerActivity, implements IMatchedAction
  17127. {
  17128. IHThorParseArg &helper;
  17129. INlpParser * parser;
  17130. INlpResultIterator * rowIter;
  17131. const void * in;
  17132. char * curSearchText;
  17133. INlpParseAlgorithm * algorithm;
  17134. size32_t curSearchTextLen;
  17135. bool anyThisGroup;
  17136. bool processRecord(const void * inRec)
  17137. {
  17138. if (helper.searchTextNeedsFree())
  17139. rtlFree(curSearchText);
  17140. curSearchTextLen = 0;
  17141. curSearchText = NULL;
  17142. helper.getSearchText(curSearchTextLen, curSearchText, inRec);
  17143. return parser->performMatch(*this, in, curSearchTextLen, curSearchText);
  17144. }
  17145. public:
  17146. CRoxieServerParseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, INlpParseAlgorithm * _algorithm)
  17147. : CRoxieServerActivity(_factory, _probeManager),
  17148. helper((IHThorParseArg &)basehelper), algorithm(_algorithm)
  17149. {
  17150. parser = NULL;
  17151. rowIter = NULL;
  17152. in = NULL;
  17153. curSearchText = NULL;
  17154. anyThisGroup = false;
  17155. curSearchTextLen = 0;
  17156. }
  17157. ~CRoxieServerParseActivity()
  17158. {
  17159. ::Release(parser);
  17160. }
  17161. virtual bool needsAllocator() const { return true; }
  17162. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  17163. {
  17164. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  17165. parser = algorithm->createParser(_ctx->queryCodeContext(), activityId, helper.queryHelper(), &helper);
  17166. rowIter = parser->queryResultIter();
  17167. }
  17168. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17169. {
  17170. anyThisGroup = false;
  17171. curSearchTextLen = 0;
  17172. curSearchText = NULL;
  17173. in = NULL;
  17174. parser->reset();
  17175. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  17176. }
  17177. virtual void reset()
  17178. {
  17179. if (helper.searchTextNeedsFree())
  17180. rtlFree(curSearchText);
  17181. curSearchText = NULL;
  17182. ReleaseClearRoxieRow(in);
  17183. CRoxieServerActivity::reset();
  17184. }
  17185. virtual unsigned onMatch(ARowBuilder & self, const void * curRecord, IMatchedResults * results, IMatchWalker * walker)
  17186. {
  17187. try
  17188. {
  17189. return helper.transform(self, curRecord, results, walker);
  17190. }
  17191. catch (IException *E)
  17192. {
  17193. throw makeWrappedException(E);
  17194. }
  17195. }
  17196. virtual const void * nextInGroup()
  17197. {
  17198. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  17199. loop
  17200. {
  17201. if (rowIter->isValid())
  17202. {
  17203. anyThisGroup = true;
  17204. OwnedConstRoxieRow out = rowIter->getRow();
  17205. rowIter->next();
  17206. processed++;
  17207. return out.getClear();
  17208. }
  17209. ReleaseClearRoxieRow(in);
  17210. in = input->nextInGroup();
  17211. if (!in)
  17212. {
  17213. if (anyThisGroup)
  17214. {
  17215. anyThisGroup = false;
  17216. return NULL;
  17217. }
  17218. in = input->nextInGroup();
  17219. if (!in)
  17220. return NULL;
  17221. }
  17222. processRecord(in);
  17223. rowIter->first();
  17224. }
  17225. }
  17226. };
  17227. class CRoxieServerParseActivityFactory : public CRoxieServerActivityFactory
  17228. {
  17229. Owned<INlpParseAlgorithm> algorithm;
  17230. Owned<IHThorParseArg> helper;
  17231. public:
  17232. CRoxieServerParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IResourceContext *rc)
  17233. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  17234. {
  17235. helper.setown((IHThorParseArg *) helperFactory());
  17236. algorithm.setown(createThorParser(rc, *helper));
  17237. }
  17238. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  17239. {
  17240. return new CRoxieServerParseActivity(this, _probeManager, algorithm);
  17241. }
  17242. };
  17243. IRoxieServerActivityFactory *createRoxieServerParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IResourceContext *rc)
  17244. {
  17245. return new CRoxieServerParseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, rc);
  17246. }
  17247. //=====================================================================================================
  17248. class CRoxieServerWorkUnitWriteActivity : public CRoxieServerInternalSinkActivity
  17249. {
  17250. IHThorWorkUnitWriteArg &helper;
  17251. bool isReread;
  17252. bool grouped;
  17253. IRoxieServerContext *serverContext;
  17254. public:
  17255. CRoxieServerWorkUnitWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _isReread, unsigned _numOutputs)
  17256. : CRoxieServerInternalSinkActivity(_factory, _probeManager, _numOutputs), helper((IHThorWorkUnitWriteArg &)basehelper), isReread(_isReread)
  17257. {
  17258. grouped = (helper.getFlags() & POFgrouped) != 0;
  17259. serverContext = NULL;
  17260. }
  17261. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  17262. {
  17263. CRoxieServerInternalSinkActivity::onCreate(_ctx, _colocalParent);
  17264. serverContext = ctx->queryServerContext();
  17265. if (!serverContext)
  17266. {
  17267. throw MakeStringException(ROXIE_PIPE_ERROR, "Pipe output activity cannot be executed in slave context");
  17268. }
  17269. }
  17270. virtual bool needsAllocator() const { return true; }
  17271. virtual void onExecute()
  17272. {
  17273. int sequence = helper.getSequence();
  17274. const char *storedName = helper.queryName();
  17275. if (!storedName)
  17276. storedName = "Dataset";
  17277. MemoryBuffer result;
  17278. FlushingStringBuffer *response = NULL;
  17279. bool saveInContext = (int) sequence < 0 || isReread;
  17280. if (!meta.queryOriginal()) // this is a bit of a hack - don't know why no meta on an output....
  17281. meta.set(input->queryOutputMeta());
  17282. Owned<IOutputRowSerializer> rowSerializer;
  17283. Owned<IXmlWriter> writer;
  17284. if ((int) sequence >= 0)
  17285. {
  17286. response = serverContext->queryResult(sequence);
  17287. if (response)
  17288. {
  17289. response->startDataset("Dataset", helper.queryName(), sequence, (helper.getFlags() & POFextend) != 0);
  17290. if (response->mlFmt==MarkupFmt_XML || response->mlFmt==MarkupFmt_JSON)
  17291. {
  17292. unsigned int writeFlags = serverContext->getXmlFlags();
  17293. if (response->mlFmt==MarkupFmt_JSON)
  17294. writeFlags |= XWFnoindent;
  17295. writer.setown(createIXmlWriter(writeFlags, 1, response, (response->mlFmt==MarkupFmt_JSON) ? WTJSON : WTStandard));
  17296. writer->outputBeginArray("Row");
  17297. }
  17298. }
  17299. }
  17300. if (serverContext->outputResultsToWorkUnit()||(response && response->isRaw))
  17301. {
  17302. createRowAllocator();
  17303. rowSerializer.setown(rowAllocator->createDiskSerializer(ctx->queryCodeContext()));
  17304. }
  17305. __int64 initialProcessed = processed;
  17306. RtlLinkedDatasetBuilder builder(rowAllocator);
  17307. loop
  17308. {
  17309. const void *row = input->nextInGroup();
  17310. if (saveInContext)
  17311. {
  17312. if (row || grouped)
  17313. builder.append(row);
  17314. }
  17315. if (grouped && (processed != initialProcessed))
  17316. {
  17317. if (serverContext->outputResultsToWorkUnit())
  17318. result.append(row == NULL);
  17319. if (response)
  17320. {
  17321. if (response->isRaw)
  17322. response->append(row == NULL);
  17323. else
  17324. {
  17325. response->append("<Row __GroupBreak__=\"1\"/>"); // sensible, but need to handle on input
  17326. }
  17327. }
  17328. }
  17329. if (!row)
  17330. {
  17331. row = input->nextInGroup();
  17332. if (!row)
  17333. break;
  17334. if (saveInContext)
  17335. builder.append(row);
  17336. }
  17337. processed++;
  17338. if (serverContext->outputResultsToWorkUnit())
  17339. {
  17340. CThorDemoRowSerializer serializerTarget(result);
  17341. rowSerializer->serialize(serializerTarget, (const byte *) row);
  17342. }
  17343. if (response)
  17344. {
  17345. if (response->isRaw)
  17346. {
  17347. // MORE - should be able to serialize straight to the response...
  17348. MemoryBuffer rowbuff;
  17349. CThorDemoRowSerializer serializerTarget(rowbuff);
  17350. rowSerializer->serialize(serializerTarget, (const byte *) row);
  17351. response->append(rowbuff.length(), rowbuff.toByteArray());
  17352. }
  17353. else if (writer)
  17354. {
  17355. writer->outputBeginNested("Row", false);
  17356. helper.serializeXml((byte *) row, *writer);
  17357. writer->outputEndNested("Row");
  17358. }
  17359. else
  17360. {
  17361. SimpleOutputWriter x;
  17362. helper.serializeXml((byte *) row, x);
  17363. x.newline();
  17364. response->append(x.str());
  17365. }
  17366. response->incrementRowCount();
  17367. response->flush(false);
  17368. }
  17369. ReleaseRoxieRow(row);
  17370. }
  17371. if (writer)
  17372. writer->outputEndArray("Row");
  17373. if (saveInContext)
  17374. serverContext->appendResultDeserialized(storedName, sequence, builder.getcount(), builder.linkrows(), (helper.getFlags() & POFextend) != 0, LINK(meta.queryOriginal()));
  17375. if (serverContext->outputResultsToWorkUnit())
  17376. serverContext->appendResultRawContext(storedName, sequence, result.length(), result.toByteArray(), processed, (helper.getFlags() & POFextend) != 0, false); // MORE - shame to do extra copy...
  17377. }
  17378. };
  17379. class CRoxieServerWorkUnitWriteActivityFactory : public CRoxieServerInternalSinkFactory
  17380. {
  17381. bool isReread;
  17382. public:
  17383. CRoxieServerWorkUnitWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  17384. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot)
  17385. {
  17386. isReread = usageCount > 0;
  17387. Owned<IHThorWorkUnitWriteArg> helper = (IHThorWorkUnitWriteArg *) helperFactory();
  17388. isInternal = (helper->getSequence()==ResultSequenceInternal);
  17389. }
  17390. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  17391. {
  17392. return new CRoxieServerWorkUnitWriteActivity(this, _probeManager, isReread, usageCount);
  17393. }
  17394. };
  17395. IRoxieServerActivityFactory *createRoxieServerWorkUnitWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  17396. {
  17397. return new CRoxieServerWorkUnitWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot);
  17398. }
  17399. //=====================================================================================================
  17400. class CRoxieServerWorkUnitWriteDictActivity : public CRoxieServerInternalSinkActivity
  17401. {
  17402. IHThorDictionaryWorkUnitWriteArg &helper;
  17403. IRoxieServerContext *serverContext;
  17404. public:
  17405. CRoxieServerWorkUnitWriteDictActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _usageCount)
  17406. : CRoxieServerInternalSinkActivity(_factory, _probeManager, _usageCount), helper((IHThorDictionaryWorkUnitWriteArg &)basehelper)
  17407. {
  17408. serverContext = NULL;
  17409. }
  17410. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  17411. {
  17412. CRoxieServerInternalSinkActivity::onCreate(_ctx, _colocalParent);
  17413. serverContext = ctx->queryServerContext();
  17414. if (!serverContext)
  17415. {
  17416. throw MakeStringException(ROXIE_PIPE_ERROR, "Write Dictionary activity cannot be executed in slave context");
  17417. }
  17418. }
  17419. virtual bool needsAllocator() const { return true; }
  17420. virtual void onExecute()
  17421. {
  17422. int sequence = helper.getSequence();
  17423. const char *storedName = helper.queryName();
  17424. assertex(storedName && *storedName);
  17425. assertex(sequence < 0);
  17426. RtlLinkedDictionaryBuilder builder(rowAllocator, helper.queryHashLookupInfo());
  17427. loop
  17428. {
  17429. const void *row = input->nextInGroup();
  17430. if (!row)
  17431. {
  17432. row = input->nextInGroup();
  17433. if (!row)
  17434. break;
  17435. }
  17436. builder.appendOwn(row);
  17437. processed++;
  17438. }
  17439. serverContext->appendResultDeserialized(storedName, sequence, builder.getcount(), builder.linkrows(), (helper.getFlags() & POFextend) != 0, LINK(meta.queryOriginal()));
  17440. }
  17441. };
  17442. class CRoxieServerWorkUnitWriteDictActivityFactory : public CRoxieServerInternalSinkFactory
  17443. {
  17444. public:
  17445. CRoxieServerWorkUnitWriteDictActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  17446. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot)
  17447. {
  17448. Owned<IHThorDictionaryWorkUnitWriteArg> helper = (IHThorDictionaryWorkUnitWriteArg *) helperFactory();
  17449. isInternal = (helper->getSequence()==ResultSequenceInternal);
  17450. }
  17451. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  17452. {
  17453. return new CRoxieServerWorkUnitWriteDictActivity(this, _probeManager, usageCount);
  17454. }
  17455. };
  17456. IRoxieServerActivityFactory *createRoxieServerWorkUnitWriteDictActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  17457. {
  17458. return new CRoxieServerWorkUnitWriteDictActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot);
  17459. }
  17460. //=================================================================================
  17461. class CRoxieServerRemoteResultActivity : public CRoxieServerInternalSinkActivity
  17462. {
  17463. IHThorRemoteResultArg &helper;
  17464. public:
  17465. CRoxieServerRemoteResultActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  17466. : CRoxieServerInternalSinkActivity(_factory, _probeManager, _numOutputs), helper((IHThorRemoteResultArg &)basehelper)
  17467. {
  17468. }
  17469. virtual void onExecute()
  17470. {
  17471. OwnedConstRoxieRow row = input->nextInGroup();
  17472. helper.sendResult(row); // should be only one row or something has gone wrong!
  17473. }
  17474. };
  17475. class CRoxieServerRemoteResultActivityFactory : public CRoxieServerInternalSinkFactory
  17476. {
  17477. public:
  17478. CRoxieServerRemoteResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  17479. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot)
  17480. {
  17481. Owned<IHThorRemoteResultArg> helper = (IHThorRemoteResultArg *) helperFactory();
  17482. isInternal = (helper->getSequence()==ResultSequenceInternal);
  17483. }
  17484. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  17485. {
  17486. return new CRoxieServerRemoteResultActivity(this, _probeManager, usageCount);
  17487. }
  17488. };
  17489. IRoxieServerActivityFactory *createRoxieServerRemoteResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  17490. {
  17491. return new CRoxieServerRemoteResultActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot);
  17492. }
  17493. //=================================================================================
  17494. class CRoxieServerXmlParseActivity : public CRoxieServerActivity, implements IXMLSelect
  17495. {
  17496. IHThorXmlParseArg &helper;
  17497. Owned<IXMLParse> xmlParser;
  17498. const void * in;
  17499. char * srchStr;
  17500. unsigned numProcessedLastGroup;
  17501. bool srchStrNeedsFree;
  17502. Owned<IColumnProvider> lastMatch;
  17503. public:
  17504. IMPLEMENT_IINTERFACE;
  17505. CRoxieServerXmlParseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17506. : CRoxieServerActivity(_factory, _probeManager),
  17507. helper((IHThorXmlParseArg &)basehelper)
  17508. {
  17509. srchStrNeedsFree = helper.searchTextNeedsFree();
  17510. numProcessedLastGroup = 0;
  17511. srchStr = NULL;
  17512. in = NULL;
  17513. }
  17514. ~CRoxieServerXmlParseActivity()
  17515. {
  17516. }
  17517. virtual bool needsAllocator() const { return true; }
  17518. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17519. {
  17520. numProcessedLastGroup = 0;
  17521. srchStr = NULL;
  17522. in = NULL;
  17523. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  17524. }
  17525. virtual void reset()
  17526. {
  17527. if (helper.searchTextNeedsFree())
  17528. rtlFree(srchStr);
  17529. srchStr = NULL;
  17530. ReleaseClearRoxieRow(in);
  17531. xmlParser.clear();
  17532. CRoxieServerActivity::reset();
  17533. }
  17534. virtual void match(IColumnProvider &entry, offset_t startOffset, offset_t endOffset)
  17535. {
  17536. lastMatch.set(&entry);
  17537. }
  17538. virtual const void *nextInGroup()
  17539. {
  17540. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  17541. loop
  17542. {
  17543. if(xmlParser)
  17544. {
  17545. loop
  17546. {
  17547. if(!xmlParser->next())
  17548. {
  17549. if (srchStrNeedsFree)
  17550. {
  17551. rtlFree(srchStr);
  17552. srchStr = NULL;
  17553. }
  17554. xmlParser.clear();
  17555. break;
  17556. }
  17557. if(lastMatch)
  17558. {
  17559. try
  17560. {
  17561. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17562. size32_t outSize = helper.transform(rowBuilder, in, lastMatch);
  17563. lastMatch.clear();
  17564. if (outSize)
  17565. {
  17566. processed++;
  17567. return rowBuilder.finalizeRowClear(outSize);
  17568. }
  17569. }
  17570. catch (IException *E)
  17571. {
  17572. throw makeWrappedException(E);
  17573. }
  17574. }
  17575. }
  17576. }
  17577. ReleaseClearRoxieRow(in);
  17578. in = input->nextInGroup();
  17579. if(!in)
  17580. {
  17581. if(numProcessedLastGroup == processed)
  17582. in = input->nextInGroup();
  17583. if(!in)
  17584. {
  17585. numProcessedLastGroup = processed;
  17586. return NULL;
  17587. }
  17588. }
  17589. size32_t srchLen;
  17590. helper.getSearchText(srchLen, srchStr, in);
  17591. OwnedRoxieString xmlIteratorPath(helper.getXmlIteratorPath());
  17592. xmlParser.setown(createXMLParse(srchStr, srchLen, xmlIteratorPath, *this));
  17593. }
  17594. }
  17595. };
  17596. class CRoxieServerXmlParseActivityFactory : public CRoxieServerActivityFactory
  17597. {
  17598. public:
  17599. CRoxieServerXmlParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  17600. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  17601. {
  17602. }
  17603. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  17604. {
  17605. return new CRoxieServerXmlParseActivity(this, _probeManager);
  17606. }
  17607. };
  17608. IRoxieServerActivityFactory *createRoxieServerXmlParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  17609. {
  17610. return new CRoxieServerXmlParseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  17611. }
  17612. //=====================================================================================================
  17613. class CRoxieServerDiskReadBaseActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler, implements IIndexReadContext
  17614. {
  17615. protected:
  17616. IHThorDiskReadBaseArg &helper;
  17617. IHThorCompoundExtra * compoundHelper;
  17618. RemoteActivityId remoteId; // Note we copy it rather than reference
  17619. Owned<CSkippableRemoteResultAdaptor> remote;
  17620. unsigned numParts;
  17621. unsigned __int64 rowLimit;
  17622. unsigned __int64 stopAfter;
  17623. Linked<IInMemoryIndexManager> manager;
  17624. Owned<IInMemoryIndexCursor> cursor;
  17625. Owned<IDirectReader> reader;
  17626. CThorContiguousRowBuffer deserializeSource;
  17627. Owned<ISourceRowPrefetcher> prefetcher;
  17628. bool eof;
  17629. bool isKeyed;
  17630. bool variableFileName;
  17631. bool isOpt;
  17632. bool sorted;
  17633. bool maySkip;
  17634. bool isLocal;
  17635. CachedOutputMetaData diskSize;
  17636. Owned<const IResolvedFile> varFileInfo;
  17637. Owned<IFileIOArray> varFiles;
  17638. inline bool useRemote()
  17639. {
  17640. return remote != NULL && numParts > 1;
  17641. }
  17642. public:
  17643. IMPLEMENT_IINTERFACE;
  17644. CRoxieServerDiskReadBaseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager)
  17645. : CRoxieServerActivity(_factory, _probeManager),
  17646. helper((IHThorDiskReadBaseArg &)basehelper),
  17647. numParts(_numParts),
  17648. remoteId(_remoteId),
  17649. manager(_manager),
  17650. isLocal(_isLocal),
  17651. sorted(_sorted),
  17652. maySkip(_maySkip),
  17653. deserializeSource(NULL)
  17654. {
  17655. if (numParts != 1 && !isLocal) // NOTE : when numParts == 0 (variable case) we create, even though we may not use
  17656. remote.setown(new CSkippableRemoteResultAdaptor(remoteId, meta.queryOriginal(), helper, *this, sorted, false, _maySkip));
  17657. compoundHelper = NULL;
  17658. eof = false;
  17659. rowLimit = (unsigned __int64) -1;
  17660. isKeyed = false;
  17661. stopAfter = I64C(0x7FFFFFFFFFFFFFFF);
  17662. diskSize.set(helper.queryDiskRecordSize());
  17663. variableFileName = allFilesDynamic || ((helper.getFlags() & (TDXvarfilename|TDXdynamicfilename)) != 0);
  17664. isOpt = (helper.getFlags() & TDRoptional) != 0;
  17665. }
  17666. virtual const IResolvedFile *queryVarFileInfo() const
  17667. {
  17668. return varFileInfo;
  17669. }
  17670. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  17671. {
  17672. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  17673. if (remote)
  17674. remote->onCreate(this, this, _ctx, _colocalParent);
  17675. }
  17676. virtual bool needsAllocator() const { return true; }
  17677. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17678. {
  17679. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  17680. if (compoundHelper)
  17681. {
  17682. rowLimit = compoundHelper->getRowLimit();
  17683. stopAfter = compoundHelper->getChooseNLimit();
  17684. }
  17685. if (!helper.canMatchAny())
  17686. eof = true;
  17687. else
  17688. {
  17689. if (variableFileName)
  17690. {
  17691. OwnedRoxieString fileName(helper.getFileName());
  17692. varFileInfo.setown(resolveLFN(fileName, isOpt));
  17693. numParts = 0;
  17694. if (varFileInfo)
  17695. {
  17696. Owned<IFilePartMap> map = varFileInfo->getFileMap();
  17697. if (map)
  17698. numParts = map->getNumParts();
  17699. }
  17700. }
  17701. if (!numParts)
  17702. {
  17703. eof = true;
  17704. }
  17705. else if (useRemote())
  17706. {
  17707. remote->onStart(parentExtractSize, parentExtract);
  17708. remote->setLimits(rowLimit, (unsigned __int64) -1, stopAfter);
  17709. unsigned fileNo = 0; // MORE - superfiles require us to do this per file part... maybe (needs thought)
  17710. // Translation into a message per channel done elsewhere....
  17711. remote->getMem(0, fileNo, 0);
  17712. remote->flush();
  17713. remote->senddone();
  17714. }
  17715. else
  17716. {
  17717. if (variableFileName)
  17718. {
  17719. unsigned channel = isLocal ? factory->queryQueryFactory().queryChannel() : 0;
  17720. varFiles.setown(varFileInfo->getIFileIOArray(isOpt, channel));
  17721. manager.setown(varFileInfo->getIndexManager(isOpt, channel, varFiles, diskSize, false, 0));
  17722. }
  17723. assertex(manager != NULL);
  17724. helper.createSegmentMonitors(this);
  17725. if (cursor)
  17726. {
  17727. isKeyed = cursor->selectKey();
  17728. cursor->reset();
  17729. }
  17730. if (!isKeyed)
  17731. {
  17732. reader.setown(manager->createReader(0, 0, 1));
  17733. deserializeSource.setStream(reader);
  17734. prefetcher.setown(diskSize.queryOriginal()->createDiskPrefetcher(ctx->queryCodeContext(), activityId));
  17735. }
  17736. helper.setCallback(reader ? reader->queryThorDiskCallback() : cursor);
  17737. }
  17738. }
  17739. }
  17740. virtual void append(IKeySegmentMonitor *segment)
  17741. {
  17742. if (!segment->isWild())
  17743. {
  17744. if (!cursor)
  17745. cursor.setown(manager->createCursor());
  17746. cursor->append(segment);
  17747. }
  17748. }
  17749. virtual unsigned ordinality() const
  17750. {
  17751. return cursor ? cursor->ordinality() : 0;
  17752. }
  17753. virtual IKeySegmentMonitor *item(unsigned idx) const
  17754. {
  17755. return cursor ? cursor->item(idx) : 0;
  17756. }
  17757. virtual void setMergeBarrier(unsigned barrierOffset)
  17758. {
  17759. // no merging so no issue...
  17760. }
  17761. virtual void stop(bool aborting)
  17762. {
  17763. if (useRemote())
  17764. remote->onStop(aborting);
  17765. CRoxieServerActivity::stop(aborting);
  17766. }
  17767. virtual void reset()
  17768. {
  17769. if (useRemote())
  17770. {
  17771. processed = remote->processed;
  17772. remote->processed = 0;
  17773. remote->onReset();
  17774. }
  17775. varFileInfo.clear();
  17776. eof = false;
  17777. if (cursor)
  17778. cursor->reset();
  17779. deserializeSource.clearStream();
  17780. CRoxieServerActivity::reset();
  17781. }
  17782. virtual void setInput(unsigned idx, IRoxieInput *_in)
  17783. {
  17784. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  17785. }
  17786. virtual void onLimitExceeded(bool isKeyed)
  17787. {
  17788. if (traceLevel > 4)
  17789. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  17790. assertex(compoundHelper);
  17791. if (isKeyed) // MORE does this exist for diskread? should it?
  17792. {
  17793. if (helper.getFlags() & (TDRkeyedlimitskips|TDRkeyedlimitcreates))
  17794. {
  17795. if (ctx->queryDebugContext())
  17796. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  17797. throw makeLimitSkipException(true);
  17798. }
  17799. else
  17800. {
  17801. UNIMPLEMENTED;
  17802. //compoundHelper->onKeyedLimitExceeded(); Doesn't exist - though the flags do... interesting...
  17803. }
  17804. }
  17805. else
  17806. {
  17807. if (helper.getFlags() & (TDRlimitskips|TDRlimitcreates))
  17808. {
  17809. if (ctx->queryDebugContext())
  17810. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  17811. throw makeLimitSkipException(false);
  17812. }
  17813. else
  17814. compoundHelper->onLimitExceeded();
  17815. }
  17816. }
  17817. virtual const void * createLimitFailRow(bool isKeyed)
  17818. {
  17819. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17820. IHThorSourceLimitTransformExtra *limitTransformExtra = static_cast<IHThorSourceLimitTransformExtra *>(helper.selectInterface(TAIsourcelimittransformextra_1));
  17821. assertex(limitTransformExtra);
  17822. size32_t outSize = isKeyed ? limitTransformExtra->transformOnKeyedLimitExceeded(rowBuilder) : limitTransformExtra->transformOnLimitExceeded(rowBuilder);
  17823. if (outSize)
  17824. return rowBuilder.finalizeRowClear(outSize);
  17825. return NULL;
  17826. }
  17827. };
  17828. class CRoxieServerDiskReadActivity : public CRoxieServerDiskReadBaseActivity
  17829. {
  17830. IHThorCompoundReadExtra * readHelper;
  17831. ConstPointerArray readrows;
  17832. bool readAheadDone;
  17833. unsigned readIndex;
  17834. public:
  17835. CRoxieServerDiskReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager)
  17836. : CRoxieServerDiskReadBaseActivity(_factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, _maySkip, _manager)
  17837. {
  17838. compoundHelper = (IHThorDiskReadArg *)&helper;
  17839. readHelper = (IHThorDiskReadArg *)&helper;
  17840. readAheadDone = false;
  17841. readIndex = 0;
  17842. }
  17843. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17844. {
  17845. rowLimit = compoundHelper->getRowLimit();
  17846. stopAfter = compoundHelper->getChooseNLimit();
  17847. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  17848. readAheadDone = false;
  17849. readIndex = 0;
  17850. }
  17851. virtual void reset()
  17852. {
  17853. while (readrows.isItem(readIndex))
  17854. ReleaseRoxieRow(readrows.item(readIndex++));
  17855. readrows.kill();
  17856. readAheadDone = false;
  17857. readIndex = 0;
  17858. CRoxieServerDiskReadBaseActivity::reset();
  17859. }
  17860. virtual const void *nextInGroup()
  17861. {
  17862. if (eof)
  17863. return NULL;
  17864. else if (useRemote())
  17865. return remote->nextInGroup();
  17866. else if (maySkip)
  17867. {
  17868. if (!readAheadDone)
  17869. {
  17870. unsigned preprocessed = 0;
  17871. while (!eof)
  17872. {
  17873. const void *row = _nextInGroup();
  17874. if (row)
  17875. preprocessed++;
  17876. if (preprocessed > rowLimit)
  17877. {
  17878. ReleaseRoxieRow(row);
  17879. while (readrows.isItem(readIndex))
  17880. ReleaseRoxieRow(readrows.item(readIndex++));
  17881. readrows.kill();
  17882. eof = true;
  17883. if (ctx->queryDebugContext())
  17884. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  17885. if (helper.getFlags() & TDRlimitskips)
  17886. return NULL;
  17887. else if (helper.getFlags() & TDRlimitcreates)
  17888. return createLimitFailRow(false);
  17889. else
  17890. throwUnexpected();
  17891. }
  17892. if (preprocessed > stopAfter) // MORE - bit of a strange place to check
  17893. {
  17894. eof = true;
  17895. ReleaseRoxieRow(row);
  17896. break;
  17897. }
  17898. readrows.append(row);
  17899. }
  17900. readAheadDone = true;
  17901. }
  17902. if (readrows.isItem(readIndex))
  17903. {
  17904. const void *ret = readrows.item(readIndex++);
  17905. if (ret)
  17906. processed++;
  17907. return ret;
  17908. }
  17909. else
  17910. {
  17911. eof = true;
  17912. return NULL;
  17913. }
  17914. }
  17915. else
  17916. {
  17917. const void *ret = _nextInGroup();
  17918. if (ret)
  17919. {
  17920. processed++;
  17921. if (processed > rowLimit)
  17922. {
  17923. if (traceLevel > 4)
  17924. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  17925. ReleaseRoxieRow(ret);
  17926. compoundHelper->onLimitExceeded();
  17927. throwUnexpected(); // onLimitExceeded is not supposed to return
  17928. }
  17929. if (processed > stopAfter) // MORE - bit of a strange place to check
  17930. {
  17931. eof = true;
  17932. ReleaseRoxieRow(ret);
  17933. return NULL;
  17934. }
  17935. }
  17936. return ret;
  17937. }
  17938. }
  17939. const void *_nextInGroup()
  17940. {
  17941. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17942. unsigned transformedSize = 0;
  17943. if (isKeyed)
  17944. {
  17945. loop
  17946. {
  17947. const void *nextCandidate = cursor->nextMatch();
  17948. if (!nextCandidate)
  17949. {
  17950. eof = true;
  17951. return NULL;
  17952. }
  17953. transformedSize = readHelper->transform(rowBuilder, nextCandidate);
  17954. if (transformedSize)
  17955. break;
  17956. }
  17957. }
  17958. else // use reader...
  17959. {
  17960. assertex(reader != NULL);
  17961. loop
  17962. {
  17963. if (deserializeSource.eos())
  17964. {
  17965. eof = true;
  17966. return NULL;
  17967. }
  17968. prefetcher->readAhead(deserializeSource);
  17969. const byte *nextRec = deserializeSource.queryRow();
  17970. if (cursor && cursor->isFiltered(nextRec))
  17971. transformedSize = 0;
  17972. else
  17973. transformedSize = readHelper->transform(rowBuilder, nextRec);
  17974. deserializeSource.finishedRow();
  17975. if (transformedSize)
  17976. break;
  17977. }
  17978. }
  17979. return rowBuilder.finalizeRowClear(transformedSize);
  17980. }
  17981. };
  17982. class CRoxieServerXmlReadActivity : public CRoxieServerDiskReadBaseActivity, implements IXMLSelect
  17983. {
  17984. IHThorXmlReadArg * readHelper;
  17985. Owned<IXmlToRowTransformer> rowTransformer;
  17986. Owned<IXMLParse> xmlParser;
  17987. Owned<IColumnProvider> lastMatch;
  17988. unsigned __int64 localOffset;
  17989. public:
  17990. IMPLEMENT_IINTERFACE;
  17991. CRoxieServerXmlReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager)
  17992. : CRoxieServerDiskReadBaseActivity(_factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, _maySkip, _manager)
  17993. {
  17994. compoundHelper = NULL;
  17995. readHelper = (IHThorXmlReadArg *)&helper;
  17996. localOffset = 0;
  17997. }
  17998. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17999. {
  18000. rowLimit = readHelper->getRowLimit();
  18001. stopAfter = readHelper->getChooseNLimit();
  18002. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  18003. if (!useRemote())
  18004. {
  18005. rowTransformer.set(readHelper->queryTransformer());
  18006. assertex(reader != NULL);
  18007. OwnedRoxieString xmlIterator(readHelper->getXmlIteratorPath());
  18008. xmlParser.setown(createXMLParse(*reader->querySimpleStream(), xmlIterator, *this, (0 != (TDRxmlnoroot & readHelper->getFlags()))?ptr_noRoot:ptr_none, (readHelper->getFlags() & TDRusexmlcontents) != 0));
  18009. }
  18010. }
  18011. virtual void reset()
  18012. {
  18013. CRoxieServerDiskReadBaseActivity::reset();
  18014. rowTransformer.clear();
  18015. xmlParser.clear();
  18016. }
  18017. virtual void match(IColumnProvider &entry, offset_t startOffset, offset_t endOffset)
  18018. {
  18019. localOffset = startOffset;
  18020. lastMatch.set(&entry);
  18021. }
  18022. virtual const void *nextInGroup()
  18023. {
  18024. if (eof)
  18025. return NULL;
  18026. else if (useRemote())
  18027. return remote->nextInGroup();
  18028. assertex(xmlParser != NULL);
  18029. try
  18030. {
  18031. while (!eof)
  18032. {
  18033. //call to next() will callback on the IXmlSelect interface
  18034. bool gotNext = false;
  18035. gotNext = xmlParser->next();
  18036. if(!gotNext)
  18037. eof = true;
  18038. else if (lastMatch)
  18039. {
  18040. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  18041. unsigned sizeGot = rowTransformer->transform(rowBuilder, lastMatch, reader->queryThorDiskCallback());
  18042. lastMatch.clear();
  18043. localOffset = 0;
  18044. if (sizeGot)
  18045. {
  18046. OwnedConstRoxieRow ret = rowBuilder.finalizeRowClear(sizeGot);
  18047. if (processed > rowLimit)
  18048. {
  18049. if (traceLevel > 4)
  18050. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  18051. readHelper->onLimitExceeded();
  18052. throwUnexpected(); // onLimitExceeded is not supposed to return
  18053. }
  18054. processed++;
  18055. if (processed > stopAfter) // MORE - bit of a strange place to check
  18056. {
  18057. eof = true;
  18058. return NULL;
  18059. }
  18060. return ret.getClear();
  18061. }
  18062. }
  18063. }
  18064. return NULL;
  18065. }
  18066. catch(IException *E)
  18067. {
  18068. throw makeWrappedException(E);
  18069. }
  18070. }
  18071. };
  18072. class CRoxieServerCsvReadActivity : public CRoxieServerDiskReadBaseActivity
  18073. {
  18074. IHThorCsvReadArg *readHelper;
  18075. ICsvParameters * csvInfo;
  18076. unsigned headerLines;
  18077. unsigned maxDiskSize;
  18078. CSVSplitter csvSplitter;
  18079. unsigned __int64 localOffset;
  18080. const char *quotes;
  18081. const char *separators;
  18082. const char *terminators;
  18083. const char *escapes;
  18084. public:
  18085. CRoxieServerCsvReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  18086. unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager,
  18087. const char *_quotes, const char *_separators, const char *_terminators, const char *_escapes)
  18088. : CRoxieServerDiskReadBaseActivity(_factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, _maySkip, _manager),
  18089. quotes(_quotes), separators(_separators), terminators(_terminators), escapes(_escapes)
  18090. {
  18091. compoundHelper = NULL;
  18092. readHelper = (IHThorCsvReadArg *)&helper;
  18093. rowLimit = readHelper->getRowLimit();
  18094. stopAfter = readHelper->getChooseNLimit();
  18095. csvInfo = readHelper->queryCsvParameters();
  18096. maxDiskSize = csvInfo->queryMaxSize();
  18097. localOffset = 0;
  18098. headerLines = 0;
  18099. }
  18100. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18101. {
  18102. rowLimit = readHelper->getRowLimit();
  18103. stopAfter = readHelper->getChooseNLimit();
  18104. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  18105. if (!useRemote())
  18106. {
  18107. headerLines = csvInfo->queryHeaderLen();
  18108. if (headerLines && isLocal && reader->queryFilePart() != 1)
  18109. 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...
  18110. if (!eof)
  18111. {
  18112. if (varFileInfo)
  18113. {
  18114. const IPropertyTree *options = varFileInfo->queryProperties();
  18115. if (options)
  18116. {
  18117. quotes = options->queryProp("@csvQuote");
  18118. separators = options->queryProp("@csvSeparate");
  18119. terminators = options->queryProp("@csvTerminate");
  18120. escapes = options->queryProp("@csvEscape");
  18121. }
  18122. }
  18123. csvSplitter.init(readHelper->getMaxColumns(), csvInfo, quotes, separators, terminators, escapes);
  18124. }
  18125. }
  18126. }
  18127. virtual const void *nextInGroup()
  18128. {
  18129. if (eof)
  18130. return NULL;
  18131. else if (useRemote())
  18132. return remote->nextInGroup();
  18133. try
  18134. {
  18135. while (!eof)
  18136. {
  18137. if (reader->eos())
  18138. {
  18139. eof = true;
  18140. break;
  18141. }
  18142. // MORE - there are rumours of a csvSplitter that operates on a stream... if/when it exists, this should use it
  18143. size32_t rowSize = 4096; // MORE - make configurable
  18144. size32_t maxRowSize = 10*1024*1024; // MORE - make configurable
  18145. size32_t thisLineLength;
  18146. loop
  18147. {
  18148. size32_t avail;
  18149. const void *peek = reader->peek(rowSize, avail);
  18150. thisLineLength = csvSplitter.splitLine(avail, (const byte *)peek);
  18151. if (thisLineLength < rowSize || avail < rowSize)
  18152. break;
  18153. if (rowSize == maxRowSize)
  18154. throw MakeStringException(0, "Row too big");
  18155. if (rowSize >= maxRowSize/2)
  18156. rowSize = maxRowSize;
  18157. else
  18158. rowSize += rowSize;
  18159. }
  18160. if (headerLines)
  18161. {
  18162. headerLines--;
  18163. reader->skip(thisLineLength);
  18164. }
  18165. else
  18166. {
  18167. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  18168. unsigned transformedSize = readHelper->transform(rowBuilder, csvSplitter.queryLengths(), (const char * *)csvSplitter.queryData());
  18169. reader->skip(thisLineLength);
  18170. if (transformedSize)
  18171. {
  18172. OwnedConstRoxieRow ret = rowBuilder.finalizeRowClear(transformedSize);
  18173. if (processed > rowLimit)
  18174. {
  18175. readHelper->onLimitExceeded();
  18176. throwUnexpected(); // onLimitExceeded is not supposed to return
  18177. }
  18178. processed++;
  18179. if (processed > stopAfter) // MORE - bit of a strange place to check
  18180. {
  18181. eof = true;
  18182. return NULL;
  18183. }
  18184. return ret.getClear();
  18185. }
  18186. }
  18187. }
  18188. return NULL;
  18189. }
  18190. catch(IException *E)
  18191. {
  18192. throw makeWrappedException(E);
  18193. }
  18194. }
  18195. virtual void reset()
  18196. {
  18197. CRoxieServerDiskReadBaseActivity::reset();
  18198. csvSplitter.reset();
  18199. localOffset = 0;
  18200. }
  18201. virtual unsigned __int64 getFilePosition(const void * row)
  18202. {
  18203. UNIMPLEMENTED; // we know offset in the reader but not sure it helps us much
  18204. }
  18205. virtual unsigned __int64 getLocalFilePosition(const void * row)
  18206. {
  18207. UNIMPLEMENTED;
  18208. }
  18209. };
  18210. class CRoxieServerDiskNormalizeActivity : public CRoxieServerDiskReadBaseActivity
  18211. {
  18212. IHThorDiskNormalizeArg *normalizeHelper;
  18213. bool firstPending;
  18214. public:
  18215. CRoxieServerDiskNormalizeActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, IInMemoryIndexManager *_manager)
  18216. : CRoxieServerDiskReadBaseActivity(_factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, false, _manager)
  18217. {
  18218. compoundHelper = (IHThorDiskNormalizeArg *)&helper;
  18219. normalizeHelper = (IHThorDiskNormalizeArg *)&helper;
  18220. firstPending = true;
  18221. }
  18222. virtual void reset()
  18223. {
  18224. firstPending = true;
  18225. CRoxieServerDiskReadBaseActivity::reset();
  18226. }
  18227. virtual const void *nextInGroup()
  18228. {
  18229. if (eof)
  18230. return NULL;
  18231. else if (useRemote())
  18232. return remote->nextInGroup();
  18233. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  18234. unsigned transformedSize = 0;
  18235. if (isKeyed)
  18236. {
  18237. loop
  18238. {
  18239. while (firstPending)
  18240. {
  18241. const void *nextCandidate = cursor->nextMatch();
  18242. if (!nextCandidate)
  18243. {
  18244. eof = true;
  18245. return NULL;
  18246. }
  18247. if (normalizeHelper->first(nextCandidate))
  18248. {
  18249. firstPending = false;
  18250. break;
  18251. }
  18252. }
  18253. transformedSize = normalizeHelper->transform(rowBuilder);
  18254. firstPending = !normalizeHelper->next();
  18255. if (transformedSize)
  18256. break;
  18257. }
  18258. }
  18259. else
  18260. {
  18261. assertex(reader != NULL);
  18262. loop
  18263. {
  18264. while (firstPending)
  18265. {
  18266. if (deserializeSource.eos())
  18267. {
  18268. eof = true;
  18269. return NULL;
  18270. }
  18271. prefetcher->readAhead(deserializeSource);
  18272. const byte *nextRec = deserializeSource.queryRow();
  18273. if (!cursor || !cursor->isFiltered(nextRec))
  18274. {
  18275. if (normalizeHelper->first(nextRec))
  18276. firstPending = false;
  18277. }
  18278. deserializeSource.finishedRow();
  18279. }
  18280. transformedSize = normalizeHelper->transform(rowBuilder);
  18281. firstPending = !normalizeHelper->next();
  18282. if (transformedSize)
  18283. break;
  18284. }
  18285. }
  18286. OwnedConstRoxieRow recBuffer = rowBuilder.finalizeRowClear(transformedSize);
  18287. processed++;
  18288. if (processed > rowLimit)
  18289. {
  18290. compoundHelper->onLimitExceeded();
  18291. throwUnexpected(); // onLimitExceeded is not supposed to return
  18292. }
  18293. if (processed > stopAfter) // MORE - bit of a strange place to check
  18294. {
  18295. eof = true;
  18296. return NULL;
  18297. }
  18298. return recBuffer.getClear();
  18299. }
  18300. };
  18301. class CRoxieServerDiskAggregateBaseActivity : public CRoxieServerDiskReadBaseActivity
  18302. {
  18303. protected:
  18304. bool done;
  18305. public:
  18306. CRoxieServerDiskAggregateBaseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager)
  18307. : CRoxieServerDiskReadBaseActivity(_factory, _probeManager, _remoteId, _numParts, _isLocal, false, false, _manager),
  18308. done(false)
  18309. {
  18310. }
  18311. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18312. {
  18313. done = false;
  18314. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  18315. }
  18316. virtual IRoxieInput *queryOutput(unsigned idx)
  18317. {
  18318. if (idx==(unsigned)-1)
  18319. idx = 0;
  18320. return idx ? NULL: this;
  18321. }
  18322. };
  18323. class CRoxieServerDiskCountActivity : public CRoxieServerDiskAggregateBaseActivity
  18324. {
  18325. IHThorDiskCountArg & countHelper;
  18326. unsigned __int64 choosenLimit;
  18327. IHThorSourceCountLimit *limitHelper;
  18328. unsigned __int64 getSkippedCount()
  18329. {
  18330. unsigned flags = countHelper.getFlags();
  18331. if (flags & TDRlimitskips)
  18332. return 0;
  18333. else if (flags & TDRlimitcreates)
  18334. return 1;
  18335. else
  18336. {
  18337. assertex(limitHelper);
  18338. if (traceLevel > 4)
  18339. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  18340. limitHelper->onLimitExceeded();
  18341. throwUnexpected(); // onLimitExceeded should always throw exception
  18342. }
  18343. }
  18344. public:
  18345. CRoxieServerDiskCountActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager)
  18346. : CRoxieServerDiskAggregateBaseActivity(_factory, _probeManager, _remoteId, _numParts, _isLocal, _manager),
  18347. countHelper((IHThorDiskCountArg &)basehelper)
  18348. {
  18349. limitHelper = static_cast<IHThorSourceCountLimit *>(basehelper.selectInterface(TAIsourcecountlimit_1));
  18350. choosenLimit = 0;
  18351. }
  18352. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18353. {
  18354. choosenLimit = countHelper.getChooseNLimit();
  18355. if (limitHelper)
  18356. {
  18357. rowLimit = limitHelper->getRowLimit();
  18358. // keyedLimit = limitHelper->getKeyedLimit(); // more - should there be one?
  18359. }
  18360. CRoxieServerDiskAggregateBaseActivity::start(parentExtractSize, parentExtract, paused);
  18361. }
  18362. virtual const void *nextInGroup()
  18363. {
  18364. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  18365. if (done) return NULL;
  18366. done = true;
  18367. unsigned __int64 totalCount = 0;
  18368. if (helper.canMatchAny() && !eof)
  18369. {
  18370. if (useRemote())
  18371. {
  18372. loop
  18373. {
  18374. const void * next = remote->nextInGroup();
  18375. if (!next)
  18376. break;
  18377. if (meta.getFixedSize() == 1)
  18378. totalCount += *(byte *)next;
  18379. else
  18380. totalCount += *(unsigned __int64 *)next;
  18381. ReleaseRoxieRow(next);
  18382. if (totalCount > rowLimit)
  18383. {
  18384. totalCount = getSkippedCount();
  18385. break;
  18386. }
  18387. else if (totalCount >= choosenLimit)
  18388. {
  18389. totalCount = choosenLimit;
  18390. break;
  18391. }
  18392. }
  18393. }
  18394. else
  18395. {
  18396. if (isKeyed)
  18397. {
  18398. loop
  18399. {
  18400. const void *nextCandidate = cursor->nextMatch();
  18401. if (!nextCandidate)
  18402. break;
  18403. totalCount += countHelper.numValid(nextCandidate);
  18404. if (totalCount > rowLimit)
  18405. {
  18406. totalCount = getSkippedCount();
  18407. break;
  18408. }
  18409. else if (totalCount >= choosenLimit)
  18410. {
  18411. totalCount = choosenLimit;
  18412. break;
  18413. }
  18414. }
  18415. }
  18416. else
  18417. {
  18418. assertex(reader != NULL);
  18419. while (!deserializeSource.eos())
  18420. {
  18421. prefetcher->readAhead(deserializeSource);
  18422. const byte *nextRec = deserializeSource.queryRow();
  18423. if (!cursor || !cursor->isFiltered(nextRec))
  18424. {
  18425. totalCount += countHelper.numValid(nextRec);
  18426. }
  18427. deserializeSource.finishedRow();
  18428. if (totalCount > rowLimit)
  18429. {
  18430. totalCount = getSkippedCount();
  18431. break;
  18432. }
  18433. else if (totalCount >= choosenLimit)
  18434. {
  18435. totalCount = choosenLimit;
  18436. break;
  18437. }
  18438. }
  18439. }
  18440. }
  18441. }
  18442. size32_t rowSize = meta.getFixedSize();
  18443. void * result = rowAllocator->createRow();
  18444. if (rowSize == 1)
  18445. *(byte *)result = (byte)totalCount;
  18446. else
  18447. {
  18448. assertex(rowSize == sizeof(unsigned __int64));
  18449. *(unsigned __int64 *)result = totalCount;
  18450. }
  18451. return rowAllocator->finalizeRow(rowSize, result, rowSize);
  18452. }
  18453. };
  18454. class CRoxieServerDiskAggregateActivity : public CRoxieServerDiskAggregateBaseActivity
  18455. {
  18456. IHThorCompoundAggregateExtra & aggregateHelper;
  18457. public:
  18458. CRoxieServerDiskAggregateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  18459. unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager)
  18460. : CRoxieServerDiskAggregateBaseActivity(_factory, _probeManager, _remoteId, _numParts, _isLocal, _manager),
  18461. aggregateHelper((IHThorDiskAggregateArg &)basehelper)
  18462. {
  18463. }
  18464. const void * gatherMerged()
  18465. {
  18466. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  18467. size32_t finalSize = 0;
  18468. if (useRemote())
  18469. {
  18470. const void * firstRow = remote->nextInGroup();
  18471. if (!firstRow)
  18472. {
  18473. rowBuilder.ensureRow();
  18474. finalSize = aggregateHelper.clearAggregate(rowBuilder);
  18475. }
  18476. else
  18477. {
  18478. // NOTE need to clone this because going to modify below, could special case 1 row only
  18479. finalSize = cloneRow(rowBuilder, firstRow, meta);
  18480. ReleaseRoxieRow(firstRow);
  18481. }
  18482. loop
  18483. {
  18484. const void * next = remote->nextInGroup();
  18485. if (!next)
  18486. break;
  18487. finalSize = aggregateHelper.mergeAggregate(rowBuilder, next);
  18488. ReleaseRoxieRow(next);
  18489. }
  18490. }
  18491. else
  18492. {
  18493. aggregateHelper.clearAggregate(rowBuilder);
  18494. if (helper.canMatchAny() && !eof)
  18495. {
  18496. if (isKeyed)
  18497. {
  18498. loop
  18499. {
  18500. const void *next = cursor->nextMatch();
  18501. if (!next)
  18502. break;
  18503. aggregateHelper.processRow(rowBuilder, next);
  18504. }
  18505. }
  18506. else
  18507. {
  18508. assertex(reader != NULL);
  18509. while (!deserializeSource.eos())
  18510. {
  18511. prefetcher->readAhead(deserializeSource);
  18512. const byte *nextRec = deserializeSource.queryRow();
  18513. if (!cursor || !cursor->isFiltered(nextRec))
  18514. {
  18515. aggregateHelper.processRow(rowBuilder, nextRec);
  18516. }
  18517. deserializeSource.finishedRow();
  18518. }
  18519. }
  18520. }
  18521. finalSize = meta.getRecordSize(rowBuilder.getSelf());
  18522. }
  18523. return rowBuilder.finalizeRowClear(finalSize);
  18524. }
  18525. virtual const void *nextInGroup()
  18526. {
  18527. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  18528. if (done) return NULL;
  18529. const void * ret = gatherMerged();
  18530. done = true;
  18531. return ret;
  18532. }
  18533. };
  18534. class CRoxieServerDiskGroupAggregateActivity : public CRoxieServerDiskAggregateBaseActivity
  18535. {
  18536. IHThorDiskGroupAggregateArg & aggregateHelper;
  18537. RowAggregator resultAggregator;
  18538. bool gathered;
  18539. public:
  18540. IMPLEMENT_IINTERFACE;
  18541. CRoxieServerDiskGroupAggregateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager)
  18542. : CRoxieServerDiskAggregateBaseActivity(_factory, _probeManager, _remoteId, _numParts, _isLocal, _manager),
  18543. aggregateHelper((IHThorDiskGroupAggregateArg &)basehelper),
  18544. resultAggregator(aggregateHelper, aggregateHelper),
  18545. gathered(false)
  18546. {
  18547. }
  18548. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18549. {
  18550. gathered= false;
  18551. CRoxieServerDiskAggregateBaseActivity::start(parentExtractSize, parentExtract, paused);
  18552. resultAggregator.start(rowAllocator);
  18553. }
  18554. virtual void reset()
  18555. {
  18556. resultAggregator.reset();
  18557. CRoxieServerDiskAggregateBaseActivity::reset();
  18558. }
  18559. void gatherMerged()
  18560. {
  18561. if (useRemote())
  18562. {
  18563. loop
  18564. {
  18565. const void * next = remote->nextInGroup();
  18566. if (!next)
  18567. break;
  18568. resultAggregator.mergeElement(next);
  18569. ReleaseRoxieRow(next);
  18570. }
  18571. }
  18572. else
  18573. {
  18574. if (helper.canMatchAny() && !eof)
  18575. {
  18576. Owned<IInMemoryFileProcessor> processor = isKeyed ?
  18577. createKeyedGroupAggregateRecordProcessor(cursor, resultAggregator, aggregateHelper) :
  18578. createUnkeyedGroupAggregateRecordProcessor(cursor, resultAggregator, aggregateHelper, manager->createReader(0, 0, 1),
  18579. ctx->queryCodeContext(), activityId);
  18580. processor->doQuery(NULL, 0, 0, 0);
  18581. }
  18582. }
  18583. gathered = true;
  18584. }
  18585. virtual const void *nextInGroup()
  18586. {
  18587. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  18588. if (done)
  18589. return NULL;
  18590. if (!gathered)
  18591. gatherMerged();
  18592. Owned<AggregateRowBuilder> next = resultAggregator.nextResult();
  18593. if (next)
  18594. {
  18595. processed++;
  18596. return next->finalizeRowClear();
  18597. }
  18598. done = true;
  18599. return NULL;
  18600. }
  18601. };
  18602. class CRoxieServerDiskReadActivityFactory : public CRoxieServerActivityFactory
  18603. {
  18604. public:
  18605. RemoteActivityId remoteId;
  18606. bool isLocal;
  18607. bool sorted;
  18608. bool maySkip;
  18609. bool variableFileName;
  18610. Owned<IFilePartMap> map;
  18611. Owned<IFileIOArray> files;
  18612. Owned<IInMemoryIndexManager> manager;
  18613. Owned<const IResolvedFile> datafile;
  18614. const char *quotes;
  18615. const char *separators;
  18616. const char *terminators;
  18617. const char *escapes;
  18618. CRoxieServerDiskReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  18619. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), remoteId(_remoteId)
  18620. {
  18621. isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  18622. Owned<IHThorDiskReadBaseArg> helper = (IHThorDiskReadBaseArg *) helperFactory();
  18623. sorted = (helper->getFlags() & TDRunsorted) == 0;
  18624. variableFileName = allFilesDynamic || ((helper->getFlags() & (TDXvarfilename|TDXdynamicfilename)) != 0);
  18625. maySkip = (helper->getFlags() & (TDRkeyedlimitskips|TDRkeyedlimitcreates|TDRlimitskips|TDRlimitcreates)) != 0;
  18626. quotes = separators = terminators = escapes = NULL;
  18627. if (!variableFileName)
  18628. {
  18629. bool isOpt = (helper->getFlags() & TDRoptional) != 0;
  18630. OwnedRoxieString fileName(helper->getFileName());
  18631. datafile.setown(_queryFactory.queryPackage().lookupFileName(fileName, isOpt, true, true, _queryFactory.queryWorkUnit()));
  18632. if (datafile)
  18633. map.setown(datafile->getFileMap());
  18634. bool isSimple = (map && map->getNumParts()==1 && !_queryFactory.getDebugValueBool("disableLocalOptimizations", false));
  18635. if (isLocal || isSimple)
  18636. {
  18637. if (datafile)
  18638. {
  18639. unsigned channel = isLocal ? queryFactory.queryChannel() : 0;
  18640. files.setown(datafile->getIFileIOArray(isOpt, channel));
  18641. manager.setown(datafile->getIndexManager(isOpt, channel, files, helper->queryDiskRecordSize(), _graphNode.getPropBool("att[@name=\"preload\"]/@value", false), _graphNode.getPropInt("att[@name=\"_preloadSize\"]/@value", 0)));
  18642. const IPropertyTree *options = datafile->queryProperties();
  18643. if (options)
  18644. {
  18645. quotes = options->queryProp("@csvQuote");
  18646. separators = options->queryProp("@csvSeparate");
  18647. terminators = options->queryProp("@csvTerminate");
  18648. escapes = options->queryProp("@csvEscape");
  18649. }
  18650. }
  18651. else
  18652. manager.setown(getEmptyIndexManager());
  18653. }
  18654. }
  18655. }
  18656. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  18657. {
  18658. unsigned numParts = map ? map->getNumParts() : 0;
  18659. switch (kind)
  18660. {
  18661. case TAKcsvread:
  18662. return new CRoxieServerCsvReadActivity(this, _probeManager, remoteId, numParts, isLocal, sorted, maySkip, manager,
  18663. quotes, separators, terminators, escapes);
  18664. case TAKxmlread:
  18665. return new CRoxieServerXmlReadActivity(this, _probeManager, remoteId, numParts, isLocal, sorted, maySkip, manager);
  18666. case TAKdiskread:
  18667. return new CRoxieServerDiskReadActivity(this, _probeManager, remoteId, numParts, isLocal, sorted, maySkip, manager);
  18668. case TAKdisknormalize:
  18669. return new CRoxieServerDiskNormalizeActivity(this, _probeManager, remoteId, numParts, isLocal, sorted, manager);
  18670. case TAKdiskcount:
  18671. return new CRoxieServerDiskCountActivity(this, _probeManager, remoteId, numParts, isLocal, manager);
  18672. case TAKdiskaggregate:
  18673. return new CRoxieServerDiskAggregateActivity(this, _probeManager, remoteId, numParts, isLocal, manager);
  18674. case TAKdiskgroupaggregate:
  18675. return new CRoxieServerDiskGroupAggregateActivity(this, _probeManager, remoteId, numParts, isLocal, manager);
  18676. }
  18677. throwUnexpected();
  18678. }
  18679. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  18680. {
  18681. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  18682. }
  18683. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  18684. {
  18685. if (datafile)
  18686. addXrefFileInfo(reply, datafile);
  18687. }
  18688. };
  18689. IRoxieServerActivityFactory *createRoxieServerDiskReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  18690. {
  18691. return new CRoxieServerDiskReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode);
  18692. }
  18693. //=================================================================================
  18694. class CRoxieServerIndexActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler
  18695. {
  18696. protected:
  18697. IHThorIndexReadBaseArg &indexHelper;
  18698. IHThorSteppedSourceExtra * steppedExtra;
  18699. Linked<IKeyArray> keySet;
  18700. Linked<TranslatorArray> translators;
  18701. CSkippableRemoteResultAdaptor remote;
  18702. CIndexTransformCallback callback;
  18703. bool sorted;
  18704. bool variableFileName;
  18705. bool variableInfoPending;
  18706. bool isOpt;
  18707. bool isLocal;
  18708. unsigned __int64 rowLimit;
  18709. unsigned __int64 keyedLimit;
  18710. unsigned __int64 choosenLimit;
  18711. unsigned accepted;
  18712. unsigned rejected;
  18713. unsigned seekGEOffset;
  18714. Owned<IKeyManager> tlk;
  18715. Owned<const IResolvedFile> varFileInfo;
  18716. const RemoteActivityId &remoteId;
  18717. void setVariableFileInfo()
  18718. {
  18719. OwnedRoxieString indexName(indexHelper.getFileName());
  18720. varFileInfo.setown(resolveLFN(indexName, isOpt));
  18721. if (varFileInfo)
  18722. {
  18723. translators.setown(new TranslatorArray) ;
  18724. keySet.setown(varFileInfo->getKeyArray(factory->queryActivityMeta(), translators, isOpt, isLocal ? factory->queryQueryFactory().queryChannel() : 0, factory->queryQueryFactory().getEnableFieldTranslation()));
  18725. }
  18726. variableInfoPending = false;
  18727. }
  18728. public:
  18729. CRoxieServerIndexActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  18730. IKeyArray * _keySet, TranslatorArray *_translators, bool _sorted, bool _isLocal, bool _maySkip)
  18731. : CRoxieServerActivity(_factory, _probeManager),
  18732. keySet(_keySet),
  18733. translators(_translators),
  18734. indexHelper((IHThorIndexReadBaseArg &)basehelper),
  18735. remote(_remoteId, meta.queryOriginal(), indexHelper, *this, _sorted, false, _maySkip),
  18736. remoteId(_remoteId),
  18737. sorted(_sorted),
  18738. isLocal(_isLocal)
  18739. {
  18740. indexHelper.setCallback(&callback);
  18741. steppedExtra = static_cast<IHThorSteppedSourceExtra *>(indexHelper.selectInterface(TAIsteppedsourceextra_1));
  18742. variableFileName = allFilesDynamic || ((indexHelper.getFlags() & (TIRvarfilename|TIRdynamicfilename)) != 0);
  18743. variableInfoPending = false;
  18744. isOpt = (indexHelper.getFlags() & TIRoptional) != 0;
  18745. seekGEOffset = 0;
  18746. // started = false;
  18747. rejected = accepted = 0;
  18748. rowLimit = choosenLimit = keyedLimit = 0;
  18749. }
  18750. virtual const IResolvedFile *queryVarFileInfo() const
  18751. {
  18752. return varFileInfo;
  18753. }
  18754. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  18755. {
  18756. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  18757. remote.onCreate(this, this, _ctx, _colocalParent);
  18758. }
  18759. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18760. {
  18761. accepted = 0;
  18762. rejected = 0;
  18763. rowLimit = (unsigned __int64) -1;
  18764. keyedLimit = (unsigned __int64 ) -1;
  18765. choosenLimit = I64C(0x7fffffffffffffff);
  18766. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  18767. remote.onStart(parentExtractSize, parentExtract);
  18768. variableInfoPending = variableFileName;
  18769. }
  18770. void processAllKeys()
  18771. {
  18772. try
  18773. {
  18774. if (indexHelper.canMatchAny())
  18775. {
  18776. if (variableInfoPending)
  18777. setVariableFileInfo();
  18778. remote.setLimits(rowLimit, keyedLimit, choosenLimit);
  18779. if (keySet)
  18780. {
  18781. // MORE - this recreates the segmonitors per part but not per fileno (which is a little backwards).
  18782. // 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
  18783. // However order is probably better to iterate fileno's inside partnos
  18784. // MORE - also not properly supporting STEPPED I fear.
  18785. // A superkey that mixes single and multipart or tlk and roroot keys might be hard
  18786. for (unsigned partNo = 0; partNo < keySet->length(); partNo++)
  18787. {
  18788. IKeyIndexBase *thisBase = keySet->queryKeyPart(partNo);
  18789. if (thisBase)
  18790. {
  18791. unsigned fileNo = 0;
  18792. IKeyIndex *thisKey = thisBase->queryPart(fileNo);
  18793. if (!thisKey->isTopLevelKey())
  18794. {
  18795. if (keyedLimit != (unsigned __int64) -1)
  18796. {
  18797. if ((indexHelper.getFlags() & TIRcountkeyedlimit) != 0)
  18798. {
  18799. Owned<IKeyManager> countKey;
  18800. countKey.setown(createKeyManager(thisKey, 0, this));
  18801. countKey->setLayoutTranslator(translators->item(fileNo));
  18802. createSegmentMonitors(countKey);
  18803. unsigned __int64 count = countKey->checkCount(keyedLimit);
  18804. if (count > keyedLimit)
  18805. {
  18806. if (traceLevel > 4)
  18807. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  18808. onLimitExceeded(true);
  18809. }
  18810. }
  18811. }
  18812. }
  18813. if (seekGEOffset && !thisKey->isTopLevelKey())
  18814. {
  18815. tlk.setown(createSingleKeyMerger(thisKey, 0, seekGEOffset, this));
  18816. }
  18817. else
  18818. {
  18819. tlk.setown(createKeyManager(thisKey, 0, this));
  18820. tlk->setLayoutTranslator(translators->item(fileNo));
  18821. }
  18822. createSegmentMonitors(tlk);
  18823. if (queryTraceLevel() > 3 || ctx->queryProbeManager())
  18824. {
  18825. StringBuffer out;
  18826. printKeyedValues(out, tlk, indexHelper.queryDiskRecordSize());
  18827. CTXLOG("Using filter %s", out.str());
  18828. if (ctx->queryProbeManager())
  18829. ctx->queryProbeManager()->setNodeProperty(this, "filter", out.str());
  18830. }
  18831. tlk->reset();
  18832. loop // for each file part
  18833. {
  18834. //block for TransformCallbackAssociation
  18835. {
  18836. TransformCallbackAssociation associate(callback, tlk);
  18837. if (thisKey->isTopLevelKey())
  18838. {
  18839. if (thisKey->isFullySorted())
  18840. {
  18841. while (tlk->lookup(false))
  18842. {
  18843. unsigned slavePart = (unsigned) tlk->queryFpos();
  18844. if (slavePart)
  18845. {
  18846. accepted++;
  18847. remote.getMem(slavePart, fileNo, 0); // the cached context is all we need to send
  18848. if (sorted && numChannels>1)
  18849. remote.flush(); // don't combine parts if we need result sorted, except on a 1-way
  18850. }
  18851. }
  18852. }
  18853. else
  18854. {
  18855. // MORE - we could check whether there are any matching parts if we wanted.
  18856. // If people are in the habit of sending null values that would be worthwhile
  18857. remote.getMem(0, fileNo, 0);
  18858. }
  18859. }
  18860. else
  18861. {
  18862. if (processSingleKey(thisKey, translators->item(fileNo)))
  18863. break;
  18864. }
  18865. }
  18866. if (++fileNo < thisBase->numParts())
  18867. {
  18868. thisKey = thisBase->queryPart(fileNo);
  18869. tlk->setKey(thisKey);
  18870. tlk->setLayoutTranslator(translators->item(fileNo));
  18871. tlk->reset();
  18872. }
  18873. else
  18874. break;
  18875. }
  18876. tlk->releaseSegmentMonitors();
  18877. tlk->setKey(NULL);
  18878. }
  18879. }
  18880. }
  18881. }
  18882. remote.flush();
  18883. remote.senddone();
  18884. }
  18885. catch (IException *E)
  18886. {
  18887. remote.setException(E);
  18888. }
  18889. }
  18890. virtual void createSegmentMonitors(IKeyManager *key)
  18891. {
  18892. indexHelper.createSegmentMonitors(key);
  18893. key->finishSegmentMonitors();
  18894. }
  18895. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans) = 0;
  18896. virtual void reset()
  18897. {
  18898. if (accepted)
  18899. noteStatistic(STATS_ACCEPTED, accepted, 1);
  18900. if (rejected)
  18901. noteStatistic(STATS_REJECTED, rejected, 1);
  18902. remote.onReset();
  18903. CRoxieServerActivity::reset();
  18904. if (varFileInfo)
  18905. {
  18906. keySet.clear();
  18907. varFileInfo.clear();
  18908. }
  18909. variableInfoPending = false;
  18910. }
  18911. virtual void stop(bool aborting)
  18912. {
  18913. remote.onStop(aborting);
  18914. CRoxieServerActivity::stop(aborting);
  18915. }
  18916. virtual void setInput(unsigned idx, IRoxieInput *_in)
  18917. {
  18918. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  18919. }
  18920. };
  18921. class CRoxieServerIndexReadBaseActivity : public CRoxieServerIndexActivity
  18922. {
  18923. IHThorSourceLimitTransformExtra * limitTransformExtra;
  18924. public:
  18925. CRoxieServerIndexReadBaseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  18926. IKeyArray * _keySet, TranslatorArray *_translators, bool _sorted, bool _isLocal, bool _maySkip)
  18927. : CRoxieServerIndexActivity(_factory, _probeManager, _remoteId, _keySet, _translators, _sorted, _isLocal, _maySkip)
  18928. {
  18929. limitTransformExtra = static_cast<IHThorSourceLimitTransformExtra *>(indexHelper.selectInterface(TAIsourcelimittransformextra_1));
  18930. }
  18931. virtual void reset()
  18932. {
  18933. remote.onReset();
  18934. CRoxieServerIndexActivity::reset();
  18935. }
  18936. virtual const void *nextInGroup()
  18937. {
  18938. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  18939. try
  18940. {
  18941. const void *ret = remote.nextInGroup();
  18942. if (ret)
  18943. processed++;
  18944. return ret;
  18945. }
  18946. catch (IException *E)
  18947. {
  18948. throw makeWrappedException(E);
  18949. }
  18950. }
  18951. protected:
  18952. virtual const void * createLimitFailRow(bool isKeyed)
  18953. {
  18954. createRowAllocator();
  18955. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  18956. size32_t outSize = isKeyed ? limitTransformExtra->transformOnKeyedLimitExceeded(rowBuilder) : limitTransformExtra->transformOnLimitExceeded(rowBuilder);
  18957. if (outSize)
  18958. return rowBuilder.finalizeRowClear(outSize);
  18959. return NULL;
  18960. }
  18961. };
  18962. class CRoxieServerIndexReadActivity : public CRoxieServerIndexReadBaseActivity, implements IIndexReadActivityInfo
  18963. {
  18964. protected:
  18965. IHThorCompoundReadExtra & readHelper;
  18966. ISteppingMeta *rawMeta;
  18967. CSteppingMeta steppingMeta;
  18968. unsigned * seekSizes;
  18969. bool optimizeSteppedPostFilter;
  18970. ISteppingMeta * projectedMeta;
  18971. unsigned maxSeekLookahead;
  18972. public:
  18973. CRoxieServerIndexReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  18974. IKeyArray * _keySet, TranslatorArray *_translators, bool _sorted, bool _isLocal, bool _maySkip, unsigned _maxSeekLookahead)
  18975. : CRoxieServerIndexReadBaseActivity(_factory, _probeManager, _remoteId, _keySet, _translators, _sorted, _isLocal, _maySkip),
  18976. readHelper((IHThorIndexReadArg &)basehelper)
  18977. {
  18978. rawMeta = readHelper.queryRawSteppingMeta();
  18979. unsigned flags = indexHelper.getFlags();
  18980. optimizeSteppedPostFilter = (flags & TIRunfilteredtransform) != 0;
  18981. seekSizes = NULL;
  18982. maxSeekLookahead = _maxSeekLookahead;
  18983. if (rawMeta)
  18984. {
  18985. const CFieldOffsetSize * fields = rawMeta->queryFields();
  18986. unsigned maxFields = rawMeta->getNumFields();
  18987. seekGEOffset = fields[0].offset;
  18988. seekSizes = new unsigned[maxFields];
  18989. seekSizes[0] = fields[0].size;
  18990. for (unsigned i=1; i < maxFields; i++)
  18991. seekSizes[i] = seekSizes[i-1] + fields[i].size;
  18992. projectedMeta = readHelper.queryProjectedSteppingMeta();
  18993. ISteppingMeta *useMeta = projectedMeta ? projectedMeta : rawMeta;
  18994. remote.setMergeInfo(useMeta); // also need to consider superfile case where there is a mix of multiway and singleparts.. ?
  18995. bool hasPostFilter = readHelper.transformMayFilter() && optimizeSteppedPostFilter;
  18996. steppingMeta.init(useMeta, hasPostFilter);
  18997. }
  18998. }
  18999. ~CRoxieServerIndexReadActivity()
  19000. {
  19001. delete [] seekSizes;
  19002. }
  19003. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19004. {
  19005. CRoxieServerIndexReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  19006. steppingMeta.setDistributed();
  19007. if (steppedExtra)
  19008. steppingMeta.setExtra(steppedExtra);
  19009. rowLimit = readHelper.getRowLimit();
  19010. keyedLimit = readHelper.getKeyedLimit();
  19011. choosenLimit = readHelper.getChooseNLimit();
  19012. if (!paused)
  19013. processAllKeys();
  19014. }
  19015. class LazyLocalKeyReader : public CInterface, implements IMessageResult, implements IMessageUnpackCursor
  19016. {
  19017. public:
  19018. IMPLEMENT_IINTERFACE;
  19019. virtual IMessageUnpackCursor *getCursor(roxiemem::IRowManager *rowMgr) const
  19020. {
  19021. Link();
  19022. return const_cast<LazyLocalKeyReader*> (this);
  19023. }
  19024. virtual const void *getMessageHeader(unsigned &length) const
  19025. {
  19026. length = 0;
  19027. return NULL;
  19028. }
  19029. virtual const void *getMessageMetadata(unsigned &length) const
  19030. {
  19031. length = 0;
  19032. return NULL;
  19033. }
  19034. virtual void discard() const
  19035. {
  19036. // nothing to do.
  19037. }
  19038. unsigned keyedCount;
  19039. unsigned matched;
  19040. bool EOFseen;
  19041. Owned<IKeyIndexSet> keySet;
  19042. Owned<IKeyManager> tlk;
  19043. CRoxieServerIndexReadActivity &owner;
  19044. LazyLocalKeyReader(CRoxieServerIndexReadActivity &_owner, IKeyIndex *key, IRecordLayoutTranslator * trans)
  19045. : owner(_owner)
  19046. {
  19047. keyedCount = 0;
  19048. matched = 0;
  19049. EOFseen = false;
  19050. keySet.setown(createKeyIndexSet());
  19051. keySet->addIndex(LINK(key));
  19052. if (owner.seekGEOffset)
  19053. tlk.setown(createKeyMerger(keySet, 0, owner.seekGEOffset, &owner));
  19054. else
  19055. tlk.setown(createKeyManager(keySet->queryPart(0), 0, &owner));
  19056. tlk->setLayoutTranslator(trans);
  19057. owner.indexHelper.createSegmentMonitors(tlk);
  19058. tlk->finishSegmentMonitors();
  19059. tlk->reset();
  19060. }
  19061. virtual const void *getNext(int length)
  19062. {
  19063. TransformCallbackAssociation associate(owner.callback, tlk);
  19064. while (tlk->lookup(true))
  19065. {
  19066. keyedCount++;
  19067. if (keyedCount > owner.keyedLimit)
  19068. {
  19069. owner.onLimitExceeded(true); // Should throw exception
  19070. throwUnexpected();
  19071. }
  19072. size32_t transformedSize;
  19073. RtlDynamicRowBuilder rowBuilder(owner.rowAllocator);
  19074. byte const * keyRow = tlk->queryKeyBuffer(owner.callback.getFPosRef());
  19075. try
  19076. {
  19077. transformedSize = owner.readHelper.transform(rowBuilder, keyRow);
  19078. owner.callback.finishedRow();
  19079. }
  19080. catch (IException *E)
  19081. {
  19082. throw owner.makeWrappedException(E);
  19083. }
  19084. if (transformedSize)
  19085. {
  19086. OwnedConstRoxieRow result = rowBuilder.finalizeRowClear(transformedSize);
  19087. matched++;
  19088. if (matched > owner.rowLimit)
  19089. {
  19090. owner.onLimitExceeded(false); // Should throw exception
  19091. throwUnexpected();
  19092. }
  19093. if (matched > owner.choosenLimit) // MORE - bit of a strange place to check
  19094. {
  19095. break;
  19096. }
  19097. owner.accepted++;
  19098. return result.getClear();
  19099. }
  19100. else
  19101. owner.rejected++;
  19102. }
  19103. EOFseen = true;
  19104. return NULL;
  19105. }
  19106. virtual bool atEOF() const
  19107. {
  19108. return EOFseen;
  19109. }
  19110. virtual bool isSerialized() const
  19111. {
  19112. return false;
  19113. }
  19114. };
  19115. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
  19116. {
  19117. createRowAllocator();
  19118. remote.injectResult(new LazyLocalKeyReader(*this, key, trans));
  19119. return false;
  19120. }
  19121. virtual void onLimitExceeded(bool isKeyed)
  19122. {
  19123. if (traceLevel > 4)
  19124. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  19125. if (isKeyed)
  19126. {
  19127. if (indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates))
  19128. {
  19129. if (ctx->queryDebugContext())
  19130. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  19131. throw makeLimitSkipException(true);
  19132. }
  19133. else
  19134. readHelper.onKeyedLimitExceeded();
  19135. }
  19136. else
  19137. {
  19138. if (indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates))
  19139. {
  19140. if (ctx->queryDebugContext())
  19141. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  19142. throw makeLimitSkipException(false);
  19143. }
  19144. else
  19145. readHelper.onLimitExceeded();
  19146. }
  19147. }
  19148. virtual void serializeSkipInfo(MemoryBuffer &out, unsigned seekLen, const void *rawSeek, unsigned numFields, const void * seek, const SmartStepExtra &stepExtra) const
  19149. {
  19150. out.append((unsigned short) numFields);
  19151. out.append((unsigned short) seekLen);
  19152. out.append((unsigned short) stepExtra.queryFlags());
  19153. IMultipleStepSeekInfo *seeks = stepExtra.queryExtraSeeks();
  19154. if (seeks)
  19155. {
  19156. unsigned lookahead = 40000/seekLen;
  19157. if (maxSeekLookahead && (lookahead > maxSeekLookahead))
  19158. lookahead = maxSeekLookahead;
  19159. seeks->ensureFilled(seek, numFields, lookahead);
  19160. out.append(lookahead != seeks->ordinality()); // seeksAreEof flag
  19161. unsigned serialized = 1; // rawseek is always serialized...
  19162. unsigned patchLength = out.length();
  19163. out.append(serialized); // NOTE - we come back and patch with the actual value...
  19164. out.append(seekLen, rawSeek);
  19165. if (seeks->ordinality())
  19166. {
  19167. const void *lastSeek = rawSeek;
  19168. byte *nextSeek = NULL;
  19169. if (projectedMeta)
  19170. nextSeek = (byte *) alloca(seekLen);
  19171. for (unsigned i = 0; i < seeks->ordinality(); i++)
  19172. {
  19173. if (projectedMeta)
  19174. {
  19175. RtlStaticRowBuilder rowBuilder(nextSeek-seekGEOffset, seekGEOffset+seekLen);
  19176. readHelper.mapOutputToInput(rowBuilder, seeks->querySeek(i), numFields); // NOTE - weird interface to mapOutputToInput means that it STARTS writing at seekGEOffset...
  19177. }
  19178. else
  19179. nextSeek = (byte *) seeks->querySeek(i)+seekGEOffset;
  19180. int diff = memcmp(nextSeek, lastSeek, seekLen);
  19181. if (diff > 0)
  19182. {
  19183. serialized++;
  19184. out.append(seekLen, nextSeek);
  19185. lastSeek = (const byte *) out.reserve(0) - seekLen;
  19186. }
  19187. }
  19188. unsigned length = out.length();
  19189. out.setWritePos(patchLength);
  19190. out.append(serialized);
  19191. out.setWritePos(length);
  19192. }
  19193. }
  19194. else
  19195. {
  19196. out.append(false);
  19197. out.append(1);
  19198. out.append(seekLen, rawSeek);
  19199. }
  19200. }
  19201. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  19202. {
  19203. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  19204. try
  19205. {
  19206. unsigned seeklen = 0;
  19207. const void *rawSeek = NULL;
  19208. if (seek && numFields)
  19209. {
  19210. seeklen = seekSizes[numFields-1];
  19211. rawSeek = (const byte *)seek + seekGEOffset;
  19212. if (projectedMeta)
  19213. {
  19214. byte * temp = (byte *) alloca(seeklen);
  19215. RtlStaticRowBuilder rawBuilder(temp-seekGEOffset, seekGEOffset+seeklen);
  19216. readHelper.mapOutputToInput(rawBuilder, seek, numFields); // NOTE - weird interface to mapOutputToInput means that it STARTS writing at seekGEOffset...
  19217. rawSeek = (byte *)temp;
  19218. }
  19219. }
  19220. const void *ret = remote.nextSteppedGE(seek, rawSeek, numFields, seeklen, wasCompleteMatch, stepExtra);
  19221. if (ret && wasCompleteMatch) // GH pleas confirm the wasCompleteMatch I just added here is right
  19222. processed++;
  19223. return ret;
  19224. }
  19225. catch (IException *E)
  19226. {
  19227. throw makeWrappedException(E);
  19228. }
  19229. }
  19230. virtual IInputSteppingMeta * querySteppingMeta()
  19231. {
  19232. if (rawMeta && steppingEnabled && ((indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates|TIRkeyedlimitskips|TIRkeyedlimitcreates)) == 0))
  19233. return &steppingMeta;
  19234. return NULL;
  19235. }
  19236. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  19237. {
  19238. if (variableInfoPending)
  19239. setVariableFileInfo();
  19240. return this;
  19241. }
  19242. virtual IKeyArray *getKeySet() const
  19243. {
  19244. return keySet.getLink();
  19245. }
  19246. virtual const IResolvedFile *getVarFileInfo() const
  19247. {
  19248. return varFileInfo.getLink();
  19249. }
  19250. virtual TranslatorArray *getTranslators() const
  19251. {
  19252. return translators.getLink();
  19253. }
  19254. virtual void mergeSegmentMonitors(IIndexReadContext *irc) const
  19255. {
  19256. indexHelper.createSegmentMonitors(irc); // NOTE: they will merge
  19257. }
  19258. virtual IRoxieServerActivity *queryActivity() { return this; }
  19259. virtual const RemoteActivityId& queryRemoteId() const
  19260. {
  19261. return remoteId;
  19262. }
  19263. };
  19264. class CRoxieServerSimpleIndexReadActivity : public CRoxieServerActivity, implements IIndexReadActivityInfo
  19265. {
  19266. IHThorCompoundReadExtra & readHelper;
  19267. IHThorIndexReadBaseArg & indexHelper;
  19268. IHThorSourceLimitTransformExtra * limitTransformExtra;
  19269. IHThorSteppedSourceExtra * steppedExtra;
  19270. bool eof;
  19271. Linked<IKeyArray>keySet;
  19272. Owned<IKeyIndexSet>keyIndexSet;
  19273. Owned<IKeyManager> tlk;
  19274. Linked<TranslatorArray> translators;
  19275. CIndexTransformCallback callback;
  19276. unsigned __int64 keyedLimit;
  19277. unsigned rowLimit;
  19278. unsigned chooseNLimit;
  19279. unsigned accepted;
  19280. unsigned rejected;
  19281. unsigned keyedCount;
  19282. ISteppingMeta * rawMeta;
  19283. ISteppingMeta * projectedMeta;
  19284. size32_t seekGEOffset;
  19285. unsigned * seekSizes;
  19286. CSteppingMeta steppingMeta;
  19287. Owned<const IResolvedFile> varFileInfo;
  19288. const RemoteActivityId &remoteId;
  19289. bool firstRead;
  19290. bool variableFileName;
  19291. bool variableInfoPending;
  19292. bool isOpt;
  19293. bool isLocal;
  19294. bool optimizeSteppedPostFilter;
  19295. // MORE there may be enough in common between this and CRoxieServerIndexActivity to warrant some refactoring
  19296. void initKeySet()
  19297. {
  19298. if ((keySet->length() > 1 || rawMeta != NULL) && translators->needsTranslation())
  19299. {
  19300. throw MakeStringException(ROXIE_UNIMPLEMENTED_ERROR, "Layout translation is not available when merging key parts or smart-stepping, as it may change record order");
  19301. }
  19302. keyIndexSet.setown(createKeyIndexSet());
  19303. for (unsigned part = 0; part < keySet->length(); part++)
  19304. {
  19305. IKeyIndexBase *kib = keySet->queryKeyPart(part);
  19306. if (kib)
  19307. {
  19308. for (unsigned subpart = 0; subpart < kib->numParts(); subpart++)
  19309. {
  19310. IKeyIndex *k = kib->queryPart(subpart);
  19311. if (k)
  19312. {
  19313. assertex(!k->isTopLevelKey());
  19314. keyIndexSet->addIndex(LINK(k));
  19315. }
  19316. }
  19317. }
  19318. }
  19319. }
  19320. void setVariableFileInfo()
  19321. {
  19322. OwnedRoxieString indexName(indexHelper.getFileName());
  19323. varFileInfo.setown(resolveLFN(indexName, isOpt));
  19324. translators.setown(new TranslatorArray) ;
  19325. keySet.setown(varFileInfo->getKeyArray(factory->queryActivityMeta(), translators, isOpt, isLocal ? factory->queryQueryFactory().queryChannel() : 0, factory->queryQueryFactory().getEnableFieldTranslation()));
  19326. initKeySet();
  19327. variableInfoPending = false;
  19328. }
  19329. void onEOF()
  19330. {
  19331. callback.setManager(NULL);
  19332. eof = true;
  19333. tlk.clear();
  19334. }
  19335. public:
  19336. CRoxieServerSimpleIndexReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  19337. IKeyArray *_keyArray, TranslatorArray *_translatorArray, bool _isLocal)
  19338. : CRoxieServerActivity(_factory, _probeManager),
  19339. readHelper((IHThorIndexReadArg &)basehelper),
  19340. indexHelper((IHThorIndexReadArg &)basehelper),
  19341. translators(_translatorArray),
  19342. keySet(_keyArray),
  19343. isLocal(_isLocal),
  19344. remoteId(_remoteId)
  19345. {
  19346. rowLimit = 0;
  19347. keyedLimit = 0;
  19348. chooseNLimit = 0;
  19349. indexHelper.setCallback(&callback);
  19350. steppedExtra = static_cast<IHThorSteppedSourceExtra *>(indexHelper.selectInterface(TAIsteppedsourceextra_1));
  19351. limitTransformExtra = static_cast<IHThorSourceLimitTransformExtra *>(indexHelper.selectInterface(TAIsourcelimittransformextra_1));
  19352. unsigned flags = indexHelper.getFlags();
  19353. variableFileName = allFilesDynamic || ((flags & (TIRvarfilename|TIRdynamicfilename)) != 0);
  19354. variableInfoPending = false;
  19355. isOpt = (flags & TIRoptional) != 0;
  19356. optimizeSteppedPostFilter = (flags & TIRunfilteredtransform) != 0;
  19357. firstRead = true;
  19358. accepted = 0;
  19359. rejected = 0;
  19360. keyedCount = 0;
  19361. eof = false;
  19362. rawMeta = readHelper.queryRawSteppingMeta();
  19363. projectedMeta = readHelper.queryProjectedSteppingMeta();
  19364. seekGEOffset = 0;
  19365. seekSizes = NULL;
  19366. if (rawMeta)
  19367. {
  19368. // MORE - should check all keys in maxFields list can actually be keyed.
  19369. const CFieldOffsetSize * fields = rawMeta->queryFields();
  19370. unsigned maxFields = rawMeta->getNumFields();
  19371. seekGEOffset = fields[0].offset;
  19372. seekSizes = new unsigned[maxFields];
  19373. seekSizes[0] = fields[0].size;
  19374. for (unsigned i=1; i < maxFields; i++)
  19375. seekSizes[i] = seekSizes[i-1] + fields[i].size;
  19376. bool hasPostFilter = readHelper.transformMayFilter() && optimizeSteppedPostFilter;
  19377. if (projectedMeta)
  19378. steppingMeta.init(projectedMeta, hasPostFilter);
  19379. else
  19380. steppingMeta.init(rawMeta, hasPostFilter);
  19381. }
  19382. }
  19383. virtual const IResolvedFile *queryVarFileInfo() const
  19384. {
  19385. return varFileInfo;
  19386. }
  19387. ~CRoxieServerSimpleIndexReadActivity()
  19388. {
  19389. delete [] seekSizes;
  19390. }
  19391. virtual bool needsAllocator() const { return true; }
  19392. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19393. {
  19394. firstRead = true;
  19395. accepted = 0;
  19396. rejected = 0;
  19397. keyedCount = 0;
  19398. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  19399. if (steppedExtra)
  19400. steppingMeta.setExtra(steppedExtra);
  19401. eof = !indexHelper.canMatchAny();
  19402. if (variableFileName)
  19403. variableInfoPending = true;
  19404. else
  19405. {
  19406. variableInfoPending = false;
  19407. if (!keyIndexSet)
  19408. initKeySet();
  19409. }
  19410. }
  19411. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  19412. {
  19413. if (variableInfoPending)
  19414. setVariableFileInfo();
  19415. return this;
  19416. }
  19417. virtual IKeyArray *getKeySet() const
  19418. {
  19419. return keySet.getLink();
  19420. }
  19421. virtual const IResolvedFile *getVarFileInfo() const
  19422. {
  19423. return varFileInfo.getLink();
  19424. }
  19425. virtual TranslatorArray *getTranslators() const
  19426. {
  19427. return translators.getLink();
  19428. }
  19429. virtual void mergeSegmentMonitors(IIndexReadContext *irc) const
  19430. {
  19431. indexHelper.createSegmentMonitors(irc); // NOTE: they will merge
  19432. }
  19433. virtual IRoxieServerActivity *queryActivity() { return this; }
  19434. virtual const RemoteActivityId& queryRemoteId() const
  19435. {
  19436. return remoteId;
  19437. }
  19438. const void *nextInGroup()
  19439. {
  19440. bool matched = true;
  19441. return nextSteppedGE(NULL, 0, matched, dummySmartStepExtra);
  19442. }
  19443. unsigned __int64 checkCount(unsigned __int64 limit)
  19444. {
  19445. unsigned numParts = keyIndexSet->numParts();
  19446. unsigned __int64 result = 0;
  19447. for (unsigned i = 0; i < numParts; i++)
  19448. {
  19449. Owned<IKeyManager> countTlk = createKeyManager(keyIndexSet->queryPart(i), 0, this);
  19450. countTlk->setLayoutTranslator(translators->item(i));
  19451. indexHelper.createSegmentMonitors(countTlk);
  19452. countTlk->finishSegmentMonitors();
  19453. result += countTlk->checkCount(limit-result);
  19454. if (result > limit)
  19455. break;
  19456. }
  19457. return result;
  19458. }
  19459. virtual const void *nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  19460. {
  19461. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  19462. if (eof)
  19463. return NULL;
  19464. if (firstRead)
  19465. {
  19466. if (variableInfoPending)
  19467. setVariableFileInfo();
  19468. rowLimit = (unsigned) readHelper.getRowLimit();
  19469. chooseNLimit = (unsigned) readHelper.getChooseNLimit();
  19470. unsigned numParts = keyIndexSet->numParts();
  19471. if (!numParts)
  19472. {
  19473. onEOF();
  19474. return NULL;
  19475. }
  19476. if (numParts > 1 || seekGEOffset)
  19477. {
  19478. tlk.setown(createKeyMerger(keyIndexSet, 0, seekGEOffset, this));
  19479. // note that we don't set up translator because we don't support it. If that ever changes...
  19480. }
  19481. else
  19482. {
  19483. tlk.setown(createKeyManager(keyIndexSet->queryPart(0), 0, this));
  19484. tlk->setLayoutTranslator(translators->item(0));
  19485. }
  19486. indexHelper.createSegmentMonitors(tlk);
  19487. tlk->finishSegmentMonitors();
  19488. if (queryTraceLevel() > 3 || ctx->queryProbeManager())
  19489. {
  19490. StringBuffer out;
  19491. printKeyedValues(out, tlk, indexHelper.queryDiskRecordSize());
  19492. CTXLOG("Using filter %s", out.str());
  19493. if (ctx->queryProbeManager())
  19494. ctx->queryProbeManager()->setNodeProperty(this, "filter", out.str());
  19495. }
  19496. tlk->reset();
  19497. callback.setManager(tlk);
  19498. keyedLimit = readHelper.getKeyedLimit();
  19499. if (keyedLimit != (unsigned __int64) -1)
  19500. {
  19501. if ((indexHelper.getFlags() & TIRcountkeyedlimit) != 0)
  19502. {
  19503. unsigned __int64 count = checkCount(keyedLimit);
  19504. if (count > keyedLimit)
  19505. {
  19506. if ((indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates)) == 0)
  19507. readHelper.onKeyedLimitExceeded();
  19508. const void * ret = NULL;
  19509. if (indexHelper.getFlags() & TIRkeyedlimitcreates)
  19510. ret = createKeyedLimitOnFailRow();
  19511. onEOF();
  19512. return ret;
  19513. }
  19514. keyedLimit = (unsigned __int64) -1;
  19515. }
  19516. }
  19517. firstRead = false;
  19518. }
  19519. if (accepted == chooseNLimit)
  19520. {
  19521. onEOF();
  19522. return NULL;
  19523. }
  19524. const byte * rawSeek = NULL;
  19525. unsigned seekSize = 0;
  19526. if (seek)
  19527. {
  19528. seekSize = seekSizes[numFields-1];
  19529. rawSeek = (const byte *)seek + seekGEOffset;
  19530. if (projectedMeta)
  19531. {
  19532. byte *temp = (byte *) alloca(seekSize);
  19533. RtlStaticRowBuilder rawBuilder(temp-seekGEOffset, seekGEOffset+seekSize);
  19534. readHelper.mapOutputToInput(rawBuilder, seek, numFields);// NOTE - weird interface to mapOutputToInput means that it STARTS writing at seekGEOffset...
  19535. rawSeek = (byte *)temp;
  19536. }
  19537. #ifdef _DEBUG
  19538. // StringBuffer seekStr;
  19539. // for (unsigned i = 0; i < seekSize; i++)
  19540. // {
  19541. // seekStr.appendf("%02x ", ((unsigned char *) rawSeek)[i]);
  19542. // }
  19543. // DBGLOG("nextSteppedGE can skip offset %d size %d value %s", seekGEOffset, seekSize, seekStr.str());
  19544. #endif
  19545. }
  19546. const byte * originalRawSeek = rawSeek;
  19547. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  19548. while (rawSeek ? tlk->lookupSkip(rawSeek, seekGEOffset, seekSize) : tlk->lookup(true))
  19549. {
  19550. checkAbort();
  19551. keyedCount++;
  19552. if (keyedCount > keyedLimit)
  19553. {
  19554. readHelper.onKeyedLimitExceeded();
  19555. break;
  19556. }
  19557. byte const * keyRow = tlk->queryKeyBuffer(callback.getFPosRef());
  19558. #ifdef _DEBUG
  19559. // StringBuffer recstr;
  19560. // unsigned size = (tlk->queryRecordSize()<80) ? tlk->queryRecordSize() : 80;
  19561. // for (unsigned i = 0; i < size; i++)
  19562. // {
  19563. // recstr.appendf("%02x ", ((unsigned char *) keyRow)[i]);
  19564. // }
  19565. // DBGLOG("nextSteppedGE Got %s", recstr.str());
  19566. if (originalRawSeek && memcmp(keyRow + seekGEOffset, originalRawSeek, seekSize) < 0)
  19567. assertex(!"smart seek failure");
  19568. #endif
  19569. size32_t transformedSize;
  19570. rowBuilder.ensureRow();
  19571. try
  19572. {
  19573. transformedSize = readHelper.transform(rowBuilder, keyRow);
  19574. //if the post filter causes a mismatch, and the stepping condition no longer matches
  19575. //then return a mismatch record - so the join code can start seeking on the other input.
  19576. if (transformedSize == 0 && optimizeSteppedPostFilter && stepExtra.returnMismatches())
  19577. {
  19578. if (memcmp(keyRow + seekGEOffset, originalRawSeek, seekSize) != 0)
  19579. {
  19580. transformedSize = readHelper.unfilteredTransform(rowBuilder, keyRow);
  19581. if (transformedSize != 0)
  19582. wasCompleteMatch = false;
  19583. }
  19584. }
  19585. callback.finishedRow();
  19586. }
  19587. catch (IException *E)
  19588. {
  19589. throw makeWrappedException(E);
  19590. }
  19591. if (transformedSize)
  19592. {
  19593. accepted++;
  19594. if (accepted > rowLimit)
  19595. {
  19596. if ((indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates)) != 0)
  19597. {
  19598. throwUnexpected(); // should not have used simple variant if maySkip set...
  19599. }
  19600. if (traceLevel > 4)
  19601. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  19602. readHelper.onLimitExceeded();
  19603. break;
  19604. }
  19605. processed++;
  19606. #ifdef _DEBUG
  19607. // const byte *ret = (const byte *) out.get();
  19608. // CommonXmlWriter xmlwrite(XWFnoindent|XWFtrim|XWFopt);
  19609. // queryOutputMeta()->toXML(ret, xmlwrite);
  19610. // DBGLOG("ROW: {%p} %s", ret, xmlwrite.str());
  19611. #endif
  19612. return rowBuilder.finalizeRowClear(transformedSize);
  19613. }
  19614. else
  19615. rejected++;
  19616. rawSeek = NULL;
  19617. }
  19618. onEOF();
  19619. return NULL;
  19620. }
  19621. virtual void reset()
  19622. {
  19623. onEOF();
  19624. if (accepted)
  19625. noteStatistic(STATS_ACCEPTED, accepted, 1);
  19626. if (rejected)
  19627. noteStatistic(STATS_REJECTED, rejected, 1);
  19628. if (variableFileName)
  19629. {
  19630. varFileInfo.clear();
  19631. translators.clear();
  19632. }
  19633. variableInfoPending = false;
  19634. CRoxieServerActivity::reset();
  19635. }
  19636. virtual void setInput(unsigned idx, IRoxieInput *_in)
  19637. {
  19638. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  19639. }
  19640. virtual IInputSteppingMeta * querySteppingMeta()
  19641. {
  19642. if (rawMeta && steppingEnabled && ((indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates|TIRkeyedlimitskips|TIRkeyedlimitcreates)) == 0))
  19643. return &steppingMeta;
  19644. return NULL;
  19645. }
  19646. protected:
  19647. const void * createKeyedLimitOnFailRow()
  19648. {
  19649. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  19650. size32_t outSize = limitTransformExtra->transformOnKeyedLimitExceeded(rowBuilder);
  19651. if (outSize)
  19652. return rowBuilder.finalizeRowClear(outSize);
  19653. return NULL;
  19654. }
  19655. };
  19656. class CRoxieServerBaseIndexActivityFactory : public CRoxieServerActivityFactory
  19657. {
  19658. public:
  19659. Owned<IKeyArray> keySet;
  19660. Owned<TranslatorArray> translatorArray;
  19661. Owned<IDefRecordMeta> activityMeta;
  19662. RemoteActivityId remoteId;
  19663. bool isSimple;
  19664. bool isLocal;
  19665. bool maySkip;
  19666. bool sorted;
  19667. bool variableFileName;
  19668. bool enableFieldTranslation;
  19669. unsigned maxSeekLookahead;
  19670. Owned<const IResolvedFile> indexfile;
  19671. CRoxieServerSideCache *cache;
  19672. CRoxieServerBaseIndexActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  19673. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), remoteId(_remoteId)
  19674. {
  19675. Owned<IHThorIndexReadBaseArg> indexHelper = (IHThorIndexReadBaseArg *) helperFactory();
  19676. unsigned flags = indexHelper->getFlags();
  19677. sorted = (flags & TIRunordered) == 0;
  19678. isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  19679. rtlDataAttr indexLayoutMeta;
  19680. size32_t indexLayoutSize;
  19681. if(!indexHelper->getIndexLayout(indexLayoutSize, indexLayoutMeta.refdata()))
  19682. assertex(indexLayoutSize==0);
  19683. MemoryBuffer m;
  19684. m.setBuffer(indexLayoutSize, indexLayoutMeta.getdata());
  19685. activityMeta.setown(deserializeRecordMeta(m, true));
  19686. enableFieldTranslation = queryFactory.getEnableFieldTranslation();
  19687. translatorArray.setown(new TranslatorArray);
  19688. variableFileName = allFilesDynamic || ((flags & (TIRvarfilename|TIRdynamicfilename)) != 0);
  19689. if (!variableFileName)
  19690. {
  19691. bool isOpt = (flags & TIRoptional) != 0;
  19692. OwnedRoxieString indexName(indexHelper->getFileName());
  19693. indexfile.setown(queryFactory.queryPackage().lookupFileName(indexName, isOpt, true, true, queryFactory.queryWorkUnit()));
  19694. if (indexfile)
  19695. keySet.setown(indexfile->getKeyArray(activityMeta, translatorArray, isOpt, isLocal ? queryFactory.queryChannel() : 0, enableFieldTranslation));
  19696. }
  19697. isSimple = isLocal;
  19698. maySkip = (flags & (TIRkeyedlimitskips|TIRlimitskips|TIRlimitcreates|TIRkeyedlimitcreates)) != 0;
  19699. if (keySet && keySet->length()==1 && !isLocal && (flags & (TIRlimitskips|TIRlimitcreates|TIRkeyedlimitskips|TIRkeyedlimitcreates))==0)
  19700. {
  19701. IKeyIndexBase *thisBase = keySet->queryKeyPart(0);
  19702. if (thisBase->numParts()==1 && !thisBase->queryPart(0)->isTopLevelKey() && !_queryFactory.getDebugValueBool("disableLocalOptimizations", false))
  19703. isSimple = true;
  19704. }
  19705. int cacheSize = _graphNode.getPropInt("hint[@name='cachehits']/@value", serverSideCacheSize);
  19706. cache = cacheSize ? new CRoxieServerSideCache(cacheSize) : NULL;
  19707. maxSeekLookahead = _graphNode.getPropInt("hint[@name='maxseeklookahead']/@value", 0);
  19708. }
  19709. ~CRoxieServerBaseIndexActivityFactory()
  19710. {
  19711. delete cache;
  19712. }
  19713. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  19714. {
  19715. if (indexfile)
  19716. addXrefFileInfo(reply, indexfile);
  19717. }
  19718. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  19719. {
  19720. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for indexread activity");
  19721. }
  19722. virtual IRoxieServerSideCache *queryServerSideCache() const
  19723. {
  19724. return cache;
  19725. }
  19726. virtual bool getEnableFieldTranslation() const
  19727. {
  19728. return enableFieldTranslation;
  19729. }
  19730. virtual IDefRecordMeta *queryActivityMeta() const
  19731. {
  19732. return activityMeta;
  19733. }
  19734. };
  19735. class CRoxieServerIndexReadActivityFactory : public CRoxieServerBaseIndexActivityFactory
  19736. {
  19737. public:
  19738. CRoxieServerIndexReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  19739. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode)
  19740. {
  19741. }
  19742. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  19743. {
  19744. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  19745. return new CRoxieServerNullActivity(this, _probeManager);
  19746. else if (isSimple && !maySkip)
  19747. return new CRoxieServerSimpleIndexReadActivity(this, _probeManager, remoteId, keySet, translatorArray, isLocal);
  19748. else
  19749. return new CRoxieServerIndexReadActivity(this, _probeManager, remoteId, keySet, translatorArray, sorted, isLocal, maySkip, maxSeekLookahead);
  19750. }
  19751. };
  19752. IRoxieServerActivityFactory *createRoxieServerIndexReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  19753. {
  19754. return new CRoxieServerIndexReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode);
  19755. }
  19756. //--------------------------------------------------------------------------------------------------------------------------
  19757. class CRoxieServerNullCountActivity : public CRoxieServerActivity
  19758. {
  19759. bool done;
  19760. public:
  19761. CRoxieServerNullCountActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  19762. : CRoxieServerActivity(_factory, _probeManager)
  19763. {
  19764. done = false;
  19765. }
  19766. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19767. {
  19768. done = false;
  19769. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  19770. }
  19771. virtual bool needsAllocator() const { return true; }
  19772. virtual const void *nextInGroup()
  19773. {
  19774. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  19775. if (done) return NULL;
  19776. done = true;
  19777. size32_t rowSize = meta.getFixedSize();
  19778. void * nullRow = rowAllocator->createRow();
  19779. if (rowSize == 1)
  19780. *(byte *)nullRow = 0;
  19781. else
  19782. {
  19783. assertex(rowSize == sizeof(unsigned __int64));
  19784. *(unsigned __int64 *)nullRow = 0;
  19785. }
  19786. return rowAllocator->finalizeRow(rowSize, nullRow, rowSize);
  19787. }
  19788. };
  19789. class CRoxieServerIndexCountActivity : public CRoxieServerIndexActivity
  19790. {
  19791. IHThorCompoundCountExtra & countHelper;
  19792. IHThorSourceCountLimit * limitHelper;
  19793. bool done;
  19794. public:
  19795. CRoxieServerIndexCountActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IKeyArray * _keySet, TranslatorArray *_translators, bool _isLocal)
  19796. : CRoxieServerIndexActivity(_factory, _probeManager, _remoteId, _keySet, _translators, false, _isLocal, false),
  19797. countHelper((IHThorIndexCountArg &)basehelper),
  19798. done(false)
  19799. {
  19800. limitHelper = static_cast<IHThorSourceCountLimit *>(basehelper.selectInterface(TAIsourcecountlimit_1));
  19801. }
  19802. virtual bool needsAllocator() const { return true; }
  19803. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19804. {
  19805. done = false;
  19806. CRoxieServerIndexActivity::start(parentExtractSize, parentExtract, paused);
  19807. choosenLimit = countHelper.getChooseNLimit();
  19808. if (limitHelper)
  19809. {
  19810. rowLimit = limitHelper->getRowLimit();
  19811. keyedLimit = limitHelper->getKeyedLimit();
  19812. }
  19813. if (!paused)
  19814. processAllKeys();
  19815. }
  19816. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
  19817. {
  19818. unsigned __int64 count = 0;
  19819. if (countHelper.hasFilter())
  19820. {
  19821. while (tlk->lookup(true))
  19822. {
  19823. try
  19824. {
  19825. count += countHelper.numValid(tlk->queryKeyBuffer(callback.getFPosRef()));
  19826. callback.finishedRow();
  19827. }
  19828. catch (IException *E)
  19829. {
  19830. throw makeWrappedException(E);
  19831. }
  19832. accepted++;
  19833. if (count >= choosenLimit) // MORE - what about limit?
  19834. break;
  19835. }
  19836. }
  19837. else
  19838. count = tlk->getCount(); //MORE: GH->RKC There should be value in providing a max limit to getCount()
  19839. if (count)
  19840. {
  19841. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), false);
  19842. if (count > choosenLimit)
  19843. count = choosenLimit;
  19844. void * recBuffer = rowAllocator->createRow();
  19845. if (meta.getFixedSize() == 1)
  19846. *(byte *)recBuffer = (byte)count;
  19847. else
  19848. {
  19849. assertex(meta.getFixedSize() == sizeof(unsigned __int64));
  19850. *(unsigned __int64 *)recBuffer = count;
  19851. }
  19852. recBuffer = rowAllocator->finalizeRow(meta.getFixedSize(), recBuffer, meta.getFixedSize());
  19853. result->append(recBuffer);
  19854. remote.injectResult(result.getClear());
  19855. //GH->RKC for count(,choosen)/exists passing in the previous count would short-circuit this much earlier
  19856. if (count >= choosenLimit)
  19857. return true;
  19858. }
  19859. return false;
  19860. }
  19861. virtual void onLimitExceeded(bool isKeyed)
  19862. {
  19863. if (traceLevel > 4)
  19864. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  19865. if (isKeyed)
  19866. {
  19867. if (indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates))
  19868. {
  19869. if (ctx->queryDebugContext())
  19870. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  19871. throw makeLimitSkipException(true);
  19872. }
  19873. else
  19874. {
  19875. assertex(limitHelper); // Should not be able to generate exception if there was not one...
  19876. limitHelper->onKeyedLimitExceeded();
  19877. }
  19878. }
  19879. else
  19880. {
  19881. if (indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates))
  19882. {
  19883. if (ctx->queryDebugContext())
  19884. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  19885. throw makeLimitSkipException(false);
  19886. }
  19887. else
  19888. {
  19889. assertex(limitHelper);
  19890. limitHelper->onLimitExceeded();
  19891. }
  19892. }
  19893. }
  19894. virtual const void *createLimitFailRow(bool isKeyed)
  19895. {
  19896. throwUnexpected();
  19897. }
  19898. virtual const void *nextInGroup()
  19899. {
  19900. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  19901. if (done) return NULL;
  19902. done = true;
  19903. unsigned __int64 totalCount = 0;
  19904. bool hasLimit = rowLimit != (unsigned __int64) -1;
  19905. try
  19906. {
  19907. loop
  19908. {
  19909. const void * next = remote.nextInGroup();
  19910. if (!next)
  19911. break;
  19912. if (meta.getFixedSize() == 1)
  19913. totalCount += *(byte *)next;
  19914. else
  19915. totalCount += *(unsigned __int64 *) next;
  19916. ReleaseRoxieRow(next);
  19917. if (totalCount > rowLimit || (totalCount > choosenLimit && !hasLimit)) // can't break out early if there is a possibility of later slave throwing limit exception
  19918. break;
  19919. }
  19920. if (totalCount > rowLimit)
  19921. {
  19922. unsigned flags = indexHelper.getFlags();
  19923. if (flags & TIRlimitskips)
  19924. totalCount = 0;
  19925. else if (flags & TIRlimitcreates)
  19926. totalCount = 1;
  19927. else
  19928. {
  19929. assertex(limitHelper);
  19930. limitHelper->onLimitExceeded();
  19931. }
  19932. }
  19933. else if (totalCount > choosenLimit)
  19934. totalCount = choosenLimit;
  19935. }
  19936. catch (IException *E)
  19937. {
  19938. if (QUERYINTERFACE(E, LimitSkipException))
  19939. {
  19940. totalCount = 0;
  19941. unsigned flags = indexHelper.getFlags();
  19942. if (E->errorCode() == KeyedLimitSkipErrorCode)
  19943. {
  19944. if (flags & TIRkeyedlimitcreates)
  19945. totalCount++;
  19946. }
  19947. else
  19948. {
  19949. if (flags & TIRlimitcreates)
  19950. totalCount++;
  19951. }
  19952. if (totalCount > choosenLimit)
  19953. totalCount = choosenLimit; // would have to be weird code (and escape the optimizer...)
  19954. E->Release();
  19955. }
  19956. else
  19957. throw ;
  19958. }
  19959. void * result = rowAllocator->createRow();
  19960. if (meta.getFixedSize() == 1)
  19961. *(byte *)result = (byte)totalCount;
  19962. else
  19963. {
  19964. assertex(meta.getFixedSize() == sizeof(unsigned __int64));
  19965. *(unsigned __int64 *)result = totalCount;
  19966. }
  19967. return rowAllocator->finalizeRow(meta.getFixedSize(), result, meta.getFixedSize());
  19968. }
  19969. };
  19970. class CRoxieServerIndexCountActivityFactory : public CRoxieServerBaseIndexActivityFactory
  19971. {
  19972. public:
  19973. CRoxieServerIndexCountActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  19974. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode)
  19975. {
  19976. }
  19977. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  19978. {
  19979. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  19980. return new CRoxieServerNullCountActivity(this, _probeManager);
  19981. // else if (isSimple)
  19982. // return new CRoxieServerSimpleIndexCountActivity(this, keySet->queryKeyPart(0)->queryPart(0));
  19983. else
  19984. return new CRoxieServerIndexCountActivity(this, _probeManager, remoteId, keySet, translatorArray, isLocal);
  19985. }
  19986. };
  19987. IRoxieServerActivityFactory *createRoxieServerIndexCountActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  19988. {
  19989. return new CRoxieServerIndexCountActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode);
  19990. }
  19991. //--------------------------------------------------------------------------------------------------------------------------
  19992. class CRoxieServerNullIndexAggregateActivity : public CRoxieServerActivity
  19993. {
  19994. IHThorIndexAggregateArg &aggregateHelper;
  19995. bool done;
  19996. public:
  19997. CRoxieServerNullIndexAggregateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  19998. : CRoxieServerActivity(_factory, _probeManager),
  19999. aggregateHelper((IHThorIndexAggregateArg &)basehelper)
  20000. {
  20001. done = false;
  20002. }
  20003. virtual bool needsAllocator() const { return true; }
  20004. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20005. {
  20006. done = false;
  20007. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  20008. }
  20009. virtual const void *nextInGroup()
  20010. {
  20011. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  20012. if (done) return NULL;
  20013. done = true;
  20014. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  20015. size32_t thisSize = aggregateHelper.clearAggregate(rowBuilder);
  20016. return rowBuilder.finalizeRowClear(thisSize);
  20017. }
  20018. };
  20019. class CRoxieServerIndexAggregateActivity : public CRoxieServerIndexActivity
  20020. {
  20021. IHThorCompoundAggregateExtra & aggregateHelper;
  20022. bool done;
  20023. public:
  20024. CRoxieServerIndexAggregateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  20025. IKeyArray * _keySet, TranslatorArray *_translators, bool _isLocal)
  20026. : CRoxieServerIndexActivity(_factory, _probeManager, _remoteId, _keySet, _translators, false, _isLocal, false),
  20027. aggregateHelper((IHThorIndexAggregateArg &)basehelper),
  20028. done(false)
  20029. {
  20030. }
  20031. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20032. {
  20033. done = false;
  20034. CRoxieServerIndexActivity::start(parentExtractSize, parentExtract, paused);
  20035. if (!paused)
  20036. processAllKeys();
  20037. }
  20038. virtual bool needsAllocator() const { return true; }
  20039. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
  20040. {
  20041. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  20042. while (tlk->lookup(true))
  20043. {
  20044. if (!rowBuilder.exists())
  20045. {
  20046. rowBuilder.ensureRow();
  20047. aggregateHelper.clearAggregate(rowBuilder);
  20048. }
  20049. try
  20050. {
  20051. aggregateHelper.processRow(rowBuilder, tlk->queryKeyBuffer(callback.getFPosRef()));
  20052. callback.finishedRow();
  20053. }
  20054. catch (IException *E)
  20055. {
  20056. throw makeWrappedException(E);
  20057. }
  20058. accepted++;
  20059. }
  20060. if (aggregateHelper.processedAnyRows())
  20061. {
  20062. size32_t size = meta.getRecordSize(rowBuilder.getSelf());
  20063. const void * recBuffer = rowBuilder.finalizeRowClear(size);
  20064. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), meta.isVariableSize());
  20065. result->append(recBuffer);
  20066. remote.injectResult(result.getClear());
  20067. }
  20068. return false;
  20069. }
  20070. virtual void onLimitExceeded(bool isKeyed)
  20071. {
  20072. if (traceLevel > 4)
  20073. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  20074. throwUnexpected();
  20075. }
  20076. virtual const void *createLimitFailRow(bool isKeyed)
  20077. {
  20078. throwUnexpected();
  20079. }
  20080. const void * gatherMerged()
  20081. {
  20082. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  20083. const void * firstRow = remote.nextInGroup();
  20084. size32_t finalSize = 0;
  20085. if (!firstRow)
  20086. {
  20087. rowBuilder.ensureRow();
  20088. finalSize = aggregateHelper.clearAggregate(rowBuilder);
  20089. }
  20090. else
  20091. {
  20092. // NOTE need to clone this because going to modify below, could special case 1 row only
  20093. finalSize = cloneRow(rowBuilder, firstRow, meta);
  20094. ReleaseRoxieRow(firstRow);
  20095. }
  20096. loop
  20097. {
  20098. const void * next = remote.nextInGroup();
  20099. if (!next)
  20100. break;
  20101. finalSize = aggregateHelper.mergeAggregate(rowBuilder, next);
  20102. ReleaseRoxieRow(next);
  20103. }
  20104. return rowBuilder.finalizeRowClear(finalSize);
  20105. }
  20106. virtual const void *nextInGroup()
  20107. {
  20108. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  20109. if (done) return NULL;
  20110. const void * ret = gatherMerged();
  20111. done = true;
  20112. return ret;
  20113. }
  20114. };
  20115. class CRoxieServerIndexAggregateActivityFactory : public CRoxieServerBaseIndexActivityFactory
  20116. {
  20117. public:
  20118. CRoxieServerIndexAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  20119. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode)
  20120. {
  20121. }
  20122. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  20123. {
  20124. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  20125. return new CRoxieServerNullIndexAggregateActivity(this, _probeManager);
  20126. // else if (isSimple)
  20127. // return new CRoxieServerSimpleIndexAggregateActivity(this, keySet->queryKeyPart(0)->queryPart(0));
  20128. else
  20129. return new CRoxieServerIndexAggregateActivity(this, _probeManager, remoteId, keySet, translatorArray, isLocal);
  20130. }
  20131. };
  20132. IRoxieServerActivityFactory *createRoxieServerIndexAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  20133. {
  20134. return new CRoxieServerIndexAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode);
  20135. }
  20136. //--------------------------------------------------------------------------------------------------------------------------
  20137. class CRoxieServerIndexGroupAggregateActivity : public CRoxieServerIndexActivity, implements IHThorGroupAggregateCallback
  20138. {
  20139. IHThorCompoundGroupAggregateExtra & aggregateHelper;
  20140. RowAggregator singleAggregator;
  20141. RowAggregator resultAggregator;
  20142. unsigned groupSegCount;
  20143. bool gathered;
  20144. bool eof;
  20145. public:
  20146. CRoxieServerIndexGroupAggregateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  20147. IKeyArray * _keySet, TranslatorArray *_translators, bool _isLocal)
  20148. : CRoxieServerIndexActivity(_factory, _probeManager, _remoteId, _keySet, _translators, false, _isLocal, false),
  20149. aggregateHelper((IHThorIndexGroupAggregateArg &)basehelper),
  20150. singleAggregator(aggregateHelper, aggregateHelper),
  20151. resultAggregator(aggregateHelper, aggregateHelper),
  20152. gathered(false), eof(true)
  20153. {
  20154. groupSegCount = 0;
  20155. }
  20156. IMPLEMENT_IINTERFACE
  20157. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20158. {
  20159. eof = false;
  20160. gathered= false;
  20161. CRoxieServerIndexActivity::start(parentExtractSize, parentExtract, paused);
  20162. groupSegCount = 0;
  20163. if (!paused)
  20164. processAllKeys();
  20165. resultAggregator.start(rowAllocator);
  20166. }
  20167. virtual bool needsAllocator() const { return true; }
  20168. virtual void reset()
  20169. {
  20170. resultAggregator.reset();
  20171. CRoxieServerIndexActivity::reset();
  20172. }
  20173. virtual void processRow(const void * next)
  20174. {
  20175. singleAggregator.addRow(next);
  20176. }
  20177. virtual void createSegmentMonitors(IKeyManager *key)
  20178. {
  20179. unsigned groupSegSize;
  20180. ThorActivityKind kind = factory->getKind();
  20181. if ((kind==TAKindexgroupcount || kind==TAKindexgroupexists))
  20182. groupSegSize = aggregateHelper.getGroupSegmentMonitorsSize();
  20183. else
  20184. groupSegSize = 0;
  20185. if (groupSegSize)
  20186. {
  20187. key->setMergeBarrier(groupSegSize);
  20188. CRoxieServerIndexActivity::createSegmentMonitors(key);
  20189. unsigned numSegs = tlk->ordinality();
  20190. for (unsigned segNo = 0; segNo < numSegs; segNo++)
  20191. {
  20192. IKeySegmentMonitor *seg = tlk->item(segNo);
  20193. if (seg->getOffset()+seg->getSize()==groupSegSize)
  20194. {
  20195. groupSegCount = segNo+1;
  20196. break;
  20197. }
  20198. }
  20199. assertex(groupSegCount);
  20200. }
  20201. else
  20202. CRoxieServerIndexActivity::createSegmentMonitors(key);
  20203. }
  20204. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
  20205. {
  20206. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), meta.isVariableSize());
  20207. singleAggregator.start(rowAllocator);
  20208. ThorActivityKind kind = factory->getKind();
  20209. while (tlk->lookup(true))
  20210. {
  20211. try
  20212. {
  20213. if (groupSegCount && !trans)
  20214. {
  20215. AggregateRowBuilder &rowBuilder = singleAggregator.addRow(tlk->queryKeyBuffer(callback.getFPosRef()));
  20216. callback.finishedRow();
  20217. if (kind==TAKindexgroupcount)
  20218. {
  20219. unsigned __int64 count = tlk->getCurrentRangeCount(groupSegCount);
  20220. aggregateHelper.processCountGrouping(rowBuilder, count-1);
  20221. }
  20222. if (!tlk->nextRange(groupSegCount))
  20223. break;
  20224. }
  20225. else
  20226. {
  20227. aggregateHelper.processRow(tlk->queryKeyBuffer(callback.getFPosRef()), this);
  20228. callback.finishedRow();
  20229. }
  20230. }
  20231. catch (IException *E)
  20232. {
  20233. throw makeWrappedException(E);
  20234. }
  20235. accepted++;
  20236. }
  20237. loop
  20238. {
  20239. Owned<AggregateRowBuilder> next = singleAggregator.nextResult();
  20240. if (!next)
  20241. break;
  20242. size32_t size = next->querySize();
  20243. result->append(next->finalizeRowClear());
  20244. }
  20245. remote.injectResult(result.getClear());
  20246. singleAggregator.reset();
  20247. return false;
  20248. }
  20249. virtual void onLimitExceeded(bool isKeyed)
  20250. {
  20251. if (traceLevel > 4)
  20252. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);DBGLOG("%d activityid = %d", __LINE__, activityId);
  20253. throwUnexpected();
  20254. }
  20255. virtual const void *createLimitFailRow(bool isKeyed)
  20256. {
  20257. throwUnexpected();
  20258. }
  20259. void gatherMerged()
  20260. {
  20261. gathered = true;
  20262. loop
  20263. {
  20264. const void * next = remote.nextInGroup();
  20265. if (!next)
  20266. break;
  20267. resultAggregator.mergeElement(next);
  20268. ReleaseRoxieRow(next);
  20269. }
  20270. }
  20271. virtual const void *nextInGroup()
  20272. {
  20273. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  20274. if (eof)
  20275. return NULL;
  20276. if (!gathered)
  20277. gatherMerged();
  20278. Owned<AggregateRowBuilder> next = resultAggregator.nextResult();
  20279. if (next)
  20280. {
  20281. processed++;
  20282. return next->finalizeRowClear();
  20283. }
  20284. eof = true;
  20285. return NULL;
  20286. }
  20287. };
  20288. class CRoxieServerIndexGroupAggregateActivityFactory : public CRoxieServerBaseIndexActivityFactory
  20289. {
  20290. public:
  20291. CRoxieServerIndexGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  20292. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode)
  20293. {
  20294. }
  20295. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  20296. {
  20297. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  20298. return new CRoxieServerNullActivity(this, _probeManager);
  20299. // else if (isSimple)
  20300. // return new CRoxieServerSimpleIndexGroupAggregateActivity(this, keySet->queryKeyPart(0)->queryPart(0));
  20301. else
  20302. return new CRoxieServerIndexGroupAggregateActivity(this, _probeManager, remoteId, keySet, translatorArray, isLocal);
  20303. }
  20304. };
  20305. IRoxieServerActivityFactory *createRoxieServerIndexGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  20306. {
  20307. return new CRoxieServerIndexGroupAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode);
  20308. }
  20309. //--------------------------------------------------------------------------------------------------------------------------
  20310. class CRoxieServerIndexNormalizeActivity : public CRoxieServerIndexReadBaseActivity
  20311. {
  20312. IHThorCompoundNormalizeExtra & readHelper;
  20313. public:
  20314. CRoxieServerIndexNormalizeActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  20315. IKeyArray * _keySet, TranslatorArray *_translators, bool _sorted, bool _isLocal)
  20316. : CRoxieServerIndexReadBaseActivity(_factory, _probeManager, _remoteId, _keySet, _translators, _sorted, _isLocal, false),
  20317. readHelper((IHThorIndexNormalizeArg &)basehelper)
  20318. {
  20319. }
  20320. virtual bool needsAllocator() const { return true; }
  20321. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20322. {
  20323. CRoxieServerIndexReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  20324. rowLimit = readHelper.getRowLimit();
  20325. keyedLimit = readHelper.getKeyedLimit();
  20326. if (!paused)
  20327. processAllKeys();
  20328. }
  20329. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
  20330. {
  20331. unsigned keyedCount = 0;
  20332. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  20333. while (tlk->lookup(true))
  20334. {
  20335. keyedCount++;
  20336. if (keyedCount > keyedLimit)
  20337. {
  20338. if (traceLevel > 4)
  20339. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  20340. onLimitExceeded(true);
  20341. break;
  20342. }
  20343. size32_t transformedSize;
  20344. if (readHelper.first(tlk->queryKeyBuffer(callback.getFPosRef())))
  20345. {
  20346. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), meta.isVariableSize());
  20347. do
  20348. {
  20349. rowBuilder.ensureRow();
  20350. try
  20351. {
  20352. transformedSize = readHelper.transform(rowBuilder);
  20353. }
  20354. catch (IException *E)
  20355. {
  20356. throw makeWrappedException(E);
  20357. }
  20358. if (transformedSize)
  20359. {
  20360. // MORE - would be a good idea to stop these asap if rowlimit exceeded
  20361. result->append(rowBuilder.finalizeRowClear(transformedSize));
  20362. accepted++;
  20363. }
  20364. else
  20365. rejected++;
  20366. } while (readHelper.next());
  20367. remote.injectResult(result.getClear());
  20368. callback.finishedRow();
  20369. }
  20370. }
  20371. return false;
  20372. }
  20373. virtual void onLimitExceeded(bool isKeyed)
  20374. {
  20375. if (traceLevel > 4)
  20376. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  20377. if (isKeyed)
  20378. {
  20379. if (indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates))
  20380. {
  20381. if (ctx->queryDebugContext())
  20382. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  20383. throw makeLimitSkipException(true);
  20384. }
  20385. else
  20386. readHelper.onKeyedLimitExceeded();
  20387. }
  20388. else
  20389. {
  20390. if (indexHelper.getFlags() & (TIRlimitskips||TIRlimitcreates))
  20391. {
  20392. if (ctx->queryDebugContext())
  20393. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  20394. throw makeLimitSkipException(false);
  20395. }
  20396. else
  20397. readHelper.onLimitExceeded();
  20398. }
  20399. }
  20400. virtual const void *createLimitFailRow(bool isKeyed)
  20401. {
  20402. UNIMPLEMENTED;
  20403. }
  20404. };
  20405. class CRoxieServerIndexNormalizeActivityFactory : public CRoxieServerBaseIndexActivityFactory
  20406. {
  20407. public:
  20408. CRoxieServerIndexNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  20409. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode)
  20410. {
  20411. }
  20412. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  20413. {
  20414. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  20415. return new CRoxieServerNullActivity(this, _probeManager);
  20416. else
  20417. return new CRoxieServerIndexNormalizeActivity(this, _probeManager, remoteId, keySet, translatorArray, sorted, isLocal);
  20418. }
  20419. };
  20420. IRoxieServerActivityFactory *createRoxieServerIndexNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  20421. {
  20422. return new CRoxieServerIndexNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode);
  20423. }
  20424. //=================================================================================
  20425. class CRoxieServerCountDiskActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler
  20426. {
  20427. unsigned __int64 answer;
  20428. public:
  20429. CRoxieServerCountDiskActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned __int64 _answer)
  20430. : CRoxieServerActivity(_factory, _probeManager),
  20431. answer(_answer)
  20432. {
  20433. }
  20434. virtual const void *nextInGroup()
  20435. {
  20436. throwUnexpected();
  20437. }
  20438. virtual void setInput(unsigned idx, IRoxieInput *_in)
  20439. {
  20440. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  20441. }
  20442. virtual __int64 evaluate()
  20443. {
  20444. return answer;
  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 CRoxieServerVariableCountDiskActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler
  20458. {
  20459. public:
  20460. CRoxieServerVariableCountDiskActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  20461. : CRoxieServerActivity(_factory, _probeManager)
  20462. {
  20463. }
  20464. virtual const void *nextInGroup()
  20465. {
  20466. throwUnexpected();
  20467. }
  20468. virtual void setInput(unsigned idx, IRoxieInput *_in)
  20469. {
  20470. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  20471. }
  20472. virtual __int64 evaluate()
  20473. {
  20474. IHThorCountFileArg &helper = (IHThorCountFileArg &) basehelper;
  20475. bool isOpt = (helper.getFlags() & TDRoptional) != 0;
  20476. unsigned recsize = helper.queryRecordSize()->getFixedSize();
  20477. assertex(recsize);
  20478. OwnedRoxieString fname(helper.getFileName());
  20479. Owned<const IResolvedFile> varFileInfo = resolveLFN(fname, isOpt);
  20480. return varFileInfo->getFileSize() / recsize;
  20481. }
  20482. virtual void onLimitExceeded(bool isKeyed)
  20483. {
  20484. if (traceLevel > 4)
  20485. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  20486. throwUnexpected();
  20487. }
  20488. virtual const void *createLimitFailRow(bool isKeyed)
  20489. {
  20490. throwUnexpected();
  20491. }
  20492. };
  20493. class CRoxieServerCountDiskActivityFactory : public CRoxieServerActivityFactory
  20494. {
  20495. public:
  20496. unsigned __int64 answer;
  20497. bool variableFileName;
  20498. Owned<const IResolvedFile> datafile;
  20499. CRoxieServerCountDiskActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  20500. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  20501. {
  20502. Owned<IHThorCountFileArg> helper = (IHThorCountFileArg *) helperFactory();
  20503. variableFileName = allFilesDynamic || ((helper->getFlags() & (TDXvarfilename|TDXdynamicfilename)) != 0);
  20504. assertex(helper->queryRecordSize()->isFixedSize());
  20505. if (!variableFileName)
  20506. {
  20507. unsigned recsize = helper->queryRecordSize()->getFixedSize();
  20508. assertex(recsize);
  20509. OwnedRoxieString fileName(helper->getFileName());
  20510. bool isOpt = (helper->getFlags() & TDRoptional) != 0;
  20511. datafile.setown(queryFactory.queryPackage().lookupFileName(fileName, isOpt, true, true, queryFactory.queryWorkUnit()));
  20512. offset_t filesize = datafile ? datafile->getFileSize() : 0;
  20513. if (filesize % recsize != 0)
  20514. 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);
  20515. answer = filesize / recsize;
  20516. }
  20517. else
  20518. answer = 0;
  20519. }
  20520. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  20521. {
  20522. if (datafile)
  20523. addXrefFileInfo(reply, datafile);
  20524. }
  20525. virtual IRoxieServerActivity *createFunction(IHThorArg &arg, IProbeManager *_probeManager) const
  20526. {
  20527. arg.Release();
  20528. if (variableFileName)
  20529. return new CRoxieServerVariableCountDiskActivity(this, _probeManager);
  20530. else
  20531. return new CRoxieServerCountDiskActivity(this, _probeManager, answer);
  20532. }
  20533. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  20534. {
  20535. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for CountDisk activity");
  20536. }
  20537. virtual bool isFunction() const
  20538. {
  20539. return true;
  20540. }
  20541. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  20542. {
  20543. return NULL;
  20544. }
  20545. };
  20546. IRoxieServerActivityFactory *createRoxieServerDiskCountActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  20547. {
  20548. return new CRoxieServerCountDiskActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  20549. }
  20550. //=================================================================================
  20551. class CRoxieServerFetchActivity : public CRoxieServerActivity, implements IRecordPullerCallback, implements IRoxieServerErrorHandler
  20552. {
  20553. IHThorFetchBaseArg &helper;
  20554. IHThorFetchContext * fetchContext;
  20555. Linked<IFilePartMap> map;
  20556. CRemoteResultAdaptor remote;
  20557. RecordPullerThread puller;
  20558. bool needsRHS;
  20559. bool variableFileName;
  20560. bool isOpt;
  20561. Owned<const IResolvedFile> varFileInfo;
  20562. public:
  20563. CRoxieServerFetchActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IFilePartMap *_map)
  20564. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorFetchBaseArg &)basehelper), map(_map), remote(_remoteId, meta.queryOriginal(), helper, *this, true, true), puller(false)
  20565. {
  20566. fetchContext = static_cast<IHThorFetchContext *>(helper.selectInterface(TAIfetchcontext_1));
  20567. needsRHS = helper.transformNeedsRhs();
  20568. variableFileName = allFilesDynamic || ((fetchContext->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  20569. isOpt = (fetchContext->getFetchFlags() & FFdatafileoptional) != 0;
  20570. }
  20571. virtual const IResolvedFile *queryVarFileInfo() const
  20572. {
  20573. return varFileInfo;
  20574. }
  20575. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  20576. {
  20577. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  20578. remote.onCreate(this, this, _ctx, _colocalParent);
  20579. }
  20580. virtual void setInput(unsigned idx, IRoxieInput *_in)
  20581. {
  20582. if (idx)
  20583. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  20584. puller.setInput(this, _in);
  20585. }
  20586. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20587. {
  20588. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  20589. remote.onStart(parentExtractSize, parentExtract);
  20590. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  20591. if (variableFileName)
  20592. {
  20593. OwnedRoxieString fname(fetchContext->getFileName());
  20594. varFileInfo.setown(resolveLFN(fname, isOpt));
  20595. if (varFileInfo)
  20596. map.setown(varFileInfo->getFileMap());
  20597. }
  20598. puller.start(parentExtractSize, parentExtract, paused, ctx->fetchPreload(), false, ctx);
  20599. }
  20600. virtual void stop(bool aborting)
  20601. {
  20602. // Called from remote, so no need to call back to it....
  20603. puller.stop(aborting);
  20604. CRoxieServerActivity::stop(aborting);
  20605. }
  20606. virtual void reset()
  20607. {
  20608. processed = remote.processed;
  20609. remote.processed = 0;
  20610. puller.reset();
  20611. if (variableFileName)
  20612. {
  20613. varFileInfo.clear();
  20614. map.clear();
  20615. }
  20616. CRoxieServerActivity::reset();
  20617. }
  20618. virtual IRoxieInput *queryOutput(unsigned idx)
  20619. {
  20620. if (idx==(unsigned)-1)
  20621. idx = 0;
  20622. return idx ? NULL : &remote;
  20623. }
  20624. virtual void processRow(const void *row)
  20625. {
  20626. // called from puller thread
  20627. offset_t rp = fetchContext->extractPosition(row);
  20628. unsigned partNo;
  20629. if (isLocalFpos(rp))
  20630. partNo = getLocalFposPart(rp) + 1;
  20631. else
  20632. partNo = map->mapOffset(rp);
  20633. if (needsRHS)
  20634. {
  20635. Owned<IEngineRowAllocator> extractAllocator = ctx->queryCodeContext()->getRowAllocator(helper.queryExtractedSize(), activityId);
  20636. RtlDynamicRowBuilder rb(extractAllocator, true);
  20637. unsigned rhsSize = helper.extractJoinFields(rb, row);
  20638. char * block = (char *) remote.getMem(partNo, 0, sizeof(rp) + sizeof(rhsSize) + rhsSize); // MORE - superfiles
  20639. *(offset_t *) block = rp;
  20640. block += sizeof(rp);
  20641. *(unsigned *) block = rhsSize;
  20642. block += sizeof(rhsSize);
  20643. memcpy(block, rb.row(), rhsSize);
  20644. }
  20645. else
  20646. *(offset_t *) remote.getMem(partNo, 0, sizeof(rp)) = rp; // MORE - superfiles
  20647. ReleaseRoxieRow(row);
  20648. }
  20649. void processEOG()
  20650. {
  20651. #ifdef FETCH_PRESERVES_GROUPING
  20652. UNIMPLEMENTED;
  20653. #endif
  20654. // else discard is correct
  20655. }
  20656. void processGroup(const ConstPointerArray &)
  20657. {
  20658. throwUnexpected();
  20659. }
  20660. void processDone()
  20661. {
  20662. // called from puller thread
  20663. remote.flush();
  20664. remote.senddone();
  20665. }
  20666. virtual bool fireException(IException *e)
  20667. {
  20668. return remote.fireException(e);
  20669. }
  20670. virtual void onLimitExceeded(bool isKeyed)
  20671. {
  20672. if (traceLevel > 4)
  20673. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  20674. if (isKeyed)
  20675. throwUnexpected();
  20676. helper.onLimitExceeded();
  20677. }
  20678. virtual const void *createLimitFailRow(bool isKeyed)
  20679. {
  20680. UNIMPLEMENTED;
  20681. }
  20682. virtual const void *nextInGroup()
  20683. {
  20684. throwUnexpected(); // I am nobody's input
  20685. }
  20686. };
  20687. class CRoxieServerFetchActivityFactory : public CRoxieServerActivityFactory
  20688. {
  20689. RemoteActivityId remoteId;
  20690. Owned<IFilePartMap> map;
  20691. bool variableFileName;
  20692. Owned<const IResolvedFile> datafile;
  20693. public:
  20694. CRoxieServerFetchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  20695. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), remoteId(_remoteId)
  20696. {
  20697. Owned<IHThorFetchBaseArg> helper = (IHThorFetchBaseArg *) helperFactory();
  20698. IHThorFetchContext *fetchContext = static_cast<IHThorFetchContext *>(helper->selectInterface(TAIfetchcontext_1));
  20699. variableFileName = allFilesDynamic || ((fetchContext->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  20700. if (!variableFileName)
  20701. {
  20702. OwnedRoxieString fname(fetchContext->getFileName());
  20703. datafile.setown(_queryFactory.queryPackage().lookupFileName(fname,
  20704. (fetchContext->getFetchFlags() & FFdatafileoptional) != 0,
  20705. true, true,
  20706. _queryFactory.queryWorkUnit()));
  20707. if (datafile)
  20708. map.setown(datafile->getFileMap());
  20709. }
  20710. }
  20711. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  20712. {
  20713. return new CRoxieServerFetchActivity(this, _probeManager, remoteId, map);
  20714. }
  20715. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  20716. {
  20717. if (datafile)
  20718. addXrefFileInfo(reply, datafile);
  20719. }
  20720. };
  20721. IRoxieServerActivityFactory *createRoxieServerFetchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  20722. {
  20723. return new CRoxieServerFetchActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode);
  20724. }
  20725. // MORE - is there any point keeping this now?
  20726. class CRoxieServerDummyActivityFactory : public CRoxieServerActivityFactory // not a real activity - just used to properly link files
  20727. {
  20728. public:
  20729. Owned<const IResolvedFile> indexfile;
  20730. Owned<const IResolvedFile> datafile;
  20731. Owned<IKeyArray> keySet;
  20732. Owned<IFileIOArray> files;
  20733. Owned<IFilePartMap> map;
  20734. TranslatorArray layoutTranslators;
  20735. CRoxieServerDummyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool isLoadDataOnly)
  20736. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  20737. {
  20738. try // does not want any missing file errors to be fatal, or throw traps - just log it
  20739. {
  20740. if (_graphNode.getPropBool("att[@name='_isSpill']/@value", false) || _graphNode.getPropBool("att[@name='_isSpillGlobal']/@value", false))
  20741. return; // ignore 'spills'
  20742. bool isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  20743. bool isOpt = _graphNode.getPropBool("att[@name='_isOpt']/@value") || pretendAllOpt;
  20744. const char *fileName = queryNodeFileName(_graphNode);
  20745. const char *indexName = queryNodeIndexName(_graphNode);
  20746. if (indexName && (!fileName || !streq(indexName, fileName)))
  20747. {
  20748. indexfile.setown(queryFactory.queryPackage().lookupFileName(indexName, isOpt, true, true, queryFactory.queryWorkUnit()));
  20749. if (indexfile)
  20750. keySet.setown(indexfile->getKeyArray(NULL, &layoutTranslators, isOpt, isLocal ? queryFactory.queryChannel() : 0, false));
  20751. }
  20752. if (fileName)
  20753. {
  20754. datafile.setown(_queryFactory.queryPackage().lookupFileName(fileName, isOpt, true, true, queryFactory.queryWorkUnit()));
  20755. if (datafile)
  20756. {
  20757. if (isLocal)
  20758. files.setown(datafile->getIFileIOArray(isOpt, queryFactory.queryChannel()));
  20759. else
  20760. map.setown(datafile->getFileMap());
  20761. }
  20762. }
  20763. }
  20764. catch(IException *E)
  20765. {
  20766. StringBuffer errors;
  20767. E->errorMessage(errors);
  20768. DBGLOG("%s File error = %s", (isLoadDataOnly) ? "LOADDATAONLY" : "SUSPENDED QUERY", errors.str());
  20769. E->Release();
  20770. }
  20771. }
  20772. 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__); }
  20773. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  20774. {
  20775. if (datafile)
  20776. addXrefFileInfo(reply, datafile);
  20777. if (indexfile)
  20778. addXrefFileInfo(reply, indexfile);
  20779. }
  20780. };
  20781. IRoxieServerActivityFactory *createRoxieServerDummyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool isLoadDataOnly)
  20782. {
  20783. return new CRoxieServerDummyActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, isLoadDataOnly);
  20784. }
  20785. //=====================================================================================================
  20786. // Keyed joins...
  20787. //
  20788. // Input records are pulled by a puller thread, which checks each LHS record to determine which (if any) channels it
  20789. // may have RHS matches on, and sends the relevant fields to the relevant slaves.
  20790. // 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
  20791. // the transform and returns rows that are created.
  20792. // 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)
  20793. //
  20794. //=====================================================================================================
  20795. class CJoinGroup;
  20796. interface IJoinProcessor
  20797. {
  20798. virtual void processEOG() = 0;
  20799. virtual CJoinGroup *createJoinGroup(const void *row) = 0;
  20800. virtual void noteEndReceived(CJoinGroup *jg, unsigned candidateCount) = 0;
  20801. virtual bool fireException(IException *E) = 0;
  20802. virtual void processCompletedGroups() = 0;
  20803. };
  20804. //------------------------------------------------------------------------------------------------------
  20805. // Class CJoinGroup has a record per LHS row, plus (if preserving grouping) a 'head of group' record
  20806. // It gathers all the corresponding RHS rows, keeping track of how may slave transactions are pending in endMarkersPending
  20807. // If preserving groups, the 'head of group' record keeps track of how many LHS records in the group are still incomplete.
  20808. // CJoinGroup records are allocated out of the Roxie row memory manager by overloading operator new, so that they are included in the
  20809. // per-query limits etc (Note that the pointer array block is not though).
  20810. // Because of that, the exact size is significant - especially whether fit just under or just over a chunking threshold...
  20811. //
  20812. // There are two phases to the life of a JoinGroup - it is created by the puller thread that is also firing off slave requests
  20813. // notePending will be called once for every slave request. Puller thread calls noteEndReceived(0) once when done - this corresponds to the
  20814. // initial count when created.
  20815. // Slave replies and are noted by the consumer thread calling addRightMatch() and noteEndReceived(n).
  20816. // Once endMarkersPending reaches 0, JoinGroup is complete. Last thread to call noteEndReceived will process the rows and destroy the group.
  20817. // There is no need for a critsec because although multiple threads will access at different times, only the consumer thread will
  20818. // access any modifiable member variables while endMarkersPending != 0 (i.e. complete() is false). Once complete returns true there is a single
  20819. // remaining reference and the JoinGroup will be processed and destroyed.
  20820. //
  20821. //------------------------------------------------------------------------------------------------------
  20822. class CJoinGroup : public CInterface, implements IInterface
  20823. {
  20824. protected:
  20825. const void *left; // LHS row
  20826. PointerArrayOf<KeyedJoinHeader> rows; // matching RHS rows
  20827. atomic_t endMarkersPending; // How many slave responses still waiting for
  20828. CJoinGroup *groupStart; // Head of group, or NULL if not grouping
  20829. unsigned lastPartNo;
  20830. unsigned pos;
  20831. unsigned candidates; // Number of RHS keyed candidates - note this may not be the same as rows.ordinality()
  20832. public:
  20833. #undef new
  20834. void *operator new(size_t size, IRowManager *a, unsigned activityId)
  20835. {
  20836. return a->allocate(size, activityId);
  20837. }
  20838. #if defined(_DEBUG) && defined(_WIN32) && !defined(USING_MPATROL)
  20839. #define new new(_NORMAL_BLOCK, __FILE__, __LINE__)
  20840. #endif
  20841. void operator delete(void *ptr, IRowManager *a, unsigned activityId)
  20842. {
  20843. ReleaseRoxieRow(ptr);
  20844. }
  20845. void operator delete(void *ptr)
  20846. {
  20847. ReleaseRoxieRow(ptr);
  20848. }
  20849. public:
  20850. IMPLEMENT_IINTERFACE;
  20851. CJoinGroup(const void *_left, CJoinGroup *_groupStart)
  20852. {
  20853. #ifdef TRACE_JOINGROUPS
  20854. DBGLOG("Creating joinGroup %p, groupstart %p", this, _groupStart);
  20855. #endif
  20856. candidates = 0;
  20857. lastPartNo = 0;
  20858. pos = 0;
  20859. left = _left;
  20860. groupStart = _groupStart;
  20861. if (_groupStart)
  20862. {
  20863. atomic_inc(&_groupStart->endMarkersPending);
  20864. }
  20865. atomic_set(&endMarkersPending, 1);
  20866. }
  20867. ~CJoinGroup()
  20868. {
  20869. #ifdef TRACE_JOINGROUPS
  20870. DBGLOG("Destroying joinGroup %p", this);
  20871. #endif
  20872. if (left)
  20873. {
  20874. ReleaseRoxieRow(left);
  20875. ForEachItemIn(idx, rows)
  20876. ReleaseRoxieRow(rows.item(idx));
  20877. rows.kill();
  20878. }
  20879. }
  20880. inline bool isHeadRecord() const
  20881. {
  20882. return left==NULL;
  20883. }
  20884. inline bool complete() const
  20885. {
  20886. return atomic_read(&endMarkersPending) == 0;
  20887. }
  20888. #ifdef TRACE_JOINGROUPS
  20889. inline void notePending(unsigned lineNo)
  20890. #else
  20891. inline void notePending()
  20892. #endif
  20893. {
  20894. assert(!complete());
  20895. atomic_inc(&endMarkersPending);
  20896. #ifdef TRACE_JOINGROUPS
  20897. DBGLOG("CJoinGroup::notePending %p from %d, count became %d group count %d", this, lineNo, atomic_read(&endMarkersPending), groupStart ? atomic_read(&groupStart->endMarkersPending) : 0);
  20898. #endif
  20899. }
  20900. inline bool inGroup(CJoinGroup *leader) const
  20901. {
  20902. return groupStart==leader;
  20903. }
  20904. inline const KeyedJoinHeader *queryRow(unsigned idx) const
  20905. {
  20906. // Single threaded by now
  20907. assert(complete());
  20908. return rows.item(idx);
  20909. }
  20910. #ifdef TRACE_JOINGROUPS
  20911. bool noteEndReceived(unsigned candidateCount, unsigned lineNo)
  20912. #else
  20913. bool noteEndReceived(unsigned candidateCount)
  20914. #endif
  20915. {
  20916. assert(!complete());
  20917. if (candidateCount)
  20918. {
  20919. candidates += candidateCount;
  20920. }
  20921. #ifdef TRACE_JOINGROUPS
  20922. 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);
  20923. #endif
  20924. // NOTE - as soon as endMarkersPending and groupStart->endMarkersPending are decremented to zero this object may get released asynchronously by other threads
  20925. // There must therefore be nothing in this method after them that acceses member variables. Think of it as a delete this...
  20926. // In particular, we can't safely reference groupStart after the dec_and_test of endMarkersPending, hence copy local first
  20927. CJoinGroup *localGroupStart = groupStart;
  20928. if (atomic_dec_and_test(&endMarkersPending))
  20929. {
  20930. if (localGroupStart)
  20931. return atomic_dec_and_test(&localGroupStart->endMarkersPending);
  20932. else
  20933. return true;
  20934. }
  20935. else
  20936. return false;
  20937. }
  20938. inline const void *queryLeft() const
  20939. {
  20940. return left;
  20941. }
  20942. void addRightMatch(KeyedJoinHeader *right)
  20943. {
  20944. assert(!complete());
  20945. unsigned short partNo = right->partNo;
  20946. if (partNo != lastPartNo)
  20947. {
  20948. // MORE - should we binchop? If we did we would need to be careful to find LAST match
  20949. if (partNo > lastPartNo)
  20950. pos = rows.length();
  20951. while (pos>0)
  20952. {
  20953. if (rows.item(pos-1)->partNo <= partNo)
  20954. break;
  20955. pos--;
  20956. }
  20957. lastPartNo = partNo;
  20958. }
  20959. rows.add(right, pos);
  20960. pos++;
  20961. }
  20962. inline unsigned rowsSeen() const
  20963. {
  20964. assert(complete());
  20965. return rows.length();
  20966. }
  20967. inline unsigned candidateCount() const
  20968. {
  20969. assert(complete());
  20970. return candidates;
  20971. }
  20972. };
  20973. #ifdef TRACE_JOINGROUPS
  20974. #define notePending() notePending(__LINE__)
  20975. #define noteEndReceived(a) noteEndReceived(a, __LINE__)
  20976. #endif
  20977. class KeyedJoinRemoteAdaptor : public CRemoteResultAdaptor // MORE - not sure it should be derived from this - makes processed all wrong, for example
  20978. {
  20979. private:
  20980. SafeQueueOf<const void, true> ready;
  20981. public:
  20982. IHThorKeyedJoinArg &helper;
  20983. unsigned joinProcessed;
  20984. bool isFullKey;
  20985. bool eof;
  20986. bool isSimple;
  20987. bool allPulled;
  20988. unsigned __int64 totalCycles;
  20989. unsigned activityId;
  20990. RecordPullerThread &puller;
  20991. SafeQueueOf<const void, true> injected; // Used in isSimple mode
  20992. Owned<IEngineRowAllocator> ccdRecordAllocator;
  20993. IJoinProcessor &processor;
  20994. KeyedJoinRemoteAdaptor(const RemoteActivityId &_remoteId, IHThorKeyedJoinArg &_helper, IRoxieServerActivity &_activity, bool _isFullKey, bool _isSimple,
  20995. RecordPullerThread &_puller, IJoinProcessor &_processor)
  20996. : helper(_helper),
  20997. CRemoteResultAdaptor(_remoteId, 0, _helper, _activity, true, true),
  20998. isFullKey(_isFullKey),
  20999. isSimple(_isSimple),
  21000. puller(_puller),
  21001. processor(_processor),
  21002. activityId(_activity.queryId())
  21003. {
  21004. joinProcessed = 0;
  21005. totalCycles = 0;
  21006. allPulled = false;
  21007. eof = false;
  21008. }
  21009. virtual void onCreate(IRoxieInput *_owner, IRoxieServerErrorHandler *_errorHandler, IRoxieSlaveContext *_ctx, IHThorArg *_colocalArg)
  21010. {
  21011. CRemoteResultAdaptor::onCreate(_owner, _errorHandler, _ctx, _colocalArg);
  21012. ccdRecordAllocator.setown(ctx->queryCodeContext()->getRowAllocator(QUERYINTERFACE(helper.queryJoinFieldsRecordSize(), IOutputMetaData), activityId));
  21013. }
  21014. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21015. {
  21016. eof = false;
  21017. joinProcessed = 0;
  21018. totalCycles = 0;
  21019. allPulled = false;
  21020. assertex(ready.ordinality()==0);
  21021. CRemoteResultAdaptor::start(parentExtractSize, parentExtract, paused);
  21022. }
  21023. virtual void reset()
  21024. {
  21025. CRemoteResultAdaptor::reset();
  21026. while (ready.ordinality())
  21027. {
  21028. const void *goer = ready.dequeue();
  21029. if (goer)
  21030. ReleaseRoxieRow(goer);
  21031. }
  21032. while (injected.ordinality())
  21033. {
  21034. const void *goer = injected.dequeue();
  21035. if (goer)
  21036. ReleaseRoxieRow(goer);
  21037. }
  21038. }
  21039. inline void addResult(const void *row)
  21040. {
  21041. ready.enqueue(row);
  21042. }
  21043. virtual unsigned __int64 queryTotalCycles() const
  21044. {
  21045. return totalCycles;
  21046. }
  21047. virtual IOutputMetaData * queryOutputMeta() const
  21048. {
  21049. return owner->queryOutputMeta();
  21050. }
  21051. virtual const void *nextInGroup()
  21052. {
  21053. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  21054. loop
  21055. {
  21056. if (eof)
  21057. return NULL;
  21058. processSlaveResults();
  21059. if (ready.ordinality())
  21060. {
  21061. const void *result = ready.dequeue();
  21062. if (result)
  21063. joinProcessed++;
  21064. return result;
  21065. }
  21066. else
  21067. eof = true;
  21068. }
  21069. }
  21070. private:
  21071. void processSlaveResults()
  21072. {
  21073. while (!ready.ordinality())
  21074. {
  21075. KeyedJoinHeader *fetchedData;
  21076. if (isSimple)
  21077. {
  21078. while (!allPulled && !injected.ordinality())
  21079. {
  21080. if (!puller.pullRecords(1))
  21081. {
  21082. puller.done();
  21083. allPulled = true;
  21084. }
  21085. }
  21086. fetchedData = (KeyedJoinHeader *) injected.dequeue();
  21087. }
  21088. else
  21089. fetchedData = (KeyedJoinHeader *) CRemoteResultAdaptor::nextInGroup();
  21090. if (fetchedData)
  21091. {
  21092. CJoinGroup *thisGroup = fetchedData->thisGroup;
  21093. if (fetchedData->partNo == (unsigned short) -1)
  21094. {
  21095. #ifdef TRACE_JOINGROUPS
  21096. CTXLOG("Got end for group %p", thisGroup);
  21097. #endif
  21098. unsigned candidateCount = (unsigned) fetchedData->fpos;
  21099. ReleaseRoxieRow(fetchedData);
  21100. processor.noteEndReceived(thisGroup, candidateCount); // note - this can throw exception. So release fetchdata before calling
  21101. }
  21102. else
  21103. {
  21104. #ifdef TRACE_JOINGROUPS
  21105. CTXLOG("Reading another %d bytes for group %p data", ccdRecordSize, thisGroup);
  21106. #endif
  21107. thisGroup->addRightMatch(fetchedData);
  21108. if (isFullKey)
  21109. {
  21110. #ifdef TRACE_JOINGROUPS
  21111. CTXLOG("Calling noteEndReceived for record returned from FETCH of full keyed join");
  21112. #endif
  21113. processor.noteEndReceived(thisGroup, 0); // note - this can throw exception. So release fetchdata before calling
  21114. }
  21115. }
  21116. }
  21117. else
  21118. break;
  21119. }
  21120. }
  21121. };
  21122. class CRoxieServerFullKeyedJoinHead: public CRoxieServerActivity, implements IRecordPullerCallback, implements IRoxieServerErrorHandler
  21123. {
  21124. IHThorKeyedJoinArg &helper;
  21125. Owned<IKeyManager> tlk;
  21126. Linked<IKeyArray> keySet;
  21127. Linked<TranslatorArray> translators;
  21128. CRemoteResultAdaptor remote;
  21129. RecordPullerThread puller;
  21130. IOutputMetaData *indexReadMeta;
  21131. IJoinProcessor *joinHandler;
  21132. bool variableIndexFileName;
  21133. bool indexReadInputRecordVariable;
  21134. bool isLocal;
  21135. Owned<IEngineRowAllocator> indexReadAllocator;
  21136. Owned<const IResolvedFile> varFileInfo;
  21137. IRoxieInput *indexReadInput;
  21138. IIndexReadActivityInfo *rootIndex;
  21139. public:
  21140. CRoxieServerFullKeyedJoinHead(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IKeyArray * _keySet, TranslatorArray *_translators, IOutputMetaData *_indexReadMeta, IJoinProcessor *_joinHandler, bool _isLocal)
  21141. : CRoxieServerActivity(_factory, _probeManager),
  21142. helper((IHThorKeyedJoinArg &)basehelper),
  21143. tlk(createKeyManager(NULL, 0, this)),
  21144. translators(_translators),
  21145. keySet(_keySet),
  21146. remote(_remoteId, 0, helper, *this, true, true),
  21147. indexReadMeta(_indexReadMeta),
  21148. joinHandler(_joinHandler),
  21149. puller(false),
  21150. isLocal(_isLocal)
  21151. {
  21152. variableIndexFileName = allFilesDynamic || ((helper.getJoinFlags() & (JFvarindexfilename|JFdynamicindexfilename)) != 0);
  21153. indexReadInputRecordVariable = indexReadMeta->isVariableSize();
  21154. indexReadInput = NULL;
  21155. rootIndex = NULL;
  21156. }
  21157. virtual const IResolvedFile *queryVarFileInfo() const
  21158. {
  21159. return varFileInfo;
  21160. }
  21161. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  21162. {
  21163. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  21164. remote.onCreate(this, this, _ctx, _colocalParent);
  21165. indexReadAllocator.setown(ctx->queryCodeContext()->getRowAllocator(indexReadMeta, activityId));
  21166. }
  21167. virtual void setInput(unsigned idx, IRoxieInput *_in)
  21168. {
  21169. if (!idx)
  21170. puller.setInput(this, _in);
  21171. else if (idx==1)
  21172. indexReadInput = _in;
  21173. else
  21174. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  21175. }
  21176. virtual void serializeExtra(MemoryBuffer &out)
  21177. {
  21178. if (helper.getJoinFlags() & JFindexfromactivity)
  21179. {
  21180. assertex(rootIndex);
  21181. const RemoteActivityId& indexId = rootIndex->queryRemoteId();
  21182. indexId.serialize(out);
  21183. // could mess about reserving space for length then patching it again, to avoid copy, but probably not worth it
  21184. MemoryBuffer tmp;
  21185. rootIndex->queryActivity()->serializeCreateStartContext(tmp);
  21186. if (rootIndex->queryActivity()->queryVarFileInfo())
  21187. {
  21188. rootIndex->queryActivity()->queryVarFileInfo()->queryTimeStamp().serialize(tmp);
  21189. tmp.append(rootIndex->queryActivity()->queryVarFileInfo()->queryCheckSum());
  21190. }
  21191. unsigned ctxlen = tmp.length();
  21192. out.append(ctxlen).append(tmp);
  21193. }
  21194. }
  21195. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21196. {
  21197. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  21198. if (indexReadInput)
  21199. {
  21200. indexReadInput->start(parentExtractSize, parentExtract, true); // paused=true because we don't want to actually run the index read
  21201. rootIndex = indexReadInput->queryIndexReadActivity();
  21202. if (!rootIndex)
  21203. throw MakeStringException(ROXIE_INTERNAL_ERROR,"Index in keyed join %d could not be resolved", queryId());
  21204. }
  21205. remote.onStart(parentExtractSize, parentExtract);
  21206. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  21207. if (rootIndex)
  21208. {
  21209. varFileInfo.setown(rootIndex->getVarFileInfo());
  21210. translators.setown(rootIndex->getTranslators());
  21211. keySet.setown(rootIndex->getKeySet());
  21212. }
  21213. else if (variableIndexFileName)
  21214. {
  21215. OwnedRoxieString indexFileName(helper.getIndexFileName());
  21216. varFileInfo.setown(resolveLFN(indexFileName, (helper.getJoinFlags() & JFindexoptional) != 0));
  21217. if (varFileInfo)
  21218. {
  21219. translators.setown(new TranslatorArray);
  21220. keySet.setown(varFileInfo->getKeyArray(factory->queryActivityMeta(), translators, false, isLocal ? factory->queryQueryFactory().queryChannel() : 0, factory->queryQueryFactory().getEnableFieldTranslation())); // MORE - isLocal?
  21221. }
  21222. }
  21223. puller.start(parentExtractSize, parentExtract, paused, ctx->fullKeyedJoinPreload(), false, ctx);
  21224. }
  21225. virtual void stop(bool aborting)
  21226. {
  21227. puller.stop(aborting);
  21228. CRoxieServerActivity::stop(aborting);
  21229. }
  21230. virtual void reset()
  21231. {
  21232. CRoxieServerActivity::reset();
  21233. puller.reset();
  21234. if (varFileInfo)
  21235. {
  21236. keySet.clear();
  21237. varFileInfo.clear();
  21238. }
  21239. }
  21240. virtual IRoxieInput *queryOutput(unsigned idx)
  21241. {
  21242. if (idx==(unsigned)-1)
  21243. idx = 0;
  21244. return idx ? NULL : &remote;
  21245. }
  21246. virtual void processRow(const void *row)
  21247. {
  21248. // MORE - this code seems to be pretty much duplicated below in half-keyed....
  21249. // called from front puller thread
  21250. // buffer up an IndexRead request
  21251. if (helper.leftCanMatch(row))
  21252. {
  21253. RtlDynamicRowBuilder extractedBuilder(indexReadAllocator);
  21254. unsigned indexReadSize = helper.extractIndexReadFields(extractedBuilder, row);
  21255. OwnedConstRoxieRow extracted;
  21256. if (indexReadSize)
  21257. extracted.setown(extractedBuilder.finalizeRowClear(indexReadSize));
  21258. CJoinGroup *jg = joinHandler->createJoinGroup(row);
  21259. for (unsigned partNo = 0; partNo < keySet->length(); partNo++)
  21260. {
  21261. IKeyIndexBase *thisBase = keySet->queryKeyPart(partNo);
  21262. if (thisBase)
  21263. {
  21264. unsigned fileNo = 0;
  21265. IKeyIndex *thisKey = thisBase->queryPart(fileNo);
  21266. try
  21267. {
  21268. tlk->setKey(thisKey);
  21269. tlk->setLayoutTranslator(translators->item(fileNo));
  21270. helper.createSegmentMonitors(tlk, extracted);
  21271. if (rootIndex)
  21272. rootIndex->mergeSegmentMonitors(tlk);
  21273. tlk->finishSegmentMonitors();
  21274. tlk->reset();
  21275. loop
  21276. {
  21277. typedef const void * cvp;
  21278. if (thisKey->isTopLevelKey())
  21279. {
  21280. bool locallySorted = !thisKey->isFullySorted();
  21281. while (locallySorted || tlk->lookup(false))
  21282. {
  21283. unsigned slavePart = locallySorted ? 0 : (unsigned) tlk->queryFpos();
  21284. if (locallySorted || slavePart)
  21285. {
  21286. cvp *outputBuffer = (cvp *) remote.getMem(slavePart, fileNo, indexReadSize + sizeof(cvp) + (indexReadInputRecordVariable ? sizeof(unsigned) : 0));
  21287. *outputBuffer++ = jg;
  21288. if (indexReadInputRecordVariable)
  21289. {
  21290. *(unsigned *) outputBuffer = indexReadSize;
  21291. outputBuffer = (cvp*) (((unsigned *) outputBuffer) + 1);
  21292. }
  21293. jg->notePending();
  21294. memcpy(outputBuffer, extracted, indexReadSize);
  21295. if (locallySorted)
  21296. {
  21297. for (unsigned i = 1; i < numChannels; i++)
  21298. jg->notePending();
  21299. break;
  21300. }
  21301. }
  21302. }
  21303. }
  21304. else
  21305. {
  21306. // MORE - this code seems to be duplicated in half keyed
  21307. unsigned accepted = 0;
  21308. unsigned rejected = 0;
  21309. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), true);
  21310. jg->notePending();
  21311. unsigned candidateCount = 0;
  21312. while (tlk->lookup(true))
  21313. {
  21314. candidateCount++;
  21315. atomic_inc(&indexRecordsRead);
  21316. KLBlobProviderAdapter adapter(tlk);
  21317. offset_t recptr;
  21318. const byte *indexRow = tlk->queryKeyBuffer(recptr);
  21319. if (helper.indexReadMatch(extracted, indexRow, recptr, &adapter))
  21320. {
  21321. KeyedJoinHeader *rhs = (KeyedJoinHeader *) ctx->queryRowManager().allocate(KEYEDJOIN_RECORD_SIZE(0), activityId);
  21322. rhs->fpos = recptr;
  21323. rhs->thisGroup = jg;
  21324. rhs->partNo = partNo;
  21325. result->append(rhs);
  21326. }
  21327. else
  21328. {
  21329. rejected++;
  21330. atomic_inc(&postFiltered);
  21331. }
  21332. }
  21333. // output an end marker for the matches to this group
  21334. KeyedJoinHeader *endMarker = (KeyedJoinHeader *) ctx->queryRowManager().allocate(KEYEDJOIN_RECORD_SIZE(0), activityId);
  21335. endMarker->fpos = (offset_t) candidateCount;
  21336. endMarker->thisGroup = jg;
  21337. endMarker->partNo = (unsigned short) -1;
  21338. result->append(endMarker);
  21339. remote.injectResult(result.getClear());
  21340. if (accepted)
  21341. noteStatistic(STATS_ACCEPTED, accepted, 1);
  21342. if (rejected)
  21343. noteStatistic(STATS_REJECTED, rejected, 1);
  21344. }
  21345. if (++fileNo < thisBase->numParts())
  21346. {
  21347. thisKey = thisBase->queryPart(fileNo);
  21348. tlk->setKey(thisKey);
  21349. tlk->setLayoutTranslator(translators->item(fileNo));
  21350. tlk->reset();
  21351. }
  21352. else
  21353. break;
  21354. }
  21355. tlk->releaseSegmentMonitors();
  21356. tlk->setKey(NULL);
  21357. }
  21358. catch (...)
  21359. {
  21360. tlk->releaseSegmentMonitors();
  21361. tlk->setKey(NULL);
  21362. throw;
  21363. }
  21364. }
  21365. }
  21366. joinHandler->noteEndReceived(jg, 0);
  21367. }
  21368. else
  21369. {
  21370. joinHandler->noteEndReceived(joinHandler->createJoinGroup(row), 0);
  21371. }
  21372. }
  21373. void processGroup(const ConstPointerArray &)
  21374. {
  21375. throwUnexpected();
  21376. }
  21377. virtual void processEOG()
  21378. {
  21379. joinHandler->processEOG();
  21380. }
  21381. virtual void processDone()
  21382. {
  21383. // called from puller thread
  21384. remote.flush();
  21385. remote.senddone();
  21386. }
  21387. virtual void onLimitExceeded(bool isKeyed)
  21388. {
  21389. if (traceLevel > 4)
  21390. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  21391. if (isKeyed)
  21392. throwUnexpected();
  21393. helper.onLimitExceeded();
  21394. }
  21395. virtual const void *createLimitFailRow(bool isKeyed)
  21396. {
  21397. throwUnexpected();
  21398. }
  21399. virtual bool fireException(IException *e)
  21400. {
  21401. // called from puller thread on failure
  21402. remote.fireException(LINK(e));
  21403. return joinHandler->fireException(e);
  21404. }
  21405. virtual const void *nextInGroup()
  21406. {
  21407. throwUnexpected(); // I am nobody's input
  21408. }
  21409. };
  21410. class CRoxieServerKeyedJoinBase : public CRoxieServerActivity, implements IRecordPullerCallback, implements IRoxieServerErrorHandler, implements IJoinProcessor
  21411. {
  21412. protected:
  21413. IHThorKeyedJoinArg &helper;
  21414. KeyedJoinRemoteAdaptor remote;
  21415. RecordPullerThread puller;
  21416. OwnedConstRoxieRow defaultRight;
  21417. Owned<IEngineRowAllocator> defaultRightAllocator;
  21418. unsigned joinFlags;
  21419. unsigned atMost;
  21420. unsigned atmostsTriggered;
  21421. unsigned abortLimit;
  21422. unsigned keepLimit;
  21423. bool limitFail;
  21424. bool limitOnFail;
  21425. bool preserveGroups;
  21426. bool cloneLeft;
  21427. bool isSimple;
  21428. bool isLocal;
  21429. ThorActivityKind activityKind;
  21430. CJoinGroup *groupStart;
  21431. CriticalSection groupsCrit;
  21432. QueueOf<CJoinGroup, false> groups;
  21433. IRoxieInput *indexReadInput;
  21434. IIndexReadActivityInfo *rootIndex;
  21435. void createDefaultRight()
  21436. {
  21437. if (!defaultRight)
  21438. {
  21439. if (!defaultRightAllocator)
  21440. defaultRightAllocator.setown(ctx->queryCodeContext()->getRowAllocator(helper.queryJoinFieldsRecordSize(), activityId));
  21441. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  21442. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  21443. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  21444. }
  21445. }
  21446. public:
  21447. CRoxieServerKeyedJoinBase(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _joinFlags
  21448. , bool isFull, bool _isSimple, bool _isLocal)
  21449. : CRoxieServerActivity(_factory, _probeManager),
  21450. helper((IHThorKeyedJoinArg &)basehelper),
  21451. remote(_remoteId, helper, *this, isFull, _isSimple, puller, *this),
  21452. joinFlags(_joinFlags),
  21453. preserveGroups(meta.isGrouped()),
  21454. puller(false),
  21455. isSimple(_isSimple),
  21456. isLocal(_isLocal),
  21457. abortLimit(0),
  21458. keepLimit(0),
  21459. atMost(0),
  21460. limitFail(false),
  21461. limitOnFail(false),
  21462. cloneLeft(false)
  21463. {
  21464. groupStart = NULL;
  21465. activityKind = _factory->getKind();
  21466. indexReadInput = NULL;
  21467. rootIndex = NULL;
  21468. atmostsTriggered = 0;
  21469. // MORE - code would be easier to read if I got more values from helper rather than passing from factory
  21470. }
  21471. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  21472. {
  21473. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  21474. remote.onCreate(this, this, _ctx, _colocalParent);
  21475. }
  21476. virtual void setInput(unsigned idx, IRoxieInput *_in)
  21477. {
  21478. if (!idx)
  21479. puller.setInput(this, _in);
  21480. else if (idx==1)
  21481. indexReadInput = _in;
  21482. else
  21483. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  21484. }
  21485. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21486. {
  21487. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  21488. if (indexReadInput)
  21489. {
  21490. indexReadInput->start(parentExtractSize, parentExtract, true); // paused=true because we don't want to actually run the index read
  21491. rootIndex = indexReadInput->queryIndexReadActivity();
  21492. if (!rootIndex)
  21493. throw MakeStringException(ROXIE_INTERNAL_ERROR,"Index in keyed join %d could not be resolved", queryId());
  21494. }
  21495. remote.onStart(parentExtractSize, parentExtract);
  21496. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  21497. atmostsTriggered = 0;
  21498. atMost = helper.getJoinLimit();
  21499. if (atMost == 0) atMost = (unsigned)-1;
  21500. abortLimit = helper.getMatchAbortLimit();
  21501. if (abortLimit == 0 || atMost != (unsigned) -1) abortLimit = (unsigned)-1;
  21502. keepLimit = helper.getKeepLimit();
  21503. if (keepLimit == 0) keepLimit = (unsigned)-1;
  21504. getLimitType(joinFlags, limitFail, limitOnFail);
  21505. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  21506. if (joinFlags & JFleftouter)
  21507. createDefaultRight();
  21508. }
  21509. virtual void stop(bool aborting)
  21510. {
  21511. puller.stop(aborting);
  21512. if (indexReadInput)
  21513. indexReadInput->stop(aborting);
  21514. CRoxieServerActivity::stop(aborting);
  21515. }
  21516. virtual unsigned __int64 queryLocalCycles() const
  21517. {
  21518. __int64 localCycles = remote.totalCycles;
  21519. localCycles -= puller.queryTotalCycles(); // MORE - debatable... but probably fair.
  21520. if (localCycles < 0)
  21521. localCycles = 0;
  21522. return localCycles;
  21523. }
  21524. virtual IRoxieInput *queryInput(unsigned idx)
  21525. {
  21526. if (idx==0)
  21527. return puller.queryInput();
  21528. else if (idx==1)
  21529. return indexReadInput;
  21530. else
  21531. return NULL;
  21532. }
  21533. virtual void reset()
  21534. {
  21535. totalCycles = remote.totalCycles;
  21536. remote.totalCycles = 0;
  21537. processed = remote.joinProcessed;
  21538. remote.joinProcessed = 0;
  21539. defaultRight.clear();
  21540. if (indexReadInput)
  21541. indexReadInput->reset();
  21542. if (atmostsTriggered)
  21543. noteStatistic(STATS_ATMOST, atmostsTriggered, 1);
  21544. CRoxieServerActivity::reset();
  21545. puller.reset();
  21546. while (groups.ordinality())
  21547. {
  21548. ::Release(groups.dequeue());
  21549. }
  21550. }
  21551. virtual IRoxieInput *queryOutput(unsigned idx)
  21552. {
  21553. if (idx==(unsigned)-1)
  21554. idx = 0;
  21555. return idx ? NULL : &remote;
  21556. }
  21557. #undef new
  21558. virtual CJoinGroup *createJoinGroup(const void *row)
  21559. {
  21560. // NOTE - we need to protect access to queue, since it's also modified by consumer thread. Groupstart is only modified by puller thread.
  21561. CriticalBlock c(groupsCrit);
  21562. if (preserveGroups && !groupStart)
  21563. {
  21564. groupStart = new (&ctx->queryRowManager(), activityId) CJoinGroup(NULL, NULL);
  21565. groups.enqueue(groupStart);
  21566. }
  21567. CJoinGroup *jg = new (&ctx->queryRowManager(), activityId) CJoinGroup(row, groupStart);
  21568. groups.enqueue(jg);
  21569. return jg;
  21570. }
  21571. #if defined(_DEBUG) && defined(_WIN32) && !defined(USING_MPATROL)
  21572. #define new new(_NORMAL_BLOCK, __FILE__, __LINE__)
  21573. #endif
  21574. void endGroup()
  21575. {
  21576. CriticalBlock c(groupsCrit);
  21577. if (groupStart)
  21578. noteEndReceived(groupStart, 0);
  21579. groupStart = NULL;
  21580. }
  21581. virtual void noteEndReceived(CJoinGroup *jg, unsigned candidateCount)
  21582. {
  21583. if (jg->noteEndReceived(candidateCount))
  21584. processCompletedGroups();
  21585. }
  21586. void processCompletedGroups()
  21587. {
  21588. loop
  21589. {
  21590. CriticalBlock c(groupsCrit);
  21591. if (!groups.head()->complete())
  21592. break;
  21593. Owned<CJoinGroup> head = groups.dequeue();
  21594. if (preserveGroups)
  21595. {
  21596. assert(head->isHeadRecord());
  21597. assert(groups.head()->inGroup(head));
  21598. unsigned joinGroupSize = 0;
  21599. while (groups.ordinality() && groups.head()->inGroup(head))
  21600. {
  21601. Owned<CJoinGroup> finger = groups.dequeue();
  21602. joinGroupSize += doJoinGroup(finger);
  21603. }
  21604. if (joinGroupSize)
  21605. remote.addResult(NULL);
  21606. }
  21607. else
  21608. doJoinGroup(head);
  21609. if (!groups.ordinality())
  21610. break;
  21611. }
  21612. }
  21613. void failLimit(const void * left)
  21614. {
  21615. helper.onMatchAbortLimitExceeded();
  21616. CommonXmlWriter xmlwrite(0);
  21617. if (input && input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  21618. {
  21619. input->queryOutputMeta()->toXML((byte *) left, xmlwrite);
  21620. }
  21621. throw MakeStringException(ROXIE_JOIN_ERROR, "More than %d match candidates in keyed join %d for row %s", abortLimit, queryId(), xmlwrite.str());
  21622. }
  21623. virtual bool needsAllocator() const { return true; }
  21624. unsigned doTransform(const void *left, const void *right, offset_t fpos_or_count, IException *except, const void **group)
  21625. {
  21626. if (cloneLeft && !except)
  21627. {
  21628. LinkRoxieRow(left);
  21629. remote.addResult((void *) left);
  21630. return 1;
  21631. }
  21632. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  21633. unsigned outSize;
  21634. try
  21635. {
  21636. outSize = except ? helper.onFailTransform(rowBuilder, left, right, fpos_or_count, except) :
  21637. (activityKind == TAKkeyeddenormalizegroup) ? helper.transform(rowBuilder, left, right, (unsigned) fpos_or_count, group) :
  21638. helper.transform(rowBuilder, left, right, fpos_or_count);
  21639. }
  21640. catch (IException *E)
  21641. {
  21642. throw makeWrappedException(E);
  21643. }
  21644. if (outSize)
  21645. {
  21646. const void *shrunk = rowBuilder.finalizeRowClear(outSize);
  21647. remote.addResult(shrunk);
  21648. return 1;
  21649. }
  21650. else
  21651. return 0;
  21652. }
  21653. unsigned doJoinGroup(CJoinGroup *jg)
  21654. {
  21655. unsigned matched = jg->rowsSeen();
  21656. unsigned added = 0;
  21657. const void *left = jg->queryLeft();
  21658. if (jg->candidateCount() > abortLimit)
  21659. {
  21660. if (limitFail)
  21661. failLimit(left);
  21662. if (ctx->queryDebugContext())
  21663. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  21664. if (limitOnFail)
  21665. {
  21666. Owned<IException> except;
  21667. try
  21668. {
  21669. failLimit(left);
  21670. }
  21671. catch(IException * e)
  21672. {
  21673. except.setown(e);
  21674. }
  21675. added = doTransform(left, defaultRight, 0, except, NULL);
  21676. }
  21677. }
  21678. else if (!matched || jg->candidateCount() > atMost)
  21679. {
  21680. if (jg->candidateCount() > atMost)
  21681. atmostsTriggered++;
  21682. switch (joinFlags & JFtypemask)
  21683. {
  21684. case JFleftouter:
  21685. case JFleftonly:
  21686. switch (activityKind)
  21687. {
  21688. case TAKkeyedjoin:
  21689. case TAKkeyeddenormalizegroup:
  21690. added = doTransform(left, defaultRight, 0, NULL, NULL);
  21691. break;
  21692. case TAKkeyeddenormalize:
  21693. LinkRoxieRow(left);
  21694. remote.addResult((void *) left);
  21695. added++;
  21696. break;
  21697. }
  21698. break;
  21699. }
  21700. }
  21701. else if (!(joinFlags & JFexclude))
  21702. {
  21703. unsigned idx = 0;
  21704. switch (activityKind)
  21705. {
  21706. case TAKkeyedjoin:
  21707. while (idx < matched)
  21708. {
  21709. const KeyedJoinHeader *rhs = jg->queryRow(idx);
  21710. added += doTransform(left, &rhs->rhsdata, rhs->fpos, NULL, NULL);
  21711. if (added==keepLimit)
  21712. break;
  21713. idx++;
  21714. }
  21715. break;
  21716. case TAKkeyeddenormalize:
  21717. {
  21718. OwnedConstRoxieRow newLeft;
  21719. newLeft.set(left);
  21720. unsigned rowSize = 0;
  21721. unsigned rightAdded = 0;
  21722. while (idx < matched)
  21723. {
  21724. const KeyedJoinHeader *rhs = jg->queryRow(idx);
  21725. try
  21726. {
  21727. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  21728. size32_t transformedSize = helper.transform(rowBuilder, newLeft, &rhs->rhsdata, rhs->fpos, idx+1);
  21729. if (transformedSize)
  21730. {
  21731. rowSize = transformedSize;
  21732. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  21733. rightAdded++;
  21734. if (rightAdded==keepLimit)
  21735. break;
  21736. }
  21737. idx++;
  21738. }
  21739. catch (IException *E)
  21740. {
  21741. throw makeWrappedException(E);
  21742. }
  21743. }
  21744. if (rowSize)
  21745. {
  21746. remote.addResult(newLeft.getClear());
  21747. added++;
  21748. }
  21749. }
  21750. break;
  21751. case TAKkeyeddenormalizegroup:
  21752. {
  21753. ConstPointerArray extractedRows;
  21754. while (idx < matched && idx < keepLimit)
  21755. {
  21756. const KeyedJoinHeader *rhs = jg->queryRow(idx);
  21757. extractedRows.append((void *) &rhs->rhsdata);
  21758. idx++;
  21759. }
  21760. added += doTransform(left, extractedRows.item(0), extractedRows.ordinality(), NULL, (const void * *)extractedRows.getArray());
  21761. }
  21762. break;
  21763. }
  21764. }
  21765. return added;
  21766. }
  21767. virtual void processDone()
  21768. {
  21769. // called from puller thread
  21770. remote.flush();
  21771. remote.senddone();
  21772. }
  21773. virtual void onLimitExceeded(bool isKeyed)
  21774. {
  21775. if (traceLevel > 4)
  21776. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  21777. if (isKeyed)
  21778. throwUnexpected();
  21779. helper.onLimitExceeded();
  21780. }
  21781. virtual const void *createLimitFailRow(bool isKeyed)
  21782. {
  21783. throwUnexpected();
  21784. }
  21785. virtual bool fireException(IException *e)
  21786. {
  21787. // called from puller thread on failure
  21788. return remote.fireException(e);
  21789. }
  21790. virtual const void *nextInGroup()
  21791. {
  21792. throwUnexpected(); // I am nobody's input
  21793. }
  21794. };
  21795. #ifdef _MSC_VER
  21796. #pragma warning ( push )
  21797. #pragma warning ( disable: 4355 )
  21798. #endif
  21799. class CRoxieServerKeyedJoinActivity : public CRoxieServerKeyedJoinBase
  21800. {
  21801. CRoxieServerFullKeyedJoinHead head;
  21802. Owned<IEngineRowAllocator> fetchInputAllocator;
  21803. Linked<IFilePartMap> map;
  21804. bool variableFetchFileName;
  21805. Owned<const IResolvedFile> varFetchFileInfo;
  21806. CachedOutputMetaData fetchInputFields;
  21807. public:
  21808. CRoxieServerKeyedJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_headId, IKeyArray * _key, TranslatorArray *_translators, IOutputMetaData *_indexReadMeta,
  21809. const RemoteActivityId &_tailId, IFilePartMap *_map, unsigned _joinFlags, bool _isLocal)
  21810. : CRoxieServerKeyedJoinBase(_factory, _probeManager, _tailId, _joinFlags, true, false, _isLocal),
  21811. head(_factory, _probeManager, _headId, _key, _translators, _indexReadMeta, this, _isLocal),
  21812. map(_map)
  21813. {
  21814. CRoxieServerKeyedJoinBase::setInput(0, head.queryOutput(0));
  21815. variableFetchFileName = allFilesDynamic || ((helper.getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  21816. }
  21817. virtual const IResolvedFile *queryVarFileInfo() const
  21818. {
  21819. return varFetchFileInfo;
  21820. }
  21821. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  21822. {
  21823. CRoxieServerKeyedJoinBase::onCreate(_ctx, _colocalParent);
  21824. head.onCreate(_ctx, _colocalParent);
  21825. fetchInputFields.set(helper.queryFetchInputRecordSize());
  21826. fetchInputAllocator.setown(ctx->queryCodeContext()->getRowAllocator(helper.queryFetchInputRecordSize(), activityId));
  21827. }
  21828. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21829. {
  21830. CRoxieServerKeyedJoinBase::start(parentExtractSize, parentExtract, paused);
  21831. if (variableFetchFileName)
  21832. {
  21833. bool isFetchOpt = (helper.getFetchFlags() & FFdatafileoptional) != 0;
  21834. OwnedRoxieString fname(helper.getFileName());
  21835. varFetchFileInfo.setown(resolveLFN(fname, isFetchOpt));
  21836. if (varFetchFileInfo)
  21837. map.setown(varFetchFileInfo->getFileMap());
  21838. }
  21839. puller.start(parentExtractSize, parentExtract, paused, ctx->keyedJoinPreload(), false, ctx);
  21840. }
  21841. virtual void setInput(unsigned idx, IRoxieInput *in)
  21842. {
  21843. head.setInput(idx, in);
  21844. }
  21845. virtual void processRow(const void *_rhs)
  21846. {
  21847. // called from puller thread
  21848. KeyedJoinHeader *rhs = (KeyedJoinHeader *) _rhs;
  21849. CJoinGroup *jg = rhs->thisGroup;
  21850. if (rhs->partNo != (unsigned short) -1)
  21851. {
  21852. unsigned partNo = map->mapOffset(rhs->fpos);
  21853. RtlDynamicRowBuilder fetchBuilder(fetchInputAllocator, true);
  21854. size32_t fisize = helper.extractFetchFields(fetchBuilder, jg->queryLeft());
  21855. if (fetchInputFields.isVariableSize())
  21856. {
  21857. KeyedJoinHeader *outRow = (KeyedJoinHeader *) remote.getMem(partNo, 0, KEYEDJOIN_RECORD_SIZE(fisize + sizeof(fisize)));
  21858. memcpy(outRow, rhs, KEYEDJOIN_RECORD_SIZE(0)); // MORE - copy constructor might be more appropriate....
  21859. ReleaseRoxieRow(rhs);
  21860. jg->notePending();
  21861. memcpy(&outRow->rhsdata, &fisize, sizeof(fisize));
  21862. memcpy((&outRow->rhsdata)+sizeof(fisize), fetchBuilder.row(), fisize);
  21863. }
  21864. else
  21865. {
  21866. KeyedJoinHeader *outRow = (KeyedJoinHeader *) remote.getMem(partNo, 0, KEYEDJOIN_RECORD_SIZE(fisize));
  21867. memcpy(outRow, rhs, KEYEDJOIN_RECORD_SIZE(0)); // MORE - copy constructor might be more appropriate....
  21868. ReleaseRoxieRow(rhs);
  21869. jg->notePending();
  21870. memcpy(&outRow->rhsdata, fetchBuilder.row(), fisize);
  21871. }
  21872. }
  21873. else
  21874. {
  21875. unsigned candidateCount = (unsigned) rhs->fpos;
  21876. // CTXLOG("Full keyed join - all results back from index");
  21877. ReleaseRoxieRow(rhs);
  21878. noteEndReceived(jg, candidateCount); // may throw exception - so release row before calling
  21879. }
  21880. }
  21881. virtual void processEOG()
  21882. {
  21883. // called from front puller thread
  21884. if (preserveGroups)
  21885. endGroup();
  21886. }
  21887. void processGroup(const ConstPointerArray &)
  21888. {
  21889. throwUnexpected();
  21890. }
  21891. };
  21892. #ifdef _MSC_VER
  21893. #pragma warning ( pop )
  21894. #endif
  21895. class CRoxieServerHalfKeyedJoinActivity : public CRoxieServerKeyedJoinBase
  21896. {
  21897. IOutputMetaData *indexReadMeta;
  21898. Owned<IEngineRowAllocator> indexReadAllocator;
  21899. Owned<IKeyManager> tlk;
  21900. bool variableIndexFileName;
  21901. bool indexReadInputRecordVariable;
  21902. Owned<const IResolvedFile> varFileInfo;
  21903. Linked<TranslatorArray> translators;
  21904. Linked<IKeyArray> keySet;
  21905. Owned<IOutputMetaData> joinPrefixedMeta;
  21906. Owned<IEngineRowAllocator> joinFieldsAllocator;
  21907. public:
  21908. CRoxieServerHalfKeyedJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IKeyArray * _keySet, TranslatorArray *_translators,
  21909. IOutputMetaData *_indexReadMeta, unsigned _joinFlags, bool _isSimple, bool _isLocal)
  21910. : CRoxieServerKeyedJoinBase(_factory, _probeManager, _remoteId, _joinFlags, false, _isSimple, _isLocal),
  21911. indexReadMeta(_indexReadMeta),
  21912. tlk(createKeyManager(NULL, 0, this)),
  21913. keySet(_keySet),
  21914. translators(_translators)
  21915. {
  21916. variableIndexFileName = allFilesDynamic || ((helper.getJoinFlags() & (JFvarindexfilename|JFdynamicindexfilename)) != 0);
  21917. indexReadInputRecordVariable = indexReadMeta->isVariableSize();
  21918. }
  21919. virtual void serializeExtra(MemoryBuffer &out)
  21920. {
  21921. if (helper.getJoinFlags() & JFindexfromactivity)
  21922. {
  21923. assertex(rootIndex);
  21924. const RemoteActivityId& indexId = rootIndex->queryRemoteId();
  21925. indexId.serialize(out);
  21926. // could mess about reserving space for length then patching it again, to avoid copy, but probably not worth it
  21927. MemoryBuffer tmp;
  21928. rootIndex->queryActivity()->serializeCreateStartContext(tmp);
  21929. if (rootIndex->queryActivity()->queryVarFileInfo())
  21930. {
  21931. rootIndex->queryActivity()->queryVarFileInfo()->queryTimeStamp().serialize(tmp);
  21932. tmp.append(rootIndex->queryActivity()->queryVarFileInfo()->queryCheckSum());
  21933. }
  21934. unsigned ctxlen = tmp.length();
  21935. out.append(ctxlen).append(tmp);
  21936. }
  21937. }
  21938. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  21939. {
  21940. CRoxieServerKeyedJoinBase::onCreate(_ctx, _colocalParent);
  21941. indexReadAllocator.setown(ctx->queryCodeContext()->getRowAllocator(indexReadMeta, activityId));
  21942. IOutputMetaData *joinFieldsMeta = helper.queryJoinFieldsRecordSize();
  21943. joinPrefixedMeta.setown(new CPrefixedOutputMeta(KEYEDJOIN_RECORD_SIZE(0), joinFieldsMeta)); // MORE - not sure if we really need this
  21944. joinFieldsAllocator.setown(ctx->queryCodeContext()->getRowAllocator(joinPrefixedMeta, activityId));
  21945. }
  21946. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21947. {
  21948. CRoxieServerKeyedJoinBase::start(parentExtractSize, parentExtract, paused);
  21949. if (rootIndex)
  21950. {
  21951. varFileInfo.setown(rootIndex->getVarFileInfo());
  21952. translators.setown(rootIndex->getTranslators());
  21953. keySet.setown(rootIndex->getKeySet());
  21954. }
  21955. else if (variableIndexFileName)
  21956. {
  21957. OwnedRoxieString indexFileName(helper.getIndexFileName());
  21958. varFileInfo.setown(resolveLFN(indexFileName, (helper.getJoinFlags() & JFindexoptional) != 0));
  21959. if (varFileInfo)
  21960. {
  21961. translators.setown(new TranslatorArray);
  21962. keySet.setown(varFileInfo->getKeyArray(factory->queryActivityMeta(), translators, false, isLocal ? factory->queryQueryFactory().queryChannel() : 0, factory->queryQueryFactory().getEnableFieldTranslation()));
  21963. }
  21964. }
  21965. puller.start(parentExtractSize, parentExtract, paused, ctx->keyedJoinPreload(), isSimple, ctx);
  21966. }
  21967. virtual const IResolvedFile *queryVarFileInfo() const
  21968. {
  21969. return varFileInfo;
  21970. }
  21971. virtual void reset()
  21972. {
  21973. CRoxieServerKeyedJoinBase::reset();
  21974. if (varFileInfo)
  21975. {
  21976. keySet.clear();
  21977. varFileInfo.clear();
  21978. }
  21979. }
  21980. virtual void processRow(const void *row)
  21981. {
  21982. // called from front puller thread
  21983. // buffer up an IndexRead request
  21984. if (helper.leftCanMatch(row) && keySet)
  21985. {
  21986. RtlDynamicRowBuilder extractBuilder(indexReadAllocator);
  21987. unsigned indexReadRecordSize = helper.extractIndexReadFields(extractBuilder, row);
  21988. OwnedConstRoxieRow extracted;
  21989. if (indexReadRecordSize)
  21990. extracted.setown(extractBuilder.finalizeRowClear(indexReadRecordSize));
  21991. CJoinGroup *jg = createJoinGroup(row);
  21992. for (unsigned partNo = 0; partNo < keySet->length(); partNo++)
  21993. {
  21994. IKeyIndexBase *thisBase = keySet->queryKeyPart(partNo);
  21995. if (thisBase)
  21996. {
  21997. unsigned fileNo = 0;
  21998. IKeyIndex *thisKey = thisBase->queryPart(fileNo);
  21999. tlk->setKey(thisKey);
  22000. tlk->setLayoutTranslator(translators->item(fileNo));
  22001. helper.createSegmentMonitors(tlk, extracted);
  22002. if (rootIndex)
  22003. rootIndex->mergeSegmentMonitors(tlk);
  22004. tlk->finishSegmentMonitors();
  22005. try
  22006. {
  22007. tlk->reset();
  22008. loop
  22009. {
  22010. typedef const void * cvp;
  22011. if (thisKey && thisKey->isTopLevelKey())
  22012. {
  22013. bool locallySorted = (!thisKey->isFullySorted());
  22014. while (locallySorted || tlk->lookup(false))
  22015. {
  22016. unsigned slavePart = locallySorted ? 0 : (unsigned) tlk->queryFpos();
  22017. if (locallySorted || slavePart)
  22018. {
  22019. cvp *outputBuffer = (cvp *) remote.getMem(slavePart, fileNo, indexReadRecordSize + sizeof(cvp) + (indexReadInputRecordVariable ? sizeof(unsigned) : 0));
  22020. *outputBuffer++ = jg;
  22021. if (indexReadInputRecordVariable)
  22022. {
  22023. *(unsigned *) outputBuffer = indexReadRecordSize;
  22024. outputBuffer = (cvp *) (((unsigned *) outputBuffer) + 1);
  22025. }
  22026. jg->notePending();
  22027. memcpy(outputBuffer, extracted, indexReadRecordSize);
  22028. if (locallySorted)
  22029. {
  22030. for (unsigned i = 1; i < numChannels; i++)
  22031. jg->notePending();
  22032. break;
  22033. }
  22034. }
  22035. }
  22036. }
  22037. else
  22038. {
  22039. unsigned accepted = 0;
  22040. unsigned rejected = 0;
  22041. Owned<CRowArrayMessageResult> result;
  22042. if (!isSimple)
  22043. result.setown(new CRowArrayMessageResult(ctx->queryRowManager(), true));
  22044. // MORE - This code seems to be duplicated in keyedJoinHead
  22045. jg->notePending();
  22046. unsigned candidateCount = 0;
  22047. while (tlk->lookup(true))
  22048. {
  22049. candidateCount++;
  22050. atomic_inc(&indexRecordsRead);
  22051. KLBlobProviderAdapter adapter(tlk);
  22052. offset_t recptr;
  22053. const byte *indexRow = tlk->queryKeyBuffer(recptr);
  22054. if (helper.indexReadMatch(extracted, indexRow, recptr, &adapter))
  22055. {
  22056. RtlDynamicRowBuilder rb(joinFieldsAllocator, true);
  22057. CPrefixedRowBuilder pb(KEYEDJOIN_RECORD_SIZE(0), rb);
  22058. accepted++;
  22059. KLBlobProviderAdapter adapter(tlk);
  22060. size32_t joinFieldsSize = helper.extractJoinFields(pb, indexRow, recptr, &adapter);
  22061. KeyedJoinHeader *rec = (KeyedJoinHeader *) rb.getUnfinalizedClear(); // lack of finalize ok as unserialized data here.
  22062. rec->fpos = recptr;
  22063. rec->thisGroup = jg;
  22064. rec->partNo = partNo;
  22065. if (isSimple)
  22066. remote.injected.enqueue(rec);
  22067. else
  22068. result->append(rec);
  22069. }
  22070. else
  22071. {
  22072. rejected++;
  22073. atomic_inc(&postFiltered);
  22074. }
  22075. }
  22076. // output an end marker for the matches to this group
  22077. KeyedJoinHeader *rec = (KeyedJoinHeader *) ctx->queryRowManager().allocate(KEYEDJOIN_RECORD_SIZE(0), activityId);
  22078. rec->fpos = (offset_t) candidateCount;
  22079. rec->thisGroup = jg;
  22080. rec->partNo = (unsigned short) -1;
  22081. if (isSimple)
  22082. remote.injected.enqueue(rec);
  22083. else
  22084. {
  22085. result->append(rec);
  22086. remote.injectResult(result.getClear());
  22087. }
  22088. if (accepted)
  22089. noteStatistic(STATS_ACCEPTED, accepted, 1);
  22090. if (rejected)
  22091. noteStatistic(STATS_REJECTED, rejected, 1);
  22092. }
  22093. if (++fileNo < thisBase->numParts())
  22094. {
  22095. thisKey = thisBase->queryPart(fileNo);
  22096. tlk->setKey(thisKey);
  22097. tlk->setLayoutTranslator(translators->item(fileNo));
  22098. tlk->reset();
  22099. }
  22100. else
  22101. break;
  22102. }
  22103. tlk->releaseSegmentMonitors();
  22104. tlk->setKey(NULL);
  22105. }
  22106. catch (...)
  22107. {
  22108. tlk->releaseSegmentMonitors();
  22109. tlk->setKey(NULL);
  22110. throw;
  22111. }
  22112. }
  22113. }
  22114. noteEndReceived(jg, 0);
  22115. }
  22116. else
  22117. {
  22118. noteEndReceived(createJoinGroup(row), 0);
  22119. }
  22120. }
  22121. virtual void processEOG()
  22122. {
  22123. // called from front puller thread
  22124. if (preserveGroups)
  22125. endGroup();
  22126. }
  22127. void processGroup(const ConstPointerArray &)
  22128. {
  22129. throwUnexpected();
  22130. }
  22131. };
  22132. class CRoxieServerKeyedJoinActivityFactory : public CRoxieServerMultiInputFactory
  22133. {
  22134. Owned<const IResolvedFile> indexfile;
  22135. Owned<const IResolvedFile> datafile;
  22136. Owned<IKeyArray> keySet;
  22137. Owned<TranslatorArray> translatorArray;
  22138. Owned<IDefRecordMeta> activityMeta;
  22139. RemoteActivityId headId;
  22140. RemoteActivityId tailId;
  22141. IOutputMetaData *indexReadMeta;
  22142. Owned<IFilePartMap> map;
  22143. Owned<IFileIOArray> files;
  22144. unsigned joinFlags;
  22145. bool isHalfKeyed;
  22146. bool isLocal;
  22147. bool enableFieldTranslation;
  22148. bool variableFetchFileName;
  22149. bool variableIndexFileName;
  22150. bool isSimple;
  22151. public:
  22152. CRoxieServerKeyedJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_headId, const RemoteActivityId &_tailId, IPropertyTree &_graphNode)
  22153. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), headId(_headId), tailId(_tailId)
  22154. {
  22155. Owned<IHThorKeyedJoinArg> helper = (IHThorKeyedJoinArg *) helperFactory();
  22156. isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  22157. isSimple = isLocal;
  22158. rtlDataAttr indexLayoutMeta;
  22159. size32_t indexLayoutSize;
  22160. if(!helper->getIndexLayout(indexLayoutSize, indexLayoutMeta.refdata()))
  22161. assertex(indexLayoutSize== 0);
  22162. MemoryBuffer m;
  22163. m.setBuffer(indexLayoutSize, indexLayoutMeta.getdata());
  22164. activityMeta.setown(deserializeRecordMeta(m, true));
  22165. enableFieldTranslation = queryFactory.getEnableFieldTranslation();
  22166. translatorArray.setown(new TranslatorArray);
  22167. joinFlags = helper->getJoinFlags();
  22168. variableIndexFileName = allFilesDynamic || ((joinFlags & (JFvarindexfilename|JFdynamicindexfilename)) != 0);
  22169. variableFetchFileName = allFilesDynamic || ((helper->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  22170. if (!variableIndexFileName)
  22171. {
  22172. bool isOpt = (joinFlags & JFindexoptional) != 0;
  22173. OwnedRoxieString indexFileName(helper->getIndexFileName());
  22174. indexfile.setown(queryFactory.queryPackage().lookupFileName(indexFileName, isOpt, true, true, queryFactory.queryWorkUnit()));
  22175. if (indexfile)
  22176. keySet.setown(indexfile->getKeyArray(activityMeta, translatorArray, isOpt, isLocal ? queryFactory.queryChannel() : 0, enableFieldTranslation));
  22177. }
  22178. if (keySet && keySet->length()==1 && !isSimple)
  22179. {
  22180. IKeyIndexBase *thisBase = keySet->queryKeyPart(0);
  22181. if (thisBase->numParts()==1 && !thisBase->queryPart(0)->isTopLevelKey() && !_queryFactory.getDebugValueBool("disableLocalOptimizations", false))
  22182. isSimple = true;
  22183. // MORE - if it's a variable filename then it MAY be simple, we don't know. Tough.
  22184. }
  22185. if (!simpleLocalKeyedJoins)
  22186. isSimple = false;
  22187. isHalfKeyed = !helper->diskAccessRequired();
  22188. indexReadMeta = QUERYINTERFACE(helper->queryIndexReadInputRecordSize(), IOutputMetaData);
  22189. if (!isHalfKeyed && !variableFetchFileName)
  22190. {
  22191. bool isFetchOpt = (helper->getFetchFlags() & FFdatafileoptional) != 0;
  22192. datafile.setown(_queryFactory.queryPackage().lookupFileName(queryNodeFileName(_graphNode), isFetchOpt, true, true, _queryFactory.queryWorkUnit()));
  22193. if (datafile)
  22194. {
  22195. if (isLocal)
  22196. files.setown(datafile->getIFileIOArray(isFetchOpt, queryFactory.queryChannel()));
  22197. else
  22198. map.setown(datafile->getFileMap());
  22199. }
  22200. }
  22201. }
  22202. virtual bool getEnableFieldTranslation() const
  22203. {
  22204. return enableFieldTranslation;
  22205. }
  22206. virtual IDefRecordMeta *queryActivityMeta() const
  22207. {
  22208. return activityMeta;
  22209. }
  22210. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  22211. {
  22212. if (isHalfKeyed)
  22213. return new CRoxieServerHalfKeyedJoinActivity(this, _probeManager,
  22214. headId, keySet, translatorArray, indexReadMeta, joinFlags, isSimple, isLocal);
  22215. else
  22216. return new CRoxieServerKeyedJoinActivity(this, _probeManager,
  22217. headId, keySet, translatorArray, indexReadMeta,
  22218. tailId, map, joinFlags, isLocal);
  22219. }
  22220. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  22221. {
  22222. if (datafile)
  22223. addXrefFileInfo(reply, datafile);
  22224. if (indexfile)
  22225. addXrefFileInfo(reply, indexfile);
  22226. }
  22227. };
  22228. IRoxieServerActivityFactory *createRoxieServerKeyedJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, const RemoteActivityId &_remoteId2, IPropertyTree &_graphNode)
  22229. {
  22230. return new CRoxieServerKeyedJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _remoteId2, _graphNode);
  22231. }
  22232. //=================================================================================
  22233. class CRoxieServerSoapActivityBase : public CRoxieServerActivity, implements ISoapCallRowProvider, implements IRoxieAbortMonitor
  22234. {
  22235. protected:
  22236. Owned<ISoapCallHelper> soaphelper;
  22237. IHThorSoapActionArg & helper;
  22238. StringBuffer authToken;
  22239. bool eof;
  22240. CriticalSection crit;
  22241. ClientCertificate *pClientCert;
  22242. public:
  22243. IMPLEMENT_IINTERFACE;
  22244. CRoxieServerSoapActivityBase(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  22245. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorSoapActionArg &)basehelper)
  22246. {
  22247. eof = false;
  22248. if (clientCert.certificate.length() > 0 && clientCert.privateKey.length() > 0 && clientCert.passphrase.length() > 0)
  22249. pClientCert = &clientCert;
  22250. else
  22251. pClientCert = NULL;
  22252. }
  22253. // ISoapCallRowProvider
  22254. virtual IHThorSoapActionArg * queryActionHelper() { return &helper; };
  22255. virtual IHThorSoapCallArg * queryCallHelper() { return NULL; };
  22256. virtual const void * getNextRow() { return NULL; };
  22257. virtual void releaseRow(const void * r) { ReleaseRoxieRow(r); };
  22258. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  22259. {
  22260. eof = false;
  22261. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  22262. authToken.append(ctx->queryAuthToken());
  22263. }
  22264. virtual void reset()
  22265. {
  22266. // MORE - Shouldn't we make sure thread is stopped etc???
  22267. soaphelper.clear();
  22268. CRoxieServerActivity::reset();
  22269. }
  22270. // IRoxieAbortMonitor
  22271. virtual void checkForAbort() { checkAbort(); }
  22272. };
  22273. //---------------------------------------------------------------------------
  22274. class CRoxieServerSoapRowCallActivity : public CRoxieServerSoapActivityBase
  22275. {
  22276. IHThorSoapCallArg & callHelper;
  22277. public:
  22278. CRoxieServerSoapRowCallActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  22279. : CRoxieServerSoapActivityBase(_factory, _probeManager), callHelper((IHThorSoapCallArg &)basehelper)
  22280. {
  22281. }
  22282. virtual IHThorSoapCallArg * queryCallHelper()
  22283. {
  22284. return &callHelper;
  22285. }
  22286. virtual bool needsAllocator() const { return true; }
  22287. virtual const void *nextInGroup()
  22288. {
  22289. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  22290. if(eof) return NULL;
  22291. if (soaphelper == NULL)
  22292. {
  22293. if (factory->getKind()==TAKhttp_rowdataset)
  22294. soaphelper.setown(createHttpCallHelper(this, rowAllocator, authToken.str(), SCrow, pClientCert, *ctx, this));
  22295. else
  22296. soaphelper.setown(createSoapCallHelper(this, rowAllocator, authToken.str(), SCrow, pClientCert, *ctx, this));
  22297. soaphelper->start();
  22298. }
  22299. OwnedConstRoxieRow ret = soaphelper->getRow();
  22300. if (!ret)
  22301. {
  22302. eof = true;
  22303. return NULL;
  22304. }
  22305. ++processed;
  22306. return ret.getClear();
  22307. }
  22308. };
  22309. class CRoxieServerSoapRowCallActivityFactory : public CRoxieServerActivityFactory
  22310. {
  22311. public:
  22312. CRoxieServerSoapRowCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  22313. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  22314. {
  22315. }
  22316. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  22317. {
  22318. return new CRoxieServerSoapRowCallActivity(this, _probeManager);
  22319. }
  22320. };
  22321. IRoxieServerActivityFactory *createRoxieServerSoapRowCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  22322. {
  22323. return new CRoxieServerSoapRowCallActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  22324. }
  22325. //---------------------------------------------------------------------------
  22326. class CRoxieServerSoapRowActionActivity : public CRoxieServerSoapActivityBase
  22327. {
  22328. public:
  22329. CRoxieServerSoapRowActionActivity (const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  22330. : CRoxieServerSoapActivityBase(_factory, _probeManager)
  22331. {}
  22332. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  22333. {
  22334. //MORE: parentExtract not passed to start - although shouldn't be a problem.
  22335. soaphelper.setown(createSoapCallHelper(this, NULL, ctx->queryAuthToken(), SCrow, pClientCert, *ctx, this));
  22336. soaphelper->start();
  22337. soaphelper->waitUntilDone();
  22338. IException *e = soaphelper->getError();
  22339. soaphelper.clear();
  22340. if (e)
  22341. throw e;
  22342. }
  22343. virtual IRoxieInput *queryOutput(unsigned idx)
  22344. {
  22345. return NULL;
  22346. }
  22347. virtual const void *nextInGroup()
  22348. {
  22349. throwUnexpected(); // I am nobody's input
  22350. }
  22351. };
  22352. class CRoxieServerSoapRowActionActivityFactory : public CRoxieServerActivityFactory
  22353. {
  22354. bool isRoot;
  22355. public:
  22356. CRoxieServerSoapRowActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  22357. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  22358. {
  22359. }
  22360. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  22361. {
  22362. return new CRoxieServerSoapRowActionActivity(this, _probeManager);
  22363. }
  22364. virtual bool isSink() const
  22365. {
  22366. return isRoot;
  22367. }
  22368. };
  22369. IRoxieServerActivityFactory *createRoxieServerSoapRowActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  22370. {
  22371. return new CRoxieServerSoapRowActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  22372. }
  22373. //---------------------------------------------------------------------------
  22374. class CRoxieServerSoapDatasetCallActivity : public CRoxieServerSoapActivityBase
  22375. {
  22376. IHThorSoapCallArg & callHelper;
  22377. public:
  22378. CRoxieServerSoapDatasetCallActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  22379. : CRoxieServerSoapActivityBase(_factory, _probeManager), callHelper((IHThorSoapCallArg &)basehelper)
  22380. {
  22381. }
  22382. virtual IHThorSoapCallArg * queryCallHelper()
  22383. {
  22384. return &callHelper;
  22385. }
  22386. virtual const void *getNextRow()
  22387. {
  22388. CriticalBlock b(crit);
  22389. const void *nextrec = input->nextInGroup();
  22390. if (!nextrec)
  22391. {
  22392. nextrec = input->nextInGroup();
  22393. }
  22394. return nextrec;
  22395. }
  22396. virtual bool needsAllocator() const { return true; }
  22397. virtual const void *nextInGroup()
  22398. {
  22399. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  22400. if(eof) return NULL;
  22401. if (soaphelper == NULL)
  22402. {
  22403. soaphelper.setown(createSoapCallHelper(this, rowAllocator, authToken.str(), SCdataset, pClientCert, *ctx, this));
  22404. soaphelper->start();
  22405. }
  22406. OwnedConstRoxieRow ret = soaphelper->getRow();
  22407. if (!ret)
  22408. {
  22409. eof = true;
  22410. return NULL;
  22411. }
  22412. ++processed;
  22413. return ret.getClear();
  22414. }
  22415. };
  22416. class CRoxieServerSoapDatasetCallActivityFactory : public CRoxieServerActivityFactory
  22417. {
  22418. public:
  22419. CRoxieServerSoapDatasetCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  22420. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  22421. {
  22422. }
  22423. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  22424. {
  22425. return new CRoxieServerSoapDatasetCallActivity(this, _probeManager);
  22426. }
  22427. };
  22428. IRoxieServerActivityFactory *createRoxieServerSoapDatasetCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  22429. {
  22430. return new CRoxieServerSoapDatasetCallActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  22431. }
  22432. //---------------------------------------------------------------------------
  22433. class CRoxieServerSoapDatasetActionActivity : public CRoxieServerSoapActivityBase
  22434. {
  22435. public:
  22436. CRoxieServerSoapDatasetActionActivity (const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  22437. : CRoxieServerSoapActivityBase(_factory, _probeManager)
  22438. {}
  22439. virtual const void *getNextRow()
  22440. {
  22441. CriticalBlock b(crit);
  22442. const void *nextrec = input->nextInGroup();
  22443. if (!nextrec)
  22444. {
  22445. nextrec = input->nextInGroup();
  22446. }
  22447. if (nextrec)
  22448. processed++;
  22449. return nextrec;
  22450. }
  22451. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  22452. {
  22453. try
  22454. {
  22455. start(parentExtractSize, parentExtract, false);
  22456. soaphelper.setown(createSoapCallHelper(this, NULL, ctx->queryAuthToken(), SCdataset, pClientCert, *ctx, this));
  22457. soaphelper->start();
  22458. soaphelper->waitUntilDone();
  22459. IException *e = soaphelper->getError();
  22460. soaphelper.clear();
  22461. if (e)
  22462. throw e;
  22463. stop(false);
  22464. }
  22465. catch (IException *E)
  22466. {
  22467. ctx->notifyAbort(E);
  22468. stop(true);
  22469. throw;
  22470. }
  22471. catch(...)
  22472. {
  22473. Owned<IException> E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught at %s:%d", __FILE__, __LINE__);
  22474. ctx->notifyAbort(E);
  22475. stop(true);
  22476. throw;
  22477. }
  22478. }
  22479. virtual IRoxieInput *queryOutput(unsigned idx)
  22480. {
  22481. return NULL;
  22482. }
  22483. virtual const void *nextInGroup()
  22484. {
  22485. throwUnexpected(); // I am nobody's input
  22486. }
  22487. };
  22488. class CRoxieServerSoapDatasetActionActivityFactory : public CRoxieServerActivityFactory
  22489. {
  22490. bool isRoot;
  22491. public:
  22492. CRoxieServerSoapDatasetActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  22493. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  22494. {
  22495. }
  22496. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  22497. {
  22498. return new CRoxieServerSoapDatasetActionActivity(this, _probeManager);
  22499. }
  22500. virtual bool isSink() const
  22501. {
  22502. return isRoot;
  22503. }
  22504. };
  22505. IRoxieServerActivityFactory *createRoxieServerSoapDatasetActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  22506. {
  22507. return new CRoxieServerSoapDatasetActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  22508. }
  22509. //=====================================================================================================
  22510. class CGraphResults : public CInterface, implements IRoxieGraphResults
  22511. {
  22512. IArrayOf<IGraphResult> results;
  22513. CriticalSection cs;
  22514. IGraphResult & select(unsigned idx)
  22515. {
  22516. CriticalBlock procedure(cs);
  22517. if (idx >= results.ordinality())
  22518. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Error reading graph result %d before it is calculated", idx);
  22519. return results.item(idx);
  22520. }
  22521. public:
  22522. IMPLEMENT_IINTERFACE
  22523. void clear()
  22524. {
  22525. CriticalBlock procedure(cs);
  22526. results.kill();
  22527. }
  22528. IRoxieInput * createIterator(unsigned id)
  22529. {
  22530. return select(id).createIterator();
  22531. }
  22532. virtual void getLinkedResult(unsigned & count, byte * * & ret, unsigned id)
  22533. {
  22534. select(id).getLinkedResult(count, ret);
  22535. }
  22536. virtual void getDictionaryResult(unsigned & count, byte * * & ret, unsigned id)
  22537. {
  22538. select(id).getLinkedResult(count, ret);
  22539. }
  22540. void setResult(unsigned id, IGraphResult * result)
  22541. {
  22542. CriticalBlock procedure(cs);
  22543. if (results.ordinality() <= id)
  22544. {
  22545. while (results.ordinality() < id)
  22546. results.append(*new CGraphResult);
  22547. results.append(*LINK(result));
  22548. }
  22549. else
  22550. results.replace(*LINK(result), id);
  22551. }
  22552. void appendResult(IGraphResult * result)
  22553. {
  22554. CriticalBlock procedure(cs);
  22555. results.append(*LINK(result));
  22556. }
  22557. };
  22558. //===================================================================================================================
  22559. class CPseudoArg : public CInterface, implements IHThorArg
  22560. {
  22561. public:
  22562. IMPLEMENT_IINTERFACE
  22563. virtual IOutputMetaData * queryOutputMeta() { return NULL; }
  22564. };
  22565. class CPseudoActivity : public CRoxieServerActivity
  22566. {
  22567. public:
  22568. CPseudoActivity(IHThorArg & _helper) : CRoxieServerActivity(_helper) {}
  22569. virtual const void *nextInGroup()
  22570. {
  22571. throwUnexpected(); // I am nobody's input
  22572. }
  22573. };
  22574. class CActivityGraph : public CInterface, implements IActivityGraph, implements IThorChildGraph, implements ILocalGraphEx, implements IRoxieServerChildGraph
  22575. {
  22576. protected:
  22577. IArrayOf<IRoxieServerActivity> activities;
  22578. IArrayOf<IRoxieInput> probes;
  22579. IRoxieServerActivityCopyArray sinks;
  22580. StringAttr graphName;
  22581. Owned<CGraphResults> results;
  22582. CGraphResults graphLoopResults;
  22583. ActivityArray & graphDefinition;
  22584. CriticalSection evaluateCrit;
  22585. IProbeManager *probeManager;
  22586. unsigned id;
  22587. unsigned loopCounter;
  22588. class ActivityGraphSlaveContext : public IndirectSlaveContext
  22589. {
  22590. SpinLock abortLock;
  22591. bool aborted;
  22592. Owned<IException> exception;
  22593. public:
  22594. ActivityGraphSlaveContext(const IRoxieContextLogger &_logctx) : logctx(_logctx), loopCounter(0), codeContext(NULL)
  22595. {
  22596. aborted = false;
  22597. }
  22598. // Note - we must track exceptions at the child level in case there is a CATCH in parent
  22599. virtual void notifyAbort(IException *E)
  22600. {
  22601. SpinBlock b(abortLock);
  22602. if (!aborted && QUERYINTERFACE(E, InterruptedSemaphoreException) == NULL)
  22603. {
  22604. aborted = true;
  22605. exception.set(E);
  22606. }
  22607. }
  22608. virtual void checkAbort()
  22609. {
  22610. if (aborted) // NOTE - don't bother getting lock before reading this (for speed) - a false read is very unlikely and not a problem
  22611. {
  22612. SpinBlock b(abortLock);
  22613. if (!exception)
  22614. exception.setown(MakeStringException(ROXIE_INTERNAL_ERROR, "Query was aborted"));
  22615. throw exception.getLink();
  22616. }
  22617. IndirectSlaveContext::checkAbort();
  22618. }
  22619. virtual ICodeContext *queryCodeContext()
  22620. {
  22621. return codeContext;
  22622. }
  22623. void setCodeContext(ICodeContext * _codeContext)
  22624. {
  22625. codeContext = _codeContext;
  22626. }
  22627. void setLoopCounter(unsigned _loopCounter)
  22628. {
  22629. loopCounter = _loopCounter;
  22630. }
  22631. virtual void noteChildGraph(unsigned id, IActivityGraph *childGraph)
  22632. {
  22633. childGraphs.setValue(id, childGraph);
  22634. }
  22635. virtual IActivityGraph * queryChildGraph(unsigned id)
  22636. {
  22637. if (queryTraceLevel() > 10)
  22638. CTXLOG("resolveChildGraph %d", id);
  22639. IActivityGraph *childGraph = childGraphs.getValue(id);
  22640. assertex(childGraph);
  22641. return childGraph;
  22642. }
  22643. // 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
  22644. virtual StringBuffer &getLogPrefix(StringBuffer &ret) const
  22645. {
  22646. logctx.getLogPrefix(ret);
  22647. if (loopCounter)
  22648. ret.appendf("{%u}", loopCounter);
  22649. return ret;
  22650. }
  22651. protected:
  22652. const IRoxieContextLogger &logctx;
  22653. unsigned loopCounter;
  22654. ICodeContext * codeContext;
  22655. MapXToMyClass<unsigned, unsigned, IActivityGraph> childGraphs;
  22656. } graphSlaveContext;
  22657. class ActivityGraphCodeContext : public IndirectCodeContext
  22658. {
  22659. public:
  22660. virtual IEclGraphResults * resolveLocalQuery(__int64 activityId)
  22661. {
  22662. if ((unsigned) activityId == container->queryId())
  22663. return container;
  22664. IActivityGraph * match = slaveContext->queryChildGraph((unsigned) activityId);
  22665. if (match)
  22666. return match->queryLocalGraph();
  22667. return IndirectCodeContext::resolveLocalQuery(activityId);
  22668. }
  22669. virtual IThorChildGraph * resolveChildQuery(__int64 activityId, IHThorArg * colocal)
  22670. {
  22671. IActivityGraph * match = slaveContext->queryChildGraph((unsigned) activityId);
  22672. return LINK(match->queryChildGraph());
  22673. }
  22674. virtual unsigned getGraphLoopCounter() const
  22675. {
  22676. return container->queryLoopCounter(); // only called if value is valid
  22677. }
  22678. void setContainer(IRoxieSlaveContext * _slaveContext, CActivityGraph * _container)
  22679. {
  22680. slaveContext = _slaveContext;
  22681. container = _container;
  22682. }
  22683. protected:
  22684. IRoxieSlaveContext * slaveContext;
  22685. CActivityGraph * container;
  22686. } graphCodeContext;
  22687. public:
  22688. IMPLEMENT_IINTERFACE;
  22689. CActivityGraph(const char *_graphName, unsigned _id, ActivityArray &x, IProbeManager *_probeManager, const IRoxieContextLogger &_logctx)
  22690. : probeManager(_probeManager), graphDefinition(x), graphName(_graphName), graphSlaveContext(_logctx)
  22691. {
  22692. id = x.getLibraryGraphId();
  22693. if (!id)
  22694. id = _id;
  22695. loopCounter = 0;
  22696. graphSlaveContext.setCodeContext(&graphCodeContext);
  22697. graphCodeContext.setContainer(&graphSlaveContext, this);
  22698. }
  22699. ~CActivityGraph()
  22700. {
  22701. if (probeManager)
  22702. probeManager->deleteGraph((IArrayOf<IActivityBase>*)&activities, (IArrayOf<IInputBase>*)&probes);
  22703. }
  22704. virtual const char *queryName() const
  22705. {
  22706. return graphName.get();
  22707. }
  22708. void createGraph()
  22709. {
  22710. ForEachItemIn(idx, graphDefinition)
  22711. {
  22712. IRoxieServerActivityFactory &donor = graphDefinition.serverItem(idx);
  22713. IRoxieServerActivity &activity = *donor.createActivity(probeManager);
  22714. activities.append(activity);
  22715. if (donor.isSink())
  22716. {
  22717. sinks.append(activity);
  22718. if (probeManager)
  22719. probeManager->noteSink(&activity);
  22720. }
  22721. }
  22722. ForEachItemIn(idx1, graphDefinition)
  22723. {
  22724. IRoxieServerActivityFactory &donor = graphDefinition.serverItem(idx1);
  22725. IRoxieServerActivity &activity = activities.item(idx1);
  22726. unsigned inputidx = 0;
  22727. loop
  22728. {
  22729. unsigned outputidx;
  22730. unsigned source = donor.getInput(inputidx, outputidx);
  22731. if (source==(unsigned) -1)
  22732. break;
  22733. connectInput(idx1, inputidx, source, outputidx, 0);
  22734. inputidx++;
  22735. }
  22736. IntArray &dependencies = donor.queryDependencies();
  22737. IntArray &dependencyIndexes = donor.queryDependencyIndexes();
  22738. IntArray &dependencyControlIds = donor.queryDependencyControlIds();
  22739. StringArray &dependencyEdgeIds = donor.queryDependencyEdgeIds();
  22740. ForEachItemIn(idx2, dependencies)
  22741. {
  22742. IRoxieServerActivity &dependencySourceActivity = activities.item(dependencies.item(idx2));
  22743. unsigned dependencySourceIndex = dependencyIndexes.item(idx2);
  22744. unsigned dependencyControlId = dependencyControlIds.item(idx2);
  22745. activity.addDependency(dependencySourceActivity, dependencySourceIndex, dependencyControlId);
  22746. if (probeManager)
  22747. probeManager->noteDependency( &dependencySourceActivity, dependencySourceIndex, dependencyControlId, dependencyEdgeIds.item(idx2), &activity);
  22748. }
  22749. }
  22750. }
  22751. void connectInput(unsigned target, unsigned targetIdx, unsigned source, unsigned sourceIdx, unsigned iteration)
  22752. {
  22753. IRoxieServerActivity &targetActivity = activities.item(target);
  22754. IRoxieServerActivity &sourceActivity = activities.item(source);
  22755. IRoxieInput * output = sourceActivity.queryOutput(sourceIdx);
  22756. if (probeManager)
  22757. {
  22758. IInputBase * inputBase = probeManager->createProbe(static_cast<IInputBase*>(output), &sourceActivity, &targetActivity, sourceIdx, targetIdx, iteration);
  22759. output = static_cast<IRoxieInput*>(inputBase);
  22760. probes.append(*LINK(output));
  22761. }
  22762. targetActivity.setInput(targetIdx, output);
  22763. }
  22764. virtual void onCreate(IRoxieSlaveContext *ctx, IHThorArg *_colocalParent)
  22765. {
  22766. graphSlaveContext.set(ctx);
  22767. if (graphDefinition.isMultiInstance())
  22768. {
  22769. graphCodeContext.set(ctx->queryCodeContext());
  22770. ctx = &graphSlaveContext;
  22771. }
  22772. ForEachItemIn(idx, activities)
  22773. {
  22774. IRoxieServerActivity *activity = &activities.item(idx);
  22775. if (activity)
  22776. activity->onCreate(ctx, _colocalParent);
  22777. }
  22778. }
  22779. virtual void abort()
  22780. {
  22781. ForEachItemIn(idx, sinks)
  22782. {
  22783. IRoxieServerActivity &sink = sinks.item(idx);
  22784. sink.stop(true);
  22785. }
  22786. }
  22787. virtual void reset()
  22788. {
  22789. ForEachItemIn(idx, sinks)
  22790. {
  22791. IRoxieServerActivity &sink = sinks.item(idx);
  22792. sink.reset();
  22793. }
  22794. }
  22795. Linked<IException> exception;
  22796. CriticalSection eCrit;
  22797. virtual void noteException(IException *E)
  22798. {
  22799. CriticalBlock b(eCrit);
  22800. if (!exception)
  22801. {
  22802. if (graphSlaveContext.queryDebugContext())
  22803. {
  22804. graphSlaveContext.queryDebugContext()->checkBreakpoint(DebugStateException, NULL, exception);
  22805. }
  22806. exception.set(E);
  22807. }
  22808. }
  22809. virtual void checkAbort()
  22810. {
  22811. CriticalBlock b(eCrit);
  22812. if (exception)
  22813. throw exception.getLink();
  22814. }
  22815. virtual void execute()
  22816. {
  22817. doExecute(0, NULL);
  22818. }
  22819. //New child query code...
  22820. virtual IThorChildGraph * queryChildGraph()
  22821. {
  22822. return this;
  22823. }
  22824. virtual IEclGraphResults * queryLocalGraph()
  22825. {
  22826. return this;
  22827. }
  22828. virtual IRoxieServerChildGraph * queryLoopGraph()
  22829. {
  22830. return this;
  22831. }
  22832. inline unsigned queryId() const
  22833. {
  22834. return id;
  22835. }
  22836. inline unsigned queryLoopCounter() const
  22837. {
  22838. return loopCounter;
  22839. }
  22840. void doExecute(unsigned parentExtractSize, const byte * parentExtract)
  22841. {
  22842. if (sinks.ordinality()==1)
  22843. sinks.item(0).execute(parentExtractSize, parentExtract);
  22844. #ifdef PARALLEL_EXECUTE
  22845. else if (!probeManager && !graphDefinition.isSequential())
  22846. {
  22847. class casyncfor: public CAsyncFor
  22848. {
  22849. public:
  22850. IActivityGraph &parent;
  22851. unsigned parentExtractSize;
  22852. const byte * parentExtract;
  22853. casyncfor(IRoxieServerActivityCopyArray &_sinks, IActivityGraph &_parent, unsigned _parentExtractSize, const byte * _parentExtract) :
  22854. sinks(_sinks), parent(_parent), parentExtractSize(_parentExtractSize), parentExtract(_parentExtract) { }
  22855. void Do(unsigned i)
  22856. {
  22857. try
  22858. {
  22859. sinks.item(i).execute(parentExtractSize, parentExtract);
  22860. }
  22861. catch (IException *E)
  22862. {
  22863. parent.noteException(E);
  22864. throw;
  22865. }
  22866. }
  22867. private:
  22868. IRoxieServerActivityCopyArray &sinks;
  22869. } afor(sinks, *this, parentExtractSize, parentExtract);
  22870. afor.For(sinks.ordinality(), sinks.ordinality());
  22871. }
  22872. #endif
  22873. else
  22874. {
  22875. ForEachItemIn(idx, sinks)
  22876. {
  22877. IRoxieServerActivity &sink = sinks.item(idx);
  22878. sink.execute(parentExtractSize, parentExtract);
  22879. }
  22880. }
  22881. }
  22882. virtual IEclGraphResults *evaluate(unsigned parentExtractSize, const byte * parentExtract)
  22883. {
  22884. CriticalBlock block(evaluateCrit);
  22885. results.setown(new CGraphResults);
  22886. try
  22887. {
  22888. doExecute(parentExtractSize, parentExtract);
  22889. }
  22890. catch (...)
  22891. {
  22892. DBGLOG("Exception thrown in child query - cleaning up");
  22893. reset();
  22894. throw;
  22895. }
  22896. reset();
  22897. return results.getClear();
  22898. }
  22899. //interface IRoxieServerChildGraph
  22900. virtual void beforeExecute()
  22901. {
  22902. results.setown(new CGraphResults);
  22903. }
  22904. virtual IRoxieInput * startOutput(unsigned id, unsigned parentExtractSize, const byte *parentExtract, bool paused)
  22905. {
  22906. IRoxieInput * ret = selectOutput(id);
  22907. ret->start(parentExtractSize, parentExtract, paused);
  22908. return ret;
  22909. }
  22910. virtual IRoxieInput * selectOutput(unsigned id)
  22911. {
  22912. ForEachItemIn(i, sinks)
  22913. {
  22914. IRoxieInput * ret = sinks.item(i).querySelectOutput(id);
  22915. if (ret)
  22916. return ret;
  22917. }
  22918. throwUnexpected();
  22919. return NULL;
  22920. }
  22921. virtual void setInputResult(unsigned id, IGraphResult * result)
  22922. {
  22923. results->setResult(id, result);
  22924. }
  22925. virtual bool querySetInputResult(unsigned id, IRoxieInput * input)
  22926. {
  22927. ForEachItemIn(i, activities)
  22928. {
  22929. if (activities.item(i).querySetStreamInput(id, input))
  22930. return true;
  22931. }
  22932. return false;
  22933. }
  22934. virtual void stopUnusedOutputs()
  22935. {
  22936. //Hmm not sure how to do this...
  22937. }
  22938. virtual void afterExecute()
  22939. {
  22940. ForEachItemIn(i, sinks)
  22941. {
  22942. sinks.item(i).stop(false);
  22943. }
  22944. if (graphSlaveContext.queryDebugContext())
  22945. {
  22946. graphSlaveContext.queryDebugContext()->checkBreakpoint(DebugStateGraphFinished, NULL, NULL);
  22947. }
  22948. reset();
  22949. }
  22950. virtual IRoxieGraphResults * execute(size32_t parentExtractSize, const byte *parentExtract)
  22951. {
  22952. doExecute(parentExtractSize, parentExtract);
  22953. return LINK(results);
  22954. }
  22955. virtual void getLinkedResult(unsigned & count, byte * * & ret, unsigned id)
  22956. {
  22957. results->getLinkedResult(count, ret, id);
  22958. }
  22959. virtual void getDictionaryResult(unsigned & count, byte * * & ret, unsigned id)
  22960. {
  22961. results->getLinkedResult(count, ret, id);
  22962. }
  22963. virtual void setResult(unsigned id, IGraphResult * result)
  22964. {
  22965. results->setResult(id, result);
  22966. }
  22967. virtual IRoxieInput * createResultIterator(unsigned id)
  22968. {
  22969. return results->createIterator(id);
  22970. }
  22971. virtual void setGraphLoopResult(IGraphResult * result)
  22972. {
  22973. graphLoopResults.appendResult(result);
  22974. }
  22975. virtual IRoxieInput * createGraphLoopResultIterator(unsigned id)
  22976. {
  22977. try
  22978. {
  22979. return graphLoopResults.createIterator(id);
  22980. }
  22981. catch (IException * e)
  22982. {
  22983. e->Release();
  22984. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Error reading graph result %d before it is calculated", id);
  22985. }
  22986. }
  22987. virtual void clearGraphLoopResults()
  22988. {
  22989. graphLoopResults.clear();
  22990. }
  22991. virtual void executeGraphLoop(size32_t parentExtractSize, const byte *parentExtract)
  22992. {
  22993. doExecute(parentExtractSize, parentExtract);
  22994. }
  22995. virtual void setGraphLoopResult(unsigned id, IGraphResult * result)
  22996. {
  22997. graphLoopResults.setResult(id, result);
  22998. }
  22999. virtual IRoxieInput * getGraphLoopResult(unsigned id)
  23000. {
  23001. return graphLoopResults.createIterator(id);
  23002. }
  23003. virtual void getProbeResponse(IPropertyTree *query)
  23004. {
  23005. if (probeManager)
  23006. probeManager->getProbeResponse(query);
  23007. }
  23008. virtual IRoxieServerChildGraph * createGraphLoopInstance(unsigned loopCounter, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &logctx)
  23009. {
  23010. throwUnexpected();
  23011. }
  23012. virtual CGraphIterationInfo *selectGraphLoopOutput()
  23013. {
  23014. return NULL;
  23015. }
  23016. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor)
  23017. {
  23018. throwUnexpected();
  23019. }
  23020. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor)
  23021. {
  23022. throwUnexpected();
  23023. }
  23024. };
  23025. class CIterationActivityGraph : public CActivityGraph
  23026. {
  23027. IHThorArg * colocalParent;
  23028. unsigned fixedParentExtractSize;
  23029. const byte * fixedParentExtract;
  23030. unsigned graphOutputActivityIndex;
  23031. public:
  23032. CIterationActivityGraph(const char *_graphName, unsigned _id, ActivityArray &x, IProbeManager *_probeManager,
  23033. unsigned _loopCounter, IRoxieSlaveContext *ctx, IHThorArg * _colocalParent, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &_logctx)
  23034. : CActivityGraph(_graphName, _id, x, _probeManager, _logctx)
  23035. {
  23036. graphOutputActivityIndex = 0;
  23037. loopCounter = _loopCounter;
  23038. colocalParent = _colocalParent;
  23039. graphSlaveContext.set(ctx);
  23040. graphSlaveContext.setLoopCounter(loopCounter);
  23041. graphCodeContext.set(ctx->queryCodeContext());
  23042. fixedParentExtractSize = parentExtractSize;
  23043. fixedParentExtract = parentExtract;
  23044. }
  23045. void createIterationGraph()
  23046. {
  23047. Owned<IRoxieServerActivity> pseudoActivity = new CPseudoActivity(*new CPseudoArg);
  23048. ForEachItemIn(idx1, graphDefinition)
  23049. activities.append(*LINK(pseudoActivity));
  23050. graphOutputActivityIndex = queryGraphOutputIndex();
  23051. recursiveCreateGraph(graphOutputActivityIndex);
  23052. }
  23053. unsigned queryGraphOutputIndex() const
  23054. {
  23055. ForEachItemIn(i, graphDefinition)
  23056. if (graphDefinition.serverItem(i).getKind() == TAKgraphloopresultwrite)
  23057. return i;
  23058. throwUnexpected();
  23059. }
  23060. void recursiveCreateGraph(unsigned whichActivity)
  23061. {
  23062. //Check to see if already created
  23063. IRoxieServerActivity & prevActivity = activities.item(whichActivity);
  23064. if (prevActivity.queryId() != 0)
  23065. {
  23066. prevActivity.noteOutputUsed(); //We need to patch up the number of outputs for splitters.
  23067. return;
  23068. }
  23069. IRoxieServerActivityFactory &donor = graphDefinition.serverItem(whichActivity);
  23070. IRoxieServerActivity * activity = NULL;
  23071. if (donor.isGraphInvariant())
  23072. {
  23073. ThorActivityKind kind = donor.getKind();
  23074. switch (kind)
  23075. {
  23076. case TAKif:
  23077. case TAKchildif:
  23078. case TAKcase:
  23079. case TAKchildcase: // MORE RKC->GH - what about FILTER with a graph-invariant condition and other latestart activities?
  23080. {
  23081. Owned<IHThorArg> helper = &donor.getHelper();
  23082. helper->onCreate(&graphCodeContext, colocalParent, NULL);
  23083. helper->onStart(fixedParentExtract, NULL);
  23084. unsigned branch;
  23085. switch (kind)
  23086. {
  23087. case TAKif: case TAKchildif:
  23088. branch = static_cast<IHThorIfArg *>(helper.get())->getCondition() ? 0 : 1;
  23089. break;
  23090. case TAKcase: case TAKchildcase:
  23091. branch = static_cast<IHThorCaseArg *>(helper.get())->getBranch();
  23092. if (branch >= donor.numInputs())
  23093. branch = donor.numInputs() - 1;
  23094. break;
  23095. default:
  23096. throwUnexpected();
  23097. }
  23098. helper.clear();
  23099. unsigned outputidx;
  23100. unsigned source = donor.getInput(branch, outputidx);
  23101. if (source ==(unsigned) -1)
  23102. activity = createRoxieServerNullActivity(&donor, probeManager);
  23103. else
  23104. activity = createRoxieServerPassThroughActivity(&donor, probeManager);
  23105. activities.replace(*activity, whichActivity);
  23106. activity->onCreate(&graphSlaveContext, colocalParent);
  23107. if (source ==(unsigned) -1)
  23108. return;
  23109. recursiveCreateGraph(source);
  23110. connectInput(whichActivity, 0, source, outputidx, loopCounter);
  23111. break;
  23112. }
  23113. }
  23114. }
  23115. if (!activity)
  23116. {
  23117. activity = donor.createActivity(probeManager);
  23118. activities.replace(*activity, whichActivity);
  23119. activity->onCreate(&graphSlaveContext, colocalParent);
  23120. activity->resetOutputsUsed();
  23121. unsigned inputidx = 0;
  23122. loop
  23123. {
  23124. unsigned outputidx;
  23125. unsigned source = donor.getInput(inputidx, outputidx);
  23126. if (source==(unsigned) -1)
  23127. break;
  23128. recursiveCreateGraph(source);
  23129. connectInput(whichActivity, inputidx, source, outputidx, loopCounter);
  23130. inputidx++;
  23131. }
  23132. }
  23133. IntArray &dependencies = donor.queryDependencies();
  23134. IntArray &dependencyIndexes = donor.queryDependencyIndexes();
  23135. IntArray &dependencyControlIds = donor.queryDependencyControlIds();
  23136. ForEachItemIn(idx2, dependencies)
  23137. {
  23138. unsigned input = dependencies.item(idx2);
  23139. recursiveCreateGraph(input);
  23140. activity->addDependency(activities.item(input),dependencyIndexes.item(idx2),dependencyControlIds.item(idx2));
  23141. }
  23142. }
  23143. virtual CGraphIterationInfo *selectGraphLoopOutput()
  23144. {
  23145. IRoxieServerActivity &sourceActivity = activities.item(graphOutputActivityIndex);
  23146. return new CGraphIterationInfo(&sourceActivity, sourceActivity.queryOutput(0), 0, loopCounter);
  23147. }
  23148. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor)
  23149. {
  23150. ForEachItemIn(i, activities)
  23151. activities.item(i).gatherIterationUsage(processor, fixedParentExtractSize, fixedParentExtract);
  23152. }
  23153. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor)
  23154. {
  23155. ForEachItemIn(i, activities)
  23156. activities.item(i).associateIterationOutputs(processor, fixedParentExtractSize, fixedParentExtract, probeManager, probes);
  23157. }
  23158. };
  23159. class CDelayedActivityGraph : public CInterface, implements IActivityGraph
  23160. {
  23161. StringAttr graphName;
  23162. ActivityArray & graphDefinition;
  23163. IProbeManager *probeManager;
  23164. unsigned id;
  23165. IRoxieSlaveContext * ctx;
  23166. IHThorArg * colocalParent;
  23167. public:
  23168. IMPLEMENT_IINTERFACE;
  23169. CDelayedActivityGraph(const char *_graphName, unsigned _id, ActivityArray &x, IProbeManager *_probeManager)
  23170. : probeManager(_probeManager), graphDefinition(x)
  23171. {
  23172. graphName.set(_graphName);
  23173. id = _id;
  23174. ctx = NULL;
  23175. colocalParent = NULL;
  23176. }
  23177. virtual const char *queryName() const { return graphName.get(); }
  23178. virtual void abort() { throwUnexpected(); }
  23179. virtual void reset() { }
  23180. virtual void execute() { throwUnexpected(); }
  23181. virtual void getProbeResponse(IPropertyTree *query) { throwUnexpected(); }
  23182. virtual void noteException(IException *E) { throwUnexpected(); }
  23183. virtual void checkAbort() { throwUnexpected(); }
  23184. virtual IThorChildGraph * queryChildGraph() { throwUnexpected(); }
  23185. virtual IEclGraphResults * queryLocalGraph() { throwUnexpected(); }
  23186. virtual IRoxieServerChildGraph * queryLoopGraph() { throwUnexpected(); }
  23187. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  23188. {
  23189. ctx = _ctx;
  23190. colocalParent = _colocalParent;
  23191. }
  23192. virtual IRoxieServerChildGraph * createGraphLoopInstance(unsigned loopCounter, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &logctx)
  23193. {
  23194. Owned<CIterationActivityGraph> ret = new CIterationActivityGraph(graphName, id, graphDefinition, probeManager, loopCounter, ctx, colocalParent, parentExtractSize, parentExtract, logctx);
  23195. ret->createIterationGraph();
  23196. return ret.getClear();
  23197. }
  23198. };
  23199. IActivityGraph *createActivityGraph(const char *_graphName, unsigned id, ActivityArray &childFactories, IRoxieServerActivity *parentActivity, IProbeManager *_probeManager, const IRoxieContextLogger &_logctx)
  23200. {
  23201. if (childFactories.isDelayed())
  23202. {
  23203. return new CDelayedActivityGraph(_graphName, id, childFactories, _probeManager);
  23204. }
  23205. else
  23206. {
  23207. Owned<IProbeManager> childProbe;
  23208. if (_probeManager)
  23209. childProbe.setown(_probeManager->startChildGraph(id, parentActivity));
  23210. Owned<CActivityGraph> ret = new CActivityGraph(_graphName, id, childFactories, childProbe, _logctx);
  23211. ret->createGraph();
  23212. if (_probeManager)
  23213. _probeManager->endChildGraph(childProbe, parentActivity);
  23214. return ret.getClear();
  23215. }
  23216. }
  23217. //================================================================================================================
  23218. #ifdef _USE_CPPUNIT
  23219. #include "unittests.hpp"
  23220. // 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...
  23221. #if _MSC_VER==1200
  23222. #undef protected
  23223. #endif
  23224. static const char *sortAlgorithm;
  23225. class TestMetaData : public CInterface, implements IOutputMetaData
  23226. {
  23227. public:
  23228. IMPLEMENT_IINTERFACE;
  23229. virtual size32_t getRecordSize(const void *) { return 10; }
  23230. virtual size32_t getMinRecordSize() const { return 10; }
  23231. virtual size32_t getFixedSize() const { return 10; }
  23232. virtual void toXML(const byte * self, IXmlWriter & out) {}
  23233. virtual unsigned getVersion() const { return OUTPUTMETADATA_VERSION; }
  23234. virtual unsigned getMetaFlags() { return 0; }
  23235. virtual void destruct(byte * self) {}
  23236. virtual IOutputRowSerializer * createDiskSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  23237. virtual IOutputRowDeserializer * createDiskDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  23238. virtual ISourceRowPrefetcher * createDiskPrefetcher(ICodeContext * ctx, unsigned activityId) { return NULL; }
  23239. virtual IOutputMetaData * querySerializedDiskMeta() { return NULL; }
  23240. virtual IOutputRowSerializer * createInternalSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  23241. virtual IOutputRowDeserializer * createInternalDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  23242. virtual void walkIndirectMembers(const byte * self, IIndirectMemberVisitor & visitor) {}
  23243. } testMeta;
  23244. class TestInput : public CInterface, implements IRoxieInput
  23245. {
  23246. char const * const *input;
  23247. IRoxieSlaveContext *ctx;
  23248. unsigned endSeen;
  23249. bool eof;
  23250. unsigned count;
  23251. unsigned __int64 totalCycles;
  23252. size32_t recordSize;
  23253. unsigned activityId;
  23254. public:
  23255. enum { STATEreset, STATEstarted, STATEstopped } state;
  23256. bool allRead;
  23257. IMPLEMENT_IINTERFACE;
  23258. TestInput(IRoxieSlaveContext *_ctx, char const * const *_input)
  23259. {
  23260. ctx = _ctx;
  23261. input = _input;
  23262. count = 0;
  23263. eof = false;
  23264. allRead = false;
  23265. endSeen = 0;
  23266. recordSize = testMeta.getFixedSize();
  23267. state = STATEreset;
  23268. totalCycles = 0;
  23269. activityId = 1;
  23270. }
  23271. virtual IOutputMetaData * queryOutputMeta() const { return &testMeta; }
  23272. virtual void prestart(unsigned parentExtractSize, const byte *parentExtract)
  23273. {
  23274. ASSERT(state == STATEreset);
  23275. }
  23276. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  23277. {
  23278. ASSERT(state == STATEreset);
  23279. state = STATEstarted;
  23280. }
  23281. virtual IRoxieServerActivity *queryActivity()
  23282. {
  23283. throwUnexpected();
  23284. }
  23285. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  23286. {
  23287. throwUnexpected();
  23288. }
  23289. virtual void stop(bool aborting)
  23290. {
  23291. state = STATEstopped;
  23292. }
  23293. virtual void reset()
  23294. {
  23295. ASSERT(state == STATEstopped);
  23296. eof = false; count = 0; endSeen = 0; allRead = false; state = STATEreset; totalCycles = 0;
  23297. }
  23298. virtual void resetEOF()
  23299. {
  23300. throwUnexpected();
  23301. }
  23302. virtual void checkAbort() {}
  23303. virtual unsigned queryId() const { return activityId; };
  23304. virtual const void *nextInGroup()
  23305. {
  23306. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  23307. ASSERT(state == STATEstarted);
  23308. ASSERT(allRead || !eof);
  23309. if (eof)
  23310. return NULL;
  23311. const char *nextSource = input[count++];
  23312. if (nextSource)
  23313. {
  23314. endSeen = 0;
  23315. void *ret = ctx->queryRowManager().ALLOCATE(recordSize);
  23316. memset(ret, 0, recordSize);
  23317. strncpy((char *) ret, nextSource, recordSize);
  23318. return ret;
  23319. }
  23320. else
  23321. {
  23322. endSeen++;
  23323. if (endSeen==2)
  23324. eof = true;
  23325. return NULL;
  23326. }
  23327. }
  23328. virtual bool nextGroup(ConstPointerArray & group)
  23329. {
  23330. const void * next;
  23331. while ((next = nextInGroup()) != NULL)
  23332. group.append(next);
  23333. if (group.ordinality())
  23334. return true;
  23335. return false;
  23336. }
  23337. virtual unsigned __int64 queryTotalCycles() const { return totalCycles; }
  23338. virtual unsigned __int64 queryLocalCycles() const { return totalCycles; }
  23339. virtual IRoxieInput *queryInput(unsigned idx) const
  23340. {
  23341. return NULL;
  23342. }
  23343. };
  23344. struct SortActivityTest : public ccdserver_hqlhelper::CThorSortArg {
  23345. public:
  23346. struct CompareClass : public ICompare {
  23347. virtual int docompare(const void * _left, const void * _right) const {
  23348. return memcmp(_left, _right, 5);
  23349. }
  23350. } compare;
  23351. virtual ICompare * queryCompare() { return &compare; }
  23352. virtual IOutputMetaData * queryOutputMeta()
  23353. {
  23354. return &testMeta;
  23355. }
  23356. virtual unsigned getAlgorithmFlags() { return TAFunstable; }
  23357. virtual const char * getAlgorithm() { return sortAlgorithm; }
  23358. };
  23359. extern "C" IHThorArg * sortActivityTestFactory() { return new SortActivityTest; }
  23360. struct MergeActivityTest : public ccdserver_hqlhelper::CThorMergeArg {
  23361. static bool isDedup;
  23362. public:
  23363. struct CompareClass : public ICompare {
  23364. virtual int docompare(const void * _left, const void * _right) const {
  23365. return memcmp(_left, _right, 5);
  23366. }
  23367. } compare;
  23368. virtual ICompare * queryCompare() { return &compare; }
  23369. virtual IOutputMetaData * queryOutputMeta()
  23370. {
  23371. return &testMeta;
  23372. }
  23373. virtual bool dedup() { return isDedup; }
  23374. };
  23375. bool MergeActivityTest::isDedup = false;
  23376. extern "C" IHThorArg * mergeActivityTestFactory() { return new MergeActivityTest; }
  23377. class CcdServerTest : public CppUnit::TestFixture
  23378. {
  23379. CPPUNIT_TEST_SUITE(CcdServerTest);
  23380. CPPUNIT_TEST(testSetup);
  23381. CPPUNIT_TEST(testHeapSort);
  23382. CPPUNIT_TEST(testInsertionSort);
  23383. CPPUNIT_TEST(testQuickSort);
  23384. CPPUNIT_TEST(testMerge);
  23385. CPPUNIT_TEST(testMergeDedup);
  23386. CPPUNIT_TEST(testMiscellaneous);
  23387. CPPUNIT_TEST(testCleanup);
  23388. CPPUNIT_TEST_SUITE_END();
  23389. protected:
  23390. SlaveContextLogger logctx;
  23391. Owned<const IQueryDll> queryDll;
  23392. Owned<IRoxiePackage> package;
  23393. Owned<IRoxieSlaveContext> ctx;
  23394. Owned<IQueryFactory> queryFactory;
  23395. void testSetup()
  23396. {
  23397. roxiemem::setTotalMemoryLimit(false, 100 * 1024 * 1024, 0, NULL);
  23398. }
  23399. void testCleanup()
  23400. {
  23401. roxiemem::releaseRoxieHeap();
  23402. }
  23403. void init()
  23404. {
  23405. package.setown(createRoxiePackage(NULL, NULL));
  23406. ctx.setown(createSlaveContext(NULL, logctx, 0, 50*1024*1024, NULL));
  23407. queryDll.setown(createExeQueryDll("roxie"));
  23408. queryFactory.setown(createServerQueryFactory("test", queryDll.getLink(), *package, NULL));
  23409. timer->reset();
  23410. }
  23411. void testActivity(IRoxieServerActivity *activity, char const * const *input, char const * const *output)
  23412. {
  23413. testActivity(activity, input, NULL, output);
  23414. }
  23415. void testActivity(IRoxieServerActivity *activity, char const * const *input, char const * const *input2, char const * const *output)
  23416. {
  23417. TestInput in(ctx, input);
  23418. TestInput in2(ctx, input2);
  23419. IRoxieInput *out = activity->queryOutput(0);
  23420. IOutputMetaData *meta = out->queryOutputMeta();
  23421. activity->setInput(0, &in);
  23422. if (input2)
  23423. activity->setInput(1, &in2);
  23424. void *buf = alloca(meta->getFixedSize());
  23425. for (unsigned iteration = 0; iteration < 8; iteration++)
  23426. {
  23427. // 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)
  23428. // This should be true whether we read all, some, or none of the data.
  23429. // Should not matter if an activity is not started
  23430. if (iteration % 4 == 0)
  23431. activity->onCreate(ctx, NULL);
  23432. unsigned count = 0;
  23433. if (iteration % 4 != 3)
  23434. {
  23435. activity->start(0, NULL, false);
  23436. ASSERT(in.state == TestInput::STATEstarted);
  23437. ASSERT(!input2 || in2.state == TestInput::STATEstarted);
  23438. loop
  23439. {
  23440. const void *next = out->nextInGroup();
  23441. if (!next)
  23442. {
  23443. ASSERT(output[count++] == NULL);
  23444. next = out->nextInGroup();
  23445. if (!next)
  23446. {
  23447. ASSERT(output[count++] == NULL);
  23448. break;
  23449. }
  23450. }
  23451. ASSERT(output[count] != NULL);
  23452. unsigned outsize = meta->getRecordSize(next);
  23453. memset(buf, 0, outsize);
  23454. strncpy((char *) buf, output[count++], outsize);
  23455. ASSERT(memcmp(next, buf, outsize) == 0);
  23456. ReleaseRoxieRow(next);
  23457. if (iteration % 4 == 2)
  23458. break;
  23459. }
  23460. if (iteration % 4 != 2)
  23461. {
  23462. // Check that reading after end is harmless
  23463. in.allRead = true;
  23464. const void *next = out->nextInGroup();
  23465. ASSERT(next == NULL);
  23466. }
  23467. }
  23468. activity->stop(false);
  23469. ASSERT(in.state == TestInput::STATEstopped);
  23470. ASSERT(!input2 || in2.state == TestInput::STATEstopped);
  23471. activity->reset();
  23472. ASSERT(in.state == TestInput::STATEreset);
  23473. ASSERT(!input2 || in2.state == TestInput::STATEreset);
  23474. ctx->queryRowManager().reportLeaks();
  23475. ASSERT(ctx->queryRowManager().numPagesAfterCleanup(true) == 0);
  23476. }
  23477. }
  23478. static int compareFunc(const void *l, const void *r)
  23479. {
  23480. return strcmp(*(char **) l, *(char **) r);
  23481. }
  23482. void testSort(unsigned type)
  23483. {
  23484. init();
  23485. sortAlgorithm = NULL;
  23486. if (type==2)
  23487. sortAlgorithm = "heapSort";
  23488. else if (type == 1)
  23489. sortAlgorithm = "insertionSort";
  23490. else
  23491. sortAlgorithm = "quickSort";
  23492. DBGLOG("Testing %s activity", sortAlgorithm);
  23493. Owned <IRoxieServerActivityFactory> factory = createRoxieServerSortActivityFactory(1, 1, *queryFactory, sortActivityTestFactory, TAKsort);
  23494. Owned <IRoxieServerActivity> activity = factory->createActivity(NULL);
  23495. const char * test[] = { NULL, NULL };
  23496. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  23497. const char * test54321[] = { "5", "4", "3", "2", "1", NULL, NULL };
  23498. const char * test11111[] = { "1", "1", "1", "1", "1", NULL, NULL };
  23499. const char * test11111_12345[] = { "1", "1", "1", "1", "1", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  23500. const char * test11111_54321[] = { "1", "1", "1", "1", "1", NULL, "5", "4", "3", "2", "1", NULL, NULL };
  23501. const char * test54321_54321[] = { "5", "4", "3", "2", "1", NULL, "5", "4", "3", "2", "1", NULL, NULL };
  23502. const char * test12345_12345[] = { "1", "2", "3", "4", "5", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  23503. testActivity(activity, test, test);
  23504. testActivity(activity, test12345, test12345);
  23505. testActivity(activity, test54321, test12345);
  23506. testActivity(activity, test11111, test11111);
  23507. testActivity(activity, test11111_12345, test11111_12345);
  23508. testActivity(activity, test11111_54321, test11111_12345);
  23509. testActivity(activity, test54321_54321, test12345_12345);
  23510. // A few larger tests
  23511. char *input[2002];
  23512. char *output[2002];
  23513. input[2000] = input[2001] = output[2000] = output[2001] = NULL;
  23514. unsigned i;
  23515. // identical
  23516. for (i=0; i<2000; i++)
  23517. {
  23518. input[i] = new char[11];
  23519. output[i] = new char[11];
  23520. sprintf(input[i], "1");
  23521. sprintf(output[i], "1");
  23522. }
  23523. testActivity(activity, input, output);
  23524. // Ascending
  23525. for (i=0; i<2000; i++)
  23526. {
  23527. sprintf(input[i], "%04d", i);
  23528. sprintf(output[i], "%04d", i);
  23529. }
  23530. testActivity(activity, input, output);
  23531. // Almost sorted
  23532. for (i=0; i<20; i++)
  23533. {
  23534. unsigned h = i*100;
  23535. sprintf(input[h], "%04d", 1900-h);
  23536. }
  23537. testActivity(activity, input, output);
  23538. // Descending
  23539. for (i=0; i<2000; i++)
  23540. {
  23541. sprintf(input[i], "%04d", 1999-i);
  23542. sprintf(output[i], "%04d", i);
  23543. }
  23544. testActivity(activity, input, output);
  23545. // Random
  23546. for (i=0; i<2000; i++)
  23547. {
  23548. unsigned r = rand() % 1500;
  23549. sprintf(input[i], "%04d", r);
  23550. sprintf(output[i], "%04d", r);
  23551. }
  23552. qsort(output, 2000, sizeof(output[0]), compareFunc);
  23553. testActivity(activity, input, output);
  23554. #if 0
  23555. // Random
  23556. #define BIGSORTSIZE 1000000
  23557. char **linput = new char*[BIGSORTSIZE +2];
  23558. char **loutput = new char *[BIGSORTSIZE+2];
  23559. linput[BIGSORTSIZE] = linput[BIGSORTSIZE+1] = loutput[BIGSORTSIZE] = loutput[BIGSORTSIZE+1] = NULL;
  23560. for (i=0; i<BIGSORTSIZE; i++)
  23561. {
  23562. unsigned r = rand() % 15000;
  23563. linput[i] = loutput[i] = new char[11];
  23564. sprintf(linput[i], "%04d", r);
  23565. }
  23566. qsort(loutput, BIGSORTSIZE, 4, compareFunc);
  23567. testActivity(activity, linput, loutput);
  23568. for (i=0; i<BIGSORTSIZE; i++)
  23569. {
  23570. delete [] linput[i];
  23571. }
  23572. delete [] linput;
  23573. delete [] loutput;
  23574. #endif
  23575. unsigned __int64 us = cycle_to_nanosec(factory->queryLocalCycles()/1000);
  23576. DBGLOG("Simple %s sorts: activity time %u.%u ms", type==2?"Heap" : (type==1 ? "Insertion" : "Quick"), (int)(us/1000), (int)(us%1000));
  23577. factory->resetNodeProgressInfo();
  23578. if (type)
  23579. {
  23580. // Other than quicksort, it's supposed to be stable. Let's check that it is
  23581. // All sort identical
  23582. for (i=0; i<2000; i++)
  23583. {
  23584. sprintf(input[i], "1 %d", i);
  23585. sprintf(output[i], "1 %d", i);
  23586. }
  23587. testActivity(activity, input, output);
  23588. // Already sorted
  23589. for (i=0; i<2000; i++)
  23590. {
  23591. sprintf(input[i], "%04d %d", i / 10, i);
  23592. sprintf(output[i], "%04d %d", i / 10, i);
  23593. }
  23594. testActivity(activity, input, output);
  23595. // Reverse order
  23596. for (i=0; i<2000; i++)
  23597. {
  23598. sprintf(input[i], "%04d %d", 199 - (i / 10), i%10);
  23599. sprintf(output[i], "%04d %d", i / 10, i%10);
  23600. }
  23601. testActivity(activity, input, output);
  23602. }
  23603. for (i=0; i<2000; i++)
  23604. {
  23605. delete [] input[i];
  23606. delete [] output[i];
  23607. }
  23608. DBGLOG("Finished testing %s sort", type==2?"Heap" : (type==1 ? "Insertion" : "Quick"));
  23609. }
  23610. void testQuickSort()
  23611. {
  23612. testSort(0);
  23613. }
  23614. void testInsertionSort()
  23615. {
  23616. testSort(1);
  23617. }
  23618. void testHeapSort()
  23619. {
  23620. testSort(2);
  23621. }
  23622. void testMerge()
  23623. {
  23624. DBGLOG("testMerge");
  23625. init();
  23626. Owned <IRoxieServerActivityFactory> factory = createRoxieServerMergeActivityFactory(1, 1, *queryFactory, mergeActivityTestFactory, TAKmerge);
  23627. factory->setInput(0,0,0);
  23628. factory->setInput(1,0,0);
  23629. Owned <IRoxieServerActivity> activity = factory->createActivity(NULL);
  23630. const char * test[] = { NULL, NULL };
  23631. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  23632. const char * test1122334455[] = { "1", "1", "2", "2", "3", "3", "4", "4", "5", "5", NULL, NULL };
  23633. const char * test11111[] = { "1", "1", "1", "1", "1", NULL, NULL };
  23634. const char * test1111111111[] = { "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", NULL, NULL };
  23635. const char * test11111_12345[] = { "1", "1", "1", "1", "1", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  23636. const char * test1111112345[] = { "1", "1", "1", "1", "1", "1", "2", "3", "4", "5", NULL, NULL };
  23637. 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 };
  23638. testActivity(activity, test, test, test);
  23639. testActivity(activity, test12345, test, test12345);
  23640. testActivity(activity, test, test12345, test12345);
  23641. testActivity(activity, test12345, test12345, test1122334455);
  23642. testActivity(activity, test11111, test, test11111);
  23643. testActivity(activity, test, test11111, test11111);
  23644. testActivity(activity, test11111, test11111, test1111111111);
  23645. testActivity(activity, test11111_12345, test, test1111112345);
  23646. testActivity(activity, test11111_12345, test11111_12345, test11111111111122334455);
  23647. // Should really test WHICH side gets kept...
  23648. // Should test with more than 2 inputs...
  23649. DBGLOG("testMerge done");
  23650. }
  23651. void testMergeDedup()
  23652. {
  23653. DBGLOG("testMergeDedup");
  23654. init();
  23655. MergeActivityTest::isDedup = true;
  23656. Owned <IRoxieServerActivityFactory> factory = createRoxieServerMergeActivityFactory(1, 1, *queryFactory, mergeActivityTestFactory, TAKmerge);
  23657. factory->setInput(0,0,0);
  23658. factory->setInput(1,0,0);
  23659. Owned <IRoxieServerActivity> activity = factory->createActivity(NULL);
  23660. const char * test[] = { NULL, NULL };
  23661. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  23662. const char * test11111[] = { "1", "1", "1", "1", "1", NULL, NULL };
  23663. const char * test11111_12345[] = { "1", "1", "1", "1", "1", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  23664. const char * test1111112345[] = { "1", "1", "1", "1", "1", "1", "2", "3", "4", "5", NULL, NULL };
  23665. testActivity(activity, test11111, test, test11111); // No dedup within a stream
  23666. testActivity(activity, test11111, test11111, test11111); // No dedup within a stream
  23667. testActivity(activity, test, test11111, test11111);
  23668. testActivity(activity, test, test, test);
  23669. testActivity(activity, test12345, test, test12345);
  23670. testActivity(activity, test, test12345, test12345);
  23671. testActivity(activity, test12345, test12345, test12345);
  23672. testActivity(activity, test11111_12345, test, test1111112345);
  23673. testActivity(activity, test11111_12345, test11111_12345, test1111112345);
  23674. // Should really test WHICH side gets kept...
  23675. // Should test with more than 2 inputs...
  23676. DBGLOG("testMergeDedup done");
  23677. }
  23678. void testMiscellaneous()
  23679. {
  23680. DBGLOG("sizeof(CriticalSection)=%u", (unsigned) sizeof(CriticalSection));
  23681. DBGLOG("sizeof(SpinLock)=%u", (unsigned) sizeof(SpinLock));
  23682. DBGLOG("sizeof(CJoinGroup)=%u", (unsigned) sizeof(CJoinGroup));
  23683. ASSERT(sizeof(CJoinGroup) <= 120);
  23684. }
  23685. };
  23686. CPPUNIT_TEST_SUITE_REGISTRATION( CcdServerTest );
  23687. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( CcdServerTest, "CcdServerTest" );
  23688. #endif