ccdserver.cpp 887 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506
  1. /*##############################################################################
  2. HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. ############################################################################## */
  13. #include "jmisc.hpp"
  14. #include "jdebug.hpp"
  15. #include "jptree.hpp"
  16. #include "rtlkey.hpp"
  17. #include "jsort.hpp"
  18. #include "jhtree.hpp"
  19. #include "jqueue.tpp"
  20. #include "jisem.hpp"
  21. #include "thorxmlread.hpp"
  22. #include "thorrparse.ipp"
  23. #include "thorxmlwrite.hpp"
  24. #include "thorsoapcall.hpp"
  25. #include "thorcommon.ipp"
  26. #include "jlzw.hpp"
  27. #include "javahash.hpp"
  28. #include "javahash.tpp"
  29. #include "thorstep.ipp"
  30. #include "thorpipe.hpp"
  31. #include "thorfile.hpp"
  32. #include "eclhelper.hpp"
  33. #include "eclrtl_imp.hpp"
  34. #include "rtlfield_imp.hpp"
  35. #include "rtlds_imp.hpp"
  36. #include "rtlread_imp.hpp"
  37. #include "dafdesc.hpp"
  38. #include "dautils.hpp"
  39. namespace ccdserver_hqlhelper
  40. {
  41. #include "eclhelper_base.hpp"
  42. }
  43. #include "ccd.hpp"
  44. #include "ccdserver.hpp"
  45. #include "ccdcontext.hpp"
  46. #include "ccdactivities.hpp"
  47. #include "ccdquery.hpp"
  48. #include "ccdstate.hpp"
  49. #include "ccdqueue.ipp"
  50. #include "ccdsnmp.hpp"
  51. #include "ccddali.hpp"
  52. #include "jsmartsock.hpp"
  53. #include "dllserver.hpp"
  54. #include "workflow.hpp"
  55. #include "roxiemem.hpp"
  56. #include "roxierowbuff.hpp"
  57. #include "roxiehelper.hpp"
  58. #include "roxielmj.hpp"
  59. #include "roxierow.hpp"
  60. #include "thorplugin.hpp"
  61. #include "keybuild.hpp"
  62. #define MAX_HTTP_HEADERSIZE 8000
  63. #define MIN_PAYLOAD_SIZE 800
  64. #pragma warning(disable : 4355)
  65. #define DEFAULT_PARALLEL_LOOP_THREADS 1
  66. #define PROBE
  67. #ifdef _DEBUG
  68. //#define FAKE_EXCEPTIONS
  69. //#define TRACE_JOINGROUPS
  70. //#define TRACE_SPLIT
  71. //#define _CHECK_HEAPSORT
  72. //#undef PARALLEL_EXECUTE
  73. //#define TRACE_SEEK_REQUESTS
  74. #endif
  75. using roxiemem::OwnedRoxieRow;
  76. using roxiemem::OwnedRoxieString;
  77. using roxiemem::OwnedConstRoxieRow;
  78. using roxiemem::IRowManager;
  79. // There is a bug in VC6 implemetation of protected which prevents nested classes from accessing owner's data. It can be tricky to work around - hence...
  80. #if _MSC_VER==1200
  81. #define protected public
  82. #endif
  83. #define TRACE_STARTSTOP // This determines if it is available - it is enabled/disabled by a configuration option
  84. static const SmartStepExtra dummySmartStepExtra(SSEFreadAhead, NULL);
  85. inline void ReleaseRoxieRowSet(ConstPointerArray &data)
  86. {
  87. ForEachItemIn(idx, data)
  88. ReleaseRoxieRow(data.item(idx));
  89. data.kill();
  90. }
  91. //=================================================================================
  92. class RestartableThread : public CInterface
  93. {
  94. class MyThread : public Thread
  95. {
  96. Linked<RestartableThread> owner;
  97. public:
  98. MyThread(RestartableThread *_owner, const char *name) : Thread(name), owner(_owner)
  99. {
  100. }
  101. virtual int run()
  102. {
  103. owner->started.signal();
  104. return owner->run();
  105. }
  106. };
  107. friend class MyThread;
  108. Semaphore started;
  109. Owned<MyThread> thread;
  110. CriticalSection crit;
  111. StringAttr name;
  112. public:
  113. RestartableThread(const char *_name) : name(_name)
  114. {
  115. }
  116. virtual void start(const char *namePrefix)
  117. {
  118. StringBuffer s(namePrefix);
  119. s.append(name);
  120. {
  121. CriticalBlock b(crit);
  122. assertex(!thread);
  123. thread.setown(new MyThread(this, s));
  124. thread->start();
  125. }
  126. started.wait();
  127. }
  128. virtual void join()
  129. {
  130. {
  131. Owned<Thread> tthread;
  132. {
  133. CriticalBlock b(crit);
  134. tthread.setown(thread.getClear());
  135. }
  136. if (tthread)
  137. tthread->join();
  138. }
  139. }
  140. virtual int run() = 0;
  141. };
  142. //================================================================================
  143. // default implementation - can be overridden for efficiency...
  144. bool IRoxieInput::nextGroup(ConstPointerArray & group)
  145. {
  146. // MORE - this should be replaced with a version that reads to a builder
  147. const void * next;
  148. while ((next = nextInGroup()) != NULL)
  149. group.append(next);
  150. if (group.ordinality())
  151. return true;
  152. return false;
  153. }
  154. void IRoxieInput::readAll(RtlLinkedDatasetBuilder &builder)
  155. {
  156. loop
  157. {
  158. const void *nextrec = nextInGroup();
  159. if (!nextrec)
  160. {
  161. nextrec = nextInGroup();
  162. if (!nextrec)
  163. break;
  164. builder.appendEOG();
  165. }
  166. builder.appendOwn(nextrec);
  167. }
  168. }
  169. inline const void * nextUngrouped(IRoxieInput * input)
  170. {
  171. const void * ret = input->nextInGroup();
  172. if (!ret)
  173. ret = input->nextInGroup();
  174. return ret;
  175. };
  176. //=================================================================================
  177. //The following don't link their arguments because that creates a circular reference
  178. //But I wish there was a better way
  179. class IndirectSlaveContext : public CInterface, implements IRoxieSlaveContext
  180. {
  181. public:
  182. IndirectSlaveContext(IRoxieSlaveContext * _ctx = NULL) : ctx(_ctx) {}
  183. IMPLEMENT_IINTERFACE
  184. void set(IRoxieSlaveContext * _ctx) { ctx = _ctx; }
  185. virtual ICodeContext *queryCodeContext()
  186. {
  187. return ctx->queryCodeContext();
  188. }
  189. virtual void checkAbort()
  190. {
  191. ctx->checkAbort();
  192. }
  193. virtual void notifyAbort(IException *E)
  194. {
  195. ctx->notifyAbort(E);
  196. }
  197. virtual IActivityGraph * queryChildGraph(unsigned id)
  198. {
  199. return ctx->queryChildGraph(id);
  200. }
  201. virtual void noteChildGraph(unsigned id, IActivityGraph *childGraph)
  202. {
  203. ctx->noteChildGraph(id, childGraph) ;
  204. }
  205. virtual IRowManager &queryRowManager()
  206. {
  207. return ctx->queryRowManager();
  208. }
  209. virtual void noteStatistic(unsigned statCode, unsigned __int64 value, unsigned count) const
  210. {
  211. ctx->noteStatistic(statCode, value, count);
  212. }
  213. virtual void CTXLOG(const char *format, ...) const
  214. {
  215. va_list args;
  216. va_start(args, format);
  217. ctx->CTXLOGva(format, args);
  218. va_end(args);
  219. }
  220. virtual void CTXLOGva(const char *format, va_list args) const
  221. {
  222. ctx->CTXLOGva(format, args);
  223. }
  224. virtual void CTXLOGa(TracingCategory category, const char *prefix, const char *text) const
  225. {
  226. ctx->CTXLOGa(category, prefix, text);
  227. }
  228. virtual void logOperatorException(IException *E, const char *file, unsigned line, const char *format, ...) const
  229. {
  230. va_list args;
  231. va_start(args, format);
  232. ctx->logOperatorExceptionVA(E, file, line, format, args);
  233. va_end(args);
  234. }
  235. virtual void logOperatorExceptionVA(IException *E, const char *file, unsigned line, const char *format, va_list args) const
  236. {
  237. ctx->logOperatorExceptionVA(E, file, line, format, args);
  238. }
  239. virtual void CTXLOGae(IException *E, const char *file, unsigned line, const char *prefix, const char *format, ...) const
  240. {
  241. va_list args;
  242. va_start(args, format);
  243. ctx->CTXLOGaeva(E, file, line, prefix, format, args);
  244. va_end(args);
  245. }
  246. virtual void CTXLOGaeva(IException *E, const char *file, unsigned line, const char *prefix, const char *format, va_list args) const
  247. {
  248. ctx->CTXLOGaeva(E, file, line, prefix, format, args);
  249. }
  250. virtual void CTXLOGl(LogItem *log) const
  251. {
  252. ctx->CTXLOGl(log);
  253. }
  254. virtual StringBuffer &getLogPrefix(StringBuffer &ret) const
  255. {
  256. return ctx->getLogPrefix(ret);
  257. }
  258. virtual unsigned queryTraceLevel() const
  259. {
  260. return ctx->queryTraceLevel();
  261. }
  262. virtual bool isIntercepted() const
  263. {
  264. return ctx->isIntercepted();
  265. }
  266. virtual bool isBlind() const
  267. {
  268. return ctx->isBlind();
  269. }
  270. virtual unsigned parallelJoinPreload()
  271. {
  272. return ctx->parallelJoinPreload();
  273. }
  274. virtual unsigned concatPreload()
  275. {
  276. return ctx->concatPreload();
  277. }
  278. virtual unsigned fetchPreload()
  279. {
  280. return ctx->fetchPreload();
  281. }
  282. virtual unsigned fullKeyedJoinPreload()
  283. {
  284. return ctx->fullKeyedJoinPreload();
  285. }
  286. virtual unsigned keyedJoinPreload()
  287. {
  288. return ctx->keyedJoinPreload();
  289. }
  290. virtual unsigned prefetchProjectPreload()
  291. {
  292. return ctx->prefetchProjectPreload();
  293. }
  294. virtual void addSlavesReplyLen(unsigned len)
  295. {
  296. ctx->addSlavesReplyLen(len);
  297. }
  298. virtual const char *queryAuthToken()
  299. {
  300. return ctx->queryAuthToken();
  301. }
  302. virtual const IResolvedFile *resolveLFN(const char *filename, bool isOpt)
  303. {
  304. return ctx->resolveLFN(filename, isOpt);
  305. }
  306. virtual IRoxieWriteHandler *createLFN(const char *filename, bool overwrite, bool extend, const StringArray &clusters)
  307. {
  308. return ctx->createLFN(filename, overwrite, extend, clusters);
  309. }
  310. virtual void onFileCallback(const RoxiePacketHeader &header, const char *lfn, bool isOpt, bool isLocal)
  311. {
  312. ctx->onFileCallback(header, lfn, isOpt, isLocal);
  313. }
  314. virtual IActivityGraph *getLibraryGraph(const LibraryCallFactoryExtra &extra, IRoxieServerActivity *parentActivity)
  315. {
  316. return ctx->getLibraryGraph(extra, parentActivity);
  317. }
  318. virtual void noteProcessed(const IRoxieContextLogger &_activityContext, const IRoxieServerActivity *_activity, unsigned _idx, unsigned _processed, unsigned __int64 _totalCycles, unsigned __int64 _localCycles) const
  319. {
  320. ctx->noteProcessed(_activityContext, _activity, _idx, _processed, _totalCycles, _localCycles);
  321. }
  322. virtual IProbeManager *queryProbeManager() const
  323. {
  324. return ctx->queryProbeManager();
  325. }
  326. virtual IDebuggableContext *queryDebugContext() const
  327. {
  328. return ctx->queryDebugContext();
  329. }
  330. virtual bool queryTimeActivities() const
  331. {
  332. return ctx->queryTimeActivities();
  333. }
  334. virtual bool queryCheckingHeap() const
  335. {
  336. return ctx->queryCheckingHeap();
  337. }
  338. virtual void printResults(IXmlWriter *output, const char *name, unsigned sequence)
  339. {
  340. ctx->printResults(output, name, sequence);
  341. }
  342. virtual void setWUState(WUState state)
  343. {
  344. ctx->setWUState(state);
  345. }
  346. virtual bool checkWuAborted()
  347. {
  348. return ctx->checkWuAborted();
  349. }
  350. virtual IWorkUnit *updateWorkUnit() const
  351. {
  352. return ctx->updateWorkUnit();
  353. }
  354. virtual IConstWorkUnit *queryWorkUnit() const
  355. {
  356. return ctx->queryWorkUnit();
  357. }
  358. virtual IRoxieServerContext *queryServerContext()
  359. {
  360. return ctx->queryServerContext();
  361. }
  362. virtual IWorkUnitRowReader *getWorkunitRowReader(const char * name, unsigned sequence, IXmlToRowTransformer * xmlTransformer, IEngineRowAllocator *rowAllocator, bool isGrouped)
  363. {
  364. return ctx->getWorkunitRowReader(name, sequence, xmlTransformer, rowAllocator, isGrouped);
  365. }
  366. protected:
  367. IRoxieSlaveContext * ctx;
  368. };
  369. //=================================================================================
  370. #define RESULT_FLUSH_THRESHOLD 10000u
  371. #ifdef _DEBUG
  372. #define SOAP_SPLIT_THRESHOLD 100u
  373. #define SOAP_SPLIT_RESERVE 200u
  374. #else
  375. #define SOAP_SPLIT_THRESHOLD 64000u
  376. #define SOAP_SPLIT_RESERVE 65535u
  377. #endif
  378. //=================================================================================
  379. class CRoxieServerActivityFactoryBase : public CActivityFactory, implements IRoxieServerActivityFactory
  380. {
  381. protected:
  382. IntArray dependencies; // things I am dependent on
  383. IntArray dependencyIndexes; // things I am dependent on
  384. IntArray dependencyControlIds; // things I am dependent on
  385. StringArray dependencyEdgeIds; // How to describe them to the debugger
  386. unsigned dependentCount; // things dependent on me
  387. mutable CriticalSection statsCrit;
  388. mutable __int64 processed;
  389. mutable __int64 started;
  390. mutable __int64 totalCycles;
  391. mutable __int64 localCycles;
  392. public:
  393. IMPLEMENT_IINTERFACE;
  394. CRoxieServerActivityFactoryBase(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  395. : CActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  396. {
  397. processed = 0;
  398. started = 0;
  399. totalCycles = 0;
  400. localCycles = 0;
  401. dependentCount = 0;
  402. }
  403. ~CRoxieServerActivityFactoryBase()
  404. {
  405. }
  406. StringBuffer &toString(StringBuffer &ret) const
  407. {
  408. return ret.appendf("%p", this);
  409. }
  410. virtual void addDependency(unsigned _source, ThorActivityKind _kind, unsigned _sourceIdx, int controlId, const char *edgeId)
  411. {
  412. dependencies.append(_source);
  413. dependencyIndexes.append(_sourceIdx);
  414. dependencyControlIds.append(controlId);
  415. dependencyEdgeIds.append(edgeId);
  416. }
  417. virtual void noteDependent(unsigned target)
  418. {
  419. dependentCount++;
  420. }
  421. virtual IntArray &queryDependencies() { return dependencies; }
  422. virtual IntArray &queryDependencyIndexes() { return dependencyIndexes; }
  423. virtual IntArray &queryDependencyControlIds() { return dependencyControlIds; }
  424. virtual StringArray &queryDependencyEdgeIds() { return dependencyEdgeIds; }
  425. virtual unsigned queryId() const { return id; }
  426. virtual unsigned querySubgraphId() const { return subgraphId; }
  427. virtual ThorActivityKind getKind() const { return kind; }
  428. virtual IOutputMetaData * queryOutputMeta() const
  429. {
  430. return meta;
  431. }
  432. virtual bool isSink() const
  433. {
  434. return false;
  435. }
  436. virtual bool isFunction() const
  437. {
  438. return false;
  439. }
  440. virtual bool isGraphInvariant() const
  441. {
  442. return false;
  443. }
  444. virtual IHThorArg &getHelper() const
  445. {
  446. return *helperFactory();
  447. }
  448. virtual IRoxieServerActivity *createFunction(IHThorArg &arg, IProbeManager *_probeManager) const
  449. {
  450. arg.Release();
  451. throwUnexpected();
  452. }
  453. virtual void noteProcessed(unsigned idx, unsigned _processed, unsigned __int64 _totalCycles, unsigned __int64 _localCycles) const
  454. {
  455. if (_processed || _totalCycles || _localCycles)
  456. {
  457. CriticalBlock b(statsCrit);
  458. #ifdef _DEBUG
  459. assertex(_totalCycles >= _localCycles);
  460. #endif
  461. processed += _processed;
  462. totalCycles += _totalCycles;
  463. localCycles += _localCycles;
  464. }
  465. }
  466. virtual void noteStarted() const
  467. {
  468. CriticalBlock b(statsCrit);
  469. started ++;
  470. }
  471. virtual void noteStarted(unsigned idx) const
  472. {
  473. throwUnexpected(); // should be implemented/required by multiOutput cases only
  474. }
  475. virtual void getEdgeProgressInfo(unsigned output, IPropertyTree &edge) const
  476. {
  477. CriticalBlock b(statsCrit);
  478. if (output == 0)
  479. {
  480. putStatsValue(&edge, "count", "sum", processed);
  481. if (started)
  482. putStatsValue(&edge, "started", "sum", started);
  483. }
  484. else
  485. ERRLOG("unexpected call to getEdgeProcessInfo for output %d in activity %d", output, queryId());
  486. }
  487. virtual void getNodeProgressInfo(IPropertyTree &node) const
  488. {
  489. CActivityFactory::getNodeProgressInfo(node);
  490. CriticalBlock b(statsCrit);
  491. if (started)
  492. putStatsValue(&node, "_roxieStarted", "sum", started);
  493. if (totalCycles)
  494. putStatsValue(&node, "totalTime", "sum", (unsigned) (cycle_to_nanosec(totalCycles)/1000));
  495. if (localCycles)
  496. putStatsValue(&node, "localTime", "sum", (unsigned) (cycle_to_nanosec(localCycles)/1000));
  497. }
  498. virtual void resetNodeProgressInfo()
  499. {
  500. CActivityFactory::resetNodeProgressInfo();
  501. CriticalBlock b(statsCrit);
  502. started = 0;
  503. totalCycles = 0;
  504. localCycles = 0;
  505. }
  506. virtual void getActivityMetrics(StringBuffer &reply) const
  507. {
  508. CActivityFactory::getActivityMetrics(reply);
  509. CriticalBlock b(statsCrit);
  510. putStatsValue(reply, "_roxieStarted", "sum", started);
  511. putStatsValue(reply, "totalTime", "sum", (unsigned) (cycle_to_nanosec(totalCycles)/1000));
  512. putStatsValue(reply, "localTime", "sum", (unsigned) (cycle_to_nanosec(localCycles)/1000));
  513. }
  514. virtual unsigned __int64 queryLocalCycles() const
  515. {
  516. return localCycles;
  517. }
  518. virtual IQueryFactory &queryQueryFactory() const
  519. {
  520. return CActivityFactory::queryQueryFactory();
  521. }
  522. virtual ActivityArray *queryChildQuery(unsigned idx, unsigned &id)
  523. {
  524. return CActivityFactory::queryChildQuery(idx, id);
  525. }
  526. virtual void addChildQuery(unsigned id, ActivityArray *childQuery)
  527. {
  528. CActivityFactory::addChildQuery(id, childQuery);
  529. }
  530. virtual void createChildQueries(IArrayOf<IActivityGraph> &childGraphs, IRoxieServerActivity *parentActivity, IProbeManager *_probeManager, const IRoxieContextLogger &_logctx) const
  531. {
  532. ForEachItemIn(idx, childQueries)
  533. {
  534. childGraphs.append(*createActivityGraph(NULL, childQueryIndexes.item(idx), childQueries.item(idx), parentActivity, _probeManager, _logctx));
  535. }
  536. }
  537. virtual void onCreateChildQueries(IRoxieSlaveContext *ctx, IHThorArg *colocalArg, IArrayOf<IActivityGraph> &childGraphs) const
  538. {
  539. ForEachItemIn(idx, childGraphs)
  540. {
  541. ctx->noteChildGraph(childQueryIndexes.item(idx), &childGraphs.item(idx));
  542. childGraphs.item(idx).onCreate(ctx, colocalArg);
  543. }
  544. }
  545. IActivityGraph * createChildGraph(IRoxieSlaveContext * ctx, IHThorArg *colocalArg, unsigned childId, IRoxieServerActivity *parentActivity, IProbeManager * _probeManager, const IRoxieContextLogger &_logctx) const
  546. {
  547. unsigned match = childQueryIndexes.find(childId);
  548. assertex(match != NotFound);
  549. Owned<IActivityGraph> graph = createActivityGraph(NULL, childQueryIndexes.item(match), childQueries.item(match), parentActivity, _probeManager, _logctx);
  550. graph->onCreate(ctx, colocalArg);
  551. return graph.getClear();
  552. }
  553. virtual IRoxieServerSideCache *queryServerSideCache() const
  554. {
  555. return NULL; // Activities that wish to support server-side caching will need to do better....
  556. }
  557. virtual bool getEnableFieldTranslation() const
  558. {
  559. throwUnexpected(); // only implemented by index-related subclasses
  560. }
  561. virtual IDefRecordMeta *queryActivityMeta() const
  562. {
  563. throwUnexpected(); // only implemented by index-related subclasses
  564. }
  565. virtual void noteStatistic(unsigned statCode, unsigned __int64 value, unsigned count) const
  566. {
  567. mystats.noteStatistic(statCode, value, count);
  568. }
  569. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  570. {
  571. // Most activities have nothing to say...
  572. }
  573. };
  574. class CRoxieServerMultiInputInfo
  575. {
  576. private:
  577. UnsignedArray inputs;
  578. UnsignedArray inputIndexes;
  579. public:
  580. void set(unsigned idx, unsigned source, unsigned sourceidx)
  581. {
  582. if (idx==inputs.length())
  583. {
  584. inputs.append(source);
  585. inputIndexes.append(sourceidx);
  586. }
  587. else
  588. {
  589. while (!inputs.isItem(idx))
  590. {
  591. inputs.append(0);
  592. inputIndexes.append(0);
  593. }
  594. inputs.replace(source, idx);
  595. inputIndexes.replace(sourceidx, idx);
  596. }
  597. }
  598. unsigned get(unsigned idx, unsigned &sourceidx) const
  599. {
  600. if (inputs.isItem(idx))
  601. {
  602. sourceidx = inputIndexes.item(idx);
  603. return inputs.item(idx);
  604. }
  605. else
  606. return (unsigned) -1;
  607. }
  608. inline unsigned ordinality() const { return inputs.ordinality(); }
  609. };
  610. class CRoxieServerMultiInputFactory : public CRoxieServerActivityFactoryBase
  611. {
  612. private:
  613. CRoxieServerMultiInputInfo inputs;
  614. public:
  615. IMPLEMENT_IINTERFACE;
  616. CRoxieServerMultiInputFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  617. : CRoxieServerActivityFactoryBase(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  618. {
  619. }
  620. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  621. {
  622. inputs.set(idx, source, sourceidx);
  623. }
  624. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  625. {
  626. return inputs.get(idx, sourceidx);
  627. }
  628. virtual unsigned numInputs() const { return inputs.ordinality(); }
  629. };
  630. class CWrappedException : public CInterface, implements IException
  631. {
  632. Owned<IException> wrapped;
  633. ThorActivityKind kind;
  634. unsigned queryId;
  635. public:
  636. IMPLEMENT_IINTERFACE;
  637. CWrappedException(IException *_wrapped, ThorActivityKind _kind, unsigned _queryId)
  638. : wrapped(_wrapped), kind(_kind), queryId(_queryId)
  639. {
  640. }
  641. virtual int errorCode() const { return wrapped->errorCode(); }
  642. virtual StringBuffer & errorMessage(StringBuffer &msg) const { return wrapped->errorMessage(msg).appendf(" (in %s %d)", getActivityText(kind), queryId); }
  643. virtual MessageAudience errorAudience() const { return wrapped->errorAudience(); }
  644. };
  645. class CRoxieServerActivityFactory : public CRoxieServerActivityFactoryBase
  646. {
  647. protected:
  648. unsigned input;
  649. unsigned inputidx;
  650. public:
  651. IMPLEMENT_IINTERFACE;
  652. CRoxieServerActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  653. : CRoxieServerActivityFactoryBase(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  654. {
  655. input = (unsigned) -1;
  656. inputidx = 0;
  657. }
  658. inline void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  659. {
  660. if (idx != 0)
  661. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: id = %d : setInput() parameter out of bounds idx = %d at %s(%d)", id, idx, __FILE__, __LINE__);
  662. if (input != -1)
  663. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: id = %d : setInput() called twice for input = %d source = %d inputidx = %d sourceidx = %d at %s(%d)", id, input, source, inputidx, sourceidx, __FILE__, __LINE__);
  664. input = source;
  665. inputidx = sourceidx;
  666. }
  667. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  668. {
  669. if (!idx)
  670. {
  671. sourceidx = inputidx;
  672. return input;
  673. }
  674. return (unsigned) -1;
  675. }
  676. virtual unsigned numInputs() const { return (input == (unsigned)-1) ? 0 : 1; }
  677. };
  678. class CRoxieServerMultiOutputFactory : public CRoxieServerActivityFactory
  679. {
  680. protected:
  681. unsigned numOutputs;
  682. unsigned __int64 *processedArray;
  683. bool *startedArray;
  684. CRoxieServerMultiOutputFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  685. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  686. {
  687. numOutputs = 0;
  688. processedArray = NULL;
  689. startedArray = NULL;
  690. }
  691. ~CRoxieServerMultiOutputFactory()
  692. {
  693. delete [] processedArray;
  694. delete [] startedArray;
  695. }
  696. void setNumOutputs(unsigned num)
  697. {
  698. numOutputs = num;
  699. if (!num)
  700. num = 1; // Even sink activities like to track how many records they process
  701. processedArray = new unsigned __int64[num];
  702. startedArray = new bool[num];
  703. for (unsigned i = 0; i < num; i++)
  704. {
  705. processedArray[i] = 0;
  706. startedArray[i] = 0;
  707. }
  708. }
  709. virtual void getEdgeProgressInfo(unsigned idx, IPropertyTree &edge) const
  710. {
  711. assertex(numOutputs ? idx < numOutputs : idx==0);
  712. CriticalBlock b(statsCrit);
  713. putStatsValue(&edge, "count", "sum", processedArray[idx]);
  714. putStatsValue(&edge, "started", "sum", startedArray[idx]);
  715. }
  716. virtual void noteProcessed(unsigned idx, unsigned _processed, unsigned __int64 _totalCycles, unsigned __int64 _localCycles) const
  717. {
  718. assertex(numOutputs ? idx < numOutputs : idx==0);
  719. CriticalBlock b(statsCrit);
  720. processedArray[idx] += _processed;
  721. totalCycles += _totalCycles;
  722. localCycles += _localCycles;
  723. }
  724. virtual void noteStarted(unsigned idx) const
  725. {
  726. assertex(numOutputs ? idx < numOutputs : idx==0);
  727. CriticalBlock b(statsCrit);
  728. startedArray[idx] = true;
  729. }
  730. };
  731. class CRoxieServerInternalSinkFactory : public CRoxieServerActivityFactory
  732. {
  733. protected:
  734. bool isInternal;
  735. bool isRoot;
  736. unsigned usageCount;
  737. public:
  738. CRoxieServerInternalSinkFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  739. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  740. {
  741. usageCount = _usageCount;
  742. isRoot = _isRoot;
  743. isInternal = false; // filled in by derived class constructor
  744. }
  745. virtual bool isSink() const
  746. {
  747. //only a sink if a root activity
  748. return isRoot && !(isInternal && dependentCount && dependentCount==usageCount); // MORE - it's possible for this to get the answer wrong still, since usageCount does not include references from main procedure. Gavin?
  749. }
  750. virtual void getEdgeProgressInfo(unsigned idx, IPropertyTree &edge) const
  751. {
  752. // There is no meaningful info to return along the dependency edge - we don't detect how many times the value has been read from the context
  753. // Just leave it blank is safest.
  754. }
  755. };
  756. typedef enum { STATEreset, STATEstarted, STATEstopped, STATEstarting } activityState;
  757. const char *queryStateText(activityState state)
  758. {
  759. switch (state)
  760. {
  761. case STATEreset: return "reset";
  762. case STATEstarted: return "started";
  763. case STATEstopped: return "stopped";
  764. case STATEstarting: return "starting";
  765. default: return "unknown";
  766. }
  767. }
  768. typedef ICopyArrayOf<IRoxieServerActivity> IRoxieServerActivityCopyArray;
  769. class CParallelActivityExecutor : public CAsyncFor
  770. {
  771. public:
  772. unsigned parentExtractSize;
  773. const byte * parentExtract;
  774. CParallelActivityExecutor(IRoxieServerActivityCopyArray & _activities, unsigned _parentExtractSize, const byte * _parentExtract) :
  775. activities(_activities), parentExtractSize(_parentExtractSize), parentExtract(_parentExtract) { }
  776. void Do(unsigned i)
  777. {
  778. activities.item(i).execute(parentExtractSize, parentExtract);
  779. }
  780. private:
  781. IRoxieServerActivityCopyArray & activities;
  782. };
  783. class CRoxieServerActivity : public CInterface, implements IRoxieServerActivity, implements IRoxieInput, implements IRoxieContextLogger
  784. {
  785. protected:
  786. IRoxieInput *input;
  787. IHThorArg &basehelper;
  788. IRoxieSlaveContext *ctx;
  789. const IRoxieServerActivityFactory *factory;
  790. IRoxieServerActivityCopyArray dependencies;
  791. IntArray dependencyControlIds;
  792. IArrayOf<IActivityGraph> childGraphs;
  793. CachedOutputMetaData meta;
  794. IHThorArg *colocalParent;
  795. IEngineRowAllocator *rowAllocator;
  796. CriticalSection statecrit;
  797. mutable StatsCollector stats;
  798. unsigned processed;
  799. unsigned __int64 totalCycles;
  800. unsigned activityId;
  801. activityState state;
  802. bool createPending;
  803. bool debugging;
  804. public:
  805. IMPLEMENT_IINTERFACE;
  806. CRoxieServerActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  807. : factory(_factory),
  808. basehelper(_factory->getHelper()),
  809. activityId(_factory->queryId())
  810. {
  811. input = NULL;
  812. ctx = NULL;
  813. meta.set(basehelper.queryOutputMeta());
  814. processed = 0;
  815. totalCycles = 0;
  816. if (factory)
  817. factory->createChildQueries(childGraphs, this, _probeManager, *this);
  818. state=STATEreset;
  819. rowAllocator = NULL;
  820. debugging = _probeManager != NULL; // Don't want to collect timing stats from debug sessions
  821. colocalParent = NULL;
  822. createPending = true;
  823. }
  824. CRoxieServerActivity(IHThorArg & _helper) : factory(NULL), basehelper(_helper)
  825. {
  826. activityId = 0;
  827. input = NULL;
  828. ctx = NULL;
  829. meta.set(basehelper.queryOutputMeta());
  830. processed = 0;
  831. totalCycles = 0;
  832. state=STATEreset;
  833. rowAllocator = NULL;
  834. debugging = false;
  835. colocalParent = NULL;
  836. createPending = true;
  837. }
  838. inline ~CRoxieServerActivity()
  839. {
  840. CriticalBlock cb(statecrit);
  841. if (traceStartStop)
  842. DBGLOG("%p destroy state=%s", this, queryStateText(state)); // Note- CTXLOG may not be safe
  843. if (state!=STATEreset)
  844. {
  845. DBGLOG("STATE: Activity %d destroyed but not reset", activityId);
  846. state = STATEreset; // bit pointless but there you go...
  847. }
  848. basehelper.Release();
  849. ::Release(rowAllocator);
  850. }
  851. virtual const IRoxieContextLogger &queryLogCtx()const
  852. {
  853. return *this;
  854. }
  855. inline void createRowAllocator()
  856. {
  857. if (!rowAllocator)
  858. rowAllocator = ctx->queryCodeContext()->getRowAllocator(meta.queryOriginal(), activityId);
  859. }
  860. // MORE - most of this is copied from ccd.hpp - can't we refactor?
  861. virtual void CTXLOG(const char *format, ...) const
  862. {
  863. va_list args;
  864. va_start(args, format);
  865. CTXLOGva(format, args);
  866. va_end(args);
  867. }
  868. virtual void CTXLOGva(const char *format, va_list args) const
  869. {
  870. StringBuffer text, prefix;
  871. getLogPrefix(prefix);
  872. text.valist_appendf(format, args);
  873. CTXLOGa(LOG_TRACING, prefix.str(), text.str());
  874. }
  875. virtual void CTXLOGa(TracingCategory category, const char *prefix, const char *text) const
  876. {
  877. if (ctx)
  878. ctx->CTXLOGa(category, prefix, text);
  879. else
  880. DBGLOG("[%s] %s", prefix, text);
  881. }
  882. virtual void logOperatorException(IException *E, const char *file, unsigned line, const char *format, ...) const
  883. {
  884. va_list args;
  885. va_start(args, format);
  886. StringBuffer prefix;
  887. getLogPrefix(prefix);
  888. CTXLOGaeva(E, file, line, prefix.str(), format, args);
  889. va_end(args);
  890. }
  891. virtual void logOperatorExceptionVA(IException *E, const char *file, unsigned line, const char *format, va_list args) const
  892. {
  893. StringBuffer prefix;
  894. getLogPrefix(prefix);
  895. CTXLOGaeva(E, file, line, prefix.str(), format, args);
  896. }
  897. virtual void CTXLOGae(IException *E, const char *file, unsigned line, const char *prefix, const char *format, ...) const
  898. {
  899. va_list args;
  900. va_start(args, format);
  901. CTXLOGaeva(E, file, line, prefix, format, args);
  902. va_end(args);
  903. }
  904. virtual void CTXLOGaeva(IException *E, const char *file, unsigned line, const char *prefix, const char *format, va_list args) const
  905. {
  906. if (ctx)
  907. ctx->CTXLOGaeva(E, file, line, prefix, format, args);
  908. else
  909. {
  910. StringBuffer ss;
  911. ss.appendf("[%s] ERROR", prefix);
  912. if (E)
  913. ss.append(": ").append(E->errorCode());
  914. if (file)
  915. ss.appendf(": %s(%d) ", file, line);
  916. if (E)
  917. E->errorMessage(ss.append(": "));
  918. if (format)
  919. {
  920. ss.append(": ").valist_appendf(format, args);
  921. }
  922. LOG(MCoperatorProgress, unknownJob, "%s", ss.str());
  923. }
  924. }
  925. virtual void CTXLOGl(LogItem *log) const
  926. {
  927. if (ctx)
  928. ctx->CTXLOGl(log);
  929. else
  930. {
  931. assert(ctx);
  932. log->Release(); // Should never happen
  933. }
  934. }
  935. virtual void noteStatistic(unsigned statCode, unsigned __int64 value, unsigned count) const
  936. {
  937. if (factory)
  938. factory->noteStatistic(statCode, value, count);
  939. if (ctx)
  940. ctx->noteStatistic(statCode, value, count);
  941. stats.noteStatistic(statCode, value, count);
  942. }
  943. virtual StringBuffer &getLogPrefix(StringBuffer &ret) const
  944. {
  945. if (ctx)
  946. ctx->getLogPrefix(ret);
  947. return ret.append('@').append(activityId);
  948. }
  949. virtual bool isIntercepted() const
  950. {
  951. return ctx ? ctx->isIntercepted() : false;
  952. }
  953. virtual bool isBlind() const
  954. {
  955. return ctx ? ctx->isBlind() : blindLogging;
  956. }
  957. virtual unsigned queryTraceLevel() const
  958. {
  959. if (ctx)
  960. return ctx->queryTraceLevel();
  961. else
  962. return traceLevel;
  963. }
  964. virtual bool isPassThrough()
  965. {
  966. return false;
  967. }
  968. virtual const IResolvedFile *resolveLFN(const char *filename, bool isOpt)
  969. {
  970. return ctx->resolveLFN(filename, isOpt);
  971. }
  972. virtual const IResolvedFile *queryVarFileInfo() const
  973. {
  974. throwUnexpected(); // should be implemented in more derived class by anyone that has a remote adaptor
  975. return NULL;
  976. }
  977. virtual void serializeSkipInfo(MemoryBuffer &out, unsigned seekLen, const void *rawSeek, unsigned numFields, const void * seek, const SmartStepExtra &stepExtra) const
  978. {
  979. throwUnexpected(); // should be implemented in more derived class wherever needed
  980. }
  981. virtual IRoxieSlaveContext *queryContext()
  982. {
  983. return ctx;
  984. }
  985. virtual IRoxieServerActivity *queryActivity() { return this; }
  986. virtual IIndexReadActivityInfo *queryIndexReadActivity() { return NULL; }
  987. virtual bool needsAllocator() const { return false; }
  988. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  989. {
  990. ctx = _ctx;
  991. colocalParent = _colocalParent;
  992. createPending = true;
  993. if (needsAllocator())
  994. createRowAllocator();
  995. processed = 0;
  996. totalCycles = 0;
  997. if (factory)
  998. factory->onCreateChildQueries(_ctx, &basehelper, childGraphs);
  999. }
  1000. virtual void serializeCreateStartContext(MemoryBuffer &out)
  1001. {
  1002. //This should only be called after onStart has been called on the helper
  1003. assertex(!createPending);
  1004. assertex(state==STATEstarted);
  1005. unsigned startlen = out.length();
  1006. basehelper.serializeCreateContext(out);
  1007. basehelper.serializeStartContext(out);
  1008. if (queryTraceLevel() > 10)
  1009. CTXLOG("serializeCreateStartContext for %d added %d bytes", activityId, out.length()-startlen);
  1010. }
  1011. virtual void serializeExtra(MemoryBuffer &out) {}
  1012. inline void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  1013. {
  1014. CriticalBlock cb(statecrit);
  1015. if (state != STATEreset && state != STATEstarting)
  1016. {
  1017. CTXLOG("STATE: Expected state to be reset, but was %s, in activity %d", queryStateText(state), activityId);
  1018. }
  1019. state=STATEstarted;
  1020. #ifdef TRACE_STARTSTOP
  1021. if (traceStartStop)
  1022. {
  1023. CTXLOG("start %d", activityId);
  1024. if (watchActivityId && watchActivityId==activityId)
  1025. {
  1026. CTXLOG("WATCH: start %d", activityId);
  1027. }
  1028. }
  1029. #endif
  1030. executeDependencies(parentExtractSize, parentExtract, 0);
  1031. if (input)
  1032. input->start(parentExtractSize, parentExtract, paused);
  1033. ensureCreated();
  1034. basehelper.onStart(parentExtract, NULL);
  1035. if (factory)
  1036. factory->noteStarted();
  1037. }
  1038. void executeDependencies(unsigned parentExtractSize, const byte *parentExtract, unsigned controlId)
  1039. {
  1040. //MORE: Create a filtered list and then use asyncfor
  1041. ForEachItemIn(idx, dependencies)
  1042. {
  1043. if (dependencyControlIds.item(idx) == controlId)
  1044. dependencies.item(idx).execute(parentExtractSize, parentExtract);
  1045. }
  1046. }
  1047. virtual unsigned __int64 queryTotalCycles() const
  1048. {
  1049. return totalCycles;
  1050. }
  1051. virtual unsigned __int64 queryLocalCycles() const
  1052. {
  1053. __int64 ret = totalCycles;
  1054. if (input) ret -= input->queryTotalCycles();
  1055. if (ret < 0)
  1056. ret = 0;
  1057. return ret;
  1058. }
  1059. virtual IRoxieInput *queryInput(unsigned idx) const
  1060. {
  1061. if (idx==0)
  1062. return input;
  1063. else
  1064. return NULL;
  1065. }
  1066. void noteProcessed(unsigned _idx, unsigned _processed, unsigned __int64 _totalCycles, unsigned __int64 _localCycles) const
  1067. {
  1068. if (factory)
  1069. {
  1070. if (!debugging)
  1071. factory->noteProcessed(_idx, _processed, _totalCycles, _localCycles);
  1072. if (ctx)
  1073. ctx->noteProcessed(*this, this, _idx, _processed, _totalCycles, _localCycles);
  1074. }
  1075. }
  1076. inline void ensureCreated()
  1077. {
  1078. if (createPending)
  1079. {
  1080. createPending = false;
  1081. basehelper.onCreate(ctx->queryCodeContext(), colocalParent, NULL);
  1082. }
  1083. }
  1084. inline void stop(bool aborting)
  1085. {
  1086. if (state != STATEstopped)
  1087. {
  1088. CriticalBlock cb(statecrit);
  1089. if (state != STATEstopped)
  1090. {
  1091. state=STATEstopped;
  1092. #ifdef TRACE_STARTSTOP
  1093. if (traceStartStop)
  1094. {
  1095. CTXLOG("stop %d", activityId);
  1096. if (watchActivityId && watchActivityId==activityId)
  1097. {
  1098. CTXLOG("WATCH: stop %d", activityId);
  1099. }
  1100. }
  1101. #endif
  1102. if (input)
  1103. input->stop(aborting);
  1104. }
  1105. }
  1106. }
  1107. inline void reset()
  1108. {
  1109. if (state != STATEreset)
  1110. {
  1111. CriticalBlock cb(statecrit);
  1112. if (state != STATEreset)
  1113. {
  1114. if (state==STATEstarted || state==STATEstarting)
  1115. {
  1116. CTXLOG("STATE: activity %d reset without stop", activityId);
  1117. stop(false);
  1118. }
  1119. if (ctx->queryTimeActivities())
  1120. {
  1121. stats.dumpStats(*this);
  1122. StringBuffer prefix, text;
  1123. getLogPrefix(prefix);
  1124. text.appendf("records processed - %d", processed);
  1125. CTXLOGa(LOG_STATISTICS, prefix.str(), text.str());
  1126. text.clear().appendf("total time - %d us", (unsigned) (cycle_to_nanosec(totalCycles)/1000));
  1127. CTXLOGa(LOG_STATISTICS, prefix.str(), text.str());
  1128. text.clear().appendf("local time - %d us", (unsigned) (cycle_to_nanosec(queryLocalCycles())/1000));
  1129. CTXLOGa(LOG_STATISTICS, prefix.str(), text.str());
  1130. }
  1131. state = STATEreset;
  1132. #ifdef TRACE_STARTSTOP
  1133. if (traceStartStop)
  1134. {
  1135. CTXLOG("reset %d", activityId);
  1136. if (watchActivityId && watchActivityId==activityId)
  1137. {
  1138. CTXLOG("WATCH: reset %d", activityId);
  1139. }
  1140. }
  1141. #endif
  1142. ForEachItemIn(idx, dependencies)
  1143. dependencies.item(idx).reset();
  1144. noteProcessed(0, processed, totalCycles, queryLocalCycles());
  1145. if (input)
  1146. input->reset();
  1147. processed = 0;
  1148. totalCycles = 0;
  1149. }
  1150. }
  1151. }
  1152. virtual void addDependency(IRoxieServerActivity &source, unsigned sourceIdx, int controlId)
  1153. {
  1154. dependencies.append(source);
  1155. dependencyControlIds.append(controlId);
  1156. }
  1157. virtual void resetEOF()
  1158. {
  1159. //would make more sense if the default implementation (and eof member) were in the base class
  1160. }
  1161. // Sink activities should override this....
  1162. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  1163. {
  1164. throw MakeStringException(ROXIE_SINK, "Internal error: execute() requires a sink");
  1165. }
  1166. virtual void executeChild(size32_t & retSize, void * & ret, unsigned parentExtractSize, const byte * parentExtract)
  1167. {
  1168. throw MakeStringException(ROXIE_SINK, "Internal error: executeChild() requires a suitable sink");
  1169. }
  1170. virtual __int64 evaluate()
  1171. {
  1172. throw MakeStringException(ROXIE_SINK, "Internal error: evaluate() requires a function");
  1173. }
  1174. virtual IRoxieInput * querySelectOutput(unsigned id)
  1175. {
  1176. return NULL;
  1177. }
  1178. virtual bool querySetStreamInput(unsigned id, IRoxieInput * _input)
  1179. {
  1180. return false;
  1181. }
  1182. virtual void setInput(unsigned idx, IRoxieInput *_in)
  1183. {
  1184. assertex(!idx);
  1185. input = _in;
  1186. }
  1187. virtual IRoxieInput *queryOutput(unsigned idx)
  1188. {
  1189. if (idx == (unsigned) -1)
  1190. idx = 0;
  1191. return idx ? NULL : this;
  1192. }
  1193. virtual IOutputMetaData *queryOutputMeta() const
  1194. {
  1195. return meta.queryOriginal();
  1196. }
  1197. virtual unsigned queryId() const
  1198. {
  1199. return activityId;
  1200. }
  1201. virtual unsigned querySubgraphId() const
  1202. {
  1203. return factory->querySubgraphId();
  1204. }
  1205. virtual void checkAbort()
  1206. {
  1207. ctx->checkAbort();
  1208. }
  1209. IException *makeWrappedException(IException *e)
  1210. {
  1211. StringBuffer msg;
  1212. ThorActivityKind activityKind = factory ? factory->getKind() : TAKnone;
  1213. CTXLOG("makeWrappedException - %s (in %s %d)", e->errorMessage(msg).str(), getActivityText(activityKind), activityId);
  1214. if (QUERYINTERFACE(e, CWrappedException) || QUERYINTERFACE(e, IUserException))
  1215. return e;
  1216. else
  1217. return new CWrappedException(e, activityKind, activityId);
  1218. }
  1219. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract)
  1220. {
  1221. }
  1222. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract, IProbeManager *probeManager, IArrayOf<IRoxieInput> &probes)
  1223. {
  1224. }
  1225. virtual void resetOutputsUsed()
  1226. {
  1227. }
  1228. virtual void noteOutputUsed()
  1229. {
  1230. }
  1231. virtual IRoxieServerSideCache *queryServerSideCache() const
  1232. {
  1233. return factory->queryServerSideCache();
  1234. }
  1235. virtual const IRoxieServerActivityFactory *queryFactory() const
  1236. {
  1237. return factory;
  1238. }
  1239. inline ThorActivityKind getKind() const
  1240. {
  1241. return factory->getKind();
  1242. }
  1243. inline bool isSink() const
  1244. {
  1245. return (factory != NULL) && factory->isSink();
  1246. }
  1247. };
  1248. //=====================================================================================================
  1249. class CRoxieServerLateStartActivity : public CRoxieServerActivity
  1250. {
  1251. protected:
  1252. IRoxieInput *input; // Don't use base class input field as we want to delay starts
  1253. bool prefiltered;
  1254. bool eof;
  1255. void lateStart(unsigned parentExtractSize, const byte *parentExtract, bool any)
  1256. {
  1257. prefiltered = !any;
  1258. eof = prefiltered;
  1259. if (!prefiltered)
  1260. input->start(parentExtractSize, parentExtract, false);
  1261. else
  1262. {
  1263. if (traceStartStop)
  1264. CTXLOG("lateStart activity stopping input early as prefiltered");
  1265. input->stop(false);
  1266. }
  1267. }
  1268. public:
  1269. CRoxieServerLateStartActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  1270. : CRoxieServerActivity(_factory, _probeManager)
  1271. {
  1272. input = NULL;
  1273. prefiltered = false;
  1274. eof = false;
  1275. }
  1276. virtual void stop(bool aborting)
  1277. {
  1278. if (!prefiltered)
  1279. {
  1280. input->stop(aborting);
  1281. }
  1282. else if (traceStartStop)
  1283. CTXLOG("lateStart activity NOT stopping input late as prefiltered");
  1284. CRoxieServerActivity::stop(aborting);
  1285. }
  1286. virtual unsigned __int64 queryLocalCycles() const
  1287. {
  1288. __int64 localCycles = totalCycles - input->queryTotalCycles();
  1289. if (localCycles < 0)
  1290. localCycles = 0;
  1291. return localCycles;
  1292. }
  1293. virtual IRoxieInput *queryInput(unsigned idx) const
  1294. {
  1295. if (idx==0)
  1296. return input;
  1297. else
  1298. return NULL;
  1299. }
  1300. virtual void reset()
  1301. {
  1302. CRoxieServerActivity::reset();
  1303. input->reset();
  1304. prefiltered = false;
  1305. }
  1306. virtual void setInput(unsigned idx, IRoxieInput *_in)
  1307. {
  1308. assertex(!idx);
  1309. input = _in;
  1310. }
  1311. };
  1312. //=====================================================================================================
  1313. atomic_t nextInstanceId;
  1314. extern unsigned getNextInstanceId()
  1315. {
  1316. return atomic_add_exchange(&nextInstanceId, 1)+1;
  1317. }
  1318. atomic_t nextRuid;
  1319. ruid_t getNextRuid()
  1320. {
  1321. ruid_t ret = atomic_add_exchange(&nextRuid, 1)+1;
  1322. while (ret < RUID_FIRST)
  1323. ret = atomic_add_exchange(&nextRuid, 1)+1; // ruids 0 and 1 are reserved for pings/unwanted discarder.
  1324. return ret;
  1325. }
  1326. void setStartRuid(unsigned restarts)
  1327. {
  1328. atomic_set(&nextRuid, restarts * 0x10000);
  1329. atomic_set(&nextInstanceId, restarts * 10000);
  1330. }
  1331. enum { LimitSkipErrorCode = 0, KeyedLimitSkipErrorCode = 1 };
  1332. class LimitSkipException : public CInterface, public IException
  1333. {
  1334. int code;
  1335. public:
  1336. LimitSkipException(int _code) { code = _code; }
  1337. IMPLEMENT_IINTERFACE;
  1338. virtual int errorCode() const { return code; }
  1339. virtual StringBuffer & errorMessage(StringBuffer &msg) const { return msg.append("LimitSkipException"); }
  1340. virtual MessageAudience errorAudience() const { return MSGAUD_internal; }
  1341. };
  1342. IException *makeLimitSkipException(bool isKeyed)
  1343. {
  1344. // We need to make sure what we throw is IException not something derived from it....
  1345. return new LimitSkipException(isKeyed ? KeyedLimitSkipErrorCode : LimitSkipErrorCode);
  1346. }
  1347. //=================================================================================
  1348. interface IRecordPullerCallback : extends IExceptionHandler
  1349. {
  1350. virtual void processRow(const void *row) = 0;
  1351. virtual void processEOG() = 0;
  1352. virtual void processGroup(const ConstPointerArray &rows) = 0;
  1353. virtual void processDone() = 0;
  1354. };
  1355. class RecordPullerThread : public RestartableThread
  1356. {
  1357. protected:
  1358. IRoxieInput *input;
  1359. IRecordPullerCallback *helper;
  1360. Semaphore started; // MORE: GH->RKC I'm pretty sure this can be deleted, since handled by RestartableThread
  1361. bool groupAtOnce, eof, eog;
  1362. CriticalSection crit;
  1363. public:
  1364. RecordPullerThread(bool _groupAtOnce)
  1365. : RestartableThread("RecordPullerThread"), groupAtOnce(_groupAtOnce)
  1366. {
  1367. input = NULL;
  1368. helper = NULL;
  1369. eof = eog = FALSE;
  1370. }
  1371. inline unsigned __int64 queryTotalCycles() const
  1372. {
  1373. return input->queryTotalCycles();
  1374. }
  1375. void setInput(IRecordPullerCallback *_helper, IRoxieInput *_input)
  1376. {
  1377. helper = _helper;
  1378. input = _input;
  1379. }
  1380. IRoxieInput *queryInput() const
  1381. {
  1382. return input;
  1383. }
  1384. void start(unsigned parentExtractSize, const byte *parentExtract, bool paused, unsigned preload, bool noThread, IRoxieSlaveContext *ctx)
  1385. {
  1386. eof = false;
  1387. eog = false;
  1388. input->start(parentExtractSize, parentExtract, paused);
  1389. try
  1390. {
  1391. if (preload && !paused)
  1392. {
  1393. if (traceLevel > 4)
  1394. DBGLOG("Preload fetching first %d records", preload);
  1395. if (groupAtOnce)
  1396. pullGroups(preload);
  1397. else
  1398. pullRecords(preload);
  1399. }
  1400. if (eof)
  1401. {
  1402. if (traceLevel > 4)
  1403. DBGLOG("No need to start puller after preload");
  1404. helper->processDone();
  1405. }
  1406. else
  1407. {
  1408. if (!noThread)
  1409. {
  1410. StringBuffer logPrefix("[");
  1411. if (ctx) ctx->getLogPrefix(logPrefix);
  1412. logPrefix.append("] ");
  1413. RestartableThread::start(logPrefix);
  1414. started.wait();
  1415. }
  1416. }
  1417. }
  1418. catch (IException *e)
  1419. {
  1420. helper->fireException(e);
  1421. }
  1422. catch (...)
  1423. {
  1424. helper->fireException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unexpected exception caught in RecordPullerThread::start"));
  1425. }
  1426. }
  1427. void stop(bool aborting)
  1428. {
  1429. if (traceStartStop)
  1430. DBGLOG("RecordPullerThread::stop");
  1431. {
  1432. 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.
  1433. input->stop(aborting);
  1434. }
  1435. RestartableThread::join();
  1436. }
  1437. void reset()
  1438. {
  1439. input->reset();
  1440. }
  1441. virtual int run()
  1442. {
  1443. started.signal();
  1444. try
  1445. {
  1446. if (groupAtOnce)
  1447. pullGroups((unsigned) -1);
  1448. else
  1449. pullRecords((unsigned) -1);
  1450. helper->processDone();
  1451. }
  1452. catch (IException *e)
  1453. {
  1454. helper->fireException(e);
  1455. }
  1456. catch (...)
  1457. {
  1458. helper->fireException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unexpected exception caught in RecordPullerThread::run"));
  1459. }
  1460. return 0;
  1461. }
  1462. void done()
  1463. {
  1464. helper->processDone();
  1465. }
  1466. bool pullRecords(unsigned preload)
  1467. {
  1468. if (eof)
  1469. return false;
  1470. while (preload)
  1471. {
  1472. const void * row;
  1473. {
  1474. CriticalBlock c(crit); // See comments in stop for why this is needed
  1475. row = input->nextInGroup();
  1476. }
  1477. if (row)
  1478. {
  1479. eog = false;
  1480. helper->processRow(row);
  1481. }
  1482. else if (!eog)
  1483. {
  1484. helper->processEOG();
  1485. eog = true;
  1486. }
  1487. else
  1488. {
  1489. eof = true;
  1490. return false;
  1491. }
  1492. if (preload != (unsigned) -1)
  1493. preload--;
  1494. }
  1495. return true;
  1496. }
  1497. void pullGroups(unsigned preload)
  1498. {
  1499. ConstPointerArray thisGroup;
  1500. unsigned rowsDone = 0;
  1501. while (preload && !eof)
  1502. {
  1503. const void *row;
  1504. {
  1505. CriticalBlock c(crit);
  1506. row = input->nextInGroup();
  1507. }
  1508. if (row)
  1509. {
  1510. thisGroup.append(row);
  1511. rowsDone++;
  1512. }
  1513. else if (thisGroup.length())
  1514. {
  1515. helper->processGroup(thisGroup);
  1516. thisGroup.kill();
  1517. if (preload != (unsigned) -1)
  1518. {
  1519. if (preload > rowsDone)
  1520. preload -= rowsDone;
  1521. else
  1522. break;
  1523. }
  1524. rowsDone = 0;
  1525. }
  1526. else
  1527. {
  1528. eof = true;
  1529. break;
  1530. }
  1531. }
  1532. }
  1533. };
  1534. //=================================================================================
  1535. #define READAHEAD_SIZE 1000
  1536. // MORE - this code copied from ThreadedConcat code - may be able to common up some.
  1537. class CRoxieServerReadAheadInput : public CInterface, implements IRoxieInput, implements IRecordPullerCallback
  1538. {
  1539. QueueOf<const void, true> buffer;
  1540. InterruptableSemaphore ready;
  1541. InterruptableSemaphore space;
  1542. CriticalSection crit;
  1543. bool eof;
  1544. bool disabled;
  1545. RecordPullerThread puller;
  1546. unsigned preload;
  1547. unsigned __int64 totalCycles;
  1548. IRoxieSlaveContext *ctx;
  1549. public:
  1550. IMPLEMENT_IINTERFACE;
  1551. CRoxieServerReadAheadInput(unsigned _preload) : puller(true), preload(_preload)
  1552. {
  1553. eof = false;
  1554. disabled = false;
  1555. totalCycles = 0;
  1556. ctx = NULL;
  1557. }
  1558. void onCreate(IRoxieSlaveContext *_ctx)
  1559. {
  1560. ctx = _ctx;
  1561. disabled = (ctx->queryDebugContext() != NULL);
  1562. }
  1563. virtual IRoxieServerActivity *queryActivity()
  1564. {
  1565. return puller.queryInput()->queryActivity();
  1566. }
  1567. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  1568. {
  1569. return puller.queryInput()->queryIndexReadActivity();
  1570. }
  1571. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  1572. {
  1573. eof = false;
  1574. totalCycles = 0;
  1575. if (disabled)
  1576. puller.queryInput()->start(parentExtractSize, parentExtract, paused);
  1577. else
  1578. {
  1579. space.reinit(READAHEAD_SIZE);
  1580. ready.reinit();
  1581. puller.start(parentExtractSize, parentExtract, paused, preload, false, ctx);
  1582. }
  1583. }
  1584. virtual void stop(bool aborting)
  1585. {
  1586. if (disabled)
  1587. puller.queryInput()->stop(aborting);
  1588. else
  1589. {
  1590. space.interrupt();
  1591. ready.interrupt();
  1592. puller.stop(aborting);
  1593. }
  1594. }
  1595. virtual void reset()
  1596. {
  1597. if (disabled)
  1598. puller.queryInput()->reset();
  1599. else
  1600. {
  1601. puller.reset();
  1602. ForEachItemIn(idx1, buffer)
  1603. ReleaseRoxieRow(buffer.item(idx1));
  1604. buffer.clear();
  1605. }
  1606. }
  1607. virtual void resetEOF()
  1608. {
  1609. throwUnexpected();
  1610. }
  1611. virtual IOutputMetaData * queryOutputMeta() const
  1612. {
  1613. return puller.queryInput()->queryOutputMeta();
  1614. }
  1615. virtual void checkAbort()
  1616. {
  1617. puller.queryInput()->checkAbort();
  1618. }
  1619. void setInput(unsigned idx, IRoxieInput *_in)
  1620. {
  1621. assertex(!idx);
  1622. puller.setInput(this, _in);
  1623. }
  1624. virtual unsigned __int64 queryTotalCycles() const
  1625. {
  1626. return totalCycles;
  1627. }
  1628. virtual unsigned __int64 queryLocalCycles() const
  1629. {
  1630. __int64 ret = totalCycles - puller.queryInput()->queryTotalCycles();
  1631. if (ret < 0) ret = 0;
  1632. return ret;
  1633. }
  1634. virtual IRoxieInput *queryInput(unsigned idx) const
  1635. {
  1636. return puller.queryInput()->queryInput(idx);
  1637. }
  1638. virtual const void * nextInGroup()
  1639. {
  1640. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  1641. if (disabled)
  1642. return puller.queryInput()->nextInGroup();
  1643. else
  1644. {
  1645. loop
  1646. {
  1647. {
  1648. CriticalBlock b(crit);
  1649. if (eof && !buffer.ordinality())
  1650. return NULL; // eof
  1651. }
  1652. ready.wait();
  1653. const void *ret;
  1654. {
  1655. CriticalBlock b(crit);
  1656. ret = buffer.dequeue();
  1657. }
  1658. space.signal();
  1659. return ret;
  1660. }
  1661. }
  1662. }
  1663. virtual unsigned queryId() const { throwUnexpected(); }
  1664. virtual bool fireException(IException *e)
  1665. {
  1666. // called from puller thread on failure
  1667. ready.interrupt(LINK(e));
  1668. space.interrupt(e);
  1669. return true;
  1670. }
  1671. virtual void processRow(const void *row)
  1672. {
  1673. {
  1674. CriticalBlock b(crit);
  1675. buffer.enqueue(row);
  1676. }
  1677. ready.signal();
  1678. space.wait();
  1679. }
  1680. virtual void processGroup(const ConstPointerArray &rows)
  1681. {
  1682. // NOTE - a bit bizarre in that it waits for the space AFTER using it.
  1683. // But the space semaphore is only there to stop infinite readahead. And otherwise it would deadlock
  1684. // if group was larger than max(space)
  1685. {
  1686. CriticalBlock b(crit);
  1687. ForEachItemIn(idx, rows)
  1688. buffer.enqueue(rows.item(idx));
  1689. buffer.enqueue(NULL);
  1690. }
  1691. for (unsigned i2 = 0; i2 <= rows.length(); i2++) // note - does 1 extra for the null
  1692. {
  1693. ready.signal();
  1694. space.wait();
  1695. }
  1696. }
  1697. virtual void processEOG()
  1698. {
  1699. // Used when output is not grouped - just ignore
  1700. }
  1701. virtual void processDone()
  1702. {
  1703. CriticalBlock b(crit);
  1704. eof = true;
  1705. ready.signal();
  1706. }
  1707. };
  1708. //=================================================================================
  1709. class CRoxieServerTwoInputActivity : public CRoxieServerActivity
  1710. {
  1711. protected:
  1712. IRoxieInput *input1;
  1713. Owned<CRoxieServerReadAheadInput> puller;
  1714. public:
  1715. CRoxieServerTwoInputActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  1716. : CRoxieServerActivity(_factory, _probeManager)
  1717. {
  1718. input1 = NULL;
  1719. }
  1720. ~CRoxieServerTwoInputActivity()
  1721. {
  1722. }
  1723. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  1724. {
  1725. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  1726. input1->start(parentExtractSize, parentExtract, paused);
  1727. }
  1728. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  1729. {
  1730. if (puller)
  1731. puller->onCreate(_ctx);
  1732. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  1733. }
  1734. virtual void stop(bool aborting)
  1735. {
  1736. input1->stop(aborting);
  1737. CRoxieServerActivity::stop(aborting);
  1738. }
  1739. virtual unsigned __int64 queryLocalCycles() const
  1740. {
  1741. __int64 ret;
  1742. __int64 inputCycles = input->queryTotalCycles();
  1743. __int64 input1Cycles = input1->queryTotalCycles();
  1744. if (puller)
  1745. ret = totalCycles - (inputCycles > input1Cycles ? inputCycles : input1Cycles);
  1746. else
  1747. ret = totalCycles - (inputCycles + input1Cycles);
  1748. if (ret < 0)
  1749. ret = 0;
  1750. return ret;
  1751. }
  1752. virtual IRoxieInput *queryInput(unsigned idx) const
  1753. {
  1754. switch (idx)
  1755. {
  1756. case 0:
  1757. return input;
  1758. case 1:
  1759. return input1;
  1760. default:
  1761. return NULL;
  1762. }
  1763. }
  1764. virtual void reset()
  1765. {
  1766. CRoxieServerActivity::reset();
  1767. if (input1)
  1768. input1->reset();
  1769. }
  1770. virtual void setInput(unsigned idx, IRoxieInput *_in)
  1771. {
  1772. switch(idx)
  1773. {
  1774. case 0:
  1775. input = _in;
  1776. break;
  1777. case 1:
  1778. input1 = _in;
  1779. break;
  1780. default:
  1781. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  1782. }
  1783. }
  1784. };
  1785. //=================================================================================
  1786. class CRoxieServerMultiInputBaseActivity : public CRoxieServerActivity
  1787. {
  1788. protected:
  1789. unsigned numInputs;
  1790. IRoxieInput **inputArray;
  1791. public:
  1792. CRoxieServerMultiInputBaseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  1793. : CRoxieServerActivity(_factory, _probeManager), numInputs(_numInputs)
  1794. {
  1795. inputArray = new IRoxieInput*[numInputs];
  1796. for (unsigned i = 0; i < numInputs; i++)
  1797. inputArray[i] = NULL;
  1798. }
  1799. ~CRoxieServerMultiInputBaseActivity()
  1800. {
  1801. delete [] inputArray;
  1802. }
  1803. virtual unsigned __int64 queryLocalCycles() const
  1804. {
  1805. __int64 localCycles = totalCycles;
  1806. for (unsigned i = 0; i < numInputs; i++)
  1807. localCycles -= inputArray[i]->queryTotalCycles();
  1808. if (localCycles < 0)
  1809. localCycles = 0;
  1810. return localCycles;
  1811. }
  1812. virtual IRoxieInput *queryInput(unsigned idx) const
  1813. {
  1814. if (idx < numInputs)
  1815. return inputArray[idx];
  1816. else
  1817. return NULL;
  1818. }
  1819. virtual void reset()
  1820. {
  1821. for (unsigned i = 0; i < numInputs; i++)
  1822. inputArray[i]->reset();
  1823. CRoxieServerActivity::reset();
  1824. }
  1825. virtual void setInput(unsigned idx, IRoxieInput *_in)
  1826. {
  1827. inputArray[idx] = _in;
  1828. }
  1829. };
  1830. //=================================================================================
  1831. class CRoxieServerMultiInputActivity : public CRoxieServerMultiInputBaseActivity
  1832. {
  1833. public:
  1834. CRoxieServerMultiInputActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  1835. : CRoxieServerMultiInputBaseActivity(_factory, _probeManager, _numInputs)
  1836. {
  1837. }
  1838. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  1839. {
  1840. CRoxieServerMultiInputBaseActivity::start(parentExtractSize, parentExtract, paused);
  1841. for (unsigned i = 0; i < numInputs; i++)
  1842. {
  1843. inputArray[i]->start(parentExtractSize, parentExtract, paused);
  1844. }
  1845. }
  1846. virtual void stop(bool aborting)
  1847. {
  1848. for (unsigned i = 0; i < numInputs; i++)
  1849. {
  1850. inputArray[i]->stop(aborting);
  1851. }
  1852. CRoxieServerMultiInputBaseActivity::stop(aborting);
  1853. }
  1854. };
  1855. //=====================================================================================================
  1856. class CRoxieServerInternalSinkActivity : public CRoxieServerActivity
  1857. {
  1858. protected:
  1859. bool executed;
  1860. CriticalSection ecrit;
  1861. Owned<IException> exception;
  1862. public:
  1863. CRoxieServerInternalSinkActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  1864. : CRoxieServerActivity(_factory, _probeManager)
  1865. {
  1866. executed = false;
  1867. }
  1868. virtual void reset()
  1869. {
  1870. executed = false;
  1871. exception.clear();
  1872. CRoxieServerActivity::reset();
  1873. }
  1874. virtual IRoxieInput *queryOutput(unsigned idx)
  1875. {
  1876. return NULL;
  1877. }
  1878. virtual const void *nextInGroup()
  1879. {
  1880. throwUnexpected(); // I am nobody's input
  1881. }
  1882. virtual void onExecute() = 0;
  1883. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  1884. {
  1885. CriticalBlock b(ecrit);
  1886. if (exception)
  1887. throw exception.getLink();
  1888. if (!executed)
  1889. {
  1890. try
  1891. {
  1892. start(parentExtractSize, parentExtract, false);
  1893. {
  1894. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext()); // unfortunately this is not really best place for seeing in debugger.
  1895. onExecute();
  1896. }
  1897. stop(false);
  1898. executed = true;
  1899. }
  1900. catch (IException *E)
  1901. {
  1902. exception.set(E); // (or maybe makeWrappedException?)
  1903. stop(true);
  1904. throw;
  1905. }
  1906. catch (...)
  1907. {
  1908. exception.set(MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught at %s:%d", __FILE__, __LINE__));
  1909. stop(true);
  1910. throw;
  1911. }
  1912. }
  1913. }
  1914. };
  1915. //=================================================================================
  1916. class CRoxieServerQueryPacket : public CInterface, implements IRoxieServerQueryPacket
  1917. {
  1918. protected:
  1919. Owned<IMessageResult> result;
  1920. Owned<IRoxieQueryPacket> packet;
  1921. Linked<IRoxieServerQueryPacket> continuation;
  1922. unsigned hash;
  1923. unsigned seq;
  1924. unsigned lastDebugSequence;
  1925. Owned<IRoxieQueryPacket> lastDebugResponse;
  1926. ILRUChain *prev;
  1927. ILRUChain *next;
  1928. bool delayed;
  1929. public:
  1930. IMPLEMENT_IINTERFACE;
  1931. CRoxieServerQueryPacket(IRoxieQueryPacket *p) : packet(p)
  1932. {
  1933. hash = 0;
  1934. seq = 0;
  1935. prev = NULL;
  1936. next = NULL;
  1937. delayed = false;
  1938. lastDebugSequence = 0;
  1939. }
  1940. virtual IRoxieQueryPacket *queryPacket() const
  1941. {
  1942. return packet;
  1943. }
  1944. virtual bool isContinuation() const
  1945. {
  1946. return packet && (packet->queryHeader().continueSequence & ~CONTINUE_SEQUENCE_SKIPTO) != 0;
  1947. }
  1948. virtual bool isDelayed() const
  1949. {
  1950. return delayed;
  1951. }
  1952. virtual bool isEnd() const
  1953. {
  1954. return false;
  1955. }
  1956. virtual bool isLimit(unsigned __int64 &_rowLimit, unsigned __int64 &_keyedLimit, unsigned __int64 &_stopAfter) const
  1957. {
  1958. return false;
  1959. }
  1960. virtual bool hasResult() const
  1961. {
  1962. return result != NULL;
  1963. }
  1964. virtual bool hasContinuation() const
  1965. {
  1966. return continuation != NULL;
  1967. }
  1968. virtual void setDelayed(bool _delayed)
  1969. {
  1970. delayed = _delayed;
  1971. }
  1972. virtual void setPacket(IRoxieQueryPacket *_packet)
  1973. {
  1974. packet.setown(_packet);
  1975. }
  1976. virtual void setSequence(unsigned _seq)
  1977. {
  1978. assertex(!IsShared());
  1979. seq = _seq;
  1980. }
  1981. virtual unsigned getSequence() const
  1982. {
  1983. return seq;
  1984. }
  1985. IMessageResult *getResult()
  1986. {
  1987. return result.getLink();
  1988. }
  1989. IMessageResult *queryResult()
  1990. {
  1991. return result;
  1992. }
  1993. void setResult(IMessageResult *r)
  1994. {
  1995. result.setown(r);
  1996. }
  1997. IRoxieServerQueryPacket *queryContinuation()
  1998. {
  1999. return continuation;
  2000. }
  2001. void setContinuation(IRoxieServerQueryPacket *c)
  2002. {
  2003. continuation.setown(c);
  2004. }
  2005. virtual unsigned queryHash() const
  2006. {
  2007. return hash;
  2008. }
  2009. virtual void setHash(unsigned _hash)
  2010. {
  2011. hash = _hash;
  2012. }
  2013. virtual ILRUChain *queryPrev() const { return prev; }
  2014. virtual ILRUChain *queryNext() const { return next; }
  2015. virtual void setPrev(ILRUChain *p) { prev = p; }
  2016. virtual void setNext(ILRUChain *n) { next = n; }
  2017. virtual void unchain()
  2018. {
  2019. if (prev && next)
  2020. {
  2021. prev->setNext(next);
  2022. next->setPrev(prev);
  2023. }
  2024. next = NULL;
  2025. prev = NULL;
  2026. }
  2027. virtual IRoxieQueryPacket *getDebugResponse(unsigned sequence)
  2028. {
  2029. if (sequence == lastDebugSequence)
  2030. return lastDebugResponse.getLink();
  2031. else if (sequence > lastDebugSequence)
  2032. {
  2033. lastDebugResponse.clear();
  2034. return NULL;
  2035. }
  2036. else
  2037. throwUnexpected();
  2038. }
  2039. virtual void setDebugResponse(unsigned sequence, IRoxieQueryPacket *response)
  2040. {
  2041. lastDebugSequence = sequence;
  2042. lastDebugResponse.set(response);
  2043. }
  2044. };
  2045. class CRoxieServerQueryPacketEndMarker : public CRoxieServerQueryPacket
  2046. {
  2047. public:
  2048. CRoxieServerQueryPacketEndMarker() : CRoxieServerQueryPacket(NULL)
  2049. {
  2050. }
  2051. virtual bool isEnd() const
  2052. {
  2053. return true;
  2054. }
  2055. };
  2056. class CRoxieServerQueryPacketLimitMarker : public CRoxieServerQueryPacket
  2057. {
  2058. unsigned __int64 rowLimit;
  2059. unsigned __int64 keyedLimit;
  2060. unsigned __int64 stopAfter;
  2061. public:
  2062. CRoxieServerQueryPacketLimitMarker(unsigned __int64 _rowLimit, unsigned __int64 _keyedLimit, unsigned __int64 _stopAfter) : CRoxieServerQueryPacket(NULL)
  2063. {
  2064. rowLimit = _rowLimit;
  2065. keyedLimit = _keyedLimit;
  2066. stopAfter = _stopAfter;
  2067. }
  2068. virtual bool isLimit(unsigned __int64 &_rowLimit, unsigned __int64 &_keyedLimit, unsigned __int64 &_stopAfter) const
  2069. {
  2070. _rowLimit = rowLimit;
  2071. _keyedLimit = keyedLimit;
  2072. _stopAfter = stopAfter;
  2073. return true;
  2074. }
  2075. };
  2076. class CRoxieServerSideCache : implements IRoxieServerSideCache, implements ILRUChain
  2077. {
  2078. protected:
  2079. unsigned cacheTableSize;
  2080. unsigned cacheTableSpace;
  2081. IRoxieServerQueryPacket **cacheTable;
  2082. mutable ILRUChain *prev;
  2083. mutable ILRUChain *next;
  2084. mutable CriticalSection crit;
  2085. virtual ILRUChain *queryPrev() const { return prev; }
  2086. virtual ILRUChain *queryNext() const { return next; }
  2087. virtual void setPrev(ILRUChain *p) { prev = p; }
  2088. virtual void setNext(ILRUChain *n) { next = n; }
  2089. virtual void unchain()
  2090. {
  2091. prev->setNext(next);
  2092. next->setPrev(prev);
  2093. next = NULL;
  2094. prev = NULL;
  2095. }
  2096. void moveToHead(IRoxieServerQueryPacket *mru)
  2097. {
  2098. mru->unchain();
  2099. mru->setNext(next);
  2100. next->setPrev(mru);
  2101. mru->setPrev(this);
  2102. next = mru;
  2103. }
  2104. IRoxieServerQueryPacket *removeLRU()
  2105. {
  2106. if (next==this)
  2107. assertex(next != this);
  2108. IRoxieServerQueryPacket *goer = (IRoxieServerQueryPacket *) next;
  2109. goer->unchain(); // NOTE - this will modify the value of next
  2110. return goer;
  2111. }
  2112. void removeEntry(IRoxieServerQueryPacket *goer)
  2113. {
  2114. unsigned v = goer->queryHash() % cacheTableSize;
  2115. loop
  2116. {
  2117. IRoxieServerQueryPacket *found = cacheTable[v];
  2118. assertex(found);
  2119. if (found == goer)
  2120. {
  2121. cacheTable[v] = NULL;
  2122. unsigned vn = v;
  2123. loop
  2124. {
  2125. vn++;
  2126. if (vn==cacheTableSize) vn = 0;
  2127. IRoxieServerQueryPacket *found2 = cacheTable[vn];
  2128. if (!found2)
  2129. break;
  2130. unsigned vm = found2->queryHash() % cacheTableSize;
  2131. if (((vn+cacheTableSize-vm) % cacheTableSize)>=((vn+cacheTableSize-v) % cacheTableSize)) // diff(vn,vm)>=diff(vn,v)
  2132. {
  2133. cacheTable[v] = found2;
  2134. v = vn;
  2135. cacheTable[v] = NULL;
  2136. }
  2137. }
  2138. cacheTableSpace++;
  2139. break;
  2140. }
  2141. v++;
  2142. if (v==cacheTableSize)
  2143. v = 0;
  2144. }
  2145. goer->Release();
  2146. }
  2147. public:
  2148. CRoxieServerSideCache(unsigned _cacheSize)
  2149. {
  2150. cacheTableSize = (_cacheSize*4)/3;
  2151. cacheTable = new IRoxieServerQueryPacket *[cacheTableSize];
  2152. memset(cacheTable, 0, cacheTableSize * sizeof(IRoxieServerQueryPacket *));
  2153. cacheTableSpace = _cacheSize;
  2154. prev = this;
  2155. next = this;
  2156. }
  2157. ~CRoxieServerSideCache()
  2158. {
  2159. for (unsigned i = 0; i < cacheTableSize; i++)
  2160. {
  2161. ::Release(cacheTable[i]);
  2162. }
  2163. delete [] cacheTable;
  2164. }
  2165. virtual IRoxieServerQueryPacket *findCachedResult(const IRoxieContextLogger &logctx, IRoxieQueryPacket *p) const
  2166. {
  2167. unsigned hash = p->hash();
  2168. unsigned et = hash % cacheTableSize;
  2169. if (traceServerSideCache)
  2170. {
  2171. StringBuffer s;
  2172. logctx.CTXLOG("CRoxieServerSideCache::findCachedResult hash %x slot %d %s", hash, et, p->queryHeader().toString(s).str());
  2173. }
  2174. CriticalBlock b(crit);
  2175. loop
  2176. {
  2177. IRoxieServerQueryPacket *found = cacheTable[et];
  2178. if (!found)
  2179. return NULL;
  2180. if (found->queryHash() == hash && found->queryPacket()->cacheMatch(p))
  2181. {
  2182. const_cast<CRoxieServerSideCache *>(this)->moveToHead(found);
  2183. if (traceServerSideCache)
  2184. logctx.CTXLOG("CRoxieServerSideCache::findCachedResult cache hit");
  2185. logctx.noteStatistic(STATS_SERVERCACHEHIT, 1, 1);
  2186. return NULL;
  2187. // 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....
  2188. //IRoxieServerQueryPacket *ret = new CRoxieServerQueryPacket(p);
  2189. //ret->setResult(found->getResult());
  2190. //return ret;
  2191. }
  2192. et++;
  2193. if (et == cacheTableSize)
  2194. et = 0;
  2195. }
  2196. }
  2197. virtual void noteCachedResult(IRoxieServerQueryPacket *out, IMessageResult *in)
  2198. {
  2199. if (true) //!in->getLength()) // MORE - separate caches for hits and nohits
  2200. {
  2201. unsigned hash = out->queryPacket()->hash();
  2202. out->setHash(hash);
  2203. unsigned et = hash % cacheTableSize;
  2204. if (traceServerSideCache)
  2205. {
  2206. StringBuffer s;
  2207. DBGLOG("CRoxieServerSideCache::noteCachedResult hash %x slot %d %s", hash, et, out->queryPacket()->queryHeader().toString(s).str());
  2208. }
  2209. CriticalBlock b(crit);
  2210. loop
  2211. {
  2212. IRoxieServerQueryPacket *found = cacheTable[et];
  2213. if (!found)
  2214. {
  2215. if (cacheTableSpace)
  2216. {
  2217. out->setResult(LINK(in));
  2218. cacheTable[et] = LINK(out);
  2219. cacheTableSpace--;
  2220. moveToHead(out);
  2221. break;
  2222. }
  2223. else
  2224. {
  2225. IRoxieServerQueryPacket *goer = removeLRU();
  2226. removeEntry(goer);
  2227. et = hash % cacheTableSize;
  2228. continue;
  2229. }
  2230. }
  2231. else if (found->queryHash()==hash && found->queryPacket()->cacheMatch(out->queryPacket()))
  2232. {
  2233. moveToHead(found);
  2234. return; // already in the cache. Because we don't cache until we have result, this can happen where
  2235. // multiple copies of a slave query are in-flight at once.
  2236. }
  2237. et++;
  2238. if (et == cacheTableSize)
  2239. et = 0;
  2240. }
  2241. }
  2242. // MORE - do we need to worry about the attachment between the MessageUnpacker and the current row manager. May all fall out ok...
  2243. // Can I easily spot a null result? Do I want to cache null results separately? only?
  2244. }
  2245. // Note that this caching mechanism (unlike the old keyed-join specific one) does not common up cases where multiple
  2246. // identical queries are in-flight at the same time. But if we can make it persistant between queries that will
  2247. // more than make up for it
  2248. };
  2249. class CRowArrayMessageUnpackCursor : public CInterface, implements IMessageUnpackCursor
  2250. {
  2251. ConstPointerArray &data;
  2252. Linked<IMessageResult> result;
  2253. public:
  2254. IMPLEMENT_IINTERFACE;
  2255. CRowArrayMessageUnpackCursor(ConstPointerArray &_data, IMessageResult *_result)
  2256. : data(_data), result(_result)
  2257. {
  2258. }
  2259. virtual bool atEOF() const
  2260. {
  2261. return data.length()==0;
  2262. }
  2263. virtual bool isSerialized() const
  2264. {
  2265. return false;
  2266. }
  2267. virtual const void * getNext(int length)
  2268. {
  2269. if (!data.length())
  2270. return NULL;
  2271. const void *ret = data.item(0);
  2272. data.remove(0);
  2273. return ret;
  2274. }
  2275. };
  2276. // MORE - should possibly move more over to the lazy version used in indexread?
  2277. class CRowArrayMessageResult : public CInterface, implements IMessageResult
  2278. {
  2279. ConstPointerArray data;
  2280. IRowManager &rowManager;
  2281. bool variableSize;
  2282. public:
  2283. IMPLEMENT_IINTERFACE;
  2284. CRowArrayMessageResult(IRowManager &_rowManager, bool _variableSize) : rowManager(_rowManager), variableSize(_variableSize)
  2285. {
  2286. }
  2287. ~CRowArrayMessageResult()
  2288. {
  2289. ReleaseRoxieRowSet(data);
  2290. }
  2291. virtual IMessageUnpackCursor *getCursor(IRowManager *rowMgr) const
  2292. {
  2293. CRowArrayMessageResult *_this = (CRowArrayMessageResult *) this;
  2294. return new CRowArrayMessageUnpackCursor(_this->data, _this);
  2295. }
  2296. virtual const void *getMessageHeader(unsigned &length) const
  2297. {
  2298. throwUnexpected(); // should never get called - I don't have a header available
  2299. length = 0;
  2300. return NULL;
  2301. }
  2302. virtual const void *getMessageMetadata(unsigned &length) const
  2303. {
  2304. length = 0;
  2305. return NULL;
  2306. }
  2307. virtual void discard() const
  2308. {
  2309. throwUnexpected();
  2310. }
  2311. void append(const void *row)
  2312. {
  2313. data.append(row);
  2314. }
  2315. };
  2316. void throwRemoteException(IMessageUnpackCursor *extra)
  2317. {
  2318. RecordLengthType *rowlen = (RecordLengthType *) extra->getNext(sizeof(RecordLengthType));
  2319. if (rowlen)
  2320. {
  2321. char *xml = (char *) extra->getNext(*rowlen);
  2322. ReleaseRoxieRow(rowlen);
  2323. Owned<IPropertyTree> p = createPTreeFromXMLString(xml);
  2324. ReleaseRoxieRow(xml);
  2325. unsigned code = p->getPropInt("Code", 0);
  2326. const char *msg = p->queryProp("Message");
  2327. if (!msg)
  2328. msg = xml;
  2329. throw MakeStringException(code, "%s", msg);
  2330. }
  2331. throwUnexpected();
  2332. }
  2333. class CRemoteResultAdaptor :public CInterface, implements IRoxieInput, implements IExceptionHandler
  2334. {
  2335. friend class CRemoteResultMerger;
  2336. class CRemoteResultMerger
  2337. {
  2338. class HeapEntry : public CInterface
  2339. {
  2340. private:
  2341. CRemoteResultAdaptor &adaptor;
  2342. IMessageUnpackCursor *cursor;
  2343. public:
  2344. const void *current;
  2345. bool isLast;
  2346. bool lastIsComplete;
  2347. IRoxieServerQueryPacket *packet;
  2348. unsigned seq;
  2349. public:
  2350. inline const void *noteResult(IMessageUnpackCursor *_cursor, bool _lastIsComplete)
  2351. {
  2352. cursor = _cursor;
  2353. lastIsComplete = _lastIsComplete;
  2354. return next();
  2355. }
  2356. public:
  2357. HeapEntry(CRemoteResultAdaptor &_adaptor, IRoxieServerQueryPacket *_packet, unsigned _seq) : adaptor(_adaptor), packet(_packet), seq(_seq)
  2358. {
  2359. cursor = NULL;
  2360. current = NULL;
  2361. isLast = false;
  2362. lastIsComplete = true;
  2363. }
  2364. ~HeapEntry()
  2365. {
  2366. ::Release(packet);
  2367. ::Release(cursor);
  2368. ReleaseRoxieRow(current);
  2369. }
  2370. bool isCompleteMatch() const
  2371. {
  2372. if (!isLast || lastIsComplete)
  2373. return true;
  2374. else
  2375. return false;
  2376. }
  2377. const void *next()
  2378. {
  2379. if (cursor)
  2380. {
  2381. ReleaseClearRoxieRow(current);
  2382. current = adaptor.getRow(cursor);
  2383. isLast = cursor->atEOF();
  2384. if (!current)
  2385. {
  2386. cursor->Release();
  2387. cursor = NULL;
  2388. }
  2389. }
  2390. return current;
  2391. }
  2392. unsigned skipTo(IRangeCompare *compare, const void *seek, unsigned numFields, bool requireExactMatch)
  2393. {
  2394. // MORE - This loop should possibly be a binchop... though it's not absolutely clear that is true (depends on term frequencies)
  2395. unsigned skipped = 0;
  2396. loop
  2397. {
  2398. int c = compare->docompare(current, seek, numFields);
  2399. //If larger than the seek values, then we may be allowed to return an inexact match,
  2400. //if equal then it is required to be an exact match,
  2401. if (c > 0)
  2402. {
  2403. if (!requireExactMatch || isCompleteMatch())
  2404. break;
  2405. }
  2406. else if ((c == 0) && isCompleteMatch())
  2407. break;
  2408. skipped++;
  2409. if (!next())
  2410. break;
  2411. }
  2412. return skipped;
  2413. }
  2414. };
  2415. CRemoteResultAdaptor &adaptor;
  2416. CIArrayOf<HeapEntry> heapEntries;
  2417. UnsignedArray heap;
  2418. IRowManager *rowManager;
  2419. unsigned numPending;
  2420. unsigned numFields;
  2421. bool endSeen;
  2422. bool remakePending;
  2423. IRangeCompare *compare;
  2424. bool deferredContinuation;
  2425. inline int doCompare(unsigned l, unsigned r)
  2426. {
  2427. int ret = compare->docompare(heapEntries.item(l).current, heapEntries.item(r).current, numFields);
  2428. if (!ret) ret = heapEntries.item(l).seq - heapEntries.item(r).seq;
  2429. return ret;
  2430. }
  2431. void makeHeap()
  2432. {
  2433. /* Permute blocks to establish the heap property
  2434. For each element p, the children are p*2+1 and p*2+2 (provided these are in range)
  2435. The children of p must both be greater than or equal to p
  2436. The parent of a child c is given by p = (c-1)/2
  2437. */
  2438. unsigned i;
  2439. unsigned n = heap.length();
  2440. unsigned *s = heap.getArray();
  2441. for (i=1; i<n; i++)
  2442. {
  2443. unsigned r = s[i];
  2444. int c = i; /* child */
  2445. while (c > 0)
  2446. {
  2447. int p = (c-1)/2; /* parent */
  2448. if ( doCompare( s[c], s[p] ) >= 0 )
  2449. break;
  2450. s[c] = s[p];
  2451. s[p] = r;
  2452. c = p;
  2453. }
  2454. }
  2455. remakePending = false;
  2456. }
  2457. void remakeHeap()
  2458. {
  2459. /* The row associated with block[0] will have changed
  2460. This code restores the heap property
  2461. */
  2462. unsigned p = 0; /* parent */
  2463. unsigned n = heap.length();
  2464. unsigned *s = heap.getArray();
  2465. while (1)
  2466. {
  2467. unsigned c = p*2 + 1; /* child */
  2468. if ( c >= n )
  2469. break;
  2470. /* Select smaller child */
  2471. if ( c+1 < n && doCompare( s[c+1], s[c] ) < 0 ) c += 1;
  2472. /* If child is greater or equal than parent then we are done */
  2473. if ( doCompare( s[c], s[p] ) >= 0 )
  2474. break;
  2475. /* Swap parent and child */
  2476. unsigned r = s[c];
  2477. s[c] = s[p];
  2478. s[p] = r;
  2479. /* child becomes parent */
  2480. p = c;
  2481. }
  2482. remakePending = false;
  2483. }
  2484. void append(IRoxieServerQueryPacket *p, unsigned seq)
  2485. {
  2486. HeapEntry &h = *new HeapEntry(adaptor, LINK(p), seq);
  2487. IMessageResult *result = p->queryResult();
  2488. assertex(result);
  2489. if (h.noteResult(result->getCursor(rowManager), isCompleteMatchFlag(result)))
  2490. {
  2491. heapEntries.append(h);
  2492. heap.append(heap.ordinality());
  2493. }
  2494. else
  2495. h.Release();
  2496. }
  2497. void removeHeap(unsigned idx)
  2498. {
  2499. heapEntries.remove(idx);
  2500. ForEachItemIn(i, heap)
  2501. {
  2502. unsigned v = heap.item(i);
  2503. assertex(v != idx);
  2504. if (v > idx)
  2505. heap.replace(v-1, i);
  2506. }
  2507. }
  2508. bool isCompleteMatchFlag(IMessageResult *result)
  2509. {
  2510. unsigned metaLen;
  2511. const byte *metaInfo = (const byte *) result->getMessageMetadata(metaLen);
  2512. if (metaLen)
  2513. {
  2514. unsigned short continuationLen = *(unsigned short *) metaInfo;
  2515. if (continuationLen >= sizeof(bool))
  2516. {
  2517. metaInfo += sizeof(unsigned short);
  2518. return *(bool *) metaInfo;
  2519. }
  2520. }
  2521. return true; // if no continuation info, last row was complete.
  2522. }
  2523. public:
  2524. CRemoteResultMerger(CRemoteResultAdaptor &_adaptor) : adaptor(_adaptor)
  2525. {
  2526. init(NULL, NULL);
  2527. }
  2528. void init(ISteppingMeta *meta, IRowManager *_rowManager)
  2529. {
  2530. if (meta)
  2531. {
  2532. numFields = meta->getNumFields();
  2533. compare = meta->queryCompare();
  2534. }
  2535. else
  2536. {
  2537. numFields = 0;
  2538. compare = NULL;
  2539. }
  2540. rowManager = _rowManager;
  2541. numPending = 0;
  2542. endSeen = false;
  2543. remakePending = false;
  2544. deferredContinuation = false;
  2545. }
  2546. void reset()
  2547. {
  2548. heapEntries.kill();
  2549. heap.kill();
  2550. numPending = 0;
  2551. endSeen = false;
  2552. remakePending = false;
  2553. deferredContinuation = false;
  2554. }
  2555. inline bool noteEndSeen()
  2556. {
  2557. bool hadSeen = endSeen;
  2558. if (!endSeen)
  2559. makeHeap();
  2560. endSeen = true;
  2561. return !hadSeen;
  2562. }
  2563. void noteResult(IRoxieServerQueryPacket *p, unsigned seq)
  2564. {
  2565. if (!p->isContinuation())
  2566. append(p, seq);
  2567. else
  2568. {
  2569. ForEachItemIn(idx, heapEntries)
  2570. {
  2571. HeapEntry &h = heapEntries.item(idx);
  2572. if (h.packet == p)
  2573. {
  2574. IMessageResult *result = p->queryResult();
  2575. if (!h.noteResult(result->getCursor(rowManager), isCompleteMatchFlag(result)))
  2576. {
  2577. heap.zap(idx);
  2578. removeHeap(idx);
  2579. }
  2580. numPending--;
  2581. if (!numPending)
  2582. makeHeap();
  2583. return;
  2584. }
  2585. }
  2586. }
  2587. // If we get here it must be a continuation for one that I have not yet consumed... we don't need to do anything.
  2588. return;
  2589. }
  2590. unsigned skipRows(unsigned &idx, const void *seek, const void *rawSeek, unsigned numFields, unsigned seekLen, const SmartStepExtra & stepExtra)
  2591. {
  2592. HeapEntry &entry = heapEntries.item(idx);
  2593. unsigned skipped = entry.current ? entry.skipTo(compare, seek, numFields, !stepExtra.returnMismatches()) : 0;
  2594. if (!entry.current)
  2595. {
  2596. IRoxieServerQueryPacket *continuation = entry.packet->queryContinuation();
  2597. if (continuation)
  2598. {
  2599. continuation->Link();
  2600. entry.packet->Release();
  2601. entry.packet = continuation;
  2602. if (continuation->hasResult())
  2603. {
  2604. IMessageResult *result = continuation->queryResult();
  2605. bool lastIsCompleteMatch = isCompleteMatchFlag(result);
  2606. entry.noteResult(result->getCursor(rowManager), lastIsCompleteMatch);
  2607. }
  2608. else
  2609. {
  2610. if (continuation->isDelayed())
  2611. {
  2612. continuation->setDelayed(false);
  2613. MemoryBuffer serializedSkip;
  2614. adaptor.activity.serializeSkipInfo(serializedSkip, seekLen, rawSeek, numFields, seek, stepExtra);
  2615. continuation->setPacket(continuation->queryPacket()->insertSkipData(serializedSkip.length(), serializedSkip.toByteArray()));
  2616. ROQ->sendPacket(continuation->queryPacket(), adaptor.activity.queryLogCtx());
  2617. adaptor.sentsome.signal();
  2618. }
  2619. numPending++;
  2620. }
  2621. }
  2622. else
  2623. {
  2624. heap.zap(idx);
  2625. removeHeap(idx);
  2626. idx--;
  2627. }
  2628. }
  2629. return skipped;
  2630. }
  2631. const void * nextSteppedGE(const void * seek, const void *rawSeek, unsigned numFields, unsigned seeklen, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  2632. {
  2633. // We discard all rows < seekval from all entries in heap
  2634. // If this results in additional slave requests, we return NULL so that we can wait for them
  2635. // If not, we rebuild the heap (if any were skipped) and return the first row
  2636. deferredContinuation = false;
  2637. if (heap.length())
  2638. {
  2639. unsigned skipped = 0;
  2640. unsigned idx = 0;
  2641. while(heapEntries.isItem(idx))
  2642. {
  2643. skipped += skipRows(idx, seek, rawSeek, numFields, seeklen, stepExtra);
  2644. idx++;
  2645. }
  2646. if (numPending)
  2647. return NULL; // can't answer yet, need more results from slaves
  2648. else
  2649. {
  2650. if (skipped)
  2651. makeHeap();
  2652. return next(wasCompleteMatch, stepExtra);
  2653. }
  2654. }
  2655. else
  2656. return NULL;
  2657. }
  2658. bool doContinuation(HeapEntry &topEntry, bool canDefer)
  2659. {
  2660. IRoxieServerQueryPacket *continuation = topEntry.packet->queryContinuation();
  2661. if (continuation)
  2662. {
  2663. if (continuation->isDelayed() && canDefer)
  2664. {
  2665. if (adaptor.activity.queryLogCtx().queryTraceLevel() > 10)
  2666. adaptor.activity.queryLogCtx().CTXLOG("Deferring continuation");
  2667. deferredContinuation = true;
  2668. }
  2669. else
  2670. {
  2671. deferredContinuation = false;
  2672. continuation->Link();
  2673. topEntry.packet->Release();
  2674. topEntry.packet = continuation;
  2675. if (continuation->hasResult())
  2676. {
  2677. IMessageResult *result = continuation->queryResult();
  2678. bool lastIsCompleteMatch = isCompleteMatchFlag(result);
  2679. topEntry.noteResult(result->getCursor(rowManager), lastIsCompleteMatch);
  2680. }
  2681. else
  2682. {
  2683. if (continuation->isDelayed()) // has the continuation been requested yet?
  2684. {
  2685. continuation->Link();
  2686. topEntry.packet->Release();
  2687. topEntry.packet = continuation;
  2688. continuation->setDelayed(false);
  2689. if (adaptor.activity.queryLogCtx().queryTraceLevel() > 10)
  2690. adaptor.activity.queryLogCtx().CTXLOG("About to send continuation, from doContinuation");
  2691. ROQ->sendPacket(continuation->queryPacket(), adaptor.activity.queryLogCtx());
  2692. adaptor.sentsome.signal();
  2693. }
  2694. numPending++; // we are waiting for one that is already in flight
  2695. }
  2696. }
  2697. return true; // next not known yet
  2698. }
  2699. else
  2700. return false;
  2701. }
  2702. const void *next(bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  2703. {
  2704. OwnedConstRoxieRow ret;
  2705. if (heap.length())
  2706. {
  2707. if (deferredContinuation)
  2708. {
  2709. unsigned top = heap.item(0);
  2710. HeapEntry &topEntry = heapEntries.item(top);
  2711. doContinuation(topEntry, false);
  2712. return NULL;
  2713. }
  2714. if (remakePending)
  2715. remakeHeap();
  2716. unsigned top = heap.item(0);
  2717. HeapEntry &topEntry = heapEntries.item(top);
  2718. ret.set(topEntry.current);
  2719. wasCompleteMatch = topEntry.isCompleteMatch();
  2720. const void *next = topEntry.next();
  2721. if (!next)
  2722. {
  2723. if (!doContinuation(topEntry, stepExtra.returnMismatches()))
  2724. {
  2725. unsigned last = heap.pop();
  2726. if (heap.length())
  2727. heap.replace(last, 0);
  2728. removeHeap(top);
  2729. }
  2730. }
  2731. remakePending = true;
  2732. }
  2733. return ret.getClear();
  2734. }
  2735. bool ready()
  2736. {
  2737. return endSeen && numPending == 0;
  2738. }
  2739. };
  2740. IRoxieServerQueryPacket *createRoxieServerQueryPacket(IRoxieQueryPacket *p, bool &cached)
  2741. {
  2742. if (serverSideCache && !debugContext)
  2743. {
  2744. IRoxieServerQueryPacket *ret = serverSideCache->findCachedResult(activity.queryLogCtx(), p);
  2745. if (ret)
  2746. {
  2747. p->Release();
  2748. cached = true;
  2749. return ret;
  2750. }
  2751. }
  2752. cached = false;
  2753. return new CRoxieServerQueryPacket(p);
  2754. }
  2755. #ifdef _DEBUG
  2756. void dumpPending()
  2757. {
  2758. CriticalBlock b(pendingCrit);
  2759. ForEachItemIn(idx, pending)
  2760. {
  2761. IRoxieServerQueryPacket &p = pending.item(idx);
  2762. StringBuffer s;
  2763. unsigned __int64 dummy;
  2764. if (p.isEnd())
  2765. s.append("END");
  2766. else if (p.isLimit(dummy, dummy, dummy))
  2767. s.append("LIMIT");
  2768. else
  2769. {
  2770. IRoxieQueryPacket *i = p.queryPacket();
  2771. s.appendf("%s", p.hasResult() ? "COMPLETE " : "PENDING ");
  2772. if (i)
  2773. {
  2774. RoxiePacketHeader &header = i->queryHeader();
  2775. header.toString(s);
  2776. }
  2777. }
  2778. DBGLOG("Pending %d %s", idx, s.str());
  2779. }
  2780. }
  2781. #endif
  2782. void abortPending()
  2783. {
  2784. CriticalBlock b(pendingCrit);
  2785. ForEachItemIn(idx, pending)
  2786. {
  2787. IRoxieServerQueryPacket &p = pending.item(idx);
  2788. if (!p.hasResult())
  2789. {
  2790. IRoxieQueryPacket *i = p.queryPacket();
  2791. if (i)
  2792. {
  2793. RoxiePacketHeader &header = i->queryHeader();
  2794. ROQ->sendAbort(header, activity.queryLogCtx());
  2795. }
  2796. }
  2797. }
  2798. pending.kill();
  2799. }
  2800. void checkDelayed()
  2801. {
  2802. if (ctx->queryDebugContext() && ctx->queryDebugContext()->getExecuteSequentially())
  2803. {
  2804. bool allDelayed = true;
  2805. CriticalBlock b(pendingCrit);
  2806. unsigned sendIdx = (unsigned) -1;
  2807. ForEachItemIn(idx, pending)
  2808. {
  2809. IRoxieServerQueryPacket &p = pending.item(idx);
  2810. if (p.queryPacket())
  2811. {
  2812. if (p.isDelayed())
  2813. {
  2814. if (sendIdx == (unsigned) -1)
  2815. sendIdx = idx;
  2816. }
  2817. else if (!p.hasResult())
  2818. {
  2819. allDelayed = false;
  2820. break;
  2821. }
  2822. }
  2823. }
  2824. if (allDelayed && sendIdx != (unsigned) -1)
  2825. {
  2826. if (activity.queryLogCtx().queryTraceLevel() > 10)
  2827. activity.queryLogCtx().CTXLOG("About to send debug-deferred from next");
  2828. pending.item(sendIdx).setDelayed(false);
  2829. ROQ->sendPacket(pending.item(sendIdx).queryPacket(), activity.queryLogCtx());
  2830. sentsome.signal();
  2831. }
  2832. }
  2833. else if (deferredStart)
  2834. {
  2835. CriticalBlock b(pendingCrit);
  2836. ForEachItemIn(idx, pending)
  2837. {
  2838. IRoxieServerQueryPacket &p = pending.item(idx);
  2839. if (p.isDelayed())
  2840. {
  2841. if (activity.queryLogCtx().queryTraceLevel() > 10)
  2842. activity.queryLogCtx().CTXLOG("About to send deferred start from next");
  2843. p.setDelayed(false);
  2844. ROQ->sendPacket(p.queryPacket(), activity.queryLogCtx());
  2845. sentsome.signal();
  2846. }
  2847. }
  2848. deferredStart = false;
  2849. }
  2850. }
  2851. void retryPending()
  2852. {
  2853. CriticalBlock b(pendingCrit);
  2854. checkDelayed();
  2855. ForEachItemIn(idx, pending)
  2856. {
  2857. IRoxieServerQueryPacket &p = pending.item(idx);
  2858. if (!p.hasResult() && !p.isDelayed())
  2859. {
  2860. IRoxieQueryPacket *i = p.queryPacket();
  2861. if (i)
  2862. {
  2863. if (!i->queryHeader().retry())
  2864. {
  2865. StringBuffer s;
  2866. IException *E = MakeStringException(ROXIE_MULTICAST_ERROR, "Failed to get response from slave(s) for %s in activity %d", i->queryHeader().toString(s).str(), queryId());
  2867. activity.queryLogCtx().logOperatorException(E, __FILE__, __LINE__, "CRemoteResultAdaptor::retry");
  2868. throw E;
  2869. }
  2870. if (!localSlave)
  2871. {
  2872. ROQ->sendPacket(i, activity.queryLogCtx());
  2873. atomic_inc(&retriesSent);
  2874. }
  2875. }
  2876. }
  2877. }
  2878. }
  2879. class ChannelBuffer
  2880. {
  2881. protected:
  2882. unsigned bufferLeft;
  2883. MemoryBuffer buffer;
  2884. char *nextBuf;
  2885. unsigned overflowSequence;
  2886. unsigned channel; // == bonded channel
  2887. bool needsFlush;
  2888. InterruptableSemaphore flowController;
  2889. const CRemoteResultAdaptor &owner;
  2890. CriticalSection crit;
  2891. public:
  2892. ChannelBuffer(const CRemoteResultAdaptor &_owner, unsigned _channel) : owner(_owner), channel(_channel), flowController(perChannelFlowLimit)
  2893. {
  2894. overflowSequence = 0;
  2895. needsFlush = false;
  2896. bufferLeft = 0;
  2897. nextBuf = NULL;
  2898. }
  2899. void init(unsigned minSize)
  2900. {
  2901. assertex(!buffer.length());
  2902. if (minSize < MIN_PAYLOAD_SIZE)
  2903. minSize = MIN_PAYLOAD_SIZE;
  2904. unsigned headerSize = sizeof(RoxiePacketHeader)+owner.headerLength();
  2905. unsigned bufferSize = headerSize+minSize;
  2906. if (bufferSize < mtu_size)
  2907. bufferSize = mtu_size;
  2908. buffer.reserveTruncate(bufferSize);
  2909. bufferLeft = bufferSize - headerSize;
  2910. assertex(buffer.toByteArray());
  2911. nextBuf = (char *) buffer.toByteArray() + headerSize;
  2912. needsFlush = false;
  2913. }
  2914. inline IRoxieQueryPacket *flush()
  2915. {
  2916. CriticalBlock cb(crit);
  2917. Owned<IRoxieQueryPacket> ret;
  2918. if (needsFlush)
  2919. {
  2920. buffer.setLength(nextBuf - buffer.toByteArray());
  2921. RoxiePacketHeader *h = (RoxiePacketHeader *) buffer.toByteArray();
  2922. h->init(owner.remoteId, owner.ruid, channel, overflowSequence);
  2923. //patch logPrefix, cachedContext and parent extract into the place reserved in the message buffer
  2924. byte * tgt = (byte*)(h+1);
  2925. owner.copyHeader(tgt, channel);
  2926. ret.setown(createRoxiePacket(buffer));
  2927. if (overflowSequence == OVERFLOWSEQUENCE_MAX)
  2928. overflowSequence = 1; // don't wrap to 0 - that is a bit special
  2929. else
  2930. overflowSequence++;
  2931. needsFlush = false;
  2932. bufferLeft = 0;
  2933. if (owner.flowControlled)
  2934. {
  2935. CriticalUnblock cub(crit);
  2936. while (!flowController.wait(1000))
  2937. {
  2938. StringBuffer s;
  2939. owner.activity.queryLogCtx().CTXLOG("Channel %d blocked by flow control: %s", channel, h->toString(s).str());
  2940. }
  2941. }
  2942. }
  2943. return ret.getClear();
  2944. }
  2945. inline void signal()
  2946. {
  2947. if (owner.flowControlled)
  2948. flowController.signal();
  2949. }
  2950. inline void interrupt(IException *e)
  2951. {
  2952. flowController.interrupt(e);
  2953. }
  2954. inline void *getBuffer(unsigned size)
  2955. {
  2956. CriticalBlock cb(crit);
  2957. if (bufferLeft >= size)
  2958. {
  2959. needsFlush = true;
  2960. void * ret = nextBuf;
  2961. nextBuf += size;
  2962. bufferLeft -= size;
  2963. return ret;
  2964. }
  2965. else if (!needsFlush)
  2966. {
  2967. init(size);
  2968. return getBuffer(size);
  2969. }
  2970. else if (owner.mergeOrder)
  2971. {
  2972. return buffer.reserve(size); // whole query needs to go as single packet if we are to merge
  2973. }
  2974. else
  2975. return NULL; // will force it to flush and start a new packet
  2976. }
  2977. };
  2978. private:
  2979. friend class CRemoteResultMerger;
  2980. bool allread;
  2981. bool contextCached;
  2982. bool preserveOrder;
  2983. InterruptableSemaphore sentsome;
  2984. Owned <IMessageCollator> mc;
  2985. Owned<IMessageUnpackCursor> mu;
  2986. Owned<IMessageResult> mr;
  2987. ChannelBuffer **buffers;
  2988. IHThorArg &helper;
  2989. unsigned __int64 stopAfter;
  2990. unsigned resendSequence;
  2991. IHThorArg *colocalArg;
  2992. IArrayOf<IRoxieServerQueryPacket> pending;
  2993. CriticalSection pendingCrit;
  2994. IRoxieServerSideCache *serverSideCache;
  2995. unsigned sentSequence;
  2996. Owned<IOutputRowDeserializer> deserializer;
  2997. Owned<IEngineRowAllocator> rowAllocator;
  2998. CRemoteResultMerger merger;
  2999. // this is only used to avoid recreating a bufferStream for each row. A better solution may be needed
  3000. MemoryBuffer tempRowBuffer;
  3001. Owned<ISerialStream> bufferStream;
  3002. CThorStreamDeserializerSource rowSource;
  3003. protected:
  3004. IRowManager *rowManager;
  3005. IRoxieInput *owner;
  3006. unsigned __int64 rowLimit;
  3007. unsigned __int64 keyedLimit;
  3008. IRoxieServerErrorHandler *errorHandler;
  3009. CachedOutputMetaData meta;
  3010. public:
  3011. ISteppingMeta *mergeOrder;
  3012. IRoxieSlaveContext *ctx;
  3013. IDebuggableContext *debugContext;
  3014. IRoxieServerActivity &activity;
  3015. unsigned parentExtractSize;
  3016. const byte * parentExtract;
  3017. bool flowControlled;
  3018. bool deferredStart;
  3019. MemoryBuffer logInfo;
  3020. MemoryBuffer cachedContext;
  3021. const RemoteActivityId &remoteId;
  3022. ruid_t ruid;
  3023. mutable CriticalSection buffersCrit;
  3024. unsigned processed;
  3025. unsigned __int64 totalCycles;
  3026. //private: //vc6 doesn't like this being private yet accessed by nested class...
  3027. const void *getRow(IMessageUnpackCursor *mu)
  3028. {
  3029. if (!mu->isSerialized() || (meta.isFixedSize() && !deserializer))
  3030. return mu->getNext(meta.getFixedSize());
  3031. else
  3032. {
  3033. RecordLengthType *rowlen = (RecordLengthType *) mu->getNext(sizeof(RecordLengthType));
  3034. if (rowlen)
  3035. {
  3036. RecordLengthType len = *rowlen;
  3037. ReleaseRoxieRow(rowlen);
  3038. const void *slaveRec = mu->getNext(len);
  3039. if (deserializer && mu->isSerialized())
  3040. {
  3041. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  3042. tempRowBuffer.setBuffer(len, const_cast<void *>(slaveRec), false);
  3043. size_t outsize = deserializer->deserialize(rowBuilder, rowSource);
  3044. ReleaseRoxieRow(slaveRec);
  3045. return rowBuilder.finalizeRowClear(outsize);
  3046. }
  3047. else
  3048. return slaveRec;
  3049. }
  3050. else
  3051. return NULL;
  3052. }
  3053. }
  3054. private:
  3055. ChannelBuffer *queryChannelBuffer(unsigned channel, bool force=false)
  3056. {
  3057. CriticalBlock cb(buffersCrit);
  3058. ChannelBuffer *b = buffers[channel];
  3059. if (!b && force)
  3060. {
  3061. if (!contextCached)
  3062. {
  3063. logInfo.clear();
  3064. unsigned char loggingFlags = LOGGING_FLAGSPRESENT | LOGGING_TRACELEVELSET;
  3065. unsigned char ctxTraceLevel = activity.queryLogCtx().queryTraceLevel() + 1; // Avoid passing a 0
  3066. if (activity.queryLogCtx().isIntercepted())
  3067. loggingFlags |= LOGGING_INTERCEPTED;
  3068. if (ctx->queryTimeActivities())
  3069. loggingFlags |= LOGGING_TIMEACTIVITIES;
  3070. if (activity.queryLogCtx().isBlind())
  3071. loggingFlags |= LOGGING_BLIND;
  3072. if (ctx->queryCheckingHeap())
  3073. loggingFlags |= LOGGING_CHECKINGHEAP;
  3074. if (ctx->queryWorkUnit())
  3075. loggingFlags |= LOGGING_WUID;
  3076. if (debugContext)
  3077. {
  3078. loggingFlags |= LOGGING_DEBUGGERACTIVE;
  3079. logInfo.append(loggingFlags).append(ctxTraceLevel);
  3080. MemoryBuffer bpInfo;
  3081. debugContext->serialize(bpInfo);
  3082. bpInfo.append((__uint64)(memsize_t) &activity);
  3083. logInfo.append((unsigned short) bpInfo.length());
  3084. logInfo.append(bpInfo.length(), bpInfo.toByteArray());
  3085. }
  3086. else
  3087. logInfo.append(loggingFlags).append(ctxTraceLevel);
  3088. StringBuffer logPrefix;
  3089. activity.queryLogCtx().getLogPrefix(logPrefix);
  3090. logInfo.append(logPrefix);
  3091. activity.serializeCreateStartContext(cachedContext.clear());
  3092. activity.serializeExtra(cachedContext);
  3093. if (activity.queryVarFileInfo())
  3094. {
  3095. activity.queryVarFileInfo()->queryTimeStamp().serialize(cachedContext);
  3096. cachedContext.append(activity.queryVarFileInfo()->queryCheckSum());
  3097. }
  3098. contextCached = true;
  3099. }
  3100. b = buffers[channel] = new ChannelBuffer(*this, channel);
  3101. }
  3102. return b;
  3103. }
  3104. void processRow(const void *got)
  3105. {
  3106. processed++;
  3107. if (processed > rowLimit)
  3108. {
  3109. ReleaseRoxieRow(got);
  3110. errorHandler->onLimitExceeded(false); // NOTE - should throw exception
  3111. throwUnexpected();
  3112. }
  3113. else if (processed > keyedLimit)
  3114. {
  3115. ReleaseRoxieRow(got);
  3116. errorHandler->onLimitExceeded(true); // NOTE - should throw exception
  3117. throwUnexpected();
  3118. }
  3119. }
  3120. public:
  3121. IMPLEMENT_IINTERFACE;
  3122. CRemoteResultAdaptor(const RemoteActivityId &_remoteId, IOutputMetaData *_meta, IHThorArg &_helper, IRoxieServerActivity &_activity, bool _preserveOrder, bool _flowControlled)
  3123. : remoteId(_remoteId), meta(_meta), activity(_activity), helper(_helper), preserveOrder(_preserveOrder), flowControlled(_flowControlled), merger(*this)
  3124. {
  3125. rowLimit = (unsigned __int64) -1;
  3126. keyedLimit = (unsigned __int64) -1;
  3127. contextCached = false;
  3128. stopAfter = I64C(0x7FFFFFFFFFFFFFFF);
  3129. buffers = new ChannelBuffer*[numChannels+1];
  3130. memset(buffers, 0, (numChannels+1)*sizeof(ChannelBuffer *));
  3131. parentExtractSize = 0;
  3132. parentExtract = NULL;
  3133. owner = NULL;
  3134. mergeOrder = NULL;
  3135. deferredStart = false;
  3136. processed = 0;
  3137. totalCycles = 0;
  3138. sentSequence = 0;
  3139. serverSideCache = activity.queryServerSideCache();
  3140. bufferStream.setown(createMemoryBufferSerialStream(tempRowBuffer));
  3141. rowSource.setStream(bufferStream);
  3142. }
  3143. ~CRemoteResultAdaptor()
  3144. {
  3145. if (mc)
  3146. {
  3147. ROQ->queryReceiveManager()->detachCollator(mc);
  3148. mc.clear();
  3149. }
  3150. for (unsigned channel = 0; channel <= numChannels; channel++)
  3151. {
  3152. delete(buffers[channel]);
  3153. }
  3154. delete [] buffers;
  3155. }
  3156. void setMeta(IOutputMetaData *newmeta)
  3157. {
  3158. meta.set(newmeta);
  3159. }
  3160. virtual IRoxieServerActivity *queryActivity()
  3161. {
  3162. return &activity;
  3163. }
  3164. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  3165. {
  3166. return NULL;
  3167. }
  3168. void setMergeInfo(ISteppingMeta *_mergeOrder)
  3169. {
  3170. mergeOrder = _mergeOrder;
  3171. deferredStart = true;
  3172. }
  3173. void send(IRoxieQueryPacket *p)
  3174. {
  3175. if (p)
  3176. {
  3177. Linked<IRoxieQueryPacket> saver(p); // avoids a race with abortPending, without keeping pendingCrit locked over the send which we might prefer not to
  3178. assertex(p->queryHeader().uid==ruid);
  3179. // MORE: Maybe we should base the fastlane flag on some other
  3180. // criteria !! (i.e A Roxie server prediction based on the
  3181. // activity type/activity behaviour/expected reply size .. etc).
  3182. //
  3183. // Currently (code below) based on high priority, seq=0, and none-child activity.
  3184. // But this could still cause too many reply packets on the fatlane
  3185. // (higher priority output Q), which may cause the activities on the
  3186. // low priority output Q to not get service on time.
  3187. if ((colocalArg == 0) && // not a child query activity??
  3188. (p->queryHeader().activityId & (ROXIE_SLA_PRIORITY | ROXIE_HIGH_PRIORITY)) &&
  3189. (p->queryHeader().overflowSequence == 0) &&
  3190. (p->queryHeader().continueSequence & ~CONTINUE_SEQUENCE_SKIPTO)==0)
  3191. p->queryHeader().retries |= ROXIE_FASTLANE;
  3192. if (p->queryHeader().channel)
  3193. {
  3194. bool cached = false;
  3195. IRoxieServerQueryPacket *rsqp = createRoxieServerQueryPacket(p, cached);
  3196. if (deferredStart)
  3197. rsqp->setDelayed(true);
  3198. rsqp->setSequence(sentSequence++);
  3199. {
  3200. CriticalBlock b(pendingCrit);
  3201. pending.append(*rsqp);
  3202. }
  3203. if (!deferredStart)
  3204. {
  3205. if (!cached)
  3206. ROQ->sendPacket(p, activity.queryLogCtx());
  3207. sentsome.signal();
  3208. }
  3209. }
  3210. else
  3211. {
  3212. // 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
  3213. // Need to add first, then send
  3214. unsigned i;
  3215. bool allCached = true;
  3216. for (i = 1; i <= numChannels; i++)
  3217. {
  3218. IRoxieQueryPacket *q = p->clonePacket(i);
  3219. bool thisChannelCached;
  3220. IRoxieServerQueryPacket *rsqp = createRoxieServerQueryPacket(q, thisChannelCached);
  3221. if (!thisChannelCached)
  3222. allCached = false;
  3223. rsqp->setSequence(sentSequence++);
  3224. if (deferredStart)
  3225. {
  3226. rsqp->setDelayed(true);
  3227. }
  3228. {
  3229. CriticalBlock b(pendingCrit);
  3230. pending.append(*rsqp);
  3231. }
  3232. if (!deferredStart)
  3233. sentsome.signal();
  3234. }
  3235. if (!allCached && !deferredStart)
  3236. ROQ->sendPacket(p, activity.queryLogCtx());
  3237. buffers[0]->signal(); // since replies won't come back on that channel...
  3238. p->Release();
  3239. }
  3240. }
  3241. }
  3242. void *getMem(unsigned partNo, unsigned fileNo, unsigned size)
  3243. {
  3244. unsigned channel = partNo ? getBondedChannel(partNo) : 0;
  3245. size += sizeof(PartNoType);
  3246. ChannelBuffer *b = queryChannelBuffer(channel, true);
  3247. char *buffer = (char *) b->getBuffer(size);
  3248. if (!buffer)
  3249. {
  3250. send(b->flush());
  3251. buffer = (char *) b->getBuffer(size);
  3252. }
  3253. PartNoType sp;
  3254. sp.partNo = partNo;
  3255. sp.fileNo = fileNo;
  3256. memcpy(buffer, &sp, sizeof(sp));
  3257. buffer += sizeof(sp);
  3258. return buffer;
  3259. }
  3260. void injectResult(IMessageResult *result)
  3261. {
  3262. IRoxieServerQueryPacket *f = new CRoxieServerQueryPacket(NULL);
  3263. f->setSequence(sentSequence++);
  3264. f->setResult(result);
  3265. CriticalBlock b(pendingCrit);
  3266. pending.append(*f);
  3267. sentsome.signal(); // MORE - arguably should only send if there is any point waking up the listener thread, to save context swicth
  3268. }
  3269. void flush()
  3270. {
  3271. for (unsigned channel = 0; channel <= numChannels; channel++)
  3272. {
  3273. ChannelBuffer *b = queryChannelBuffer(channel, false);
  3274. if (b)
  3275. send(b->flush());
  3276. }
  3277. }
  3278. void interruptBuffers(IException *e)
  3279. {
  3280. for (unsigned channel = 0; channel <= numChannels; channel++)
  3281. {
  3282. ChannelBuffer *b = queryChannelBuffer(channel, false);
  3283. if (b)
  3284. b->interrupt(LINK(e));
  3285. }
  3286. }
  3287. void senddone()
  3288. {
  3289. CriticalBlock b(pendingCrit);
  3290. pending.append(*new CRoxieServerQueryPacketEndMarker);
  3291. sentsome.signal();
  3292. }
  3293. bool fireException(IException *e)
  3294. {
  3295. {
  3296. CriticalBlock b(pendingCrit);
  3297. pending.append(*new CRoxieServerQueryPacketEndMarker);
  3298. }
  3299. interruptBuffers(e);
  3300. if (mc)
  3301. mc->interrupt(LINK(e));
  3302. sentsome.interrupt(e);
  3303. return true;
  3304. }
  3305. virtual void onCreate(IRoxieInput *_owner, IRoxieServerErrorHandler *_errorHandler, IRoxieSlaveContext *_ctx, IHThorArg *_colocalArg)
  3306. {
  3307. owner = _owner;
  3308. errorHandler = _errorHandler;
  3309. ctx = _ctx;
  3310. debugContext = ctx->queryDebugContext();
  3311. colocalArg = _colocalArg;
  3312. if (meta.needsSerializeDisk())
  3313. {
  3314. deserializer.setown(meta.createDiskDeserializer(_ctx->queryCodeContext(), activity.queryId()));
  3315. rowAllocator.setown(ctx->queryCodeContext()->getRowAllocator(meta.queryOriginal(), activity.queryId()));
  3316. }
  3317. if (ctx->queryDebugContext() && ctx->queryDebugContext()->getExecuteSequentially())
  3318. deferredStart = true;
  3319. }
  3320. virtual unsigned queryId() const
  3321. {
  3322. return owner->queryId();
  3323. }
  3324. virtual void onStart(unsigned _parentExtractSize, const byte * _parentExtract)
  3325. {
  3326. #ifdef TRACE_STARTSTOP
  3327. if (traceStartStop)
  3328. activity.queryLogCtx().CTXLOG("RRAonstart");
  3329. #endif
  3330. sentsome.reinit();
  3331. ruid = getNextRuid();
  3332. rowManager = &ctx->queryRowManager();
  3333. if (mergeOrder)
  3334. merger.init(mergeOrder, rowManager);
  3335. if (mc)
  3336. {
  3337. ROQ->queryReceiveManager()->detachCollator(mc); // Should never happen - implies someone forgot to call onReset!
  3338. }
  3339. mc.setown(ROQ->queryReceiveManager()->createMessageCollator(rowManager, ruid));
  3340. allread = false;
  3341. mu.clear();
  3342. contextCached = false;
  3343. processed = 0;
  3344. totalCycles = 0;
  3345. resendSequence = 0;
  3346. sentSequence = 0;
  3347. for (unsigned channel = 0; channel <= numChannels; channel++)
  3348. {
  3349. delete(buffers[channel]);
  3350. buffers[channel] = NULL;
  3351. }
  3352. flush();
  3353. parentExtractSize = _parentExtractSize;
  3354. parentExtract = _parentExtract;
  3355. }
  3356. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  3357. {
  3358. #ifdef TRACE_STARTSTOP
  3359. if (traceStartStop)
  3360. activity.queryLogCtx().CTXLOG("RRAstart");
  3361. #endif
  3362. owner->start(parentExtractSize, parentExtract, paused);
  3363. totalCycles = 0;
  3364. }
  3365. void checkAbort()
  3366. {
  3367. owner->checkAbort();
  3368. }
  3369. void setLimits(unsigned __int64 _rowLimit, unsigned __int64 _keyedLimit, unsigned __int64 _stopAfter)
  3370. {
  3371. if (ctx->queryProbeManager())
  3372. {
  3373. if (_rowLimit != (unsigned __int64) -1) ctx->queryProbeManager()->setNodePropertyInt(&activity, "rowLimit", _rowLimit);
  3374. if (_keyedLimit != (unsigned __int64) -1) ctx->queryProbeManager()->setNodePropertyInt(&activity, "keyedLimit", _keyedLimit);
  3375. if (_stopAfter != I64C(0x7FFFFFFFFFFFFFFF)) ctx->queryProbeManager()->setNodePropertyInt(&activity, "choosenLimit", _stopAfter);
  3376. }
  3377. {
  3378. CriticalBlock b(pendingCrit);
  3379. if (pending.length())
  3380. {
  3381. #ifdef _DEBUG
  3382. dumpPending(); // MORE - only defined in debug build - could have put the ifdef inside the dumpPending method
  3383. #endif
  3384. assertex(pending.length()==0);
  3385. }
  3386. pending.append(*new CRoxieServerQueryPacketLimitMarker(_rowLimit, _keyedLimit, _stopAfter));
  3387. }
  3388. sentsome.signal();
  3389. rowLimit = _rowLimit;
  3390. keyedLimit = _keyedLimit;
  3391. stopAfter = _stopAfter;
  3392. }
  3393. virtual void stop(bool aborting)
  3394. {
  3395. #ifdef TRACE_STARTSTOP
  3396. if (traceStartStop)
  3397. activity.queryLogCtx().CTXLOG("RRAstop");
  3398. #endif
  3399. onStop(aborting);
  3400. owner->stop(aborting);
  3401. }
  3402. void onStop(bool aborting)
  3403. {
  3404. #ifdef TRACE_STARTSTOP
  3405. if (traceStartStop)
  3406. activity.queryLogCtx().CTXLOG("RRAonstop");
  3407. #endif
  3408. abortPending();
  3409. interruptBuffers(NULL);
  3410. sentsome.interrupt();
  3411. if (mc) // May not be set if start() chain threw exception
  3412. mc->interrupt();
  3413. }
  3414. virtual void reset()
  3415. {
  3416. #ifdef TRACE_STARTSTOP
  3417. if (traceStartStop)
  3418. activity.queryLogCtx().CTXLOG("RRAreset");
  3419. #endif
  3420. owner->reset();
  3421. onReset();
  3422. }
  3423. virtual void resetEOF()
  3424. {
  3425. throwUnexpected();
  3426. }
  3427. virtual void onReset()
  3428. {
  3429. #ifdef TRACE_STARTSTOP
  3430. if (traceStartStop)
  3431. activity.queryLogCtx().CTXLOG("RRAonreset");
  3432. #endif
  3433. if (mc)
  3434. ROQ->queryReceiveManager()->detachCollator(mc);
  3435. merger.reset();
  3436. pending.kill();
  3437. if (mc && ctx)
  3438. ctx->addSlavesReplyLen(mc->queryBytesReceived());
  3439. mc.clear(); // Or we won't free memory for graphs that get recreated
  3440. mu.clear(); //ditto
  3441. deferredStart = false;
  3442. // NOTE: do NOT clear mergeOrder - this is set at create time not per child query
  3443. }
  3444. virtual IOutputMetaData * queryOutputMeta() const
  3445. {
  3446. return helper.queryOutputMeta();
  3447. }
  3448. virtual unsigned __int64 queryTotalCycles() const
  3449. {
  3450. return totalCycles;
  3451. }
  3452. virtual unsigned __int64 queryLocalCycles() const
  3453. {
  3454. return owner->queryLocalCycles();
  3455. }
  3456. virtual IRoxieInput *queryInput(unsigned idx) const
  3457. {
  3458. return owner->queryInput(idx);
  3459. }
  3460. const void * nextSteppedGE(const void *seek, const void *rawSeek, unsigned numFields, unsigned seekLen, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  3461. {
  3462. if (activity.queryLogCtx().queryTraceLevel() > 20)
  3463. {
  3464. StringBuffer recstr;
  3465. unsigned i;
  3466. for (i = 0; i < seekLen; i++)
  3467. {
  3468. recstr.appendf("%02x ", ((unsigned char *) rawSeek)[i]);
  3469. }
  3470. activity.queryLogCtx().CTXLOG("CRemoteResultAdaptor::nextSteppedGE(rawSeek=%s numFields=%d, seeklen=%d, returnMismatches=%d)", recstr.str(), numFields, seekLen, stepExtra.returnMismatches());
  3471. }
  3472. assertex(mergeOrder);
  3473. if (deferredStart)
  3474. {
  3475. CriticalBlock b(pendingCrit);
  3476. ForEachItemIn(idx, pending)
  3477. {
  3478. IRoxieServerQueryPacket &p = pending.item(idx);
  3479. if (p.isDelayed())
  3480. {
  3481. p.setDelayed(false);
  3482. if (activity.queryLogCtx().queryTraceLevel() > 10)
  3483. activity.queryLogCtx().CTXLOG("About to send deferred start from nextSteppedGE, setting requireExact to %d", !stepExtra.returnMismatches());
  3484. MemoryBuffer serializedSkip;
  3485. activity.serializeSkipInfo(serializedSkip, seekLen, rawSeek, numFields, seek, stepExtra);
  3486. p.setPacket(p.queryPacket()->insertSkipData(serializedSkip.length(), serializedSkip.toByteArray()));
  3487. ROQ->sendPacket(p.queryPacket(), activity.queryLogCtx());
  3488. sentsome.signal();
  3489. }
  3490. }
  3491. deferredStart = false;
  3492. }
  3493. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  3494. if (processed==stopAfter)
  3495. return NULL;
  3496. if (allread)
  3497. return NULL;
  3498. loop
  3499. {
  3500. if (merger.ready())
  3501. {
  3502. const void *got = merger.nextSteppedGE(seek, rawSeek, numFields, seekLen, wasCompleteMatch, stepExtra);
  3503. if (got)
  3504. {
  3505. processRow(got);
  3506. return got;
  3507. }
  3508. }
  3509. if (!reload()) // MORE - should pass the seek info here...
  3510. return NULL;
  3511. }
  3512. }
  3513. virtual const void *nextInGroup()
  3514. {
  3515. // If we are merging then we need to do a heapsort on all
  3516. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  3517. if (activity.queryLogCtx().queryTraceLevel() > 10)
  3518. {
  3519. activity.queryLogCtx().CTXLOG("CRemoteResultAdaptor::nextInGroup()");
  3520. }
  3521. loop
  3522. {
  3523. checkDelayed();
  3524. if (processed==stopAfter)
  3525. return NULL;
  3526. if (allread)
  3527. return NULL;
  3528. // If we can still consume from the merger or the most recently retrieved mu, do so.
  3529. const void *got = NULL;
  3530. if (mergeOrder && merger.ready())
  3531. {
  3532. bool matched = true;
  3533. got = merger.next(matched, dummySmartStepExtra);
  3534. }
  3535. else if (mu)
  3536. got = getRow(mu);
  3537. if (got)
  3538. {
  3539. processRow(got);
  3540. return got;
  3541. }
  3542. if (!reload())
  3543. return NULL;
  3544. }
  3545. }
  3546. bool reload()
  3547. {
  3548. // Wait for something to be returned from a slave....
  3549. mu.clear();
  3550. sentsome.wait();
  3551. // must be at least an endMarker on the queue since sentsome was signalled
  3552. {
  3553. CriticalBlock b(pendingCrit);
  3554. IRoxieServerQueryPacket &top = pending.item(0);
  3555. if (top.isLimit(rowLimit, keyedLimit, stopAfter)) // This is really a start marker...
  3556. {
  3557. pending.remove(0);
  3558. return true;
  3559. }
  3560. else if (top.isEnd())
  3561. {
  3562. pending.remove(0);
  3563. allread = true;
  3564. if (activity.queryLogCtx().queryTraceLevel() > 5)
  3565. activity.queryLogCtx().CTXLOG("All read on ruid %x", ruid);
  3566. return false;
  3567. }
  3568. else if (mergeOrder)
  3569. {
  3570. unsigned idx = 0;
  3571. bool added = false;
  3572. while (pending.isItem(idx))
  3573. {
  3574. IRoxieServerQueryPacket &item = pending.item(idx);
  3575. if (item.isEnd())
  3576. {
  3577. if (merger.noteEndSeen())
  3578. {
  3579. sentsome.signal(); // Because we waited, yet didn't actually consume anything
  3580. added = true;
  3581. }
  3582. break;
  3583. }
  3584. else if (item.hasResult())
  3585. {
  3586. merger.noteResult(&item, item.getSequence());
  3587. pending.remove(idx);
  3588. added = true;
  3589. }
  3590. else if (item.isContinuation())
  3591. idx++;
  3592. else
  3593. break;
  3594. }
  3595. if (added)
  3596. return true;
  3597. }
  3598. else if (top.hasResult())
  3599. {
  3600. mr.setown(pending.item(0).getResult());
  3601. mu.setown(mr->getCursor(rowManager));
  3602. pending.remove(0);
  3603. return true;
  3604. }
  3605. }
  3606. getNextUnpacker();
  3607. return true;
  3608. }
  3609. void getNextUnpacker()
  3610. {
  3611. mu.clear();
  3612. unsigned ctxTraceLevel = activity.queryLogCtx().queryTraceLevel();
  3613. loop
  3614. {
  3615. checkDelayed();
  3616. unsigned timeout = remoteId.isSLAPriority() ? slaTimeout : (remoteId.isHighPriority() ? highTimeout : lowTimeout);
  3617. owner->checkAbort();
  3618. bool anyActivity;
  3619. if (ctxTraceLevel > 5)
  3620. activity.queryLogCtx().CTXLOG("Calling getNextUnpacker(%d)", timeout);
  3621. mr.setown(mc->getNextResult(timeout, anyActivity));
  3622. if (ctxTraceLevel > 6)
  3623. activity.queryLogCtx().CTXLOG("Called getNextUnpacker(%d), activity=%d", timeout, anyActivity);
  3624. owner->checkAbort();
  3625. if (mr)
  3626. {
  3627. unsigned roxieHeaderLen;
  3628. const RoxiePacketHeader &header = *(const RoxiePacketHeader *) mr->getMessageHeader(roxieHeaderLen);
  3629. #ifdef _DEBUG
  3630. assertex(roxieHeaderLen == sizeof(RoxiePacketHeader));
  3631. #endif
  3632. if (ctxTraceLevel > 5)
  3633. {
  3634. StringBuffer s;
  3635. activity.queryLogCtx().CTXLOG("getNextUnpacker got packet %s", header.toString(s).str());
  3636. }
  3637. CriticalBlock b(pendingCrit);
  3638. unsigned idx = 0;
  3639. IRoxieServerQueryPacket *original = NULL;
  3640. IRoxieQueryPacket *op;
  3641. while (pending.isItem(idx))
  3642. {
  3643. original = &pending.item(idx);
  3644. op = original->queryPacket();
  3645. if (op && header.matchPacket(op->queryHeader()))
  3646. break;
  3647. original = NULL;
  3648. idx++;
  3649. }
  3650. if (!original || original->hasResult())
  3651. {
  3652. switch (header.activityId)
  3653. {
  3654. case ROXIE_FILECALLBACK:
  3655. {
  3656. // tell slave to abort
  3657. //if (ctxTraceLevel > 5)
  3658. {
  3659. StringBuffer s;
  3660. activity.queryLogCtx().CTXLOG("Redundant callback on query %s", header.toString(s).str());
  3661. }
  3662. Owned<IMessageUnpackCursor> callbackData = mr->getCursor(rowManager);
  3663. OwnedConstRoxieRow len = callbackData->getNext(sizeof(RecordLengthType));
  3664. if (len)
  3665. {
  3666. RecordLengthType *rowlen = (RecordLengthType *) len.get();
  3667. OwnedConstRoxieRow row = callbackData->getNext(*rowlen);
  3668. const char *rowdata = (const char *) row.get();
  3669. // bool isOpt = * (bool *) rowdata;
  3670. // bool isLocal = * (bool *) (rowdata+1);
  3671. ROQ->sendAbortCallback(header, rowdata+2, activity.queryLogCtx());
  3672. }
  3673. else
  3674. throwUnexpected();
  3675. break;
  3676. }
  3677. // MORE - ROXIE_ALIVE perhaps should go here too
  3678. case ROXIE_TRACEINFO:
  3679. {
  3680. Owned<IMessageUnpackCursor> extra = mr->getCursor(rowManager);
  3681. loop
  3682. {
  3683. RecordLengthType *rowlen = (RecordLengthType *) extra->getNext(sizeof(RecordLengthType));
  3684. if (rowlen)
  3685. {
  3686. char *logInfo = (char *) extra->getNext(*rowlen);
  3687. MemoryBuffer buf;
  3688. buf.setBuffer(*rowlen, logInfo, false);
  3689. activity.queryLogCtx().CTXLOGl(new LogItem(buf));
  3690. ReleaseRoxieRow(rowlen);
  3691. ReleaseRoxieRow(logInfo);
  3692. }
  3693. else
  3694. break;
  3695. }
  3696. break;
  3697. }
  3698. default:
  3699. if (ctxTraceLevel > 3)
  3700. activity.queryLogCtx().CTXLOG("Discarding packet %p - original %p is NULL or has result already", mr.get(), original);
  3701. mr->discard();
  3702. break;
  3703. }
  3704. mr.clear();
  3705. }
  3706. else
  3707. {
  3708. atomic_inc(&resultsReceived);
  3709. switch (header.activityId)
  3710. {
  3711. case ROXIE_DEBUGCALLBACK:
  3712. {
  3713. Owned<IMessageUnpackCursor> callbackData = mr->getCursor(rowManager);
  3714. OwnedConstRoxieRow len = callbackData->getNext(sizeof(RecordLengthType));
  3715. if (len)
  3716. {
  3717. RecordLengthType *rowlen = (RecordLengthType *) len.get();
  3718. OwnedConstRoxieRow row = callbackData->getNext(*rowlen);
  3719. char *rowdata = (char *) row.get();
  3720. if (ctxTraceLevel > 5)
  3721. {
  3722. StringBuffer s;
  3723. activity.queryLogCtx().CTXLOG("Callback on query %s for debug", header.toString(s).str());
  3724. }
  3725. MemoryBuffer slaveInfo;
  3726. slaveInfo.setBuffer(*rowlen, rowdata, false);
  3727. unsigned debugSequence;
  3728. slaveInfo.read(debugSequence);
  3729. Owned<IRoxieQueryPacket> reply = original->getDebugResponse(debugSequence);
  3730. if (!reply)
  3731. reply.setown(activity.queryContext()->queryDebugContext()->onDebugCallback(header, *rowlen, rowdata));
  3732. if (reply)
  3733. {
  3734. original->setDebugResponse(debugSequence, reply);
  3735. ROQ->sendPacket(reply, activity.queryLogCtx());
  3736. }
  3737. }
  3738. else
  3739. throwUnexpected();
  3740. // MORE - somehow we need to make sure slave gets a reply even if I'm not waiting (in udp layer)
  3741. // Leave original message on pending queue in original location - this is not a reply to it.
  3742. break;
  3743. }
  3744. case ROXIE_FILECALLBACK:
  3745. {
  3746. // we need to send back to the slave a message containing the file info requested.
  3747. Owned<IMessageUnpackCursor> callbackData = mr->getCursor(rowManager);
  3748. OwnedConstRoxieRow len = callbackData->getNext(sizeof(RecordLengthType));
  3749. if (len)
  3750. {
  3751. RecordLengthType *rowlen = (RecordLengthType *) len.get();
  3752. OwnedConstRoxieRow row = callbackData->getNext(*rowlen);
  3753. const char *rowdata = (const char *) row.get();
  3754. bool isOpt = * (bool *) rowdata;
  3755. bool isLocal = * (bool *) (rowdata+1);
  3756. const char *lfn = rowdata+2;
  3757. if (ctxTraceLevel > 5)
  3758. {
  3759. StringBuffer s;
  3760. activity.queryLogCtx().CTXLOG("Callback on query %s file %s", header.toString(s).str(),(const char *) lfn);
  3761. }
  3762. activity.queryContext()->onFileCallback(header, lfn, isOpt, isLocal);
  3763. }
  3764. else
  3765. throwUnexpected();
  3766. // MORE - somehow we need to make sure slave gets a reply even if I'm not waiting (in udp layer)
  3767. // Leave original message on pending queue in original location - this is not a reply to it.
  3768. break;
  3769. }
  3770. case ROXIE_KEYEDLIMIT_EXCEEDED:
  3771. activity.queryLogCtx().CTXLOG("ROXIE_KEYEDLIMIT_EXCEEDED");
  3772. errorHandler->onLimitExceeded(true); // NOTE - should throw exception!
  3773. throwUnexpected();
  3774. case ROXIE_LIMIT_EXCEEDED:
  3775. activity.queryLogCtx().CTXLOG("ROXIE_LIMIT_EXCEEDED");
  3776. errorHandler->onLimitExceeded(false); // NOTE - should throw exception!
  3777. throwUnexpected();
  3778. case ROXIE_TRACEINFO:
  3779. {
  3780. Owned<IMessageUnpackCursor> extra = mr->getCursor(rowManager);
  3781. loop
  3782. {
  3783. RecordLengthType *rowlen = (RecordLengthType *) extra->getNext(sizeof(RecordLengthType));
  3784. if (rowlen)
  3785. {
  3786. char *logInfo = (char *) extra->getNext(*rowlen);
  3787. MemoryBuffer buf;
  3788. buf.setBuffer(*rowlen, logInfo, false);
  3789. activity.queryLogCtx().CTXLOGl(new LogItem(buf));
  3790. ReleaseRoxieRow(rowlen);
  3791. ReleaseRoxieRow(logInfo);
  3792. }
  3793. else
  3794. break;
  3795. }
  3796. break;
  3797. }
  3798. case ROXIE_EXCEPTION:
  3799. if (ctxTraceLevel > 1)
  3800. {
  3801. StringBuffer s;
  3802. activity.queryLogCtx().CTXLOG("Exception on query %s", header.toString(s).str());
  3803. }
  3804. op->queryHeader().noteException(header.retries);
  3805. if (op->queryHeader().allChannelsFailed())
  3806. {
  3807. activity.queryLogCtx().CTXLOG("Multiple exceptions on query - aborting");
  3808. Owned<IMessageUnpackCursor> exceptionData = mr->getCursor(rowManager);
  3809. throwRemoteException(exceptionData);
  3810. }
  3811. // Leave it on pending queue in original location
  3812. break;
  3813. case ROXIE_ALIVE:
  3814. if (ctxTraceLevel > 4)
  3815. {
  3816. StringBuffer s;
  3817. activity.queryLogCtx().CTXLOG("ROXIE_ALIVE: %s", header.toString(s).str());
  3818. }
  3819. op->queryHeader().noteAlive(header.retries & ROXIE_RETRIES_MASK);
  3820. // Leave it on pending queue in original location
  3821. break;
  3822. default:
  3823. if (header.retries & ROXIE_RETRIES_MASK)
  3824. atomic_inc(&retriesNeeded);
  3825. unsigned metaLen;
  3826. const void *metaData = mr->getMessageMetadata(metaLen);
  3827. if (metaLen)
  3828. {
  3829. // We got back first chunk but there is more.
  3830. // resend the packet, with the cursor info provided.
  3831. // MORE - if smart-stepping, we don't want to send the continuation immediately. Other cases it's not clear that we do.
  3832. if (ctxTraceLevel > 1)
  3833. {
  3834. StringBuffer s;
  3835. activity.queryLogCtx().CTXLOG("Additional data size %d on query %s mergeOrder %p", metaLen, header.toString(s).str(), mergeOrder);
  3836. }
  3837. if (*((unsigned short *) metaData) + sizeof(unsigned short) != metaLen)
  3838. {
  3839. StringBuffer s;
  3840. activity.queryLogCtx().CTXLOG("Additional data size %d on query %s mergeOrder %p", metaLen, header.toString(s).str(), mergeOrder);
  3841. activity.queryLogCtx().CTXLOG("Additional data is corrupt");
  3842. throwUnexpected();
  3843. }
  3844. MemoryBuffer nextQuery;
  3845. nextQuery.append(sizeof(RoxiePacketHeader), &header);
  3846. nextQuery.append(metaLen, metaData);
  3847. nextQuery.append(op->getTraceLength(), op->queryTraceInfo());
  3848. nextQuery.append(op->getContextLength(), op->queryContextData());
  3849. if (resendSequence == CONTINUESEQUENCE_MAX)
  3850. {
  3851. activity.queryLogCtx().CTXLOG("ERROR: Continuation sequence wrapped"); // shouldn't actually matter.... but suggests a very iffy query!
  3852. resendSequence = 1;
  3853. }
  3854. else
  3855. resendSequence++;
  3856. RoxiePacketHeader *newHeader = (RoxiePacketHeader *) nextQuery.toByteArray();
  3857. newHeader->continueSequence = resendSequence; // NOTE - we clear the skipTo flag since continuation of a skip is NOT a skip...
  3858. newHeader->retries &= ~ROXIE_RETRIES_MASK;
  3859. IRoxieQueryPacket *resend = createRoxiePacket(nextQuery);
  3860. CRoxieServerQueryPacket *fqp = new CRoxieServerQueryPacket(resend);
  3861. fqp->setSequence(original->getSequence());
  3862. pending.add(*fqp, idx+1); // note that pending takes ownership. sendPacket does not release.
  3863. original->setContinuation(LINK(fqp));
  3864. if (mergeOrder)
  3865. fqp->setDelayed(true);
  3866. else
  3867. {
  3868. ROQ->sendPacket(resend, activity.queryLogCtx());
  3869. sentsome.signal();
  3870. }
  3871. // Note that we don't attempt to cache results that have continuation records - too tricky !
  3872. }
  3873. else
  3874. {
  3875. if (serverSideCache)
  3876. serverSideCache->noteCachedResult(original, mr);
  3877. }
  3878. unsigned channel = header.channel;
  3879. {
  3880. ChannelBuffer *b = queryChannelBuffer(channel); // If not something is wrong, or we sent out on channel 0?
  3881. if (b)
  3882. b->signal();
  3883. }
  3884. original->setResult(mr.getClear());
  3885. sentsome.signal();
  3886. return;
  3887. }
  3888. }
  3889. }
  3890. else
  3891. {
  3892. if (!anyActivity)
  3893. {
  3894. activity.queryLogCtx().CTXLOG("Input has stalled - retry required?");
  3895. retryPending();
  3896. }
  3897. }
  3898. }
  3899. }
  3900. inline unsigned headerLength() const
  3901. {
  3902. return logInfo.length() + cachedContext.length() + sizeof(unsigned) + parentExtractSize;
  3903. }
  3904. void copyHeader(byte *tgt, unsigned channel) const
  3905. {
  3906. unsigned len = logInfo.length();
  3907. memcpy(tgt, logInfo.toByteArray(), len);
  3908. tgt += len;
  3909. *(unsigned *) tgt = parentExtractSize;
  3910. tgt += sizeof(unsigned);
  3911. memcpy(tgt, parentExtract, parentExtractSize);
  3912. tgt += parentExtractSize;
  3913. memcpy(tgt, cachedContext.toByteArray(), cachedContext.length());
  3914. tgt += cachedContext.length();
  3915. }
  3916. };
  3917. class CSkippableRemoteResultAdaptor : public CRemoteResultAdaptor
  3918. {
  3919. Owned <IException> exception;
  3920. bool skipping;
  3921. ConstPointerArray buff;
  3922. unsigned index;
  3923. bool pulled;
  3924. void pullInput()
  3925. {
  3926. try
  3927. {
  3928. if (exception)
  3929. throw exception.getClear();
  3930. unsigned __int64 count = 0;
  3931. loop
  3932. {
  3933. const void * next = CRemoteResultAdaptor::nextInGroup();
  3934. if (next == NULL)
  3935. {
  3936. next = CRemoteResultAdaptor::nextInGroup();
  3937. if(next == NULL)
  3938. break;
  3939. buff.append(NULL);
  3940. }
  3941. count++;
  3942. if (count > rowLimit)
  3943. {
  3944. ReleaseRoxieRow(next);
  3945. ReleaseRoxieRowSet(buff);
  3946. errorHandler->onLimitExceeded(false); // throws an exception - user or LimitSkipException
  3947. throwUnexpected();
  3948. }
  3949. else if (count > keyedLimit)
  3950. {
  3951. ReleaseRoxieRow(next);
  3952. ReleaseRoxieRowSet(buff);
  3953. errorHandler->onLimitExceeded(true); // throws an exception - user or LimitSkipException
  3954. throwUnexpected();
  3955. }
  3956. buff.append(next);
  3957. }
  3958. }
  3959. catch (IException *E)
  3960. {
  3961. if (QUERYINTERFACE(E, LimitSkipException))
  3962. {
  3963. Owned<IException> cleanup = E;
  3964. ReleaseRoxieRowSet(buff);
  3965. const void *onfail = errorHandler->createLimitFailRow(E->errorCode() == KeyedLimitSkipErrorCode);
  3966. if (onfail)
  3967. buff.append(onfail);
  3968. }
  3969. else
  3970. throw;
  3971. }
  3972. pulled = true;
  3973. }
  3974. public:
  3975. CSkippableRemoteResultAdaptor(const RemoteActivityId &_remoteId, IOutputMetaData *_meta, IHThorArg &_helper, IRoxieServerActivity &_activity, bool _preserveOrder, bool _flowControlled, bool _skipping) :
  3976. CRemoteResultAdaptor(_remoteId, _meta, _helper, _activity, _preserveOrder, _flowControlled)
  3977. {
  3978. skipping = _skipping;
  3979. index = 0;
  3980. pulled = false;
  3981. }
  3982. void setException(IException *E)
  3983. {
  3984. exception.setown(E);
  3985. }
  3986. virtual void onReset()
  3987. {
  3988. while (buff.isItem(index))
  3989. ReleaseRoxieRow(buff.item(index++));
  3990. buff.kill();
  3991. pulled = false;
  3992. exception.clear();
  3993. CRemoteResultAdaptor::onReset();
  3994. }
  3995. void onStart(unsigned _parentExtractSize, const byte * _parentExtract)
  3996. {
  3997. index = 0;
  3998. pulled = false;
  3999. CRemoteResultAdaptor::onStart(_parentExtractSize, _parentExtract);
  4000. }
  4001. virtual const void * nextSteppedGE(const void *seek, const void *rawSeek, unsigned numFields, unsigned seeklen, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  4002. {
  4003. // 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
  4004. if (exception)
  4005. throw exception.getClear();
  4006. return CRemoteResultAdaptor::nextSteppedGE(seek, rawSeek, numFields, seeklen, wasCompleteMatch, stepExtra);
  4007. }
  4008. virtual const void *nextInGroup()
  4009. {
  4010. if (skipping)
  4011. {
  4012. if(!pulled)
  4013. pullInput();
  4014. if(buff.isItem(index))
  4015. {
  4016. const void * next = buff.item(index++);
  4017. if(next)
  4018. processed++;
  4019. return next;
  4020. }
  4021. return NULL;
  4022. }
  4023. else
  4024. {
  4025. if (exception)
  4026. throw exception.getClear();
  4027. return CRemoteResultAdaptor::nextInGroup();
  4028. }
  4029. }
  4030. };
  4031. //=================================================================================
  4032. class CRoxieServerApplyActivity : public CRoxieServerInternalSinkActivity
  4033. {
  4034. IHThorApplyArg &helper;
  4035. public:
  4036. CRoxieServerApplyActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4037. : CRoxieServerInternalSinkActivity(_factory, _probeManager), helper((IHThorApplyArg &) basehelper)
  4038. {
  4039. }
  4040. virtual void onExecute()
  4041. {
  4042. helper.start();
  4043. loop
  4044. {
  4045. const void * next = input->nextInGroup();
  4046. if (!next)
  4047. {
  4048. next = input->nextInGroup();
  4049. if (!next)
  4050. break;
  4051. }
  4052. helper.apply(next);
  4053. ReleaseRoxieRow(next);
  4054. }
  4055. helper.end();
  4056. }
  4057. };
  4058. class CRoxieServerApplyActivityFactory : public CRoxieServerActivityFactory
  4059. {
  4060. bool isRoot;
  4061. public:
  4062. CRoxieServerApplyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  4063. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  4064. {
  4065. }
  4066. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4067. {
  4068. return new CRoxieServerApplyActivity(this, _probeManager);
  4069. }
  4070. virtual bool isSink() const
  4071. {
  4072. return isRoot;
  4073. }
  4074. };
  4075. IRoxieServerActivityFactory *createRoxieServerApplyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  4076. {
  4077. return new CRoxieServerApplyActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  4078. }
  4079. //=================================================================================
  4080. class CRoxieServerNullActivity : public CRoxieServerActivity
  4081. {
  4082. public:
  4083. CRoxieServerNullActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4084. : CRoxieServerActivity(_factory, _probeManager)
  4085. {
  4086. }
  4087. virtual const void *nextInGroup()
  4088. {
  4089. return NULL;
  4090. }
  4091. };
  4092. IRoxieServerActivity * createRoxieServerNullActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4093. {
  4094. return new CRoxieServerNullActivity(_factory, _probeManager);
  4095. }
  4096. class CRoxieServerNullActivityFactory : public CRoxieServerActivityFactory
  4097. {
  4098. public:
  4099. CRoxieServerNullActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4100. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4101. {
  4102. }
  4103. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4104. {
  4105. return new CRoxieServerNullActivity(this, _probeManager);
  4106. }
  4107. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  4108. {
  4109. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for null activity");
  4110. }
  4111. };
  4112. IRoxieServerActivityFactory *createRoxieServerNullActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4113. {
  4114. return new CRoxieServerNullActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4115. }
  4116. //=================================================================================
  4117. class CRoxieServerPassThroughActivity : public CRoxieServerActivity
  4118. {
  4119. public:
  4120. CRoxieServerPassThroughActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4121. : CRoxieServerActivity(_factory, _probeManager)
  4122. {
  4123. }
  4124. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  4125. {
  4126. return input->gatherConjunctions(collector);
  4127. }
  4128. virtual void resetEOF()
  4129. {
  4130. input->resetEOF();
  4131. }
  4132. virtual const void *nextInGroup()
  4133. {
  4134. const void * next = input->nextInGroup();
  4135. if (next)
  4136. processed++;
  4137. return next;
  4138. }
  4139. virtual bool isPassThrough()
  4140. {
  4141. return true;
  4142. }
  4143. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  4144. {
  4145. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  4146. const void * next = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  4147. if (next)
  4148. processed++;
  4149. return next;
  4150. }
  4151. IInputSteppingMeta * querySteppingMeta()
  4152. {
  4153. return input->querySteppingMeta();
  4154. }
  4155. };
  4156. IRoxieServerActivity * createRoxieServerPassThroughActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4157. {
  4158. return new CRoxieServerPassThroughActivity(_factory, _probeManager);
  4159. }
  4160. //=================================================================================
  4161. class CRoxieServerChildBaseActivity : public CRoxieServerActivity
  4162. {
  4163. protected:
  4164. bool eof;
  4165. bool first;
  4166. public:
  4167. CRoxieServerChildBaseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4168. : CRoxieServerActivity(_factory, _probeManager)
  4169. {
  4170. eof = false;
  4171. first = true;
  4172. }
  4173. ~CRoxieServerChildBaseActivity()
  4174. {
  4175. }
  4176. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4177. {
  4178. eof = false;
  4179. first = true;
  4180. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  4181. }
  4182. };
  4183. class CRoxieServerChildBaseActivityFactory : public CRoxieServerActivityFactory
  4184. {
  4185. public:
  4186. CRoxieServerChildBaseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4187. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4188. {
  4189. }
  4190. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  4191. {
  4192. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  4193. }
  4194. };
  4195. //=================================================================================
  4196. class CRoxieServerChildIteratorActivity : public CRoxieServerChildBaseActivity
  4197. {
  4198. IHThorChildIteratorArg &helper;
  4199. public:
  4200. CRoxieServerChildIteratorActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4201. : CRoxieServerChildBaseActivity(_factory, _probeManager), helper((IHThorChildIteratorArg &) basehelper)
  4202. {
  4203. }
  4204. virtual bool needsAllocator() const { return true; }
  4205. virtual const void *nextInGroup()
  4206. {
  4207. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  4208. if (eof)
  4209. return NULL;
  4210. bool ok;
  4211. if (first)
  4212. {
  4213. ok = helper.first();
  4214. first = false;
  4215. }
  4216. else
  4217. ok = helper.next();
  4218. try
  4219. {
  4220. while (ok)
  4221. {
  4222. processed++;
  4223. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  4224. unsigned outSize = helper.transform(rowBuilder);
  4225. if (outSize)
  4226. return rowBuilder.finalizeRowClear(outSize);
  4227. ok = helper.next();
  4228. }
  4229. }
  4230. catch (IException *E)
  4231. {
  4232. throw makeWrappedException(E);
  4233. }
  4234. eof = true;
  4235. return NULL;
  4236. }
  4237. };
  4238. class CRoxieServerChildIteratorActivityFactory : public CRoxieServerChildBaseActivityFactory
  4239. {
  4240. public:
  4241. CRoxieServerChildIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4242. : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4243. {
  4244. }
  4245. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4246. {
  4247. return new CRoxieServerChildIteratorActivity(this, _probeManager);
  4248. }
  4249. };
  4250. IRoxieServerActivityFactory *createRoxieServerChildIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4251. {
  4252. return new CRoxieServerChildIteratorActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4253. }
  4254. //=================================================================================
  4255. class CRoxieServerChildNormalizeActivity : public CRoxieServerChildBaseActivity
  4256. {
  4257. IHThorChildNormalizeArg &helper;
  4258. public:
  4259. CRoxieServerChildNormalizeActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4260. : CRoxieServerChildBaseActivity(_factory, _probeManager), helper((IHThorChildNormalizeArg &) basehelper)
  4261. {
  4262. }
  4263. virtual bool needsAllocator() const { return true; }
  4264. virtual const void *nextInGroup()
  4265. {
  4266. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  4267. if (eof)
  4268. return NULL;
  4269. bool ok;
  4270. if (first)
  4271. {
  4272. ok = helper.first();
  4273. first = false;
  4274. }
  4275. else
  4276. ok = helper.next();
  4277. if (ok)
  4278. {
  4279. try
  4280. {
  4281. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  4282. do {
  4283. unsigned outSize = helper.transform(rowBuilder);
  4284. if (outSize)
  4285. {
  4286. processed++;
  4287. return rowBuilder.finalizeRowClear(outSize);
  4288. }
  4289. ok = helper.next();
  4290. }
  4291. while (ok);
  4292. }
  4293. catch (IException *E)
  4294. {
  4295. throw makeWrappedException(E);
  4296. }
  4297. }
  4298. eof = true;
  4299. return NULL;
  4300. }
  4301. };
  4302. class CRoxieServerChildNormalizeActivityFactory : public CRoxieServerChildBaseActivityFactory
  4303. {
  4304. public:
  4305. CRoxieServerChildNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4306. : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4307. {
  4308. }
  4309. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4310. {
  4311. return new CRoxieServerChildNormalizeActivity(this, _probeManager);
  4312. }
  4313. };
  4314. IRoxieServerActivityFactory *createRoxieServerNewChildNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4315. {
  4316. return new CRoxieServerChildNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4317. }
  4318. //=================================================================================
  4319. class CRoxieServerChildAggregateActivity : public CRoxieServerChildBaseActivity
  4320. {
  4321. IHThorChildAggregateArg &helper;
  4322. public:
  4323. CRoxieServerChildAggregateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4324. : CRoxieServerChildBaseActivity(_factory, _probeManager), helper((IHThorChildAggregateArg &) basehelper)
  4325. {
  4326. }
  4327. virtual bool needsAllocator() const { return true; }
  4328. virtual const void *nextInGroup()
  4329. {
  4330. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  4331. if (eof)
  4332. return NULL;
  4333. eof = true;
  4334. processed++;
  4335. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  4336. helper.clearAggregate(rowBuilder);
  4337. helper.processRows(rowBuilder);
  4338. size32_t finalSize = meta.getRecordSize(rowBuilder.getSelf());
  4339. return rowBuilder.finalizeRowClear(finalSize);
  4340. }
  4341. };
  4342. class CRoxieServerChildAggregateActivityFactory : public CRoxieServerChildBaseActivityFactory
  4343. {
  4344. public:
  4345. CRoxieServerChildAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4346. : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4347. {
  4348. }
  4349. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4350. {
  4351. return new CRoxieServerChildAggregateActivity(this, _probeManager);
  4352. }
  4353. };
  4354. IRoxieServerActivityFactory *createRoxieServerNewChildAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4355. {
  4356. return new CRoxieServerChildAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4357. }
  4358. //=================================================================================
  4359. class CRoxieServerChildGroupAggregateActivity : public CRoxieServerChildBaseActivity, public IHThorGroupAggregateCallback
  4360. {
  4361. IHThorChildGroupAggregateArg &helper;
  4362. RowAggregator aggregated;
  4363. public:
  4364. IMPLEMENT_IINTERFACE
  4365. CRoxieServerChildGroupAggregateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4366. : CRoxieServerChildBaseActivity(_factory, _probeManager), helper((IHThorChildGroupAggregateArg &) basehelper),
  4367. aggregated(helper, helper)
  4368. {
  4369. }
  4370. void processRow(const void * next)
  4371. {
  4372. aggregated.addRow(next);
  4373. }
  4374. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4375. {
  4376. CRoxieServerChildBaseActivity::start(parentExtractSize, parentExtract, paused);
  4377. aggregated.start(rowAllocator);
  4378. }
  4379. virtual void reset()
  4380. {
  4381. aggregated.reset();
  4382. CRoxieServerChildBaseActivity::reset();
  4383. }
  4384. virtual bool needsAllocator() const { return true; }
  4385. virtual const void *nextInGroup()
  4386. {
  4387. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  4388. if (eof)
  4389. return NULL;
  4390. if (first)
  4391. {
  4392. helper.processRows(this);
  4393. first = false;
  4394. }
  4395. Owned<AggregateRowBuilder> next = aggregated.nextResult();
  4396. if (next)
  4397. {
  4398. processed++;
  4399. return next->finalizeRowClear();
  4400. }
  4401. eof = true;
  4402. return NULL;
  4403. }
  4404. };
  4405. class CRoxieServerChildGroupAggregateActivityFactory : public CRoxieServerChildBaseActivityFactory
  4406. {
  4407. public:
  4408. CRoxieServerChildGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4409. : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4410. {
  4411. }
  4412. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4413. {
  4414. return new CRoxieServerChildGroupAggregateActivity(this, _probeManager);
  4415. }
  4416. };
  4417. IRoxieServerActivityFactory *createRoxieServerNewChildGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4418. {
  4419. return new CRoxieServerChildGroupAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4420. }
  4421. //=================================================================================
  4422. class CRoxieServerChildThroughNormalizeActivity : public CRoxieServerChildBaseActivity
  4423. {
  4424. IHThorChildThroughNormalizeArg &helper;
  4425. const void * lastInput;
  4426. unsigned numProcessedLastGroup;
  4427. bool ok;
  4428. public:
  4429. CRoxieServerChildThroughNormalizeActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4430. : CRoxieServerChildBaseActivity(_factory, _probeManager), helper((IHThorChildThroughNormalizeArg &) basehelper)
  4431. {
  4432. lastInput = NULL;
  4433. numProcessedLastGroup = 0;
  4434. ok = false;
  4435. }
  4436. virtual void stop(bool aborting)
  4437. {
  4438. CRoxieServerChildBaseActivity::stop(aborting);
  4439. ReleaseRoxieRow(lastInput);
  4440. lastInput = NULL;
  4441. }
  4442. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4443. {
  4444. CRoxieServerChildBaseActivity::start(parentExtractSize, parentExtract, paused);
  4445. numProcessedLastGroup = processed;
  4446. ok = false;
  4447. }
  4448. virtual bool needsAllocator() const { return true; }
  4449. virtual const void *nextInGroup()
  4450. {
  4451. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  4452. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  4453. loop
  4454. {
  4455. if (ok)
  4456. ok = helper.next();
  4457. while (!ok)
  4458. {
  4459. ReleaseRoxieRow(lastInput);
  4460. lastInput = input->nextInGroup();
  4461. if (!lastInput)
  4462. {
  4463. if (numProcessedLastGroup != processed)
  4464. {
  4465. numProcessedLastGroup = processed;
  4466. return NULL;
  4467. }
  4468. lastInput = input->nextInGroup();
  4469. if (!lastInput)
  4470. return NULL;
  4471. }
  4472. ok = helper.first(lastInput);
  4473. }
  4474. try
  4475. {
  4476. do
  4477. {
  4478. unsigned outSize = helper.transform(rowBuilder);
  4479. if (outSize)
  4480. {
  4481. processed++;
  4482. return rowBuilder.finalizeRowClear(outSize);
  4483. }
  4484. ok = helper.next();
  4485. } while (ok);
  4486. }
  4487. catch (IException *E)
  4488. {
  4489. throw makeWrappedException(E);
  4490. }
  4491. }
  4492. }
  4493. };
  4494. class CRoxieServerChildThroughNormalizeActivityFactory : public CRoxieServerActivityFactory
  4495. {
  4496. public:
  4497. CRoxieServerChildThroughNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4498. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4499. {
  4500. }
  4501. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4502. {
  4503. return new CRoxieServerChildThroughNormalizeActivity(this, _probeManager);
  4504. }
  4505. };
  4506. IRoxieServerActivityFactory *createRoxieServerNewChildThroughNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4507. {
  4508. return new CRoxieServerChildThroughNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4509. }
  4510. //=================================================================================
  4511. class CRoxieServerDistributionActivity : public CRoxieServerInternalSinkActivity
  4512. {
  4513. IHThorDistributionArg &helper;
  4514. public:
  4515. CRoxieServerDistributionActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4516. : CRoxieServerInternalSinkActivity(_factory, _probeManager), helper((IHThorDistributionArg &)basehelper)
  4517. {
  4518. }
  4519. virtual void onExecute()
  4520. {
  4521. MemoryAttr ma;
  4522. IDistributionTable * * accumulator = (IDistributionTable * *)ma.allocate(helper.queryInternalRecordSize()->getMinRecordSize());
  4523. helper.clearAggregate(accumulator);
  4524. OwnedConstRoxieRow nextrec(input->nextInGroup());
  4525. loop
  4526. {
  4527. if (!nextrec)
  4528. {
  4529. nextrec.setown(input->nextInGroup());
  4530. if (!nextrec)
  4531. break;
  4532. }
  4533. helper.process(accumulator, nextrec);
  4534. nextrec.setown(input->nextInGroup());
  4535. }
  4536. StringBuffer result;
  4537. result.append("<XML>");
  4538. helper.gatherResult(accumulator, result);
  4539. result.append("</XML>");
  4540. helper.sendResult(result.length(), result.str());
  4541. helper.destruct(accumulator);
  4542. }
  4543. };
  4544. class CRoxieServerDistributionActivityFactory : public CRoxieServerActivityFactory
  4545. {
  4546. bool isRoot;
  4547. public:
  4548. CRoxieServerDistributionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  4549. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  4550. {
  4551. }
  4552. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4553. {
  4554. return new CRoxieServerDistributionActivity(this, _probeManager);
  4555. }
  4556. virtual bool isSink() const
  4557. {
  4558. return isRoot;
  4559. }
  4560. };
  4561. IRoxieServerActivityFactory *createRoxieServerDistributionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  4562. {
  4563. return new CRoxieServerDistributionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  4564. }
  4565. //=================================================================================
  4566. class CRoxieServerLinkedRawIteratorActivity : public CRoxieServerActivity
  4567. {
  4568. IHThorLinkedRawIteratorArg &helper;
  4569. public:
  4570. CRoxieServerLinkedRawIteratorActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4571. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorLinkedRawIteratorArg &) basehelper)
  4572. {
  4573. }
  4574. virtual const void *nextInGroup()
  4575. {
  4576. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  4577. const void *ret =helper.next();
  4578. if (ret)
  4579. {
  4580. LinkRoxieRow(ret);
  4581. processed++;
  4582. }
  4583. return ret;
  4584. }
  4585. };
  4586. class CRoxieServerLinkedRawIteratorActivityFactory : public CRoxieServerActivityFactory
  4587. {
  4588. public:
  4589. CRoxieServerLinkedRawIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4590. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4591. {
  4592. }
  4593. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4594. {
  4595. return new CRoxieServerLinkedRawIteratorActivity(this, _probeManager);
  4596. }
  4597. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  4598. {
  4599. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  4600. }
  4601. };
  4602. IRoxieServerActivityFactory *createRoxieServerLinkedRawIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4603. {
  4604. return new CRoxieServerLinkedRawIteratorActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4605. }
  4606. //=================================================================================
  4607. class CRoxieServerDatasetResultActivity : public CRoxieServerActivity
  4608. {
  4609. public:
  4610. CRoxieServerDatasetResultActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4611. : CRoxieServerActivity(_factory, _probeManager)
  4612. {
  4613. }
  4614. virtual const void *nextInGroup()
  4615. {
  4616. throwUnexpected();
  4617. }
  4618. virtual void executeChild(size32_t & retSize, void * & ret, unsigned parentExtractSize, const byte * parentExtract)
  4619. {
  4620. try
  4621. {
  4622. start(parentExtractSize, parentExtract, false);
  4623. {
  4624. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  4625. MemoryBuffer result;
  4626. IRecordSize * inputMeta = input->queryOutputMeta();
  4627. loop
  4628. {
  4629. const void *nextrec = input->nextInGroup();
  4630. if (!nextrec)
  4631. {
  4632. nextrec = input->nextInGroup();
  4633. if (!nextrec)
  4634. break;
  4635. }
  4636. result.append(inputMeta->getRecordSize(nextrec), nextrec);
  4637. ReleaseRoxieRow(nextrec);
  4638. }
  4639. retSize = result.length();
  4640. ret = result.detach();
  4641. }
  4642. stop(false);
  4643. reset();
  4644. }
  4645. catch(IException *E)
  4646. {
  4647. ctx->notifyAbort(E);
  4648. stop(true);
  4649. reset();
  4650. throw;
  4651. }
  4652. catch(...)
  4653. {
  4654. Owned<IException> E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught at %s:%d", __FILE__, __LINE__);
  4655. ctx->notifyAbort(E);
  4656. stop(true);
  4657. reset();
  4658. throw;
  4659. }
  4660. }
  4661. };
  4662. class CRoxieServerDatasetResultActivityFactory : public CRoxieServerActivityFactory
  4663. {
  4664. bool isRoot;
  4665. public:
  4666. CRoxieServerDatasetResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  4667. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  4668. {
  4669. }
  4670. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4671. {
  4672. return new CRoxieServerDatasetResultActivity(this, _probeManager);
  4673. }
  4674. virtual bool isSink() const
  4675. {
  4676. return isRoot;
  4677. }
  4678. };
  4679. IRoxieServerActivityFactory *createRoxieServerDatasetResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  4680. {
  4681. return new CRoxieServerDatasetResultActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  4682. }
  4683. //=================================================================================
  4684. class CRoxieServerInlineTableActivity : public CRoxieServerActivity
  4685. {
  4686. IHThorInlineTableArg &helper;
  4687. __uint64 curRow;
  4688. __uint64 numRows;
  4689. public:
  4690. CRoxieServerInlineTableActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4691. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorInlineTableArg &) basehelper)
  4692. {
  4693. }
  4694. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4695. {
  4696. curRow = 0;
  4697. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  4698. numRows = helper.numRows();
  4699. }
  4700. virtual bool needsAllocator() const { return true; }
  4701. virtual const void *nextInGroup()
  4702. {
  4703. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  4704. // Filtering empty rows, returns the next valid row
  4705. while (curRow < numRows)
  4706. {
  4707. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  4708. unsigned outSize = helper.getRow(rowBuilder, curRow++);
  4709. if (outSize)
  4710. {
  4711. processed++;
  4712. return rowBuilder.finalizeRowClear(outSize);
  4713. }
  4714. }
  4715. return NULL;
  4716. }
  4717. virtual void setInput(unsigned idx, IRoxieInput *_in)
  4718. {
  4719. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  4720. }
  4721. };
  4722. class CRoxieServerInlineTableActivityFactory : public CRoxieServerActivityFactory
  4723. {
  4724. public:
  4725. CRoxieServerInlineTableActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4726. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4727. {
  4728. }
  4729. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4730. {
  4731. return new CRoxieServerInlineTableActivity(this, _probeManager);
  4732. }
  4733. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  4734. {
  4735. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for InlineTable activity");
  4736. }
  4737. };
  4738. IRoxieServerActivityFactory *createRoxieServerInlineTableActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4739. {
  4740. return new CRoxieServerInlineTableActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4741. }
  4742. //=================================================================================
  4743. class CRoxieServerWorkUnitReadActivity : public CRoxieServerActivity
  4744. {
  4745. IHThorWorkunitReadArg &helper;
  4746. Owned<IWorkUnitRowReader> wuReader; // MORE - can we use IRoxieInput instead?
  4747. public:
  4748. CRoxieServerWorkUnitReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4749. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorWorkunitReadArg &)basehelper)
  4750. {
  4751. }
  4752. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  4753. {
  4754. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  4755. if (!ctx->queryServerContext())
  4756. {
  4757. throw MakeStringException(ROXIE_INTERNAL_ERROR, "Workunit read activity cannot be executed in slave context");
  4758. }
  4759. }
  4760. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4761. {
  4762. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  4763. IXmlToRowTransformer * xmlTransformer = helper.queryXmlTransformer();
  4764. OwnedRoxieString fromWuid(helper.getWUID());
  4765. if (fromWuid)
  4766. UNIMPLEMENTED;
  4767. wuReader.setown(ctx->getWorkunitRowReader(helper.queryName(), helper.querySequence(), xmlTransformer, rowAllocator, meta.isGrouped()));
  4768. // MORE _ should that be in onCreate?
  4769. }
  4770. virtual void reset()
  4771. {
  4772. wuReader.clear();
  4773. CRoxieServerActivity::reset();
  4774. };
  4775. virtual bool needsAllocator() const { return true; }
  4776. virtual const void *nextInGroup()
  4777. {
  4778. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  4779. const void *ret = wuReader->nextInGroup();
  4780. if (ret)
  4781. processed++;
  4782. return ret;
  4783. }
  4784. virtual void setInput(unsigned idx, IRoxieInput *_in)
  4785. {
  4786. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  4787. }
  4788. };
  4789. class CRoxieServerWorkUnitReadActivityFactory : public CRoxieServerActivityFactory
  4790. {
  4791. public:
  4792. CRoxieServerWorkUnitReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4793. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4794. {
  4795. }
  4796. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4797. {
  4798. return new CRoxieServerWorkUnitReadActivity(this, _probeManager);
  4799. }
  4800. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  4801. {
  4802. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for WorkUnitRead activity");
  4803. }
  4804. };
  4805. IRoxieServerActivityFactory *createRoxieServerWorkUnitReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4806. {
  4807. return new CRoxieServerWorkUnitReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4808. }
  4809. //=================================================================================
  4810. interface ILocalGraphEx : public IEclGraphResults
  4811. {
  4812. public:
  4813. virtual void setResult(unsigned id, IGraphResult * result) = 0;
  4814. virtual IRoxieInput * createResultIterator(unsigned id) = 0;
  4815. virtual void setGraphLoopResult(IGraphResult * result) = 0;
  4816. virtual IRoxieInput * createGraphLoopResultIterator(unsigned id) = 0;
  4817. };
  4818. class CSafeRoxieInput : public CInterface, implements IRoxieInput
  4819. {
  4820. public:
  4821. CSafeRoxieInput(IRoxieInput * _input) : input(_input) {}
  4822. IMPLEMENT_IINTERFACE
  4823. virtual IOutputMetaData * queryOutputMeta() const
  4824. {
  4825. return input->queryOutputMeta();
  4826. }
  4827. virtual unsigned queryId() const
  4828. {
  4829. return input->queryId();
  4830. }
  4831. virtual unsigned __int64 queryTotalCycles() const
  4832. {
  4833. return input->queryTotalCycles();
  4834. }
  4835. virtual unsigned __int64 queryLocalCycles() const
  4836. {
  4837. return input->queryLocalCycles();
  4838. }
  4839. virtual IRoxieInput *queryInput(unsigned idx) const
  4840. {
  4841. return input->queryInput(idx);
  4842. }
  4843. virtual IRoxieServerActivity *queryActivity()
  4844. {
  4845. return input->queryActivity();
  4846. }
  4847. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  4848. {
  4849. return input->queryIndexReadActivity();
  4850. }
  4851. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4852. {
  4853. CriticalBlock procedure(cs);
  4854. input->start(parentExtractSize, parentExtract, paused);
  4855. }
  4856. virtual void stop(bool aborting)
  4857. {
  4858. CriticalBlock procedure(cs);
  4859. input->stop(aborting);
  4860. }
  4861. virtual void reset()
  4862. {
  4863. CriticalBlock procedure(cs);
  4864. input->reset();
  4865. }
  4866. virtual void resetEOF()
  4867. {
  4868. CriticalBlock procedure(cs);
  4869. input->resetEOF();
  4870. }
  4871. virtual void checkAbort()
  4872. {
  4873. CriticalBlock procedure(cs);
  4874. input->checkAbort();
  4875. }
  4876. virtual const void *nextInGroup()
  4877. {
  4878. CriticalBlock procedure(cs);
  4879. return input->nextInGroup();
  4880. }
  4881. virtual bool nextGroup(ConstPointerArray & group)
  4882. {
  4883. CriticalBlock procedure(cs);
  4884. return input->nextGroup(group);
  4885. }
  4886. private:
  4887. CriticalSection cs;
  4888. Linked<IRoxieInput> input;
  4889. };
  4890. //=================================================================================
  4891. class CPseudoRoxieInput : public CInterface, implements IRoxieInput
  4892. {
  4893. protected:
  4894. unsigned __int64 totalCycles;
  4895. public:
  4896. IMPLEMENT_IINTERFACE;
  4897. CPseudoRoxieInput()
  4898. {
  4899. totalCycles = 0;
  4900. }
  4901. virtual unsigned __int64 queryTotalCycles() const
  4902. {
  4903. return totalCycles;
  4904. }
  4905. virtual unsigned __int64 queryLocalCycles() const
  4906. {
  4907. return totalCycles;
  4908. }
  4909. virtual IRoxieInput *queryInput(unsigned idx) const
  4910. {
  4911. return NULL;
  4912. }
  4913. virtual IRoxieServerActivity *queryActivity()
  4914. {
  4915. throwUnexpected();
  4916. }
  4917. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  4918. {
  4919. throwUnexpected();
  4920. }
  4921. virtual IOutputMetaData * queryOutputMeta() const { throwUnexpected(); }
  4922. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused) { }
  4923. virtual void stop(bool aborting) { }
  4924. virtual void reset() { totalCycles = 0; }
  4925. virtual void checkAbort() { }
  4926. virtual unsigned queryId() const { throwUnexpected(); }
  4927. virtual void resetEOF() { }
  4928. };
  4929. class CIndirectRoxieInput : public CPseudoRoxieInput
  4930. {
  4931. public:
  4932. CIndirectRoxieInput(IRoxieInput * _input = NULL) : input(_input)
  4933. {
  4934. }
  4935. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4936. {
  4937. input->start(parentExtractSize, parentExtract, paused);
  4938. }
  4939. virtual void stop(bool aborting)
  4940. {
  4941. input->stop(aborting);
  4942. }
  4943. virtual void reset()
  4944. {
  4945. input->reset();
  4946. totalCycles = 0;
  4947. }
  4948. virtual void checkAbort()
  4949. {
  4950. input->checkAbort();
  4951. }
  4952. virtual const void * nextInGroup()
  4953. {
  4954. return input->nextInGroup();
  4955. }
  4956. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  4957. {
  4958. return input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  4959. }
  4960. virtual unsigned __int64 queryLocalCycles() const
  4961. {
  4962. __int64 ret = totalCycles - input->queryTotalCycles();
  4963. if (ret < 0)
  4964. ret = 0;
  4965. return ret;
  4966. }
  4967. virtual IRoxieInput *queryInput(unsigned idx) const
  4968. {
  4969. return input->queryInput(idx);
  4970. }
  4971. virtual unsigned queryId() const
  4972. {
  4973. return input->queryId();
  4974. }
  4975. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  4976. {
  4977. return input->gatherConjunctions(collector);
  4978. }
  4979. virtual void resetEOF()
  4980. {
  4981. input->resetEOF();
  4982. }
  4983. virtual unsigned numConcreteOutputs() const
  4984. {
  4985. return input->numConcreteOutputs();
  4986. }
  4987. virtual IRoxieInput * queryConcreteInput(unsigned idx)
  4988. {
  4989. return input->queryConcreteInput(idx);
  4990. }
  4991. virtual IOutputMetaData * queryOutputMeta() const
  4992. {
  4993. return input->queryOutputMeta();
  4994. }
  4995. virtual IRoxieServerActivity *queryActivity()
  4996. {
  4997. return input->queryActivity();
  4998. }
  4999. void setInput(IRoxieInput * _input)
  5000. {
  5001. input = _input;
  5002. }
  5003. protected:
  5004. IRoxieInput * input;
  5005. };
  5006. class CExtractMapperInput : public CIndirectRoxieInput
  5007. {
  5008. unsigned savedParentExtractSize;
  5009. const byte * savedParentExtract;
  5010. public:
  5011. CExtractMapperInput(IRoxieInput * _input = NULL) : CIndirectRoxieInput(_input)
  5012. {
  5013. savedParentExtractSize = 0;
  5014. savedParentExtract = NULL;
  5015. }
  5016. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5017. {
  5018. input->start(savedParentExtractSize, savedParentExtract, paused);
  5019. }
  5020. void setParentExtract(unsigned _savedParentExtractSize, const byte * _savedParentExtract)
  5021. {
  5022. savedParentExtractSize = _savedParentExtractSize;
  5023. savedParentExtract = _savedParentExtract;
  5024. }
  5025. };
  5026. class CGraphResult : public CInterface, implements IGraphResult
  5027. {
  5028. CriticalSection cs;
  5029. byte **rowset;
  5030. size32_t count;
  5031. bool complete;
  5032. void clear()
  5033. {
  5034. CriticalBlock func(cs);
  5035. rtlReleaseRowset(count, rowset);
  5036. rowset = NULL;
  5037. count = 0;
  5038. complete = false;
  5039. }
  5040. public:
  5041. IMPLEMENT_IINTERFACE
  5042. CGraphResult()
  5043. {
  5044. complete = false; // dummy result is not supposed to be used...
  5045. rowset = NULL;
  5046. count = 0;
  5047. }
  5048. CGraphResult(size32_t _count, byte **_rowset)
  5049. : count(_count), rowset(_rowset)
  5050. {
  5051. complete = true;
  5052. }
  5053. ~CGraphResult()
  5054. {
  5055. clear();
  5056. }
  5057. // interface IGraphResult
  5058. virtual IRoxieInput * createIterator()
  5059. {
  5060. if (!complete)
  5061. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Internal Error: Reading uninitialised graph result");
  5062. return new CGraphResultIterator(this);
  5063. }
  5064. virtual void getLinkedResult(unsigned & countResult, byte * * & result)
  5065. {
  5066. if (!complete)
  5067. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Internal Error: Reading uninitialised graph result");
  5068. result = rtlLinkRowset(rowset);
  5069. countResult = count;
  5070. }
  5071. virtual const void * getLinkedRowResult()
  5072. {
  5073. if (!complete)
  5074. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Internal Error: Reading uninitialised graph result");
  5075. if (count != 1)
  5076. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Internal Error: Expected a single row result");
  5077. const void * ret = rowset[0];
  5078. LinkRoxieRow(ret);
  5079. return ret;
  5080. }
  5081. //other
  5082. const void * getRow(unsigned i)
  5083. {
  5084. CriticalBlock func(cs);
  5085. if (i >= count)
  5086. return NULL;
  5087. const void * ret = rowset[i];
  5088. if (ret) LinkRoxieRow(ret);
  5089. return ret;
  5090. }
  5091. protected:
  5092. class CGraphResultIterator : public CPseudoRoxieInput
  5093. {
  5094. unsigned i;
  5095. Linked<CGraphResult> result;
  5096. public:
  5097. CGraphResultIterator(CGraphResult * _result) : result(_result) { i = 0; }
  5098. IMPLEMENT_IINTERFACE
  5099. public:
  5100. virtual const void * nextInGroup()
  5101. {
  5102. return result->getRow(i++);
  5103. }
  5104. };
  5105. };
  5106. //=================================================================================
  5107. class CRoxieServerLocalResultReadActivity : public CRoxieServerActivity
  5108. {
  5109. IHThorLocalResultReadArg &helper;
  5110. Owned<IRoxieInput> iter;
  5111. ILocalGraphEx * graph;
  5112. unsigned graphId;
  5113. unsigned sequence;
  5114. public:
  5115. CRoxieServerLocalResultReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId)
  5116. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorLocalResultReadArg &)basehelper), graphId(_graphId)
  5117. {
  5118. graph = NULL;
  5119. sequence = 0;
  5120. }
  5121. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  5122. {
  5123. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  5124. graph = static_cast<ILocalGraphEx *>(_ctx->queryCodeContext()->resolveLocalQuery(graphId));
  5125. sequence = helper.querySequence();
  5126. }
  5127. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5128. {
  5129. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5130. iter.setown(graph->createResultIterator(sequence));
  5131. }
  5132. virtual void reset()
  5133. {
  5134. iter.clear();
  5135. CRoxieServerActivity::reset();
  5136. };
  5137. virtual const void *nextInGroup()
  5138. {
  5139. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  5140. const void * next = iter->nextInGroup();
  5141. if (next)
  5142. {
  5143. processed++;
  5144. atomic_inc(&rowsIn);
  5145. }
  5146. return next;
  5147. }
  5148. virtual void setInput(unsigned idx, IRoxieInput *_in)
  5149. {
  5150. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  5151. }
  5152. };
  5153. class CRoxieServerLocalResultReadActivityFactory : public CRoxieServerActivityFactory
  5154. {
  5155. unsigned graphId;
  5156. public:
  5157. CRoxieServerLocalResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _graphId)
  5158. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), graphId(_graphId)
  5159. {
  5160. }
  5161. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  5162. {
  5163. return new CRoxieServerLocalResultReadActivity(this, _probeManager, graphId);
  5164. }
  5165. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  5166. {
  5167. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for LocalResultRead activity");
  5168. }
  5169. };
  5170. IRoxieServerActivityFactory *createRoxieServerLocalResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned graphId)
  5171. {
  5172. return new CRoxieServerLocalResultReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, graphId);
  5173. }
  5174. //=================================================================================
  5175. class CRoxieServerLocalResultStreamReadActivity : public CRoxieServerActivity
  5176. {
  5177. IHThorLocalResultReadArg &helper;
  5178. Owned<IRoxieInput> streamInput;
  5179. unsigned sequence;
  5180. public:
  5181. CRoxieServerLocalResultStreamReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5182. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorLocalResultReadArg &)basehelper)
  5183. {
  5184. sequence = 0;
  5185. }
  5186. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  5187. {
  5188. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  5189. sequence = helper.querySequence();
  5190. }
  5191. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5192. {
  5193. assertex(streamInput != NULL);
  5194. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5195. streamInput->start(parentExtractSize, parentExtract, paused);
  5196. }
  5197. virtual void stop(bool aborting)
  5198. {
  5199. CRoxieServerActivity::stop(aborting);
  5200. streamInput->stop(aborting);
  5201. }
  5202. virtual void reset()
  5203. {
  5204. streamInput->reset();
  5205. CRoxieServerActivity::reset();
  5206. };
  5207. virtual const void *nextInGroup()
  5208. {
  5209. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  5210. const void * next = streamInput->nextInGroup();
  5211. if (next)
  5212. {
  5213. processed++;
  5214. atomic_inc(&rowsIn);
  5215. }
  5216. return next;
  5217. }
  5218. virtual bool querySetStreamInput(unsigned id, IRoxieInput * _input)
  5219. {
  5220. if (id == sequence)
  5221. {
  5222. streamInput.set(_input);
  5223. return true;
  5224. }
  5225. return false;
  5226. }
  5227. virtual void setInput(unsigned idx, IRoxieInput *_in)
  5228. {
  5229. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  5230. }
  5231. };
  5232. class CRoxieServerLocalResultStreamReadActivityFactory : public CRoxieServerActivityFactory
  5233. {
  5234. public:
  5235. CRoxieServerLocalResultStreamReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  5236. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  5237. {
  5238. }
  5239. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  5240. {
  5241. return new CRoxieServerLocalResultStreamReadActivity(this, _probeManager);
  5242. }
  5243. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  5244. {
  5245. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for LocalResultRead activity");
  5246. }
  5247. };
  5248. IRoxieServerActivityFactory *createRoxieServerLocalResultStreamReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  5249. {
  5250. return new CRoxieServerLocalResultStreamReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  5251. }
  5252. //=====================================================================================================
  5253. class CRoxieServerLocalResultWriteActivity : public CRoxieServerInternalSinkActivity
  5254. {
  5255. IHThorLocalResultWriteArg &helper;
  5256. ILocalGraphEx * graph;
  5257. unsigned graphId;
  5258. public:
  5259. CRoxieServerLocalResultWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId)
  5260. : CRoxieServerInternalSinkActivity(_factory, _probeManager), helper((IHThorLocalResultWriteArg &)basehelper), graphId(_graphId)
  5261. {
  5262. graph = NULL;
  5263. }
  5264. virtual bool needsAllocator() const { return true; }
  5265. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  5266. {
  5267. CRoxieServerInternalSinkActivity::onCreate(_ctx, _colocalParent);
  5268. graph = static_cast<ILocalGraphEx *>(_ctx->queryCodeContext()->resolveLocalQuery(graphId));
  5269. }
  5270. virtual void onExecute()
  5271. {
  5272. RtlLinkedDatasetBuilder builder(rowAllocator);
  5273. input->readAll(builder);
  5274. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  5275. graph->setResult(helper.querySequence(), result);
  5276. }
  5277. IRoxieInput * querySelectOutput(unsigned id)
  5278. {
  5279. if (id == helper.querySequence())
  5280. {
  5281. executed = true;
  5282. return LINK(input);
  5283. }
  5284. return NULL;
  5285. }
  5286. };
  5287. class CRoxieServerLocalResultWriteActivityFactory : public CRoxieServerInternalSinkFactory
  5288. {
  5289. unsigned graphId;
  5290. public:
  5291. CRoxieServerLocalResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, unsigned _graphId, bool _isRoot)
  5292. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot), graphId(_graphId)
  5293. {
  5294. isInternal = true;
  5295. Owned<IHThorLocalResultWriteArg> helper = (IHThorLocalResultWriteArg *) helperFactory();
  5296. }
  5297. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  5298. {
  5299. return new CRoxieServerLocalResultWriteActivity(this, _probeManager, graphId);
  5300. }
  5301. };
  5302. IRoxieServerActivityFactory *createRoxieServerLocalResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, unsigned _graphId, bool _isRoot)
  5303. {
  5304. return new CRoxieServerLocalResultWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _graphId, _isRoot);
  5305. }
  5306. //=====================================================================================================
  5307. class CRoxieServerDictionaryResultWriteActivity : public CRoxieServerInternalSinkActivity
  5308. {
  5309. IHThorDictionaryResultWriteArg &helper;
  5310. ILocalGraphEx * graph;
  5311. unsigned graphId;
  5312. public:
  5313. CRoxieServerDictionaryResultWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId)
  5314. : CRoxieServerInternalSinkActivity(_factory, _probeManager), helper((IHThorDictionaryResultWriteArg &)basehelper), graphId(_graphId)
  5315. {
  5316. graph = NULL;
  5317. }
  5318. virtual bool needsAllocator() const { return true; }
  5319. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  5320. {
  5321. CRoxieServerInternalSinkActivity::onCreate(_ctx, _colocalParent);
  5322. graph = static_cast<ILocalGraphEx *>(_ctx->queryCodeContext()->resolveLocalQuery(graphId));
  5323. }
  5324. virtual void onExecute()
  5325. {
  5326. unsigned sequence = helper.querySequence();
  5327. RtlLinkedDictionaryBuilder builder(rowAllocator, helper.queryHashLookupInfo());
  5328. loop
  5329. {
  5330. const void *row = input->nextInGroup();
  5331. if (!row)
  5332. {
  5333. row = input->nextInGroup();
  5334. if (!row)
  5335. break;
  5336. }
  5337. builder.appendOwn(row);
  5338. processed++;
  5339. }
  5340. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  5341. graph->setResult(helper.querySequence(), result);
  5342. }
  5343. IRoxieInput * querySelectOutput(unsigned id)
  5344. {
  5345. if (id == helper.querySequence())
  5346. {
  5347. executed = true;
  5348. return LINK(input);
  5349. }
  5350. return NULL;
  5351. }
  5352. };
  5353. class CRoxieServerDictionaryResultWriteActivityFactory : public CRoxieServerInternalSinkFactory
  5354. {
  5355. unsigned graphId;
  5356. public:
  5357. CRoxieServerDictionaryResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, unsigned _graphId, bool _isRoot)
  5358. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot), graphId(_graphId)
  5359. {
  5360. isInternal = true;
  5361. }
  5362. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  5363. {
  5364. return new CRoxieServerDictionaryResultWriteActivity(this, _probeManager, graphId);
  5365. }
  5366. };
  5367. IRoxieServerActivityFactory *createRoxieServerDictionaryResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, unsigned _graphId, bool _isRoot)
  5368. {
  5369. return new CRoxieServerDictionaryResultWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _graphId, _isRoot);
  5370. }
  5371. //=================================================================================
  5372. class CRoxieServerGraphLoopResultReadActivity : public CRoxieServerActivity
  5373. {
  5374. protected:
  5375. IHThorGraphLoopResultReadArg &helper;
  5376. Owned<IRoxieInput> iter;
  5377. ILocalGraphEx * graph;
  5378. unsigned graphId;
  5379. unsigned sequence;
  5380. public:
  5381. CRoxieServerGraphLoopResultReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId)
  5382. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorGraphLoopResultReadArg &)basehelper), graphId(_graphId)
  5383. {
  5384. graph = NULL;
  5385. sequence = 0;
  5386. }
  5387. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  5388. {
  5389. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  5390. graph = static_cast<ILocalGraphEx *>(_ctx->queryCodeContext()->resolveLocalQuery(graphId));
  5391. }
  5392. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5393. {
  5394. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5395. if (iter)
  5396. iter->start(parentExtractSize, parentExtract, paused);
  5397. else
  5398. {
  5399. sequence = helper.querySequence();
  5400. if ((int)sequence >= 0)
  5401. {
  5402. try
  5403. {
  5404. iter.setown(graph->createGraphLoopResultIterator(sequence));
  5405. }
  5406. catch (IException * E)
  5407. {
  5408. throw makeWrappedException(E);
  5409. }
  5410. }
  5411. }
  5412. }
  5413. virtual void stop(bool aborting)
  5414. {
  5415. if (iter)
  5416. iter->stop(aborting);
  5417. CRoxieServerActivity::stop(aborting);
  5418. }
  5419. virtual void reset()
  5420. {
  5421. if (iter)
  5422. iter->reset();
  5423. iter.clear();
  5424. CRoxieServerActivity::reset();
  5425. };
  5426. virtual const void *nextInGroup()
  5427. {
  5428. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  5429. const void * next = iter ? iter->nextInGroup() : NULL;
  5430. if (next)
  5431. {
  5432. processed++;
  5433. atomic_inc(&rowsIn);
  5434. }
  5435. return next;
  5436. }
  5437. virtual void setInput(unsigned idx, IRoxieInput *_in)
  5438. {
  5439. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  5440. }
  5441. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract)
  5442. {
  5443. ensureCreated();
  5444. basehelper.onStart(parentExtract, NULL);
  5445. processor.noteUseIteration(helper.querySequence());
  5446. }
  5447. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract, IProbeManager *probeManager, IArrayOf<IRoxieInput> &probes)
  5448. {
  5449. //helper already initialised from the gratherIterationUsage() call.
  5450. iter.set(processor.connectIterationOutput(helper.querySequence(), probeManager, probes, this, 0));
  5451. }
  5452. virtual IInputSteppingMeta * querySteppingMeta()
  5453. {
  5454. assertex(iter);
  5455. return iter->querySteppingMeta();
  5456. }
  5457. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  5458. {
  5459. assertex(iter);
  5460. return iter->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  5461. }
  5462. };
  5463. //variety of CRoxieServerGraphLoopResultReadActivity created internally with a predefined sequence number
  5464. class CRoxieServerInternalGraphLoopResultReadActivity : public CRoxieServerGraphLoopResultReadActivity
  5465. {
  5466. public:
  5467. CRoxieServerInternalGraphLoopResultReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId, unsigned _sequence)
  5468. : CRoxieServerGraphLoopResultReadActivity(_factory, _probeManager, _graphId)
  5469. {
  5470. sequence = _sequence;
  5471. }
  5472. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5473. {
  5474. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5475. if ((int)sequence >= 0)
  5476. {
  5477. try
  5478. {
  5479. iter.setown(graph->createGraphLoopResultIterator(sequence));
  5480. }
  5481. catch (IException * E)
  5482. {
  5483. throw makeWrappedException(E);
  5484. }
  5485. }
  5486. }
  5487. };
  5488. class CRoxieServerGraphLoopResultReadActivityFactory : public CRoxieServerActivityFactory
  5489. {
  5490. unsigned graphId;
  5491. public:
  5492. CRoxieServerGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _graphId)
  5493. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), graphId(_graphId)
  5494. {
  5495. }
  5496. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  5497. {
  5498. return new CRoxieServerGraphLoopResultReadActivity(this, _probeManager, graphId);
  5499. }
  5500. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  5501. {
  5502. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for GraphLoopResultRead activity");
  5503. }
  5504. };
  5505. IRoxieServerActivityFactory *createRoxieServerGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned graphId)
  5506. {
  5507. return new CRoxieServerGraphLoopResultReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, graphId);
  5508. }
  5509. //=====================================================================================================
  5510. class CRoxieServerGraphLoopResultWriteActivity : public CRoxieServerInternalSinkActivity
  5511. {
  5512. IHThorGraphLoopResultWriteArg &helper;
  5513. ILocalGraphEx * graph;
  5514. unsigned graphId;
  5515. public:
  5516. CRoxieServerGraphLoopResultWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId)
  5517. : CRoxieServerInternalSinkActivity(_factory, _probeManager), helper((IHThorGraphLoopResultWriteArg &)basehelper), graphId(_graphId)
  5518. {
  5519. graph = NULL;
  5520. }
  5521. virtual bool needsAllocator() const { return true; }
  5522. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  5523. {
  5524. CRoxieServerInternalSinkActivity::onCreate(_ctx, _colocalParent);
  5525. graph = static_cast<ILocalGraphEx *>(_ctx->queryCodeContext()->resolveLocalQuery(graphId));
  5526. }
  5527. virtual void onExecute()
  5528. {
  5529. RtlLinkedDatasetBuilder builder(rowAllocator);
  5530. input->readAll(builder);
  5531. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  5532. graph->setGraphLoopResult(result);
  5533. }
  5534. virtual IRoxieInput *queryOutput(unsigned idx)
  5535. {
  5536. if (idx==0)
  5537. return this;
  5538. else
  5539. return NULL;
  5540. }
  5541. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  5542. {
  5543. return input->gatherConjunctions(collector);
  5544. }
  5545. virtual void resetEOF()
  5546. {
  5547. input->resetEOF();
  5548. }
  5549. virtual const void *nextInGroup()
  5550. {
  5551. const void * next = input->nextInGroup();
  5552. if (next)
  5553. processed++;
  5554. return next;
  5555. }
  5556. virtual bool isPassThrough()
  5557. {
  5558. return true;
  5559. }
  5560. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  5561. {
  5562. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  5563. const void * next = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  5564. if (next)
  5565. processed++;
  5566. return next;
  5567. }
  5568. IInputSteppingMeta * querySteppingMeta()
  5569. {
  5570. return input->querySteppingMeta();
  5571. }
  5572. virtual IOutputMetaData * queryOutputMeta() const
  5573. {
  5574. return input->queryOutputMeta();
  5575. }
  5576. };
  5577. class CRoxieServerGraphLoopResultWriteActivityFactory : public CRoxieServerInternalSinkFactory
  5578. {
  5579. unsigned graphId;
  5580. public:
  5581. CRoxieServerGraphLoopResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, unsigned _graphId)
  5582. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, true), graphId(_graphId)
  5583. {
  5584. isInternal = true;
  5585. Owned<IHThorGraphLoopResultWriteArg> helper = (IHThorGraphLoopResultWriteArg *) helperFactory();
  5586. }
  5587. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  5588. {
  5589. return new CRoxieServerGraphLoopResultWriteActivity(this, _probeManager, graphId);
  5590. }
  5591. };
  5592. IRoxieServerActivityFactory *createRoxieServerGraphLoopResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, unsigned _graphId)
  5593. {
  5594. return new CRoxieServerGraphLoopResultWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _graphId);
  5595. }
  5596. #if 0
  5597. //=====================================================================================================
  5598. CHThorLocalResultSpillActivity::CHThorLocalResultSpillActivity(IAgentContext &_agent, ActivityId const & _id, IHThorLocalResultSpillArg &_arg)
  5599. : CHThorSimpleActivityBase(_agent, _id, _arg), helper(_arg)
  5600. {
  5601. next = NULL;
  5602. }
  5603. void CHThorLocalResultSpillActivity::ready()
  5604. {
  5605. CHThorSimpleActivityBase::ready();
  5606. next = input->nextInGroup();
  5607. grouped = input->isGrouped();
  5608. rowdata.clear();
  5609. }
  5610. const void * CHThorLocalResultSpillActivity::nextInGroup()
  5611. {
  5612. const void * ret = next;
  5613. next = input->nextInGroup();
  5614. if (!ret && !next)
  5615. return NULL;
  5616. if (ret)
  5617. {
  5618. size32_t thisSize = outputMeta->getRecordSize(ret);
  5619. rowdata.append(thisSize, ret);
  5620. if (grouped)
  5621. rowdata.append(next == NULL);
  5622. }
  5623. return ret;
  5624. }
  5625. void CHThorLocalResultSpillActivity::done()
  5626. {
  5627. loop
  5628. {
  5629. const void * ret = nextInGroup();
  5630. if (!ret)
  5631. {
  5632. ret = nextInGroup();
  5633. if (!ret)
  5634. break;
  5635. }
  5636. ReleaseRoxieRow(ret);
  5637. }
  5638. agent.setLocalResult(helper.querySequence(), rowdata.length(), rowdata.toByteArray());
  5639. CHThorSimpleActivityBase::done();
  5640. }
  5641. #endif
  5642. //=================================================================================
  5643. class CRoxieServerDedupActivity : public CRoxieServerActivity
  5644. {
  5645. protected:
  5646. IHThorDedupArg &helper;
  5647. unsigned numKept;
  5648. unsigned numToKeep;
  5649. public:
  5650. CRoxieServerDedupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5651. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorDedupArg &)basehelper)
  5652. {
  5653. numKept = 0;
  5654. numToKeep = 0;
  5655. }
  5656. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5657. {
  5658. numKept = 0;
  5659. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5660. numToKeep = helper.numToKeep();
  5661. }
  5662. };
  5663. class CRoxieServerDedupKeepLeftActivity : public CRoxieServerDedupActivity
  5664. {
  5665. IRangeCompare * stepCompare;
  5666. const void *prev;
  5667. public:
  5668. CRoxieServerDedupKeepLeftActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5669. : CRoxieServerDedupActivity(_factory, _probeManager)
  5670. {
  5671. prev = NULL;
  5672. stepCompare = NULL;
  5673. }
  5674. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5675. {
  5676. prev = NULL;
  5677. CRoxieServerDedupActivity::start(parentExtractSize, parentExtract, paused);
  5678. IInputSteppingMeta * stepMeta = input->querySteppingMeta();
  5679. stepCompare = NULL;
  5680. if (stepMeta)
  5681. stepCompare = stepMeta->queryCompare();
  5682. }
  5683. virtual void reset()
  5684. {
  5685. ReleaseClearRoxieRow(prev);
  5686. CRoxieServerDedupActivity::reset();
  5687. }
  5688. virtual const void * nextInGroup()
  5689. {
  5690. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  5691. const void * next;
  5692. loop
  5693. {
  5694. next = input->nextInGroup();
  5695. if (!prev || !next || !helper.matches(prev,next))
  5696. {
  5697. numKept = 0;
  5698. break;
  5699. }
  5700. if (numKept < numToKeep-1)
  5701. {
  5702. numKept++;
  5703. break;
  5704. }
  5705. ReleaseRoxieRow(next);
  5706. }
  5707. ReleaseRoxieRow(prev);
  5708. prev = next;
  5709. if (next)
  5710. {
  5711. LinkRoxieRow(next);
  5712. processed++;
  5713. }
  5714. return next;
  5715. }
  5716. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  5717. {
  5718. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  5719. const void * next;
  5720. loop
  5721. {
  5722. next = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  5723. //If the record was an in-exact match from the index then return it immediately
  5724. //and don't cause it to dedup following legal records.
  5725. if (!wasCompleteMatch)
  5726. {
  5727. assertex(stepExtra.returnMismatches());
  5728. return next;
  5729. }
  5730. if (!prev || !next || !helper.matches(prev,next))
  5731. {
  5732. numKept = 0;
  5733. break;
  5734. }
  5735. if (numKept < numToKeep-1)
  5736. {
  5737. numKept++;
  5738. break;
  5739. }
  5740. //Unusual - deduping by x,y stepped on x,y,z - still want any record back as soon as possible.
  5741. if (stepExtra.returnMismatches())
  5742. {
  5743. //If asked to return mismatches we are only interested in mismatches that will force the stepped
  5744. //condition to advance
  5745. if (stepCompare->docompare(next, seek, numFields) != 0)
  5746. {
  5747. wasCompleteMatch = false;
  5748. break;
  5749. }
  5750. }
  5751. ReleaseRoxieRow(next);
  5752. }
  5753. ReleaseRoxieRow(prev);
  5754. prev = next;
  5755. if (next)
  5756. {
  5757. LinkRoxieRow(next);
  5758. processed++;
  5759. }
  5760. return next;
  5761. }
  5762. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  5763. {
  5764. return input->gatherConjunctions(collector);
  5765. }
  5766. virtual void resetEOF()
  5767. {
  5768. input->resetEOF();
  5769. }
  5770. IInputSteppingMeta * querySteppingMeta()
  5771. {
  5772. return input->querySteppingMeta();
  5773. }
  5774. };
  5775. //=================================================================================
  5776. class CRoxieServerDedupKeepRightActivity : public CRoxieServerDedupActivity
  5777. {
  5778. const void *kept;
  5779. bool first;
  5780. public:
  5781. CRoxieServerDedupKeepRightActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5782. : CRoxieServerDedupActivity(_factory, _probeManager)
  5783. {
  5784. kept = NULL;
  5785. first = true;
  5786. }
  5787. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5788. {
  5789. first = true;
  5790. kept = NULL;
  5791. CRoxieServerDedupActivity::start(parentExtractSize, parentExtract, paused);
  5792. }
  5793. virtual void reset()
  5794. {
  5795. ReleaseClearRoxieRow(kept);
  5796. CRoxieServerActivity::reset();
  5797. }
  5798. virtual const void * nextInGroup()
  5799. {
  5800. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  5801. if (first)
  5802. {
  5803. kept = input->nextInGroup();
  5804. first = false;
  5805. }
  5806. const void * next;
  5807. loop
  5808. {
  5809. next = input->nextInGroup();
  5810. if (!kept || !next || !helper.matches(kept,next))
  5811. {
  5812. numKept = 0;
  5813. break;
  5814. }
  5815. if (numKept < numToKeep-1)
  5816. {
  5817. numKept++;
  5818. break;
  5819. }
  5820. ReleaseRoxieRow(kept);
  5821. kept = next;
  5822. }
  5823. const void * ret = kept;
  5824. kept = next;
  5825. // CTXLOG("dedup returns %p", ret);
  5826. if (ret) processed++;
  5827. return ret;
  5828. }
  5829. };
  5830. class CRoxieServerDedupAllActivity : public CRoxieServerActivity
  5831. {
  5832. IHThorDedupArg &helper;
  5833. unsigned survivorIndex;
  5834. ConstPointerArray survivors;
  5835. bool keepLeft;
  5836. bool eof;
  5837. bool first;
  5838. ICompare *primaryCompare;
  5839. public:
  5840. CRoxieServerDedupAllActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _keepLeft)
  5841. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorDedupArg &)basehelper)
  5842. {
  5843. keepLeft = _keepLeft;
  5844. primaryCompare = helper.queryComparePrimary();
  5845. eof = false;
  5846. first = true;
  5847. survivorIndex = 0;
  5848. }
  5849. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5850. {
  5851. eof = false;
  5852. first = true;
  5853. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5854. }
  5855. virtual void reset()
  5856. {
  5857. #ifdef _DEBUG
  5858. while (survivors.isItem(survivorIndex))
  5859. {
  5860. ReleaseRoxieRow(survivors.item(survivorIndex++));
  5861. }
  5862. #endif
  5863. survivors.kill();
  5864. eof = false;
  5865. first = true;
  5866. CRoxieServerActivity::reset();
  5867. }
  5868. void dedupRange(unsigned first, unsigned last, ConstPointerArray & group)
  5869. {
  5870. for (unsigned idxL = first; idxL < last; idxL++)
  5871. {
  5872. const void * left = group.item(idxL);
  5873. if (left)
  5874. {
  5875. for (unsigned idxR = first; idxR < last; idxR++)
  5876. {
  5877. const void * right = group.item(idxR);
  5878. if ((idxL != idxR) && right)
  5879. {
  5880. if (helper.matches(left, right))
  5881. {
  5882. if (keepLeft)
  5883. {
  5884. group.replace(NULL, idxR);
  5885. ReleaseRoxieRow(right);
  5886. }
  5887. else
  5888. {
  5889. group.replace(NULL, idxL);
  5890. ReleaseRoxieRow(left);
  5891. break;
  5892. }
  5893. }
  5894. }
  5895. }
  5896. }
  5897. }
  5898. }
  5899. void dedupRangeIndirect(unsigned first, unsigned last, void *** index)
  5900. {
  5901. for (unsigned idxL = first; idxL < last; idxL++)
  5902. {
  5903. void * left = *(index[idxL]);
  5904. if (left)
  5905. {
  5906. for (unsigned idxR = first; idxR < last; idxR++)
  5907. {
  5908. void * right = *(index[idxR]);
  5909. if ((idxL != idxR) && right)
  5910. {
  5911. if (helper.matches(left, right))
  5912. {
  5913. if (keepLeft)
  5914. {
  5915. *(index[idxR]) = NULL;
  5916. ReleaseRoxieRow(right);
  5917. }
  5918. else
  5919. {
  5920. *(index[idxL]) = NULL;
  5921. ReleaseRoxieRow(left);
  5922. break;
  5923. }
  5924. }
  5925. }
  5926. }
  5927. }
  5928. }
  5929. }
  5930. bool calcNextDedupAll()
  5931. {
  5932. survivors.kill();
  5933. survivorIndex = 0;
  5934. ConstPointerArray group;
  5935. if (eof || !input->nextGroup(group))
  5936. {
  5937. eof = true;
  5938. return false;
  5939. }
  5940. unsigned max = group.ordinality();
  5941. if (primaryCompare)
  5942. {
  5943. //hard, if not impossible, to hit this code once optimisations in place
  5944. MemoryAttr indexbuff(max*sizeof(void **));
  5945. void *** index = (void ***)indexbuff.bufferBase();
  5946. qsortvecstable(const_cast<void * *>(group.getArray()), max, *primaryCompare, index);
  5947. unsigned first = 0;
  5948. for (unsigned idx = 1; idx < max; idx++)
  5949. {
  5950. if (primaryCompare->docompare(*(index[first]), *(index[idx])) != 0)
  5951. {
  5952. dedupRangeIndirect(first, idx, index);
  5953. first = idx;
  5954. }
  5955. }
  5956. dedupRangeIndirect(first, max, index);
  5957. for(unsigned idx2=0; idx2<max; ++idx2)
  5958. {
  5959. void * cur = *(index[idx2]);
  5960. if(cur)
  5961. survivors.append(cur);
  5962. }
  5963. }
  5964. else
  5965. {
  5966. dedupRange(0, max, group);
  5967. for(unsigned idx=0; idx<max; ++idx)
  5968. {
  5969. const void * cur = group.item(idx);
  5970. if(cur)
  5971. survivors.append(cur);
  5972. }
  5973. }
  5974. return true;
  5975. }
  5976. virtual const void *nextInGroup()
  5977. {
  5978. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  5979. if (first)
  5980. {
  5981. calcNextDedupAll();
  5982. first = false;
  5983. }
  5984. while (survivors.isItem(survivorIndex))
  5985. {
  5986. const void *ret = survivors.item(survivorIndex++);
  5987. if (ret)
  5988. {
  5989. processed++;
  5990. return ret;
  5991. }
  5992. }
  5993. calcNextDedupAll();
  5994. return NULL;
  5995. }
  5996. };
  5997. class CRoxieServerDedupActivityFactory : public CRoxieServerActivityFactory
  5998. {
  5999. bool compareAll;
  6000. bool keepLeft;
  6001. public:
  6002. CRoxieServerDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6003. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  6004. {
  6005. Owned<IHThorDedupArg> helper = (IHThorDedupArg *) helperFactory();
  6006. compareAll = helper->compareAll();
  6007. keepLeft = helper->keepLeft();
  6008. }
  6009. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  6010. {
  6011. if (compareAll)
  6012. return new CRoxieServerDedupAllActivity(this, _probeManager, keepLeft);
  6013. else if (keepLeft)
  6014. return new CRoxieServerDedupKeepLeftActivity(this, _probeManager);
  6015. else
  6016. return new CRoxieServerDedupKeepRightActivity(this, _probeManager);
  6017. }
  6018. };
  6019. IRoxieServerActivityFactory *createRoxieServerDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6020. {
  6021. return new CRoxieServerDedupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  6022. }
  6023. //=================================================================================
  6024. class CRoxieServerHashDedupActivity : public CRoxieServerActivity
  6025. {
  6026. bool eof;
  6027. IHThorHashDedupArg &helper;
  6028. class HashDedupElement
  6029. {
  6030. public:
  6031. HashDedupElement(unsigned _hash, const void *_keyRow)
  6032. : hash(_hash), keyRow(_keyRow)
  6033. {
  6034. }
  6035. ~HashDedupElement()
  6036. {
  6037. ReleaseRoxieRow(keyRow);
  6038. }
  6039. inline unsigned queryHash() const
  6040. {
  6041. return hash;
  6042. }
  6043. inline const void *queryRow() const
  6044. {
  6045. return keyRow;
  6046. }
  6047. private:
  6048. unsigned hash;
  6049. const void *keyRow;
  6050. };
  6051. class HashDedupTable : public SuperHashTable
  6052. {
  6053. public:
  6054. HashDedupTable(IHThorHashDedupArg & _helper, unsigned _activityId)
  6055. : helper(_helper),
  6056. activityId(_activityId),
  6057. keySize(helper.queryKeySize())
  6058. {
  6059. }
  6060. virtual ~HashDedupTable() { releaseAll(); }
  6061. virtual unsigned getHashFromElement(const void *et) const
  6062. {
  6063. const HashDedupElement *element = reinterpret_cast<const HashDedupElement *>(et);
  6064. return element->queryHash();
  6065. }
  6066. virtual unsigned getHashFromFindParam(const void *fp) const { throwUnexpected(); }
  6067. virtual const void * getFindParam(const void *et) const { throwUnexpected(); }
  6068. virtual bool matchesElement(const void *et, const void *searchET) const { throwUnexpected(); }
  6069. virtual bool matchesFindParam(const void *et, const void *key, unsigned fphash) const
  6070. {
  6071. const HashDedupElement *element = reinterpret_cast<const HashDedupElement *>(et);
  6072. if (fphash != element->queryHash())
  6073. return false;
  6074. return (helper.queryKeyCompare()->docompare(element->queryRow(), key) == 0);
  6075. }
  6076. virtual void onAdd(void *et) {}
  6077. virtual void onRemove(void *et)
  6078. {
  6079. const HashDedupElement *element = reinterpret_cast<const HashDedupElement *>(et);
  6080. delete element;
  6081. }
  6082. void onCreate(IRoxieSlaveContext *ctx)
  6083. {
  6084. keyRowAllocator.setown(ctx->queryCodeContext()->getRowAllocator(keySize.queryOriginal(), activityId));
  6085. }
  6086. void reset()
  6087. {
  6088. kill();
  6089. }
  6090. bool insert(const void * row)
  6091. {
  6092. unsigned hash = helper.queryHash()->hash(row);
  6093. RtlDynamicRowBuilder keyRowBuilder(keyRowAllocator, true);
  6094. size32_t thisKeySize = helper.recordToKey(keyRowBuilder, row);
  6095. OwnedConstRoxieRow keyRow = keyRowBuilder.finalizeRowClear(thisKeySize);
  6096. if (find(hash, keyRow.get()))
  6097. return false;
  6098. addNew(new HashDedupElement(hash, keyRow.getClear()), hash);
  6099. return true;
  6100. }
  6101. private:
  6102. IHThorHashDedupArg & helper;
  6103. CachedOutputMetaData keySize;
  6104. Owned<IEngineRowAllocator> keyRowAllocator;
  6105. unsigned activityId;
  6106. } table;
  6107. public:
  6108. CRoxieServerHashDedupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6109. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorHashDedupArg &)basehelper), table(helper, activityId)
  6110. {
  6111. eof = false;
  6112. }
  6113. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6114. {
  6115. eof = false;
  6116. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6117. }
  6118. virtual void onCreate(IRoxieSlaveContext *ctx, IHThorArg *_colocalParent)
  6119. {
  6120. CRoxieServerActivity::onCreate(ctx, colocalParent);
  6121. table.onCreate(ctx);
  6122. }
  6123. virtual void reset()
  6124. {
  6125. table.reset();
  6126. eof = false;
  6127. CRoxieServerActivity::reset();
  6128. }
  6129. virtual const void *nextInGroup()
  6130. {
  6131. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  6132. while(!eof)
  6133. {
  6134. const void * next = input->nextInGroup();
  6135. if(!next)
  6136. {
  6137. if (table.count() == 0)
  6138. eof = true;
  6139. table.reset();
  6140. return NULL;
  6141. }
  6142. if(table.insert(next))
  6143. return next;
  6144. else
  6145. ReleaseRoxieRow(next);
  6146. }
  6147. return NULL;
  6148. }
  6149. };
  6150. class CRoxieServerHashDedupActivityFactory : public CRoxieServerActivityFactory
  6151. {
  6152. public:
  6153. CRoxieServerHashDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6154. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  6155. {
  6156. }
  6157. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  6158. {
  6159. return new CRoxieServerHashDedupActivity(this, _probeManager);
  6160. }
  6161. };
  6162. IRoxieServerActivityFactory *createRoxieServerHashDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6163. {
  6164. return new CRoxieServerHashDedupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  6165. }
  6166. //=================================================================================
  6167. class CRoxieServerRollupActivity : public CRoxieServerActivity
  6168. {
  6169. IHThorRollupArg &helper;
  6170. OwnedConstRoxieRow left;
  6171. OwnedConstRoxieRow prev;
  6172. OwnedConstRoxieRow right;
  6173. bool readFirstRow;
  6174. public:
  6175. CRoxieServerRollupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6176. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorRollupArg &)basehelper)
  6177. {
  6178. readFirstRow = false;
  6179. }
  6180. ~CRoxieServerRollupActivity()
  6181. {
  6182. }
  6183. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6184. {
  6185. readFirstRow = false;
  6186. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6187. }
  6188. virtual void reset()
  6189. {
  6190. left.clear();
  6191. prev.clear();
  6192. right.clear();
  6193. CRoxieServerActivity::reset();
  6194. }
  6195. virtual bool needsAllocator() const { return true; }
  6196. virtual const void * nextInGroup()
  6197. {
  6198. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  6199. if (!readFirstRow)
  6200. {
  6201. left.setown(input->nextInGroup());
  6202. prev.set(left);
  6203. readFirstRow = true;
  6204. }
  6205. loop
  6206. {
  6207. right.setown(input->nextInGroup());
  6208. if(!prev || !right || !helper.matches(prev,right))
  6209. {
  6210. const void * ret = left.getClear();
  6211. if(ret)
  6212. processed++;
  6213. left.setown(right.getClear());
  6214. prev.set(left);
  6215. return ret;
  6216. }
  6217. try
  6218. {
  6219. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  6220. unsigned outSize = helper.transform(rowBuilder, left, right);
  6221. if (outSize)
  6222. left.setown(rowBuilder.finalizeRowClear(outSize));
  6223. if (helper.getFlags() & RFrolledismatchleft)
  6224. prev.set(left);
  6225. else
  6226. prev.set(right);
  6227. }
  6228. catch(IException * E)
  6229. {
  6230. throw makeWrappedException(E);
  6231. }
  6232. }
  6233. }
  6234. };
  6235. class CRoxieServerRollupActivityFactory : public CRoxieServerActivityFactory
  6236. {
  6237. public:
  6238. CRoxieServerRollupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6239. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  6240. {
  6241. }
  6242. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  6243. {
  6244. return new CRoxieServerRollupActivity(this, _probeManager);
  6245. }
  6246. };
  6247. IRoxieServerActivityFactory *createRoxieServerRollupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6248. {
  6249. return new CRoxieServerRollupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  6250. }
  6251. //=================================================================================
  6252. class CRoxieServerNormalizeActivity : public CRoxieServerActivity
  6253. {
  6254. IHThorNormalizeArg &helper;
  6255. unsigned numThisRow;
  6256. unsigned curRow;
  6257. const void *buffer;
  6258. unsigned numProcessedLastGroup;
  6259. public:
  6260. CRoxieServerNormalizeActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6261. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorNormalizeArg &)basehelper)
  6262. {
  6263. buffer = NULL;
  6264. numThisRow = 0;
  6265. curRow = 0;
  6266. numProcessedLastGroup = 0;
  6267. }
  6268. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6269. {
  6270. numThisRow = 0;
  6271. curRow = 0;
  6272. numProcessedLastGroup = 0;
  6273. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6274. }
  6275. virtual void reset()
  6276. {
  6277. ReleaseClearRoxieRow(buffer);
  6278. CRoxieServerActivity::reset();
  6279. }
  6280. virtual bool needsAllocator() const { return true; }
  6281. virtual const void * nextInGroup()
  6282. {
  6283. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  6284. loop
  6285. {
  6286. while (curRow == numThisRow)
  6287. {
  6288. if (buffer)
  6289. ReleaseClearRoxieRow(buffer);
  6290. buffer = input->nextInGroup();
  6291. if (!buffer && (processed == numProcessedLastGroup))
  6292. buffer = input->nextInGroup();
  6293. if (!buffer)
  6294. {
  6295. numProcessedLastGroup = processed;
  6296. return NULL;
  6297. }
  6298. curRow = 0;
  6299. numThisRow = helper.numExpandedRows(buffer);
  6300. }
  6301. try
  6302. {
  6303. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  6304. unsigned actualSize = helper.transform(rowBuilder, buffer, ++curRow);
  6305. if (actualSize != 0)
  6306. {
  6307. processed++;
  6308. return rowBuilder.finalizeRowClear(actualSize);
  6309. }
  6310. }
  6311. catch (IException *E)
  6312. {
  6313. throw makeWrappedException(E);
  6314. }
  6315. }
  6316. }
  6317. };
  6318. class CRoxieServerNormalizeActivityFactory : public CRoxieServerActivityFactory
  6319. {
  6320. public:
  6321. CRoxieServerNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6322. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  6323. {
  6324. }
  6325. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  6326. {
  6327. return new CRoxieServerNormalizeActivity(this, _probeManager);
  6328. }
  6329. };
  6330. IRoxieServerActivityFactory *createRoxieServerNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6331. {
  6332. return new CRoxieServerNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  6333. }
  6334. //=================================================================================
  6335. class CRoxieServerNormalizeChildActivity : public CRoxieServerActivity
  6336. {
  6337. IHThorNormalizeChildArg &helper;
  6338. unsigned numThisRow;
  6339. unsigned curRow;
  6340. const void *buffer;
  6341. unsigned numProcessedLastGroup;
  6342. INormalizeChildIterator * cursor;
  6343. const void * curChildRow;
  6344. bool advanceInput()
  6345. {
  6346. loop
  6347. {
  6348. ReleaseClearRoxieRow(buffer);
  6349. buffer = input->nextInGroup();
  6350. if (!buffer && (processed == numProcessedLastGroup))
  6351. buffer = input->nextInGroup();
  6352. if (!buffer)
  6353. {
  6354. numProcessedLastGroup = processed;
  6355. return false;
  6356. }
  6357. curChildRow = cursor->first(buffer);
  6358. if (curChildRow)
  6359. {
  6360. curRow = 0;
  6361. return true;
  6362. }
  6363. }
  6364. }
  6365. public:
  6366. CRoxieServerNormalizeChildActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6367. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorNormalizeChildArg &)basehelper)
  6368. {
  6369. buffer = NULL;
  6370. cursor = NULL;
  6371. numThisRow = 0;
  6372. curRow = 0;
  6373. numProcessedLastGroup = 0;
  6374. curChildRow = NULL;
  6375. }
  6376. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6377. {
  6378. numThisRow = 0;
  6379. curRow = 0;
  6380. numProcessedLastGroup = 0;
  6381. curChildRow = NULL;
  6382. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6383. cursor = helper.queryIterator();
  6384. }
  6385. virtual void stop(bool aborting)
  6386. {
  6387. CRoxieServerActivity::stop(aborting);
  6388. }
  6389. virtual void reset()
  6390. {
  6391. cursor = NULL;
  6392. ReleaseClearRoxieRow(buffer);
  6393. CRoxieServerActivity::reset();
  6394. }
  6395. virtual bool needsAllocator() const { return true; }
  6396. const void *nextInGroup()
  6397. {
  6398. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  6399. loop
  6400. {
  6401. if (!buffer)
  6402. {
  6403. if (!advanceInput())
  6404. return NULL;
  6405. }
  6406. try
  6407. {
  6408. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  6409. size32_t outSize = helper.transform(rowBuilder, buffer, curChildRow, ++curRow);
  6410. curChildRow = cursor->next();
  6411. if (!curChildRow)
  6412. ReleaseClearRoxieRow(buffer);
  6413. if (outSize != 0)
  6414. {
  6415. processed++;
  6416. return rowBuilder.finalizeRowClear(outSize);
  6417. }
  6418. }
  6419. catch (IException *E)
  6420. {
  6421. throw makeWrappedException(E);
  6422. }
  6423. }
  6424. }
  6425. };
  6426. class CRoxieServerNormalizeChildActivityFactory : public CRoxieServerActivityFactory
  6427. {
  6428. public:
  6429. CRoxieServerNormalizeChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6430. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  6431. {
  6432. }
  6433. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  6434. {
  6435. return new CRoxieServerNormalizeChildActivity(this, _probeManager);
  6436. }
  6437. };
  6438. IRoxieServerActivityFactory *createRoxieServerNormalizeChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6439. {
  6440. return new CRoxieServerNormalizeChildActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  6441. }
  6442. //=================================================================================
  6443. class CRoxieServerNormalizeLinkedChildActivity : public CRoxieServerActivity
  6444. {
  6445. IHThorNormalizeLinkedChildArg &helper;
  6446. OwnedConstRoxieRow curParent;
  6447. OwnedConstRoxieRow curChild;
  6448. unsigned numProcessedLastGroup;
  6449. bool advanceInput()
  6450. {
  6451. loop
  6452. {
  6453. curParent.setown(input->nextInGroup());
  6454. if (!curParent && (processed == numProcessedLastGroup))
  6455. curParent.setown(input->nextInGroup());
  6456. if (!curParent)
  6457. {
  6458. numProcessedLastGroup = processed;
  6459. return false;
  6460. }
  6461. curChild.set(helper.first(curParent));
  6462. if (curChild)
  6463. return true;
  6464. }
  6465. }
  6466. public:
  6467. CRoxieServerNormalizeLinkedChildActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6468. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorNormalizeLinkedChildArg &)basehelper)
  6469. {
  6470. numProcessedLastGroup = 0;
  6471. }
  6472. ~CRoxieServerNormalizeLinkedChildActivity()
  6473. {
  6474. }
  6475. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6476. {
  6477. numProcessedLastGroup = 0;
  6478. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6479. }
  6480. virtual void reset()
  6481. {
  6482. curParent.clear();
  6483. curChild.clear();
  6484. CRoxieServerActivity::reset();
  6485. }
  6486. const void *nextInGroup()
  6487. {
  6488. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  6489. loop
  6490. {
  6491. if (!curParent)
  6492. {
  6493. if (!advanceInput())
  6494. return NULL;
  6495. }
  6496. try
  6497. {
  6498. const void *ret = curChild.getClear();
  6499. curChild.set(helper.next());
  6500. if (!curChild)
  6501. curParent.clear();
  6502. if (ret)
  6503. {
  6504. processed++;
  6505. return ret;
  6506. }
  6507. }
  6508. catch (IException *E)
  6509. {
  6510. throw makeWrappedException(E);
  6511. }
  6512. }
  6513. }
  6514. };
  6515. class CRoxieServerNormalizeLinkedChildActivityFactory : public CRoxieServerActivityFactory
  6516. {
  6517. public:
  6518. CRoxieServerNormalizeLinkedChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6519. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  6520. {
  6521. }
  6522. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  6523. {
  6524. return new CRoxieServerNormalizeLinkedChildActivity(this, _probeManager);
  6525. }
  6526. };
  6527. IRoxieServerActivityFactory *createRoxieServerNormalizeLinkedChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6528. {
  6529. return new CRoxieServerNormalizeLinkedChildActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  6530. }
  6531. //=================================================================================
  6532. interface ISortAlgorithm : extends IInterface
  6533. {
  6534. virtual void prepare(IRoxieInput *input) = 0;
  6535. virtual const void *next() = 0;
  6536. virtual void reset() = 0;
  6537. };
  6538. class CQuickSortAlgorithm : implements CInterfaceOf<ISortAlgorithm>
  6539. {
  6540. unsigned curIndex;
  6541. ConstPointerArray sorted;
  6542. ICompare *compare;
  6543. public:
  6544. CQuickSortAlgorithm(ICompare *_compare) : compare(_compare)
  6545. {
  6546. curIndex = 0;
  6547. }
  6548. virtual void prepare(IRoxieInput *input)
  6549. {
  6550. curIndex = 0;
  6551. if (input->nextGroup(sorted))
  6552. qsortvec(const_cast<void * *>(sorted.getArray()), sorted.ordinality(), *compare);
  6553. }
  6554. virtual const void *next()
  6555. {
  6556. if (sorted.isItem(curIndex))
  6557. return sorted.item(curIndex++);
  6558. return NULL;
  6559. }
  6560. virtual void reset()
  6561. {
  6562. while (sorted.isItem(curIndex))
  6563. ReleaseRoxieRow(sorted.item(curIndex++));
  6564. curIndex = 0;
  6565. sorted.kill();
  6566. }
  6567. };
  6568. class CSpillingQuickSortAlgorithm : implements CInterfaceOf<ISortAlgorithm>, implements roxiemem::IBufferedRowCallback
  6569. {
  6570. enum {
  6571. InitialSortElements = 0,
  6572. //The number of rows that can be added without entering a critical section, and therefore also the number
  6573. //of rows that might not get freed when memory gets tight.
  6574. CommitStep=32
  6575. };
  6576. roxiemem::DynamicRoxieOutputRowArray rowsToSort;
  6577. roxiemem::RoxieSimpleInputRowArray sorted;
  6578. ICompare *compare;
  6579. IRoxieSlaveContext * ctx;
  6580. Owned<IDiskMerger> diskMerger;
  6581. Owned<IRowStream> diskReader;
  6582. Owned<IOutputMetaData> rowMeta;
  6583. unsigned activityId;
  6584. public:
  6585. CSpillingQuickSortAlgorithm(ICompare *_compare, IRoxieSlaveContext * _ctx, IOutputMetaData * _rowMeta, unsigned _activityId)
  6586. : rowsToSort(&_ctx->queryRowManager(), InitialSortElements, CommitStep, _activityId), ctx(_ctx), compare(_compare), rowMeta(_rowMeta), activityId(_activityId)
  6587. {
  6588. ctx->queryRowManager().addRowBuffer(this);
  6589. }
  6590. ~CSpillingQuickSortAlgorithm()
  6591. {
  6592. ctx->queryRowManager().removeRowBuffer(this);
  6593. diskReader.clear();
  6594. }
  6595. virtual void prepare(IRoxieInput *input)
  6596. {
  6597. loop
  6598. {
  6599. const void * next = input->nextInGroup();
  6600. if (!next)
  6601. break;
  6602. if (!rowsToSort.append(next))
  6603. {
  6604. {
  6605. roxiemem::RoxieOutputRowArrayLock block(rowsToSort);
  6606. //We should have been called back to free any committed rows, but occasionally it may not (e.g., if
  6607. //the problem is global memory is exhausted) - in which case force a spill here (but add any pending
  6608. //rows first).
  6609. if (rowsToSort.numCommitted() != 0)
  6610. {
  6611. rowsToSort.flush();
  6612. spillRows();
  6613. }
  6614. //Ensure new rows are written to the head of the array. It needs to be a separate call because
  6615. //spillRows() cannot shift active row pointer since it can be called from any thread
  6616. rowsToSort.flush();
  6617. }
  6618. if (!rowsToSort.append(next))
  6619. {
  6620. ReleaseRoxieRow(next);
  6621. throw MakeStringException(ROXIEMM_MEMORY_LIMIT_EXCEEDED, "Insufficient memory to append sort row");
  6622. }
  6623. }
  6624. }
  6625. rowsToSort.flush();
  6626. roxiemem::RoxieOutputRowArrayLock block(rowsToSort);
  6627. if (diskMerger)
  6628. {
  6629. spillRows();
  6630. rowsToSort.kill();
  6631. diskReader.setown(diskMerger->merge(compare));
  6632. }
  6633. else
  6634. {
  6635. unsigned numRows = rowsToSort.numCommitted();
  6636. if (numRows)
  6637. {
  6638. const void * * rows = rowsToSort.getBlock(numRows);
  6639. //MORE: Should this be parallel? Should that be dependent on whether it is grouped? Should be a hint.
  6640. qsortvec(const_cast<void * *>(rows), numRows, *compare);
  6641. }
  6642. sorted.transferFrom(rowsToSort);
  6643. }
  6644. }
  6645. virtual const void *next()
  6646. {
  6647. if(diskReader)
  6648. return diskReader->nextRow();
  6649. return sorted.dequeue();
  6650. }
  6651. virtual void reset()
  6652. {
  6653. //MORE: This could transfer any row pointer from sorted back to rowsToSort. It would trade
  6654. //fewer heap allocations with not freeing up the memory from large group sorts.
  6655. rowsToSort.clearRows();
  6656. sorted.kill();
  6657. //Disk reader must be cleared before the merger - or the files may still be locked.
  6658. diskReader.clear();
  6659. diskMerger.clear();
  6660. }
  6661. //interface roxiemem::IBufferedRowCallback
  6662. virtual unsigned getSpillCost() const
  6663. {
  6664. //Spill global sorts before grouped sorts
  6665. if (rowMeta->isGrouped())
  6666. return 20;
  6667. return 10;
  6668. }
  6669. virtual bool freeBufferedRows(bool critical)
  6670. {
  6671. roxiemem::RoxieOutputRowArrayLock block(rowsToSort);
  6672. return spillRows();
  6673. }
  6674. protected:
  6675. bool spillRows()
  6676. {
  6677. unsigned numRows = rowsToSort.numCommitted();
  6678. if (numRows == 0)
  6679. return false;
  6680. const void * * rows = rowsToSort.getBlock(numRows);
  6681. qsortvec(const_cast<void * *>(rows), numRows, *compare);
  6682. Owned<IRowWriter> out = queryMerger()->createWriteBlock();
  6683. for (unsigned i= 0; i < numRows; i++)
  6684. {
  6685. out->putRow(rows[i]);
  6686. }
  6687. rowsToSort.noteSpilled(numRows);
  6688. return true;
  6689. }
  6690. IDiskMerger * queryMerger()
  6691. {
  6692. if (!diskMerger)
  6693. {
  6694. unsigned __int64 seq = (memsize_t)this ^ get_cycles_now();
  6695. StringBuffer spillBasename;
  6696. spillBasename.append(tempDirectory).append(PATHSEPCHAR).appendf("spill_sort_%"I64F"u", seq);
  6697. Owned<IRowLinkCounter> linker = new RoxieRowLinkCounter();
  6698. Owned<IRowInterfaces> rowInterfaces = createRowInterfaces(rowMeta, activityId, ctx->queryCodeContext());
  6699. diskMerger.setown(createDiskMerger(rowInterfaces, linker, spillBasename));
  6700. }
  6701. return diskMerger;
  6702. }
  6703. };
  6704. #define INSERTION_SORT_BLOCKSIZE 1024
  6705. class SortedBlock : public CInterface, implements IInterface
  6706. {
  6707. unsigned sequence;
  6708. const void **rows;
  6709. unsigned length;
  6710. unsigned pos;
  6711. SortedBlock(const SortedBlock &);
  6712. public:
  6713. IMPLEMENT_IINTERFACE;
  6714. SortedBlock(unsigned _sequence, IRowManager *rowManager, unsigned activityId) : sequence(_sequence)
  6715. {
  6716. rows = (const void **) rowManager->allocate(INSERTION_SORT_BLOCKSIZE * sizeof(void *), activityId);
  6717. length = 0;
  6718. pos = 0;
  6719. }
  6720. ~SortedBlock()
  6721. {
  6722. while (pos < length)
  6723. ReleaseRoxieRow(rows[pos++]);
  6724. ReleaseRoxieRow(rows);
  6725. }
  6726. int compareTo(SortedBlock *r, ICompare *compare)
  6727. {
  6728. int rc = compare->docompare(rows[pos], r->rows[r->pos]);
  6729. if (!rc)
  6730. rc = sequence - r->sequence;
  6731. return rc;
  6732. }
  6733. const void *next()
  6734. {
  6735. if (pos < length)
  6736. return rows[pos++];
  6737. else
  6738. return NULL;
  6739. }
  6740. inline bool eof()
  6741. {
  6742. return pos==length;
  6743. }
  6744. bool insert(const void *next, ICompare *_compare )
  6745. {
  6746. unsigned b = length;
  6747. if (b == INSERTION_SORT_BLOCKSIZE)
  6748. return false;
  6749. else if (b < 7)
  6750. {
  6751. while (b)
  6752. {
  6753. if (_compare->docompare(next, rows[b-1]) >= 0)
  6754. break;
  6755. b--;
  6756. }
  6757. if (b != length)
  6758. memmove(&rows[b+1], &rows[b], (length - b) * sizeof(void *));
  6759. rows[b] = next;
  6760. length++;
  6761. return true;
  6762. }
  6763. else
  6764. {
  6765. unsigned int a = 0;
  6766. while ((int)a<b)
  6767. {
  6768. int i = (a+b)/2;
  6769. int rc = _compare->docompare(next, rows[i]);
  6770. if (rc>=0)
  6771. a = i+1;
  6772. else
  6773. b = i;
  6774. }
  6775. if (a != length)
  6776. memmove(&rows[a+1], &rows[a], (length - a) * sizeof(void *));
  6777. rows[a] = next;
  6778. length++;
  6779. return true;
  6780. }
  6781. }
  6782. };
  6783. class CInsertionSortAlgorithm : implements CInterfaceOf<ISortAlgorithm>
  6784. {
  6785. SortedBlock *curBlock;
  6786. unsigned blockNo;
  6787. IArrayOf<SortedBlock> blocks;
  6788. unsigned activityId;
  6789. IRowManager *rowManager;
  6790. ICompare *compare;
  6791. void newBlock()
  6792. {
  6793. blocks.append(*curBlock);
  6794. curBlock = new SortedBlock(blockNo++, rowManager, activityId);
  6795. }
  6796. inline static int doCompare(SortedBlock &l, SortedBlock &r, ICompare *compare)
  6797. {
  6798. return l.compareTo(&r, compare);
  6799. }
  6800. void makeHeap()
  6801. {
  6802. /* Permute blocks to establish the heap property
  6803. For each element p, the children are p*2+1 and p*2+2 (provided these are in range)
  6804. The children of p must both be greater than or equal to p
  6805. The parent of a child c is given by p = (c-1)/2
  6806. */
  6807. unsigned i;
  6808. unsigned n = blocks.length();
  6809. SortedBlock **s = blocks.getArray();
  6810. for (i=1; i<n; i++)
  6811. {
  6812. SortedBlock * r = s[i];
  6813. int c = i; /* child */
  6814. while (c > 0)
  6815. {
  6816. int p = (c-1)/2; /* parent */
  6817. if ( doCompare( blocks.item(c), blocks.item(p), compare ) >= 0 )
  6818. break;
  6819. s[c] = s[p];
  6820. s[p] = r;
  6821. c = p;
  6822. }
  6823. }
  6824. }
  6825. void remakeHeap()
  6826. {
  6827. /* The row associated with block[0] will have changed
  6828. This code restores the heap property
  6829. */
  6830. unsigned p = 0; /* parent */
  6831. unsigned n = blocks.length();
  6832. SortedBlock **s = blocks.getArray();
  6833. while (1)
  6834. {
  6835. unsigned c = p*2 + 1; /* child */
  6836. if ( c >= n )
  6837. break;
  6838. /* Select smaller child */
  6839. if ( c+1 < n && doCompare( blocks.item(c+1), blocks.item(c), compare ) < 0 ) c += 1;
  6840. /* If child is greater or equal than parent then we are done */
  6841. if ( doCompare( blocks.item(c), blocks.item(p), compare ) >= 0 )
  6842. break;
  6843. /* Swap parent and child */
  6844. SortedBlock *r = s[c];
  6845. s[c] = s[p];
  6846. s[p] = r;
  6847. /* child becomes parent */
  6848. p = c;
  6849. }
  6850. }
  6851. public:
  6852. CInsertionSortAlgorithm(ICompare *_compare, IRowManager *_rowManager, unsigned _activityId)
  6853. : compare(_compare)
  6854. {
  6855. rowManager = _rowManager;
  6856. activityId = _activityId;
  6857. curBlock = NULL;
  6858. blockNo = 0;
  6859. }
  6860. virtual void reset()
  6861. {
  6862. blocks.kill();
  6863. delete curBlock;
  6864. curBlock = NULL;
  6865. blockNo = 0;
  6866. }
  6867. virtual void prepare(IRoxieInput *input)
  6868. {
  6869. blockNo = 0;
  6870. curBlock = new SortedBlock(blockNo++, rowManager, activityId);
  6871. loop
  6872. {
  6873. const void *next = input->nextInGroup();
  6874. if (!next)
  6875. break;
  6876. if (!curBlock->insert(next, compare))
  6877. {
  6878. newBlock();
  6879. curBlock->insert(next, compare);
  6880. }
  6881. }
  6882. if (blockNo > 1)
  6883. {
  6884. blocks.append(*curBlock);
  6885. curBlock = NULL;
  6886. makeHeap();
  6887. }
  6888. }
  6889. virtual const void * next()
  6890. {
  6891. const void *ret;
  6892. if (blockNo==1) // single block case..
  6893. {
  6894. ret = curBlock->next();
  6895. }
  6896. else if (blocks.length())
  6897. {
  6898. SortedBlock &top = blocks.item(0);
  6899. ret = top.next();
  6900. if (top.eof())
  6901. blocks.replace(blocks.popGet(), 0);
  6902. remakeHeap();
  6903. }
  6904. else
  6905. ret = NULL;
  6906. return ret;
  6907. }
  6908. };
  6909. class CHeapSortAlgorithm : implements CInterfaceOf<ISortAlgorithm>
  6910. {
  6911. unsigned curIndex;
  6912. ConstPointerArray sorted;
  6913. bool inputAlreadySorted;
  6914. IntArray sequences;
  6915. bool eof;
  6916. ICompare *compare;
  6917. #ifdef _CHECK_HEAPSORT
  6918. void checkHeap() const
  6919. {
  6920. unsigned n = sorted.ordinality();
  6921. if (n)
  6922. {
  6923. ICompare *_compare = compare;
  6924. void **s = sorted.getArray();
  6925. int *sq = sequences.getArray();
  6926. unsigned p;
  6927. #if 0
  6928. CTXLOG("------------------------%d entries-----------------", n);
  6929. for (p = 0; p < n; p++)
  6930. {
  6931. CTXLOG("HEAP %d: %d %.10s", p, sq[p], s[p] ? s[p] : "..");
  6932. }
  6933. #endif
  6934. for (p = 0; p < n; p++)
  6935. {
  6936. unsigned c = p*2+1;
  6937. if (c<n)
  6938. assertex(!s[c] || (docompare(p, c, _compare, s, sq) <= 0));
  6939. c++;
  6940. if (c<n)
  6941. assertex(!s[c] || (docompare(p, c, _compare, s, sq) <= 0));
  6942. }
  6943. }
  6944. }
  6945. #else
  6946. inline void checkHeap() const {}
  6947. #endif
  6948. const void *removeHeap()
  6949. {
  6950. unsigned n = sorted.ordinality();
  6951. if (n)
  6952. {
  6953. const void *ret = sorted.item(0);
  6954. if (n > 1 && ret)
  6955. {
  6956. ICompare *_compare = compare;
  6957. const void **s = sorted.getArray();
  6958. int *sq = sequences.getArray();
  6959. unsigned v = 0; // vacancy
  6960. loop
  6961. {
  6962. unsigned c = 2*v + 1;
  6963. if (c < n)
  6964. {
  6965. unsigned f = c; // favourite to fill it
  6966. c++;
  6967. if (c < n && s[c] && (!s[f] || (docompare(f, c, _compare, s, sq) > 0))) // is the smaller of the children
  6968. f = c;
  6969. sq[v] = sq[f];
  6970. if ((s[v] = s[f]) != NULL)
  6971. v = f;
  6972. else
  6973. break;
  6974. }
  6975. else
  6976. {
  6977. s[v] = NULL;
  6978. break;
  6979. }
  6980. }
  6981. }
  6982. checkHeap();
  6983. return ret;
  6984. }
  6985. else
  6986. return NULL;
  6987. }
  6988. static inline int docompare(unsigned l, unsigned r, ICompare *_compare, const void **s, int *sq)
  6989. {
  6990. int rc = _compare->docompare(s[l], s[r]);
  6991. if (!rc)
  6992. rc = sq[l] - sq[r];
  6993. return rc;
  6994. }
  6995. void insertHeap(const void *next)
  6996. {
  6997. // Upside-down heap sort
  6998. // Maintain a heap where every parent is lower than each of its children
  6999. // Root (at node 0) is lowest record seen, nodes 2n+1, 2n+2 are the children
  7000. // To insert a row, add it at end then keep swapping with parent as long as parent is greater
  7001. // To remove a row, take row 0, then recreate heap by replacing it with smaller of two children and so on down the tree
  7002. // Nice features:
  7003. // 1. Deterministic
  7004. // 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
  7005. // 3. Already sorted case can be spotted at zero cost while reading.
  7006. // 4. If you don't read all the results, you don't have to complete the sort
  7007. // BUT it is NOT stable, so we have to use a parallel array of sequence numbers
  7008. unsigned n = sorted.ordinality();
  7009. sorted.append(next);
  7010. sequences.append(n);
  7011. if (!n)
  7012. return;
  7013. ICompare *_compare = compare;
  7014. const void **s = sorted.getArray();
  7015. if (inputAlreadySorted)
  7016. {
  7017. if (_compare->docompare(next, s[n-1]) >= 0)
  7018. return;
  7019. else
  7020. {
  7021. // MORE - could delay creating sequences until now...
  7022. inputAlreadySorted = false;
  7023. }
  7024. }
  7025. int *sq = sequences.getArray();
  7026. unsigned q = n;
  7027. while (n)
  7028. {
  7029. unsigned parent = (n-1) / 2;
  7030. const void *p = s[parent];
  7031. if (_compare->docompare(p, next) <= 0)
  7032. break;
  7033. s[n] = p;
  7034. sq[n] = sq[parent];
  7035. s[parent] = next;
  7036. sq[parent] = q;
  7037. n = parent;
  7038. }
  7039. }
  7040. public:
  7041. CHeapSortAlgorithm(ICompare *_compare) : compare(_compare)
  7042. {
  7043. inputAlreadySorted = true;
  7044. curIndex = 0;
  7045. eof = false;
  7046. }
  7047. virtual void reset()
  7048. {
  7049. eof = false;
  7050. if (inputAlreadySorted)
  7051. {
  7052. while (sorted.isItem(curIndex))
  7053. ReleaseRoxieRow(sorted.item(curIndex++));
  7054. sorted.kill();
  7055. }
  7056. else
  7057. {
  7058. ReleaseRoxieRowSet(sorted);
  7059. }
  7060. inputAlreadySorted = true;
  7061. sequences.kill();
  7062. }
  7063. virtual void prepare(IRoxieInput *input)
  7064. {
  7065. inputAlreadySorted = true;
  7066. curIndex = 0;
  7067. eof = false;
  7068. assertex(sorted.ordinality()==0);
  7069. const void *next = input->nextInGroup();
  7070. if (!next)
  7071. {
  7072. eof = true;
  7073. return;
  7074. }
  7075. loop
  7076. {
  7077. insertHeap(next);
  7078. next = input->nextInGroup();
  7079. if (!next)
  7080. break;
  7081. }
  7082. checkHeap();
  7083. }
  7084. virtual const void * next()
  7085. {
  7086. if (inputAlreadySorted)
  7087. {
  7088. if (sorted.isItem(curIndex))
  7089. {
  7090. return sorted.item(curIndex++);
  7091. }
  7092. else
  7093. return NULL;
  7094. }
  7095. else
  7096. return removeHeap();
  7097. }
  7098. };
  7099. typedef enum {heapSort, insertionSort, quickSort, spillingQuickSort, unknownSort } RoxieSortAlgorithm;
  7100. class CRoxieServerSortActivity : public CRoxieServerActivity
  7101. {
  7102. protected:
  7103. IHThorSortArg &helper;
  7104. ICompare *compare;
  7105. Owned<ISortAlgorithm> sorter;
  7106. bool readInput;
  7107. RoxieSortAlgorithm sortAlgorithm;
  7108. unsigned sortFlags;
  7109. public:
  7110. CRoxieServerSortActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, RoxieSortAlgorithm _sortAlgorithm, unsigned _sortFlags)
  7111. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorSortArg &)basehelper), sortAlgorithm(_sortAlgorithm), sortFlags(_sortFlags)
  7112. {
  7113. compare = helper.queryCompare();
  7114. readInput = false;
  7115. }
  7116. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  7117. {
  7118. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  7119. switch (sortAlgorithm)
  7120. {
  7121. case heapSort:
  7122. sorter.setown(new CHeapSortAlgorithm(compare));
  7123. break;
  7124. case insertionSort:
  7125. sorter.setown(new CInsertionSortAlgorithm(compare, &ctx->queryRowManager(), activityId));
  7126. break;
  7127. case quickSort:
  7128. sorter.setown(new CQuickSortAlgorithm(compare));
  7129. break;
  7130. case spillingQuickSort:
  7131. sorter.setown(new CSpillingQuickSortAlgorithm(compare, ctx, meta, activityId));
  7132. break;
  7133. case unknownSort:
  7134. sorter.clear(); // create it later....
  7135. break;
  7136. default:
  7137. throwUnexpected();
  7138. break;
  7139. }
  7140. }
  7141. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7142. {
  7143. assertex(!readInput);
  7144. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7145. }
  7146. virtual void reset()
  7147. {
  7148. if (sorter)
  7149. sorter->reset();
  7150. readInput = false;
  7151. CRoxieServerActivity::reset();
  7152. }
  7153. virtual const void * nextInGroup()
  7154. {
  7155. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  7156. if (!readInput)
  7157. {
  7158. if (sortAlgorithm == unknownSort)
  7159. {
  7160. sorter.clear();
  7161. IHThorAlgorithm *sortMethod = static_cast<IHThorAlgorithm *>(helper.selectInterface(TAIalgorithm_1));
  7162. OwnedRoxieString useAlgorithm(sortMethod->getAlgorithm());
  7163. if (useAlgorithm)
  7164. {
  7165. if (stricmp(useAlgorithm, "quicksort")==0)
  7166. {
  7167. if (sortFlags & TAFstable)
  7168. throw MakeStringException(ROXIE_UNKNOWN_ALGORITHM, "Invalid stable sort algorithm %s requested", useAlgorithm.get());
  7169. sorter.setown(new CQuickSortAlgorithm(compare));
  7170. }
  7171. else if (stricmp(useAlgorithm, "heapsort")==0)
  7172. sorter.setown(new CHeapSortAlgorithm(compare));
  7173. else if (stricmp(useAlgorithm, "insertionsort")==0)
  7174. sorter.setown(new CInsertionSortAlgorithm(compare, &ctx->queryRowManager(), activityId));
  7175. else
  7176. {
  7177. WARNLOG(ROXIE_UNKNOWN_ALGORITHM, "Ignoring unsupported sort order algorithm '%s', using default", useAlgorithm.get());
  7178. if (sortFlags & TAFunstable)
  7179. sorter.setown(new CQuickSortAlgorithm(compare));
  7180. else
  7181. sorter.setown(new CHeapSortAlgorithm(compare));
  7182. }
  7183. }
  7184. else
  7185. 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...
  7186. }
  7187. sorter->prepare(input);
  7188. readInput = true;
  7189. }
  7190. const void *ret = sorter->next();
  7191. if (ret)
  7192. processed++;
  7193. else
  7194. {
  7195. sorter->reset();
  7196. readInput = false; // ready for next group
  7197. }
  7198. return ret;
  7199. }
  7200. };
  7201. class CRoxieServerSortActivityFactory : public CRoxieServerActivityFactory
  7202. {
  7203. RoxieSortAlgorithm sortAlgorithm;
  7204. unsigned sortFlags;
  7205. public:
  7206. CRoxieServerSortActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  7207. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  7208. {
  7209. sortAlgorithm = heapSort;
  7210. sortFlags = TAFstable;
  7211. Owned<IHThorSortArg> sortHelper = (IHThorSortArg *) helperFactory();
  7212. IHThorAlgorithm *sortMethod = static_cast<IHThorAlgorithm *>(sortHelper->selectInterface(TAIalgorithm_1));
  7213. if (sortMethod)
  7214. {
  7215. sortFlags = sortMethod->getAlgorithmFlags();
  7216. if (sortFlags & TAFunstable)
  7217. sortAlgorithm = quickSort;
  7218. if (!(sortFlags & TAFconstant))
  7219. sortAlgorithm = unknownSort;
  7220. else
  7221. {
  7222. OwnedRoxieString useAlgorithm(sortMethod->getAlgorithm());
  7223. if (useAlgorithm)
  7224. {
  7225. if (stricmp(useAlgorithm, "quicksort")==0)
  7226. {
  7227. if (sortFlags & TAFstable)
  7228. throw MakeStringException(ROXIE_UNKNOWN_ALGORITHM, "Invalid stable sort algorithm %s requested", useAlgorithm.get());
  7229. sortAlgorithm = quickSort;
  7230. }
  7231. else if (stricmp(useAlgorithm, "spillingquicksort")==0)
  7232. {
  7233. if (sortFlags & TAFstable)
  7234. throw MakeStringException(ROXIE_UNKNOWN_ALGORITHM, "Invalid stable sort algorithm %s requested", useAlgorithm.get());
  7235. sortAlgorithm = spillingQuickSort;
  7236. }
  7237. else if (stricmp(useAlgorithm, "heapsort")==0)
  7238. sortAlgorithm = heapSort; // NOTE - we do allow UNSTABLE('heapsort') in order to facilitate runtime selection
  7239. else if (stricmp(useAlgorithm, "insertionsort")==0)
  7240. sortAlgorithm = insertionSort;
  7241. else
  7242. {
  7243. WARNLOG(ROXIE_UNKNOWN_ALGORITHM, "Ignoring unsupported sort order algorithm '%s', using default", useAlgorithm.get());
  7244. if (sortFlags & TAFunstable)
  7245. sortAlgorithm = quickSort;
  7246. else
  7247. sortAlgorithm = heapSort;
  7248. }
  7249. }
  7250. }
  7251. }
  7252. }
  7253. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  7254. {
  7255. return new CRoxieServerSortActivity(this, _probeManager, sortAlgorithm, sortFlags);
  7256. }
  7257. };
  7258. IRoxieServerActivityFactory *createRoxieServerSortActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  7259. {
  7260. return new CRoxieServerSortActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  7261. }
  7262. //=====================================================================================================
  7263. class CRoxieServerSortedActivity : public CRoxieServerActivity
  7264. {
  7265. IHThorSortedArg &helper;
  7266. ICompare * compare;
  7267. const void *prev;
  7268. IRangeCompare * stepCompare;
  7269. public:
  7270. CRoxieServerSortedActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  7271. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorSortedArg &)basehelper)
  7272. {
  7273. prev = NULL;
  7274. compare = helper.queryCompare();
  7275. stepCompare = NULL;
  7276. }
  7277. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7278. {
  7279. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7280. IInputSteppingMeta * stepMeta = input->querySteppingMeta();
  7281. if (stepMeta)
  7282. stepCompare = stepMeta->queryCompare();
  7283. prev = NULL;
  7284. }
  7285. virtual void reset()
  7286. {
  7287. ReleaseClearRoxieRow(prev);
  7288. CRoxieServerActivity::reset();
  7289. }
  7290. virtual const void * nextInGroup()
  7291. {
  7292. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  7293. const void *ret = input->nextInGroup();
  7294. if (ret && prev && compare->docompare(prev, ret) > 0)
  7295. {
  7296. // MORE - better to give mismatching rows that indexes?
  7297. throw MakeStringException(ROXIE_NOT_SORTED, "SORTED(%u) detected incorrectly sorted rows (row %d, %d))", activityId, processed, processed+1);
  7298. }
  7299. ReleaseRoxieRow(prev);
  7300. prev = ret;
  7301. if (ret)
  7302. {
  7303. LinkRoxieRow(prev);
  7304. processed++;
  7305. }
  7306. return ret;
  7307. }
  7308. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  7309. {
  7310. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  7311. const void *ret = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  7312. if (ret && prev && compare->docompare(prev, ret) > 0)
  7313. {
  7314. // MORE - better to give mismatching rows that indexes?
  7315. throw MakeStringException(ROXIE_NOT_SORTED, "SORTED(%u) detected incorrectly sorted rows (row %d, %d))", activityId, processed, processed+1);
  7316. }
  7317. ReleaseRoxieRow(prev);
  7318. prev = ret;
  7319. if (ret)
  7320. {
  7321. LinkRoxieRow(prev);
  7322. processed++;
  7323. }
  7324. return ret;
  7325. }
  7326. IInputSteppingMeta * querySteppingMeta()
  7327. {
  7328. return input->querySteppingMeta();
  7329. }
  7330. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  7331. {
  7332. return input->gatherConjunctions(collector);
  7333. }
  7334. virtual void resetEOF()
  7335. {
  7336. input->resetEOF();
  7337. }
  7338. };
  7339. class CRoxieServerSortedActivityFactory : public CRoxieServerActivityFactory
  7340. {
  7341. public:
  7342. CRoxieServerSortedActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  7343. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  7344. {
  7345. }
  7346. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  7347. {
  7348. return new CRoxieServerSortedActivity(this, _probeManager);
  7349. }
  7350. };
  7351. IRoxieServerActivityFactory *createRoxieServerSortedActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  7352. {
  7353. return new CRoxieServerSortedActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  7354. }
  7355. //=====================================================================================================
  7356. class CRoxieServerThroughSpillActivity : public CRoxieServerActivity
  7357. {
  7358. /*
  7359. BE VERY CAREFUL - this code is tricky.
  7360. Note that starts and stops (and resets) can occur in strange orders
  7361. The FIRST start OR stop must initialize the activity but only the first START should call the upstream start.
  7362. The last stop should call the upstream stop.
  7363. The first reset should call the upstream reset.
  7364. 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
  7365. not yet had start or stop called - for this to happen init() is called on all outputs on the first start or stop.
  7366. Some outputs may be completely pruned away when used in a GRAPH - these outputs should not receive any start/stop/reset and should be
  7367. ignored in the minIndex calculation
  7368. */
  7369. public:
  7370. IHThorArg &helper;
  7371. unsigned activeOutputs;
  7372. unsigned numOutputs;
  7373. unsigned numOriginalOutputs;
  7374. QueueOf<const void, true> buffer;
  7375. CriticalSection crit;
  7376. CriticalSection crit2;
  7377. unsigned tailIdx;
  7378. unsigned headIdx;
  7379. Owned<IException> error;
  7380. class OutputAdaptor : public CInterface, implements IRoxieInput
  7381. {
  7382. bool eof, eofpending, stopped;
  7383. public:
  7384. CRoxieServerThroughSpillActivity *parent;
  7385. unsigned idx;
  7386. unsigned oid;
  7387. unsigned processed;
  7388. unsigned __int64 totalCycles;
  7389. public:
  7390. IMPLEMENT_IINTERFACE;
  7391. OutputAdaptor()
  7392. {
  7393. parent = NULL;
  7394. oid = 0;
  7395. idx = 0;
  7396. processed = 0;
  7397. totalCycles = 0;
  7398. eofpending = false;
  7399. eof = false;
  7400. stopped = false;
  7401. }
  7402. ~OutputAdaptor()
  7403. {
  7404. if (traceStartStop)
  7405. DBGLOG("%p ~OutputAdaptor %d", this, oid);
  7406. }
  7407. void init()
  7408. {
  7409. if (traceStartStop)
  7410. DBGLOG("%p init Input adaptor %d", this, oid);
  7411. idx = 0;
  7412. processed = 0;
  7413. totalCycles = 0;
  7414. eofpending = false;
  7415. eof = false;
  7416. stopped = false;
  7417. }
  7418. virtual unsigned queryId() const
  7419. {
  7420. return parent->queryId();
  7421. }
  7422. virtual IRoxieServerActivity *queryActivity()
  7423. {
  7424. return parent;
  7425. }
  7426. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  7427. {
  7428. return parent->queryIndexReadActivity();
  7429. }
  7430. virtual unsigned __int64 queryTotalCycles() const
  7431. {
  7432. return totalCycles;
  7433. }
  7434. virtual unsigned __int64 queryLocalCycles() const
  7435. {
  7436. return 0;
  7437. }
  7438. virtual IRoxieInput *queryInput(unsigned idx) const
  7439. {
  7440. return parent->queryInput(idx);
  7441. }
  7442. virtual const void * nextInGroup()
  7443. {
  7444. ActivityTimer t(totalCycles, timeActivities, parent->ctx->queryDebugContext());
  7445. if (eof)
  7446. return NULL;
  7447. const void *ret = parent->readBuffered(idx, oid);
  7448. #ifdef TRACE_SPLIT
  7449. parent->CTXLOG("Adaptor %d got back %p for record %d", oid, ret, idx);
  7450. #endif
  7451. idx++;
  7452. if (ret)
  7453. {
  7454. processed++;
  7455. eofpending = false;
  7456. }
  7457. else if (eofpending)
  7458. eof = true;
  7459. else
  7460. eofpending = true;
  7461. return ret;
  7462. }
  7463. virtual IOutputMetaData * queryOutputMeta() const
  7464. {
  7465. return parent->queryOutputMeta();
  7466. }
  7467. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7468. {
  7469. // NOTE: it is tempting to move the init() of all output adaptors here. However that is not a good idea,
  7470. // since adaptors that have not yet started or stopped (but are going to) still need to have been init()'ed
  7471. // for minIndex to give the correct answers
  7472. // therefore, we call init() on all adaptors on receipt of the first start() or stop()
  7473. if (traceStartStop)
  7474. parent->CTXLOG("%p start Input adaptor %d stopped = %d", this, oid, stopped);
  7475. parent->start(oid, parentExtractSize, parentExtract, paused);
  7476. }
  7477. virtual void stop(bool aborting)
  7478. {
  7479. if (traceStartStop)
  7480. parent->CTXLOG("%p stop Input adaptor %d stopped = %d", this, oid, stopped);
  7481. if (!stopped)
  7482. {
  7483. parent->stop(oid, idx, aborting); // NOTE - may call init()
  7484. stopped = true; // parent code relies on stop being called exactly once per adaptor, so make sure it is!
  7485. idx = (unsigned) -1; // causes minIndex not to save rows for me...
  7486. }
  7487. };
  7488. virtual void reset()
  7489. {
  7490. if (traceStartStop)
  7491. parent->CTXLOG("%p reset Input adaptor %d stopped = %d", this, oid, stopped);
  7492. parent->reset(oid);
  7493. parent->noteProcessed(oid, processed, 0, 0);
  7494. processed = 0;
  7495. idx = 0; // value should not be relevant really but this is the safest...
  7496. stopped = false;
  7497. };
  7498. virtual void resetEOF()
  7499. {
  7500. parent->resetEOF();
  7501. }
  7502. virtual void checkAbort()
  7503. {
  7504. parent->checkAbort();
  7505. }
  7506. } *adaptors;
  7507. bool *used;
  7508. unsigned nextFreeOutput()
  7509. {
  7510. unsigned i = numOutputs;
  7511. while (i)
  7512. {
  7513. i--;
  7514. if (!used[i])
  7515. return i;
  7516. }
  7517. throwUnexpected();
  7518. }
  7519. unsigned minIndex(unsigned exceptOid)
  7520. {
  7521. // MORE - yukky code (and slow). Could keep them heapsorted by idx or something
  7522. // this is trying to determine whethwe any of the adaptors will in the future read a given record
  7523. unsigned minIdx = (unsigned) -1;
  7524. for (unsigned i = 0; i < numOutputs; i++)
  7525. {
  7526. if (i != exceptOid && used[i] && adaptors[i].idx < minIdx)
  7527. minIdx = adaptors[i].idx;
  7528. }
  7529. return minIdx;
  7530. }
  7531. void initOutputs()
  7532. {
  7533. activeOutputs = numOutputs;
  7534. for (unsigned i = 0; i < numOriginalOutputs; i++)
  7535. if (used[i])
  7536. adaptors[i].init();
  7537. state = STATEstarting;
  7538. }
  7539. public:
  7540. CRoxieServerThroughSpillActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  7541. : CRoxieServerActivity(_factory, _probeManager), helper(basehelper), numOutputs(_numOutputs)
  7542. {
  7543. numOriginalOutputs = numOutputs;
  7544. adaptors = new OutputAdaptor[numOutputs];
  7545. used = new bool[numOutputs];
  7546. for (unsigned i = 0; i < numOutputs; i++)
  7547. {
  7548. adaptors[i].parent = this;
  7549. adaptors[i].oid = i;
  7550. used[i] = false;
  7551. }
  7552. tailIdx = 0;
  7553. headIdx = 0;
  7554. activeOutputs = numOutputs;
  7555. }
  7556. ~CRoxieServerThroughSpillActivity()
  7557. {
  7558. delete [] adaptors;
  7559. delete [] used;
  7560. }
  7561. const void *readBuffered(unsigned idx, unsigned oid)
  7562. {
  7563. CriticalBlock b(crit);
  7564. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext()); // NOTE - time spent waiting for crit not included here. Is that right?
  7565. if (idx == headIdx) // test once without getting the crit2 sec
  7566. {
  7567. CriticalUnblock b1(crit);
  7568. CriticalBlock b2(crit2);
  7569. if (error)
  7570. {
  7571. throw error.getLink();
  7572. }
  7573. if (idx == headIdx) // test again now that we have it
  7574. {
  7575. try
  7576. {
  7577. const void *row = input->nextInGroup();
  7578. CriticalBlock b3(crit);
  7579. headIdx++;
  7580. if (activeOutputs==1)
  7581. {
  7582. #ifdef TRACE_SPLIT
  7583. CTXLOG("spill %d optimised return of %p", activityId, row);
  7584. #endif
  7585. return row; // optimization for the case where only one output still active.
  7586. }
  7587. buffer.enqueue(row);
  7588. }
  7589. catch (IException *E)
  7590. {
  7591. #ifdef TRACE_SPLIT
  7592. CTXLOG("spill %d caught exception", activityId);
  7593. #endif
  7594. error.set(E);
  7595. throw;
  7596. }
  7597. catch (...)
  7598. {
  7599. IException *E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught in CRoxieServerThroughSpillActivity::readBuffered");
  7600. error.set(E);
  7601. throw E;
  7602. }
  7603. }
  7604. }
  7605. idx -= tailIdx;
  7606. if (!idx)
  7607. {
  7608. unsigned min = minIndex(oid);
  7609. if (min > tailIdx)
  7610. {
  7611. tailIdx++;
  7612. const void *ret = buffer.dequeue(); // no need to link - last puller
  7613. #ifdef TRACE_SPLIT
  7614. CTXLOG("last puller return of %p", ret);
  7615. #endif
  7616. return ret;
  7617. }
  7618. }
  7619. const void *ret = buffer.item(idx);
  7620. if (ret) LinkRoxieRow(ret);
  7621. #ifdef TRACE_SPLIT
  7622. CTXLOG("standard return of %p", ret);
  7623. #endif
  7624. return ret;
  7625. }
  7626. virtual void start(unsigned oid, unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7627. {
  7628. CriticalBlock b(crit);
  7629. if (error)
  7630. throw error.getLink();
  7631. if (factory)
  7632. factory->noteStarted(oid);
  7633. if (traceStartStop)
  7634. CTXLOG("SPLIT %p: start %d child %d activeOutputs %d numOutputs %d numOriginalOutputs %d state %s", this, activityId, oid, activeOutputs, numOutputs, numOriginalOutputs, queryStateText(state));
  7635. if (state != STATEstarted)
  7636. {
  7637. if (state != STATEstarting)
  7638. initOutputs();
  7639. tailIdx = 0;
  7640. headIdx = 0;
  7641. error.clear();
  7642. try
  7643. {
  7644. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7645. }
  7646. catch (IException *E)
  7647. {
  7648. #ifdef TRACE_SPLIT
  7649. CTXLOG("spill %d caught exception in start", activityId);
  7650. #endif
  7651. error.set(E);
  7652. throw;
  7653. }
  7654. catch (...)
  7655. {
  7656. IException *E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught in CRoxieServerThroughSpillActivity::start");
  7657. error.set(E);
  7658. throw E;
  7659. }
  7660. }
  7661. }
  7662. void stop(unsigned oid, unsigned idx, bool aborting)
  7663. {
  7664. // Note that OutputAdaptor code ensures that stop is not called more than once per adaptor
  7665. CriticalBlock b(crit);
  7666. #ifdef TRACE_STARTSTOP
  7667. if (traceStartStop)
  7668. {
  7669. CTXLOG("SPLIT %p: stop %d child %d activeOutputs %d numOutputs %d numOriginalOutputs %d state %s", this, activityId, oid, activeOutputs, numOutputs, numOriginalOutputs, queryStateText(state));
  7670. if (watchActivityId && watchActivityId==activityId)
  7671. {
  7672. CTXLOG("WATCH: stop %d", activityId);
  7673. }
  7674. }
  7675. #endif
  7676. if (state != STATEstarting && state != STATEstarted)
  7677. initOutputs();
  7678. if (activeOutputs > 1)
  7679. {
  7680. if (tailIdx==idx)
  7681. {
  7682. // Discard all buffered rows that are there purely for this adaptor to read them
  7683. unsigned min = minIndex(oid);
  7684. if (min != (unsigned) -1)
  7685. // what does -1 signify?? No-one wants anything? In which case can't we kill all rows??
  7686. // Should never happen though if there are still some active.
  7687. // there may be a small window where adaptors are blocked on the semaphore...
  7688. {
  7689. #ifdef TRACE_SPLIT
  7690. CTXLOG("%p: Discarding buffered rows from %d to %d for oid %x (%d outputs active)", this, idx, min, oid, activeOutputs);
  7691. #endif
  7692. while (tailIdx < min)
  7693. {
  7694. ReleaseRoxieRow(buffer.dequeue());
  7695. tailIdx++;
  7696. }
  7697. }
  7698. }
  7699. activeOutputs--;
  7700. return;
  7701. }
  7702. #ifdef TRACE_SPLIT
  7703. CTXLOG("%p: All outputs done", this);
  7704. #endif
  7705. activeOutputs = numOutputs;
  7706. CRoxieServerActivity::stop(aborting);
  7707. };
  7708. void reset(unsigned oid)
  7709. {
  7710. if (traceStartStop)
  7711. CTXLOG("SPLIT %p: reset %d child %d activeOutputs %d numOutputs %d numOriginalOutputs %d state %s", this, activityId, oid, activeOutputs, numOutputs, numOriginalOutputs, queryStateText(state));
  7712. activeOutputs = numOutputs;
  7713. while (buffer.ordinality())
  7714. ReleaseRoxieRow(buffer.dequeue());
  7715. error.clear();
  7716. if (state != STATEreset) // make sure input is only reset once
  7717. CRoxieServerActivity::reset();
  7718. };
  7719. virtual unsigned __int64 queryLocalCycles() const
  7720. {
  7721. return 0;
  7722. }
  7723. virtual const void *nextInGroup()
  7724. {
  7725. throwUnexpected(); // Internal logic error - we are not anybody's input
  7726. }
  7727. virtual IOutputMetaData * queryOutputMeta() const
  7728. {
  7729. // if (outputMeta)
  7730. // return outputMeta;
  7731. // else
  7732. return input->queryOutputMeta(); // not always known (e.g. disk write - though Gavin _could_ fill it in)
  7733. }
  7734. virtual IRoxieInput *queryOutput(unsigned idx)
  7735. {
  7736. if (idx==(unsigned)-1)
  7737. idx = nextFreeOutput(); // MORE - what is this used for?
  7738. assertex(idx < numOriginalOutputs);
  7739. assertex(!used[idx]);
  7740. used[idx] = true;
  7741. return &adaptors[idx];
  7742. }
  7743. virtual void resetOutputsUsed()
  7744. {
  7745. numOutputs = 1;
  7746. activeOutputs = 1;
  7747. // MORE RKC->GH should we be clearing the used array here? anywhere?
  7748. }
  7749. virtual void noteOutputUsed()
  7750. {
  7751. assertex(numOutputs < numOriginalOutputs);
  7752. numOutputs++;
  7753. activeOutputs = numOutputs;
  7754. }
  7755. virtual bool isPassThrough()
  7756. {
  7757. return numOutputs==1;
  7758. }
  7759. };
  7760. class CRoxieServerThroughSpillActivityFactory : public CRoxieServerMultiOutputFactory
  7761. {
  7762. public:
  7763. CRoxieServerThroughSpillActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  7764. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  7765. {
  7766. Owned<IHThorSpillArg> helper = (IHThorSpillArg *) helperFactory();
  7767. setNumOutputs(helper->getTempUsageCount() + 1);
  7768. }
  7769. CRoxieServerThroughSpillActivityFactory(IQueryFactory &_queryFactory, HelperFactory *_helperFactory, unsigned _numOutputs)
  7770. : CRoxieServerMultiOutputFactory(0, 0, _queryFactory, _helperFactory, TAKsplit)
  7771. {
  7772. setNumOutputs(_numOutputs);
  7773. }
  7774. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  7775. {
  7776. return new CRoxieServerThroughSpillActivity(this, _probeManager, numOutputs);
  7777. }
  7778. };
  7779. IRoxieServerActivityFactory *createRoxieServerThroughSpillActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  7780. {
  7781. return new CRoxieServerThroughSpillActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  7782. }
  7783. IRoxieServerActivityFactory *createRoxieServerThroughSpillActivityFactory(IQueryFactory &_queryFactory, HelperFactory *_factory, unsigned _numOutputs)
  7784. {
  7785. return new CRoxieServerThroughSpillActivityFactory(_queryFactory, _factory, _numOutputs);
  7786. }
  7787. //----------------------------------------------------------------------------------------------
  7788. class CRoxieServerSplitActivityFactory : public CRoxieServerMultiOutputFactory
  7789. {
  7790. public:
  7791. CRoxieServerSplitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  7792. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  7793. {
  7794. Owned<IHThorSplitArg> helper = (IHThorSplitArg *) helperFactory();
  7795. setNumOutputs(helper->numBranches());
  7796. }
  7797. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  7798. {
  7799. return new CRoxieServerThroughSpillActivity(this, _probeManager, numOutputs);
  7800. }
  7801. };
  7802. IRoxieServerActivityFactory *createRoxieServerSplitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  7803. {
  7804. return new CRoxieServerSplitActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  7805. }
  7806. //=====================================================================================================
  7807. #define PIPE_BUFSIZE 0x8000
  7808. static IException *createPipeFailureException(const char *cmd, unsigned retcode, IPipeProcess *pipe)
  7809. {
  7810. StringBuffer msg;
  7811. if(pipe->hasError())
  7812. {
  7813. try
  7814. {
  7815. char error[512];
  7816. size32_t sz = pipe->readError(sizeof(error), error);
  7817. if(sz && sz!=(size32_t)-1)
  7818. msg.append(", stderr: '").append(sz, error).append("'");
  7819. }
  7820. catch (IException *e)
  7821. {
  7822. EXCLOG(e, "Error reading pipe stderr");
  7823. e->Release();
  7824. }
  7825. }
  7826. return MakeStringException(ROXIE_PIPE_ERROR, "Pipe process %s returned error %u%s", cmd, retcode, msg.str());
  7827. }
  7828. class CRoxieServerPipeReadActivity : public CRoxieServerActivity
  7829. {
  7830. IHThorPipeReadArg &helper;
  7831. Owned<IPipeProcess> pipe;
  7832. StringAttr pipeCommand;
  7833. Owned<IOutputRowDeserializer> rowDeserializer;
  7834. Owned<IReadRowStream> readTransformer;
  7835. bool groupSignalled;
  7836. public:
  7837. CRoxieServerPipeReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  7838. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorPipeReadArg &)basehelper)
  7839. {
  7840. groupSignalled = true;
  7841. }
  7842. virtual bool needsAllocator() const { return true; }
  7843. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  7844. {
  7845. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  7846. rowDeserializer.setown(rowAllocator->createDiskDeserializer(ctx->queryCodeContext()));
  7847. }
  7848. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7849. {
  7850. groupSignalled = true; // i.e. don't start with a NULL row
  7851. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7852. if (!readTransformer)
  7853. {
  7854. OwnedRoxieString xmlIteratorPath(helper.getXmlIteratorPath());
  7855. readTransformer.setown(createReadRowStream(rowAllocator, rowDeserializer, helper.queryXmlTransformer(), helper.queryCsvTransformer(), xmlIteratorPath, helper.getPipeFlags()));
  7856. }
  7857. OwnedRoxieString pipeProgram(helper.getPipeProgram());
  7858. openPipe(pipeProgram);
  7859. }
  7860. virtual void stop(bool aborting)
  7861. {
  7862. CRoxieServerActivity::stop(aborting);
  7863. pipe.clear();
  7864. readTransformer->setStream(NULL);
  7865. }
  7866. virtual const void *nextInGroup()
  7867. {
  7868. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  7869. while (!waitForPipe())
  7870. {
  7871. if (!pipe)
  7872. return NULL;
  7873. if (helper.getPipeFlags() & TPFgroupeachrow)
  7874. {
  7875. if (!groupSignalled)
  7876. {
  7877. groupSignalled = true;
  7878. return NULL;
  7879. }
  7880. }
  7881. }
  7882. const void *ret = readTransformer->next();
  7883. assertex(ret != NULL); // if ret can ever be NULL then we need to recode this logic
  7884. processed++;
  7885. groupSignalled = false;
  7886. return ret;
  7887. }
  7888. protected:
  7889. bool waitForPipe()
  7890. {
  7891. if (!pipe)
  7892. return false; // done
  7893. if (!readTransformer->eos())
  7894. return true;
  7895. verifyPipe();
  7896. return false;
  7897. }
  7898. void openPipe(char const * cmd)
  7899. {
  7900. pipeCommand.setown(cmd);
  7901. pipe.setown(createPipeProcess());
  7902. if(!pipe->run(NULL, cmd, ".", false, true, true, 0x10000))
  7903. throw MakeStringException(ROXIE_PIPE_ERROR, "Could not run pipe process %s", cmd);
  7904. Owned<ISimpleReadStream> pipeReader = pipe->getOutputStream();
  7905. readTransformer->setStream(pipeReader.get());
  7906. }
  7907. void verifyPipe()
  7908. {
  7909. if (pipe)
  7910. {
  7911. unsigned err = pipe->wait();
  7912. if(err && !(helper.getPipeFlags() & TPFnofail))
  7913. {
  7914. throw createPipeFailureException(pipeCommand.get(), err, pipe);
  7915. }
  7916. pipe.clear();
  7917. }
  7918. }
  7919. };
  7920. class CRoxieServerPipeThroughActivity : public CRoxieServerActivity, implements IRecordPullerCallback
  7921. {
  7922. IHThorPipeThroughArg &helper;
  7923. RecordPullerThread puller;
  7924. Owned<IPipeProcess> pipe;
  7925. StringAttr pipeCommand;
  7926. InterruptableSemaphore pipeVerified;
  7927. InterruptableSemaphore pipeOpened;
  7928. CachedOutputMetaData inputMeta;
  7929. Owned<IOutputRowSerializer> rowSerializer;
  7930. Owned<IOutputRowDeserializer> rowDeserializer;
  7931. Owned<IPipeWriteXformHelper> writeTransformer;
  7932. Owned<IReadRowStream> readTransformer;
  7933. bool firstRead;
  7934. bool recreate;
  7935. bool inputExhausted;
  7936. bool groupSignalled;
  7937. public:
  7938. CRoxieServerPipeThroughActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  7939. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorPipeThroughArg &)basehelper), puller(false)
  7940. {
  7941. recreate = helper.recreateEachRow();
  7942. groupSignalled = true;
  7943. firstRead = false;
  7944. inputExhausted = false;
  7945. }
  7946. virtual bool needsAllocator() const { return true; }
  7947. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  7948. {
  7949. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  7950. rowSerializer.setown(inputMeta.createDiskSerializer(ctx->queryCodeContext(), activityId));
  7951. rowDeserializer.setown(rowAllocator->createDiskDeserializer(ctx->queryCodeContext()));
  7952. writeTransformer.setown(createPipeWriteXformHelper(helper.getPipeFlags(), helper.queryXmlOutput(), helper.queryCsvOutput(), rowSerializer));
  7953. }
  7954. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7955. {
  7956. firstRead = true;
  7957. inputExhausted = false;
  7958. groupSignalled = true; // i.e. don't start with a NULL row
  7959. pipeVerified.reinit();
  7960. pipeOpened.reinit();
  7961. writeTransformer->ready();
  7962. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7963. if (!readTransformer)
  7964. {
  7965. OwnedRoxieString xmlIterator(helper.getXmlIteratorPath());
  7966. readTransformer.setown(createReadRowStream(rowAllocator, rowDeserializer, helper.queryXmlTransformer(), helper.queryCsvTransformer(), xmlIterator, helper.getPipeFlags()));
  7967. }
  7968. if(!recreate)
  7969. {
  7970. OwnedRoxieString pipeProgram(helper.getPipeProgram());
  7971. openPipe(pipeProgram);
  7972. }
  7973. puller.start(parentExtractSize, parentExtract, paused, 0, false, ctx); // Pipe does not support preload presently - locks up
  7974. }
  7975. virtual void setInput(unsigned idx, IRoxieInput *_in)
  7976. {
  7977. if (idx)
  7978. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  7979. puller.setInput(this, _in);
  7980. inputMeta.set(_in->queryOutputMeta());
  7981. }
  7982. virtual void stop(bool aborting)
  7983. {
  7984. pipeVerified.interrupt(NULL);
  7985. pipeOpened.interrupt(NULL);
  7986. puller.stop(aborting);
  7987. CRoxieServerActivity::stop(aborting);
  7988. pipe.clear();
  7989. readTransformer->setStream(NULL);
  7990. }
  7991. virtual void reset()
  7992. {
  7993. puller.reset();
  7994. CRoxieServerActivity::reset();
  7995. }
  7996. virtual const void *nextInGroup()
  7997. {
  7998. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  7999. while (!waitForPipe())
  8000. {
  8001. if (!pipe)
  8002. return NULL;
  8003. if (helper.getPipeFlags() & TPFgroupeachrow)
  8004. {
  8005. if (!groupSignalled)
  8006. {
  8007. groupSignalled = true;
  8008. return NULL;
  8009. }
  8010. }
  8011. }
  8012. const void *ret = readTransformer->next();
  8013. assertex(ret != NULL); // if ret can ever be NULL then we need to recode this logic
  8014. processed++;
  8015. groupSignalled = false;
  8016. return ret;
  8017. }
  8018. virtual void processRow(const void *row)
  8019. {
  8020. // called from puller thread
  8021. if(recreate)
  8022. openPipe(helper.getNameFromRow(row));
  8023. writeTransformer->writeTranslatedText(row, pipe);
  8024. ReleaseRoxieRow(row);
  8025. if(recreate)
  8026. {
  8027. closePipe();
  8028. pipeVerified.wait();
  8029. }
  8030. }
  8031. virtual void processDone()
  8032. {
  8033. // called from puller thread
  8034. if(recreate)
  8035. {
  8036. inputExhausted = true;
  8037. pipeOpened.signal();
  8038. }
  8039. else
  8040. {
  8041. closePipe();
  8042. pipeVerified.wait();
  8043. }
  8044. }
  8045. virtual void processEOG()
  8046. {
  8047. }
  8048. void processGroup(const ConstPointerArray &)
  8049. {
  8050. throwUnexpected();
  8051. }
  8052. virtual bool fireException(IException *e)
  8053. {
  8054. pipeOpened.interrupt(LINK(e));
  8055. pipeVerified.interrupt(e);
  8056. return true;
  8057. }
  8058. private:
  8059. bool waitForPipe()
  8060. {
  8061. if (firstRead)
  8062. {
  8063. pipeOpened.wait();
  8064. firstRead = false;
  8065. }
  8066. if (!pipe)
  8067. return false; // done
  8068. if (!readTransformer->eos())
  8069. return true;
  8070. verifyPipe();
  8071. if (recreate && !inputExhausted)
  8072. pipeOpened.wait();
  8073. return false;
  8074. }
  8075. void openPipe(char const * cmd)
  8076. {
  8077. pipeCommand.setown(cmd);
  8078. pipe.setown(createPipeProcess());
  8079. if(!pipe->run(NULL, cmd, ".", true, true, true, 0x10000))
  8080. throw MakeStringException(ROXIE_PIPE_ERROR, "Could not run pipe process %s", cmd);
  8081. writeTransformer->writeHeader(pipe);
  8082. Owned<ISimpleReadStream> pipeReader = pipe->getOutputStream();
  8083. readTransformer->setStream(pipeReader.get());
  8084. pipeOpened.signal();
  8085. }
  8086. void closePipe()
  8087. {
  8088. writeTransformer->writeFooter(pipe);
  8089. pipe->closeInput();
  8090. }
  8091. void verifyPipe()
  8092. {
  8093. if (pipe)
  8094. {
  8095. unsigned err = pipe->wait();
  8096. if(err && !(helper.getPipeFlags() & TPFnofail))
  8097. {
  8098. throw createPipeFailureException(pipeCommand.get(), err, pipe);
  8099. }
  8100. pipe.clear();
  8101. pipeVerified.signal();
  8102. }
  8103. }
  8104. };
  8105. class CRoxieServerPipeWriteActivity : public CRoxieServerInternalSinkActivity
  8106. {
  8107. IHThorPipeWriteArg &helper;
  8108. Owned<IPipeProcess> pipe;
  8109. StringAttr pipeCommand;
  8110. CachedOutputMetaData inputMeta;
  8111. Owned<IOutputRowSerializer> rowSerializer;
  8112. Owned<IPipeWriteXformHelper> writeTransformer;
  8113. bool firstRead;
  8114. bool recreate;
  8115. bool inputExhausted;
  8116. public:
  8117. CRoxieServerPipeWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8118. : CRoxieServerInternalSinkActivity(_factory, _probeManager), helper((IHThorPipeWriteArg &)basehelper)
  8119. {
  8120. recreate = helper.recreateEachRow();
  8121. firstRead = false;
  8122. inputExhausted = false;
  8123. }
  8124. virtual bool needsAllocator() const { return true; }
  8125. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  8126. {
  8127. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  8128. inputMeta.set(input->queryOutputMeta());
  8129. rowSerializer.setown(inputMeta.createDiskSerializer(ctx->queryCodeContext(), activityId));
  8130. writeTransformer.setown(createPipeWriteXformHelper(helper.getPipeFlags(), helper.queryXmlOutput(), helper.queryCsvOutput(), rowSerializer));
  8131. }
  8132. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8133. {
  8134. firstRead = true;
  8135. inputExhausted = false;
  8136. writeTransformer->ready();
  8137. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8138. if(!recreate)
  8139. {
  8140. OwnedRoxieString pipeProgram(helper.getPipeProgram());
  8141. openPipe(pipeProgram);
  8142. }
  8143. }
  8144. virtual void stop(bool aborting)
  8145. {
  8146. CRoxieServerActivity::stop(aborting);
  8147. pipe.clear();
  8148. }
  8149. virtual void onExecute()
  8150. {
  8151. loop
  8152. {
  8153. const void *row = input->nextInGroup();
  8154. if (!row)
  8155. {
  8156. row = input->nextInGroup();
  8157. if (!row)
  8158. break;
  8159. }
  8160. processed++;
  8161. if(recreate)
  8162. openPipe(helper.getNameFromRow(row));
  8163. writeTransformer->writeTranslatedText(row, pipe);
  8164. ReleaseRoxieRow(row);
  8165. if(recreate)
  8166. closePipe();
  8167. }
  8168. closePipe();
  8169. }
  8170. private:
  8171. void openPipe(char const * cmd)
  8172. {
  8173. pipeCommand.setown(cmd);
  8174. pipe.setown(createPipeProcess());
  8175. if(!pipe->run(NULL, cmd, ".", true, false, true, 0x10000))
  8176. throw MakeStringException(ROXIE_PIPE_ERROR, "Could not run pipe process %s", cmd);
  8177. writeTransformer->writeHeader(pipe);
  8178. }
  8179. void closePipe()
  8180. {
  8181. writeTransformer->writeFooter(pipe);
  8182. pipe->closeInput();
  8183. unsigned err = pipe->wait();
  8184. if(err && !(helper.getPipeFlags() & TPFnofail))
  8185. {
  8186. throw createPipeFailureException(pipeCommand.get(), err, pipe);
  8187. }
  8188. pipe.clear();
  8189. }
  8190. };
  8191. class CRoxieServerPipeReadActivityFactory : public CRoxieServerActivityFactory
  8192. {
  8193. public:
  8194. CRoxieServerPipeReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8195. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  8196. {
  8197. }
  8198. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8199. {
  8200. return new CRoxieServerPipeReadActivity(this, _probeManager);
  8201. }
  8202. };
  8203. class CRoxieServerPipeThroughActivityFactory : public CRoxieServerActivityFactory
  8204. {
  8205. public:
  8206. CRoxieServerPipeThroughActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8207. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  8208. {
  8209. }
  8210. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8211. {
  8212. return new CRoxieServerPipeThroughActivity(this, _probeManager);
  8213. }
  8214. };
  8215. class CRoxieServerPipeWriteActivityFactory : public CRoxieServerInternalSinkFactory
  8216. {
  8217. public:
  8218. CRoxieServerPipeWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  8219. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot)
  8220. {
  8221. }
  8222. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8223. {
  8224. return new CRoxieServerPipeWriteActivity(this, _probeManager);
  8225. }
  8226. };
  8227. IRoxieServerActivityFactory *createRoxieServerPipeReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8228. {
  8229. return new CRoxieServerPipeReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  8230. }
  8231. IRoxieServerActivityFactory *createRoxieServerPipeThroughActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8232. {
  8233. return new CRoxieServerPipeThroughActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  8234. }
  8235. IRoxieServerActivityFactory *createRoxieServerPipeWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  8236. {
  8237. return new CRoxieServerPipeWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot);
  8238. }
  8239. //=====================================================================================================
  8240. class CRoxieServerStreamedIteratorActivity : public CRoxieServerActivity
  8241. {
  8242. IHThorStreamedIteratorArg &helper;
  8243. Owned<IRowStream> rows;
  8244. public:
  8245. CRoxieServerStreamedIteratorActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8246. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorStreamedIteratorArg &)basehelper)
  8247. {
  8248. }
  8249. ~CRoxieServerStreamedIteratorActivity()
  8250. {
  8251. }
  8252. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8253. {
  8254. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8255. rows.setown(helper.createInput());
  8256. }
  8257. virtual void stop(bool aborting)
  8258. {
  8259. if (rows)
  8260. {
  8261. rows->stop();
  8262. rows.clear();
  8263. }
  8264. CRoxieServerActivity::stop(aborting);
  8265. }
  8266. virtual const void *nextInGroup()
  8267. {
  8268. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  8269. assertex(rows != NULL);
  8270. const void * next = rows->nextRow();
  8271. if (next)
  8272. processed++;
  8273. return next;
  8274. }
  8275. };
  8276. class CRoxieServerStreamedIteratorActivityFactory : public CRoxieServerActivityFactory
  8277. {
  8278. public:
  8279. CRoxieServerStreamedIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8280. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  8281. {
  8282. }
  8283. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8284. {
  8285. return new CRoxieServerStreamedIteratorActivity(this, _probeManager);
  8286. }
  8287. };
  8288. IRoxieServerActivityFactory *createRoxieServerStreamedIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8289. {
  8290. return new CRoxieServerStreamedIteratorActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  8291. }
  8292. //=====================================================================================================
  8293. class CRoxieServerFilterActivity : public CRoxieServerLateStartActivity
  8294. {
  8295. IHThorFilterArg &helper;
  8296. bool anyThisGroup;
  8297. IRangeCompare * stepCompare;
  8298. public:
  8299. CRoxieServerFilterActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8300. : CRoxieServerLateStartActivity(_factory, _probeManager), helper((IHThorFilterArg &)basehelper)
  8301. {
  8302. anyThisGroup = false;
  8303. stepCompare = NULL;
  8304. }
  8305. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8306. {
  8307. anyThisGroup = false;
  8308. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  8309. lateStart(parentExtractSize, parentExtract, helper.canMatchAny());
  8310. stepCompare = NULL;
  8311. if (!eof)
  8312. {
  8313. IInputSteppingMeta * stepMeta = input->querySteppingMeta();
  8314. if (stepMeta)
  8315. stepCompare = stepMeta->queryCompare();
  8316. }
  8317. }
  8318. virtual const void * nextInGroup()
  8319. {
  8320. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  8321. if (eof)
  8322. return NULL;
  8323. loop
  8324. {
  8325. const void * ret = input->nextInGroup();
  8326. if (!ret)
  8327. {
  8328. //stop returning two NULLs in a row.
  8329. if (anyThisGroup)
  8330. {
  8331. anyThisGroup = false;
  8332. return NULL;
  8333. }
  8334. ret = input->nextInGroup();
  8335. if (!ret)
  8336. {
  8337. eof = true;
  8338. return NULL; // eof...
  8339. }
  8340. }
  8341. if (helper.isValid(ret))
  8342. {
  8343. anyThisGroup = true;
  8344. processed++;
  8345. return ret;
  8346. }
  8347. ReleaseRoxieRow(ret);
  8348. }
  8349. }
  8350. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  8351. {
  8352. //Could assert that this isn't grouped
  8353. // MORE - will need rethinking once we rethink the nextSteppedGE interface for global smart-stepping.
  8354. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  8355. if (eof)
  8356. return NULL;
  8357. loop
  8358. {
  8359. const void * ret = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  8360. if (!ret)
  8361. {
  8362. eof = true;
  8363. return NULL;
  8364. }
  8365. if (!wasCompleteMatch)
  8366. {
  8367. anyThisGroup = false; // RKC->GH - is this right??
  8368. return ret;
  8369. }
  8370. if (helper.isValid(ret))
  8371. {
  8372. anyThisGroup = true;
  8373. processed++;
  8374. return ret;
  8375. }
  8376. if (!stepExtra.returnMismatches())
  8377. {
  8378. ReleaseRoxieRow(ret);
  8379. return nextInGroup();
  8380. }
  8381. //If asked to return mismatches we are only interested in mismatches that will force the stepped
  8382. //condition to advance
  8383. if (stepCompare->docompare(ret, seek, numFields) != 0)
  8384. {
  8385. wasCompleteMatch = false;
  8386. anyThisGroup = false; // WHY?
  8387. return ret;
  8388. }
  8389. ReleaseRoxieRow(ret);
  8390. }
  8391. }
  8392. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  8393. {
  8394. return input->gatherConjunctions(collector);
  8395. }
  8396. virtual void resetEOF()
  8397. {
  8398. eof = prefiltered;
  8399. anyThisGroup = false;
  8400. input->resetEOF();
  8401. }
  8402. IInputSteppingMeta * querySteppingMeta()
  8403. {
  8404. return input->querySteppingMeta();
  8405. }
  8406. };
  8407. class CRoxieServerFilterActivityFactory : public CRoxieServerActivityFactory
  8408. {
  8409. public:
  8410. CRoxieServerFilterActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8411. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  8412. {
  8413. }
  8414. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8415. {
  8416. return new CRoxieServerFilterActivity(this, _probeManager);
  8417. }
  8418. };
  8419. IRoxieServerActivityFactory *createRoxieServerFilterActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8420. {
  8421. return new CRoxieServerFilterActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  8422. }
  8423. //=====================================================================================================
  8424. class CRoxieServerFilterGroupActivity : public CRoxieServerLateStartActivity
  8425. {
  8426. IHThorFilterGroupArg &helper;
  8427. unsigned curIndex;
  8428. ConstPointerArray gathered;
  8429. IRangeCompare * stepCompare;
  8430. public:
  8431. CRoxieServerFilterGroupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8432. : CRoxieServerLateStartActivity(_factory, _probeManager), helper((IHThorFilterGroupArg &)basehelper)
  8433. {
  8434. curIndex = 0;
  8435. stepCompare = NULL;
  8436. }
  8437. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8438. {
  8439. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  8440. lateStart(parentExtractSize, parentExtract, helper.canMatchAny());//sets eof
  8441. assertex(eof == !helper.canMatchAny());
  8442. curIndex = 0;
  8443. stepCompare = NULL;
  8444. if (!eof)
  8445. {
  8446. IInputSteppingMeta * inputStepping = input->querySteppingMeta();
  8447. if (inputStepping)
  8448. stepCompare = inputStepping->queryCompare();
  8449. }
  8450. }
  8451. virtual void reset()
  8452. {
  8453. releaseGathered();
  8454. CRoxieServerLateStartActivity::reset();
  8455. }
  8456. inline void releaseGathered()
  8457. {
  8458. while (gathered.isItem(curIndex))
  8459. ReleaseRoxieRow(gathered.item(curIndex++));
  8460. gathered.kill();
  8461. }
  8462. virtual const void * nextInGroup()
  8463. {
  8464. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  8465. loop
  8466. {
  8467. if (eof)
  8468. return NULL;
  8469. if (gathered.ordinality())
  8470. {
  8471. if (gathered.isItem(curIndex))
  8472. {
  8473. const void * ret = gathered.item(curIndex++);
  8474. processed++;
  8475. return ret;
  8476. }
  8477. curIndex = 0;
  8478. gathered.kill();
  8479. return NULL;
  8480. }
  8481. const void * ret = input->nextInGroup();
  8482. while (ret)
  8483. {
  8484. gathered.append(ret);
  8485. ret = input->nextInGroup();
  8486. }
  8487. unsigned num = gathered.ordinality();
  8488. if (num != 0)
  8489. {
  8490. if (!helper.isValid(num, (const void * *)gathered.getArray()))
  8491. ReleaseRoxieRowSet(gathered); // read next group
  8492. }
  8493. else
  8494. eof = true;
  8495. }
  8496. }
  8497. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  8498. {
  8499. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  8500. if (eof)
  8501. return NULL;
  8502. if (gathered.ordinality())
  8503. {
  8504. while (gathered.isItem(curIndex))
  8505. {
  8506. const void * ret = gathered.item(curIndex++);
  8507. if (stepCompare->docompare(ret, seek, numFields) >= 0)
  8508. {
  8509. processed++;
  8510. return ret;
  8511. }
  8512. ReleaseRoxieRow(ret);
  8513. }
  8514. curIndex = 0;
  8515. gathered.kill();
  8516. //nextSteppedGE never returns an end of group marker.
  8517. }
  8518. //Not completely sure about this - it could lead the the start of a group being skipped,
  8519. //so the group filter could potentially work on a different group. If so, we'd need to check the
  8520. //next fields were a subset of the grouping fields - more an issue for the group activity.
  8521. //MORE: What do we do with wasCompleteMatch? something like the following????
  8522. #if 0
  8523. loop
  8524. {
  8525. const void * ret;
  8526. if (stepExtra.returnMismatches())
  8527. {
  8528. bool matchedCompletely = true;
  8529. ret = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  8530. if (!wasCompleteMatch)
  8531. return ret;
  8532. }
  8533. else
  8534. ret = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  8535. #endif
  8536. const void * ret = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  8537. while (ret)
  8538. {
  8539. gathered.append(ret);
  8540. ret = input->nextInGroup();
  8541. }
  8542. unsigned num = gathered.ordinality();
  8543. if (num != 0)
  8544. {
  8545. if (!helper.isValid(num, (const void * *)gathered.getArray()))
  8546. ReleaseRoxieRowSet(gathered); // read next group
  8547. }
  8548. else
  8549. eof = true;
  8550. return nextUngrouped(this);
  8551. }
  8552. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  8553. {
  8554. return input->gatherConjunctions(collector);
  8555. }
  8556. virtual void resetEOF()
  8557. {
  8558. eof = false;
  8559. releaseGathered();
  8560. input->resetEOF();
  8561. }
  8562. IInputSteppingMeta * querySteppingMeta()
  8563. {
  8564. return input->querySteppingMeta();
  8565. }
  8566. };
  8567. class CRoxieServerFilterGroupActivityFactory : public CRoxieServerActivityFactory
  8568. {
  8569. public:
  8570. CRoxieServerFilterGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8571. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  8572. {
  8573. }
  8574. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8575. {
  8576. return new CRoxieServerFilterGroupActivity(this, _probeManager);
  8577. }
  8578. };
  8579. IRoxieServerActivityFactory *createRoxieServerFilterGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8580. {
  8581. return new CRoxieServerFilterGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  8582. }
  8583. //=================================================================================
  8584. class CRoxieServerSideEffectActivity : public CRoxieServerActivity
  8585. {
  8586. IHThorSideEffectArg &helper;
  8587. CriticalSection ecrit;
  8588. Owned<IException> exception;
  8589. bool executed;
  8590. public:
  8591. CRoxieServerSideEffectActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8592. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorSideEffectArg &)basehelper)
  8593. {
  8594. executed = false;
  8595. }
  8596. virtual const void * nextInGroup()
  8597. {
  8598. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  8599. CriticalBlock b(ecrit);
  8600. if (exception)
  8601. throw(exception.getLink());
  8602. if (!executed)
  8603. {
  8604. try
  8605. {
  8606. executed = true;
  8607. helper.action();
  8608. }
  8609. catch(IException *E)
  8610. {
  8611. exception.set(E);
  8612. throw;
  8613. }
  8614. }
  8615. return NULL;
  8616. }
  8617. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  8618. {
  8619. CriticalBlock b(ecrit);
  8620. if (exception)
  8621. throw(exception.getLink());
  8622. if (!executed)
  8623. {
  8624. try
  8625. {
  8626. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  8627. executed = true;
  8628. start(parentExtractSize, parentExtract, false);
  8629. helper.action();
  8630. stop(false);
  8631. }
  8632. catch(IException *E)
  8633. {
  8634. ctx->notifyAbort(E);
  8635. stop(true);
  8636. exception.set(E);
  8637. throw;
  8638. }
  8639. }
  8640. }
  8641. virtual void reset()
  8642. {
  8643. executed = false;
  8644. exception.clear();
  8645. CRoxieServerActivity::reset();
  8646. }
  8647. };
  8648. class CRoxieServerSideEffectActivityFactory : public CRoxieServerActivityFactory
  8649. {
  8650. bool isRoot;
  8651. public:
  8652. CRoxieServerSideEffectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  8653. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  8654. {
  8655. }
  8656. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8657. {
  8658. return new CRoxieServerSideEffectActivity(this, _probeManager);
  8659. }
  8660. virtual bool isSink() const
  8661. {
  8662. return isRoot && !meta.queryOriginal();
  8663. }
  8664. };
  8665. IRoxieServerActivityFactory *createRoxieServerSideEffectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  8666. {
  8667. return new CRoxieServerSideEffectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  8668. }
  8669. //=================================================================================
  8670. class CRoxieServerActionActivity : public CRoxieServerInternalSinkActivity
  8671. {
  8672. IHThorActionArg &helper;
  8673. public:
  8674. CRoxieServerActionActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8675. : CRoxieServerInternalSinkActivity(_factory, _probeManager), helper((IHThorActionArg &)basehelper)
  8676. {
  8677. }
  8678. virtual void onExecute()
  8679. {
  8680. helper.action();
  8681. }
  8682. };
  8683. class CRoxieServerActionActivityFactory : public CRoxieServerInternalSinkFactory
  8684. {
  8685. public:
  8686. CRoxieServerActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  8687. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot)
  8688. {
  8689. }
  8690. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8691. {
  8692. return new CRoxieServerActionActivity(this, _probeManager);
  8693. }
  8694. };
  8695. IRoxieServerActivityFactory *createRoxieServerActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  8696. {
  8697. return new CRoxieServerActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot);
  8698. }
  8699. //=================================================================================
  8700. class CRoxieServerSampleActivity : public CRoxieServerActivity
  8701. {
  8702. IHThorSampleArg &helper;
  8703. unsigned numSamples;
  8704. unsigned numToSkip;
  8705. unsigned whichSample;
  8706. bool anyThisGroup;
  8707. bool eof;
  8708. public:
  8709. CRoxieServerSampleActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8710. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorSampleArg &)basehelper)
  8711. {
  8712. numSamples = 0;
  8713. numToSkip = 0;
  8714. whichSample = 0;
  8715. anyThisGroup = false;
  8716. eof = false;
  8717. }
  8718. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8719. {
  8720. anyThisGroup = false;
  8721. eof = false;
  8722. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8723. numSamples = helper.getProportion();
  8724. whichSample = helper.getSampleNumber();
  8725. numToSkip = (whichSample ? whichSample-1 : 0);
  8726. }
  8727. virtual const void * nextInGroup()
  8728. {
  8729. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  8730. if (eof)
  8731. return NULL;
  8732. loop
  8733. {
  8734. const void * ret = input->nextInGroup();
  8735. if (!ret)
  8736. {
  8737. //this does work with groups - may or may not be useful...
  8738. //reset the sample for each group.... probably best.
  8739. numToSkip = (whichSample ? whichSample-1 : 0);
  8740. if (anyThisGroup)
  8741. {
  8742. anyThisGroup = false;
  8743. return NULL;
  8744. }
  8745. ret = input->nextInGroup();
  8746. if (!ret)
  8747. {
  8748. eof = true;
  8749. return NULL; // eof...
  8750. }
  8751. }
  8752. if (numToSkip == 0)
  8753. {
  8754. anyThisGroup = true;
  8755. numToSkip = numSamples-1;
  8756. processed++;
  8757. return ret;
  8758. }
  8759. numToSkip--;
  8760. ReleaseRoxieRow(ret);
  8761. }
  8762. }
  8763. };
  8764. class CRoxieServerSampleActivityFactory : public CRoxieServerActivityFactory
  8765. {
  8766. public:
  8767. CRoxieServerSampleActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8768. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  8769. {
  8770. }
  8771. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8772. {
  8773. return new CRoxieServerSampleActivity(this, _probeManager);
  8774. }
  8775. };
  8776. IRoxieServerActivityFactory *createRoxieServerSampleActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8777. {
  8778. return new CRoxieServerSampleActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  8779. }
  8780. //=================================================================================
  8781. class CRoxieServerChooseSetsActivity : public CRoxieServerActivity
  8782. {
  8783. IHThorChooseSetsArg &helper;
  8784. unsigned numSets;
  8785. unsigned * setCounts;
  8786. bool done;
  8787. public:
  8788. CRoxieServerChooseSetsActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8789. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorChooseSetsArg &)basehelper)
  8790. {
  8791. setCounts = NULL;
  8792. numSets = 0;
  8793. done = false;
  8794. }
  8795. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8796. {
  8797. done = false;
  8798. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8799. numSets = helper.getNumSets();
  8800. setCounts = new unsigned[numSets];
  8801. memset(setCounts, 0, sizeof(unsigned)*numSets);
  8802. helper.setCounts(setCounts);
  8803. }
  8804. virtual void reset()
  8805. {
  8806. delete [] setCounts;
  8807. setCounts = NULL;
  8808. CRoxieServerActivity::reset();
  8809. }
  8810. virtual const void * nextInGroup()
  8811. {
  8812. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  8813. if (done)
  8814. return NULL;
  8815. loop
  8816. {
  8817. const void * ret = input->nextInGroup();
  8818. if (!ret)
  8819. {
  8820. ret = input->nextInGroup();
  8821. if (!ret)
  8822. {
  8823. done = true;
  8824. return NULL;
  8825. }
  8826. }
  8827. processed++;
  8828. switch (helper.getRecordAction(ret))
  8829. {
  8830. case 2:
  8831. done = true;
  8832. return ret;
  8833. case 1:
  8834. return ret;
  8835. }
  8836. ReleaseRoxieRow(ret);
  8837. }
  8838. }
  8839. };
  8840. class CRoxieServerChooseSetsActivityFactory : public CRoxieServerActivityFactory
  8841. {
  8842. public:
  8843. CRoxieServerChooseSetsActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8844. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  8845. {
  8846. }
  8847. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8848. {
  8849. return new CRoxieServerChooseSetsActivity(this, _probeManager);
  8850. }
  8851. };
  8852. IRoxieServerActivityFactory *createRoxieServerChooseSetsActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8853. {
  8854. return new CRoxieServerChooseSetsActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  8855. }
  8856. //=================================================================================
  8857. class CRoxieServerChooseSetsExActivity : public CRoxieServerActivity
  8858. {
  8859. protected:
  8860. IHThorChooseSetsExArg &helper;
  8861. unsigned numSets;
  8862. unsigned curIndex;
  8863. unsigned * setCounts;
  8864. count_t * limits;
  8865. bool done;
  8866. ConstPointerArray gathered;
  8867. virtual bool includeRow(const void * row) = 0;
  8868. virtual void calculateSelection() = 0;
  8869. public:
  8870. CRoxieServerChooseSetsExActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8871. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorChooseSetsExArg &)basehelper)
  8872. {
  8873. setCounts = NULL;
  8874. limits = NULL;
  8875. done = false;
  8876. curIndex = 0;
  8877. numSets = 0;
  8878. }
  8879. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8880. {
  8881. done = false;
  8882. curIndex = 0;
  8883. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8884. numSets = helper.getNumSets();
  8885. setCounts = new unsigned[numSets];
  8886. memset(setCounts, 0, sizeof(unsigned)*numSets);
  8887. limits = (count_t *)calloc(sizeof(count_t), numSets);
  8888. helper.getLimits(limits);
  8889. }
  8890. virtual void reset()
  8891. {
  8892. delete [] setCounts;
  8893. setCounts = NULL;
  8894. free(limits);
  8895. limits = NULL;
  8896. while (gathered.isItem(curIndex))
  8897. ReleaseRoxieRow(gathered.item(curIndex++));
  8898. gathered.kill();
  8899. CRoxieServerActivity::reset();
  8900. }
  8901. virtual const void * nextInGroup()
  8902. {
  8903. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  8904. if (gathered.ordinality() == 0)
  8905. {
  8906. curIndex = 0;
  8907. if (!input->nextGroup(gathered))
  8908. {
  8909. done = true;
  8910. return NULL;
  8911. }
  8912. ForEachItemIn(idx1, gathered)
  8913. {
  8914. unsigned category = helper.getCategory(gathered.item(idx1));
  8915. if (category)
  8916. setCounts[category-1]++;
  8917. }
  8918. calculateSelection();
  8919. }
  8920. while (gathered.isItem(curIndex))
  8921. {
  8922. const void * row = gathered.item(curIndex);
  8923. gathered.replace(NULL, curIndex);
  8924. curIndex++;
  8925. if (includeRow(row))
  8926. {
  8927. processed++;
  8928. return row;
  8929. }
  8930. ReleaseRoxieRow(row);
  8931. }
  8932. gathered.kill();
  8933. return NULL;
  8934. }
  8935. };
  8936. class CRoxieServerChooseSetsLastActivity : public CRoxieServerChooseSetsExActivity
  8937. {
  8938. unsigned * numToSkip;
  8939. public:
  8940. CRoxieServerChooseSetsLastActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager) : CRoxieServerChooseSetsExActivity(_factory, _probeManager)
  8941. {
  8942. numToSkip = NULL;
  8943. }
  8944. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8945. {
  8946. CRoxieServerChooseSetsExActivity::start(parentExtractSize, parentExtract, paused);
  8947. numToSkip = (unsigned *)calloc(sizeof(unsigned), numSets);
  8948. }
  8949. virtual void reset()
  8950. {
  8951. free(numToSkip);
  8952. numToSkip = NULL;
  8953. CRoxieServerChooseSetsExActivity::reset();
  8954. }
  8955. protected:
  8956. virtual void calculateSelection()
  8957. {
  8958. for (unsigned idx=0; idx < numSets; idx++)
  8959. {
  8960. if (setCounts[idx] < limits[idx])
  8961. numToSkip[idx] = 0;
  8962. else
  8963. numToSkip[idx] = (unsigned)(setCounts[idx] - limits[idx]);
  8964. }
  8965. }
  8966. virtual bool includeRow(const void * row)
  8967. {
  8968. unsigned category = helper.getCategory(row);
  8969. if (category)
  8970. {
  8971. if (numToSkip[category-1] == 0)
  8972. return true;
  8973. numToSkip[category-1]--;
  8974. }
  8975. return false;
  8976. }
  8977. };
  8978. class CRoxieServerChooseSetsEnthActivity : public CRoxieServerChooseSetsExActivity
  8979. {
  8980. count_t * counter;
  8981. public:
  8982. CRoxieServerChooseSetsEnthActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager) : CRoxieServerChooseSetsExActivity(_factory, _probeManager)
  8983. {
  8984. counter = NULL;
  8985. }
  8986. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8987. {
  8988. CRoxieServerChooseSetsExActivity::start(parentExtractSize, parentExtract, paused);
  8989. counter = (count_t *)calloc(sizeof(count_t), numSets);
  8990. }
  8991. virtual void reset()
  8992. {
  8993. free(counter);
  8994. counter = NULL;
  8995. CRoxieServerChooseSetsExActivity::reset();
  8996. }
  8997. protected:
  8998. virtual void calculateSelection()
  8999. {
  9000. }
  9001. virtual bool includeRow(const void * row)
  9002. {
  9003. unsigned category = helper.getCategory(row);
  9004. if (category)
  9005. {
  9006. assertex(category <= numSets);
  9007. counter[category-1] += limits[category-1];
  9008. if(counter[category-1] >= setCounts[category-1])
  9009. {
  9010. counter[category-1] -= setCounts[category-1];
  9011. return true;
  9012. }
  9013. }
  9014. return false;
  9015. }
  9016. };
  9017. class CRoxieServerChooseSetsEnthActivityFactory : public CRoxieServerActivityFactory
  9018. {
  9019. public:
  9020. CRoxieServerChooseSetsEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9021. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  9022. {
  9023. }
  9024. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  9025. {
  9026. return new CRoxieServerChooseSetsEnthActivity(this, _probeManager);
  9027. }
  9028. };
  9029. IRoxieServerActivityFactory *createRoxieServerChooseSetsEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9030. {
  9031. return new CRoxieServerChooseSetsEnthActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  9032. }
  9033. class CRoxieServerChooseSetsLastActivityFactory : public CRoxieServerActivityFactory
  9034. {
  9035. public:
  9036. CRoxieServerChooseSetsLastActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9037. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  9038. {
  9039. }
  9040. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  9041. {
  9042. return new CRoxieServerChooseSetsLastActivity(this, _probeManager);
  9043. }
  9044. };
  9045. IRoxieServerActivityFactory *createRoxieServerChooseSetsLastActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9046. {
  9047. return new CRoxieServerChooseSetsLastActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  9048. }
  9049. //=================================================================================
  9050. class CRoxieServerEnthActivity : public CRoxieServerActivity
  9051. {
  9052. IHThorEnthArg &helper;
  9053. unsigned __int64 numerator;
  9054. unsigned __int64 denominator;
  9055. unsigned __int64 counter;
  9056. bool eof;
  9057. public:
  9058. CRoxieServerEnthActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9059. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorEnthArg &)basehelper)
  9060. {
  9061. eof = false;
  9062. numerator = denominator = counter = 0;
  9063. }
  9064. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9065. {
  9066. eof = false;
  9067. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9068. numerator = helper.getProportionNumerator();
  9069. denominator = helper.getProportionDenominator();
  9070. if(denominator == 0) denominator = 1; //MORE: simplest way to avoid disaster in this case
  9071. counter = (helper.getSampleNumber()-1) * greatestCommonDivisor(numerator, denominator);
  9072. if (counter >= denominator)
  9073. counter %= denominator;
  9074. }
  9075. inline bool wanted()
  9076. {
  9077. counter += numerator;
  9078. if(counter >= denominator)
  9079. {
  9080. counter -= denominator;
  9081. return true;
  9082. }
  9083. return false;
  9084. }
  9085. virtual const void * nextInGroup()
  9086. {
  9087. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  9088. if (eof)
  9089. return NULL;
  9090. const void * ret;
  9091. loop
  9092. {
  9093. ret = input->nextInGroup();
  9094. if(!ret) //end of group
  9095. ret = input->nextInGroup();
  9096. if(!ret) //eof
  9097. {
  9098. eof = true;
  9099. return ret;
  9100. }
  9101. if (wanted())
  9102. return ret;
  9103. ReleaseRoxieRow(ret);
  9104. }
  9105. }
  9106. };
  9107. class CRoxieServerEnthActivityFactory : public CRoxieServerActivityFactory
  9108. {
  9109. public:
  9110. CRoxieServerEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9111. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  9112. {
  9113. }
  9114. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  9115. {
  9116. return new CRoxieServerEnthActivity(this, _probeManager);
  9117. }
  9118. };
  9119. IRoxieServerActivityFactory *createRoxieServerEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9120. {
  9121. return new CRoxieServerEnthActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  9122. }
  9123. //=================================================================================
  9124. class CRoxieServerAggregateActivity : public CRoxieServerActivity
  9125. {
  9126. IHThorAggregateArg &helper;
  9127. bool eof;
  9128. bool isInputGrouped;
  9129. bool abortEarly;
  9130. public:
  9131. CRoxieServerAggregateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9132. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorAggregateArg &)basehelper)
  9133. {
  9134. eof = false;
  9135. isInputGrouped = false;
  9136. abortEarly = false;
  9137. }
  9138. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9139. {
  9140. eof = false;
  9141. isInputGrouped = input->queryOutputMeta()->isGrouped(); // could be done earlier, in setInput?
  9142. abortEarly = !isInputGrouped && (factory->getKind() == TAKexistsaggregate); // ditto
  9143. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9144. }
  9145. virtual bool needsAllocator() const { return true; }
  9146. virtual const void * nextInGroup()
  9147. {
  9148. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  9149. if (eof)
  9150. return NULL;
  9151. const void * next = input->nextInGroup();
  9152. if (!next && isInputGrouped)
  9153. {
  9154. eof = true;
  9155. return NULL;
  9156. }
  9157. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  9158. size32_t finalSize = helper.clearAggregate(rowBuilder);
  9159. if (next)
  9160. {
  9161. finalSize = helper.processFirst(rowBuilder, next);
  9162. ReleaseRoxieRow(next);
  9163. if (!abortEarly)
  9164. {
  9165. loop
  9166. {
  9167. next = input->nextInGroup();
  9168. if (!next)
  9169. break;
  9170. finalSize = helper.processNext(rowBuilder, next);
  9171. ReleaseRoxieRow(next);
  9172. }
  9173. }
  9174. }
  9175. if (!isInputGrouped) // either read all, or aborted early
  9176. eof = true;
  9177. processed++;
  9178. return rowBuilder.finalizeRowClear(finalSize);
  9179. }
  9180. };
  9181. class CRoxieServerAggregateActivityFactory : public CRoxieServerActivityFactory
  9182. {
  9183. public:
  9184. CRoxieServerAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9185. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  9186. {
  9187. }
  9188. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  9189. {
  9190. return new CRoxieServerAggregateActivity(this, _probeManager);
  9191. }
  9192. };
  9193. IRoxieServerActivityFactory *createRoxieServerAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9194. {
  9195. return new CRoxieServerAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  9196. }
  9197. //=================================================================================
  9198. typedef unsigned t_hashPrefix;
  9199. class CRoxieServerHashAggregateActivity : public CRoxieServerActivity
  9200. {
  9201. IHThorHashAggregateArg &helper;
  9202. RowAggregator aggregated;
  9203. bool eof;
  9204. bool gathered;
  9205. bool isGroupedAggregate;
  9206. public:
  9207. CRoxieServerHashAggregateActivity(const IRoxieServerActivityFactory *_factory, bool _isGroupedAggregate, IProbeManager *_probeManager)
  9208. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorHashAggregateArg &)basehelper),
  9209. isGroupedAggregate(_isGroupedAggregate),
  9210. aggregated(helper, helper)
  9211. {
  9212. eof = false;
  9213. gathered = false;
  9214. }
  9215. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9216. {
  9217. eof = false;
  9218. gathered = false;
  9219. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9220. }
  9221. virtual void reset()
  9222. {
  9223. aggregated.reset();
  9224. CRoxieServerActivity::reset();
  9225. }
  9226. virtual bool needsAllocator() const { return true; }
  9227. virtual const void * nextInGroup()
  9228. {
  9229. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  9230. if (eof)
  9231. return NULL;
  9232. if (!gathered)
  9233. {
  9234. aggregated.start(rowAllocator);
  9235. bool eog = true;
  9236. loop
  9237. {
  9238. const void * next = input->nextInGroup();
  9239. if (!next)
  9240. {
  9241. if (isGroupedAggregate)
  9242. {
  9243. if (eog)
  9244. eof = true;
  9245. break;
  9246. }
  9247. next = input->nextInGroup();
  9248. if (!next)
  9249. break;
  9250. }
  9251. eog = false;
  9252. aggregated.addRow(next);
  9253. ReleaseRoxieRow(next);
  9254. }
  9255. gathered = true;
  9256. }
  9257. Owned<AggregateRowBuilder> next = aggregated.nextResult();
  9258. if (next)
  9259. {
  9260. processed++;
  9261. return next->finalizeRowClear();
  9262. }
  9263. if (!isGroupedAggregate)
  9264. eof = true;
  9265. aggregated.reset();
  9266. gathered = false;
  9267. return NULL;
  9268. }
  9269. };
  9270. class CRoxieServerHashAggregateActivityFactory : public CRoxieServerActivityFactory
  9271. {
  9272. public:
  9273. CRoxieServerHashAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9274. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  9275. {
  9276. isGroupedAggregate = _graphNode.getPropBool("att[@name='grouped']/@value");
  9277. }
  9278. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  9279. {
  9280. return new CRoxieServerHashAggregateActivity(this, isGroupedAggregate, _probeManager);
  9281. }
  9282. protected:
  9283. bool isGroupedAggregate;
  9284. };
  9285. IRoxieServerActivityFactory *createRoxieServerHashAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9286. {
  9287. return new CRoxieServerHashAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9288. }
  9289. //=================================================================================
  9290. class CRoxieServerDegroupActivity : public CRoxieServerActivity
  9291. {
  9292. IHThorDegroupArg &helper;
  9293. bool eof;
  9294. public:
  9295. CRoxieServerDegroupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9296. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorDegroupArg &)basehelper)
  9297. {
  9298. eof = false;
  9299. }
  9300. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9301. {
  9302. eof = false;
  9303. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9304. }
  9305. virtual const void * nextInGroup()
  9306. {
  9307. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  9308. if (eof)
  9309. return NULL;
  9310. const void * ret = input->nextInGroup();
  9311. if (!ret)
  9312. ret = input->nextInGroup();
  9313. if (ret)
  9314. processed++;
  9315. else
  9316. eof = true;
  9317. return ret;
  9318. }
  9319. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  9320. {
  9321. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  9322. if (eof)
  9323. return NULL;
  9324. const void * ret = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  9325. if (ret)
  9326. processed++;
  9327. else
  9328. eof = true;
  9329. return ret;
  9330. }
  9331. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  9332. {
  9333. return input->gatherConjunctions(collector);
  9334. }
  9335. virtual void resetEOF()
  9336. {
  9337. eof = false;
  9338. input->resetEOF();
  9339. }
  9340. IInputSteppingMeta * querySteppingMeta()
  9341. {
  9342. return input->querySteppingMeta();
  9343. }
  9344. };
  9345. class CRoxieServerDegroupActivityFactory : public CRoxieServerActivityFactory
  9346. {
  9347. public:
  9348. CRoxieServerDegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9349. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  9350. {
  9351. }
  9352. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  9353. {
  9354. return new CRoxieServerDegroupActivity(this, _probeManager);
  9355. }
  9356. };
  9357. IRoxieServerActivityFactory *createRoxieServerDegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9358. {
  9359. return new CRoxieServerDegroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  9360. }
  9361. //=================================================================================
  9362. class CRoxieServerSpillReadActivity : public CRoxieServerActivity
  9363. {
  9364. IHThorDiskReadArg &helper;
  9365. bool needTransform;
  9366. bool eof;
  9367. bool anyThisGroup;
  9368. unsigned __int64 rowLimit;
  9369. unsigned __int64 choosenLimit;
  9370. public:
  9371. CRoxieServerSpillReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9372. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorDiskReadArg &)basehelper)
  9373. {
  9374. needTransform = helper.needTransform();
  9375. rowLimit = (unsigned __int64) -1;
  9376. choosenLimit = 0;
  9377. eof = false;
  9378. anyThisGroup = false;
  9379. }
  9380. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9381. {
  9382. anyThisGroup = false;
  9383. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9384. if (helper.canMatchAny())
  9385. eof = false;
  9386. else
  9387. eof = true;
  9388. choosenLimit = helper.getChooseNLimit();
  9389. rowLimit = helper.getRowLimit();
  9390. helper.setCallback(NULL); // members should not be called - change if they are
  9391. }
  9392. virtual bool needsAllocator() const { return true; }
  9393. virtual const void * nextInGroup()
  9394. {
  9395. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  9396. if (eof)
  9397. return NULL;
  9398. if (processed==choosenLimit)
  9399. {
  9400. eof = true;
  9401. return NULL;
  9402. }
  9403. if (needTransform)
  9404. {
  9405. loop
  9406. {
  9407. const void *in = input->nextInGroup();
  9408. if (!in)
  9409. {
  9410. if (anyThisGroup)
  9411. {
  9412. anyThisGroup = false;
  9413. return NULL;
  9414. }
  9415. in = input->nextInGroup();
  9416. if (!in)
  9417. {
  9418. eof = true;
  9419. return NULL; // eof...
  9420. }
  9421. }
  9422. unsigned outSize;
  9423. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  9424. try
  9425. {
  9426. outSize = helper.transform(rowBuilder, in);
  9427. ReleaseRoxieRow(in);
  9428. }
  9429. catch (IException *E)
  9430. {
  9431. throw makeWrappedException(E);
  9432. }
  9433. if (outSize)
  9434. {
  9435. anyThisGroup = true;
  9436. processed++;
  9437. if (processed==rowLimit)
  9438. {
  9439. if (traceLevel > 4)
  9440. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  9441. helper.onLimitExceeded();
  9442. }
  9443. return rowBuilder.finalizeRowClear(outSize);
  9444. }
  9445. }
  9446. }
  9447. else
  9448. {
  9449. const void *ret = input->nextInGroup();
  9450. if (ret)
  9451. {
  9452. processed++;
  9453. if (processed==rowLimit)
  9454. {
  9455. if (traceLevel > 4)
  9456. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  9457. ReleaseClearRoxieRow(ret);
  9458. helper.onLimitExceeded(); // should not return
  9459. throwUnexpected();
  9460. }
  9461. }
  9462. return ret;
  9463. }
  9464. }
  9465. };
  9466. class CRoxieServerSpillReadActivityFactory : public CRoxieServerActivityFactory
  9467. {
  9468. public:
  9469. CRoxieServerSpillReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9470. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  9471. {
  9472. }
  9473. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  9474. {
  9475. return new CRoxieServerSpillReadActivity(this, _probeManager);
  9476. }
  9477. virtual void addDependency(unsigned source, ThorActivityKind sourceKind, unsigned sourceIdx, int controlId, const char *edgeId)
  9478. {
  9479. if (sourceKind==TAKspill || sourceKind==TAKdiskwrite) // Bit of a hack - codegen probably should differentiate
  9480. setInput(0, source, sourceIdx);
  9481. else
  9482. CRoxieServerActivityFactory::addDependency(source, kind, sourceIdx, controlId, edgeId);
  9483. }
  9484. };
  9485. IRoxieServerActivityFactory *createRoxieServerSpillReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9486. {
  9487. return new CRoxieServerSpillReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  9488. }
  9489. //=================================================================================
  9490. class CRoxieServerSpillWriteActivity : public CRoxieServerActivity
  9491. {
  9492. public:
  9493. CRoxieServerSpillWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9494. : CRoxieServerActivity(_factory, _probeManager)
  9495. {
  9496. }
  9497. ~CRoxieServerSpillWriteActivity()
  9498. {
  9499. }
  9500. virtual const void *nextInGroup()
  9501. {
  9502. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  9503. return input->nextInGroup();
  9504. }
  9505. };
  9506. //==================================================================================
  9507. class CRoxieServerDiskWriteActivity : public CRoxieServerInternalSinkActivity, implements IRoxiePublishCallback
  9508. {
  9509. protected:
  9510. Owned<IExtRowWriter> outSeq;
  9511. Owned<IOutputRowSerializer> rowSerializer;
  9512. Linked<IFileIOStream> diskout;
  9513. bool blockcompressed;
  9514. bool extend;
  9515. bool overwrite;
  9516. bool encrypted;
  9517. bool grouped;
  9518. IHThorDiskWriteArg &helper;
  9519. StringBuffer lfn; // logical filename
  9520. CachedOutputMetaData diskmeta;
  9521. Owned<IRoxieWriteHandler> writer;
  9522. bool tallycrc;
  9523. unsigned __int64 uncompressedBytesWritten;
  9524. CRC32 crc;
  9525. void updateWorkUnitResult(unsigned __int64 reccount)
  9526. {
  9527. assertex(writer);
  9528. // MORE - a lot of this is common with hthor
  9529. 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
  9530. {
  9531. WorkunitUpdate wu = ctx->updateWorkUnit();
  9532. if (wu)
  9533. {
  9534. unsigned flags = helper.getFlags();
  9535. WUFileKind fileKind;
  9536. if (TDXtemporary & flags)
  9537. fileKind = WUFileTemporary;
  9538. else if(TDXjobtemp & flags)
  9539. fileKind = WUFileJobOwned;
  9540. else if(TDWowned & flags)
  9541. fileKind = WUFileOwned;
  9542. else
  9543. fileKind = WUFileStandard;
  9544. StringArray clusters;
  9545. writer->getClusters(clusters);
  9546. wu->addFile(lfn.str(), &clusters, helper.getTempUsageCount(), fileKind, NULL);
  9547. if (!(flags & TDXtemporary) && helper.getSequence() >= 0)
  9548. {
  9549. Owned<IWUResult> result = wu->updateResultBySequence(helper.getSequence());
  9550. if (result)
  9551. {
  9552. result->setResultTotalRowCount(reccount);
  9553. result->setResultStatus(ResultStatusCalculated);
  9554. if (helper.getFlags() & TDWresult)
  9555. result->setResultFilename(lfn.str());
  9556. else
  9557. result->setResultLogicalName(lfn.str());
  9558. }
  9559. }
  9560. }
  9561. }
  9562. }
  9563. void resolve()
  9564. {
  9565. OwnedRoxieString rawLogicalName = helper.getFileName();
  9566. assertex(rawLogicalName);
  9567. assertex((helper.getFlags() & TDXtemporary) == 0);
  9568. StringArray clusters;
  9569. unsigned clusterIdx = 0;
  9570. while(true)
  9571. {
  9572. OwnedRoxieString cluster(helper.getCluster(clusterIdx));
  9573. if(!cluster)
  9574. break;
  9575. clusters.append(cluster);
  9576. clusterIdx++;
  9577. }
  9578. if (clusters.length())
  9579. {
  9580. if (extend)
  9581. throw MakeStringException(0, "Cannot combine EXTEND and CLUSTER flags on disk write of file %s", rawLogicalName.get());
  9582. }
  9583. else
  9584. {
  9585. if (roxieName.length())
  9586. clusters.append(roxieName.str());
  9587. else
  9588. clusters.append(".");
  9589. }
  9590. writer.setown(ctx->createLFN(rawLogicalName, overwrite, extend, clusters)); // MORE - if there's a workunit, use if for scope.
  9591. // MORE - need to check somewhere that single part if it's an existing file or an external one...
  9592. }
  9593. public:
  9594. CRoxieServerDiskWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9595. : CRoxieServerInternalSinkActivity(_factory, _probeManager), helper((IHThorDiskWriteArg &)basehelper)
  9596. {
  9597. extend = ((helper.getFlags() & TDWextend) != 0);
  9598. overwrite = ((helper.getFlags() & TDWoverwrite) != 0);
  9599. grouped = false; // don't think we need to support it...
  9600. diskmeta.set(helper.queryDiskRecordSize());
  9601. blockcompressed = (((helper.getFlags() & TDWnewcompress) != 0) || (((helper.getFlags() & TDXcompress) != 0) && (diskmeta.getFixedSize() >= MIN_ROWCOMPRESS_RECSIZE))); //always use new compression
  9602. encrypted = false; // set later
  9603. tallycrc = true;
  9604. uncompressedBytesWritten = 0;
  9605. }
  9606. ~CRoxieServerDiskWriteActivity()
  9607. {
  9608. }
  9609. virtual bool needsAllocator() const
  9610. {
  9611. return true;
  9612. }
  9613. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9614. {
  9615. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9616. resolve();
  9617. Owned<IFileIO> io;
  9618. void *ekey;
  9619. size32_t ekeylen;
  9620. helper.getEncryptKey(ekeylen, ekey);
  9621. Owned<ICompressor> ecomp;
  9622. if (ekeylen!=0)
  9623. {
  9624. ecomp.setown(createAESCompressor256(ekeylen,ekey));
  9625. memset(ekey,0,ekeylen);
  9626. rtlFree(ekey);
  9627. encrypted = true;
  9628. blockcompressed = true;
  9629. }
  9630. if (blockcompressed)
  9631. io.setown(createCompressedFileWriter(writer->queryFile(), (diskmeta.isFixedSize() ? diskmeta.getFixedSize() : 0), extend, true, ecomp));
  9632. else
  9633. io.setown(writer->queryFile()->open(extend ? IFOwrite : IFOcreate));
  9634. if (!io)
  9635. throw MakeStringException(errno, "Failed to create%s file %s for writing", (encrypted ? " encrypted" : (blockcompressed ? " compressed" : "")), writer->queryFile()->queryFilename());
  9636. diskout.setown(createBufferedIOStream(io));
  9637. if (extend)
  9638. diskout->seek(0, IFSend);
  9639. tallycrc = !factory->queryQueryFactory().getDebugValueBool("skipFileFormatCrcCheck", false) && !(helper.getFlags() & TDRnocrccheck) && !blockcompressed;
  9640. Owned<IRowInterfaces> rowIf = createRowInterfaces(input->queryOutputMeta(), activityId, ctx->queryCodeContext());
  9641. rowSerializer.set(rowIf->queryRowSerializer());
  9642. unsigned rwFlags = rw_autoflush;
  9643. if(grouped)
  9644. rwFlags |= rw_grouped;
  9645. if(tallycrc)
  9646. rwFlags |= rw_crc;
  9647. if(!factory->queryQueryFactory().getDebugValueBool("skipFileFormatCrcCheck", false) && !(helper.getFlags() & TDRnocrccheck))
  9648. rwFlags |= rw_crc;
  9649. outSeq.setown(createRowWriter(diskout, rowIf, rwFlags));
  9650. }
  9651. virtual void stop(bool aborting)
  9652. {
  9653. if (aborting)
  9654. {
  9655. if (writer)
  9656. writer->finish(false, this);
  9657. }
  9658. else
  9659. {
  9660. outSeq->flush(&crc);
  9661. updateWorkUnitResult(processed);
  9662. uncompressedBytesWritten = outSeq->getPosition();
  9663. writer->finish(true, this);
  9664. }
  9665. writer.clear();
  9666. CRoxieServerActivity::stop(aborting);
  9667. }
  9668. virtual void reset()
  9669. {
  9670. CRoxieServerActivity::reset();
  9671. diskout.clear();
  9672. outSeq.clear();
  9673. writer.clear();
  9674. uncompressedBytesWritten = 0;
  9675. crc.reset();
  9676. }
  9677. virtual void onExecute()
  9678. {
  9679. loop
  9680. {
  9681. const void *nextrec = input->nextInGroup();
  9682. if (!nextrec)
  9683. {
  9684. nextrec = input->nextInGroup();
  9685. if (!nextrec)
  9686. break;
  9687. }
  9688. processed++;
  9689. outSeq->putRow(nextrec);
  9690. }
  9691. }
  9692. virtual void setFileProperties(IFileDescriptor *desc) const
  9693. {
  9694. IPropertyTree &partProps = desc->queryPart(0)->queryProperties(); //properties of the first file part.
  9695. IPropertyTree &fileProps = desc->queryProperties(); // properties of the logical file
  9696. if (blockcompressed)
  9697. {
  9698. // caller has already set @size from file size...
  9699. fileProps.setPropBool("@blockCompressed", true);
  9700. fileProps.setPropInt64("@compressedSize", partProps.getPropInt64("@size", 0));
  9701. partProps.setPropInt64("@compressedSize", partProps.getPropInt64("@size", 0));
  9702. fileProps.setPropInt64("@size", uncompressedBytesWritten);
  9703. partProps.setPropInt64("@size", uncompressedBytesWritten);
  9704. }
  9705. else if (tallycrc)
  9706. partProps.setPropInt64("@fileCrc", crc.get());
  9707. if (encrypted)
  9708. fileProps.setPropBool("@encrypted", true);
  9709. fileProps.setPropInt64("@recordCount", processed);
  9710. unsigned flags = helper.getFlags();
  9711. if (flags & TDWpersist)
  9712. fileProps.setPropBool("@persistent", true);
  9713. if (grouped)
  9714. fileProps.setPropBool("@grouped", true);
  9715. if (flags & (TDWowned|TDXjobtemp|TDXtemporary))
  9716. fileProps.setPropBool("@owned", true);
  9717. if (flags & TDWresult)
  9718. fileProps.setPropBool("@result", true);
  9719. IConstWorkUnit *workUnit = ctx->queryWorkUnit();
  9720. if (workUnit)
  9721. {
  9722. SCMStringBuffer owner, wuid, job;
  9723. fileProps.setProp("@owner", workUnit->getUser(owner).str());
  9724. fileProps.setProp("@workunit", workUnit->getWuid(wuid).str());
  9725. fileProps.setProp("@job", workUnit->getJobName(job).str());
  9726. }
  9727. if (flags & TDWexpires)
  9728. setExpiryTime(fileProps, helper.getExpiryDays());
  9729. if (flags & TDWupdate)
  9730. {
  9731. unsigned eclCRC;
  9732. unsigned __int64 totalCRC;
  9733. helper.getUpdateCRCs(eclCRC, totalCRC);
  9734. fileProps.setPropInt("@eclCRC", eclCRC);
  9735. fileProps.setPropInt64("@totalCRC", totalCRC);
  9736. }
  9737. fileProps.setPropInt("@formatCrc", helper.getFormatCrc());
  9738. IRecordSize * inputMeta = input->queryOutputMeta();
  9739. if ((inputMeta->isFixedSize()) && !isOutputTransformed())
  9740. fileProps.setPropInt("@recordSize", inputMeta->getFixedSize() + (grouped ? 1 : 0));
  9741. const char *recordECL = helper.queryRecordECL();
  9742. if (recordECL && *recordECL)
  9743. fileProps.setProp("ECL", recordECL);
  9744. fileProps.setProp("@kind", "flat"); // default, derivitives may override
  9745. }
  9746. virtual IUserDescriptor *queryUserDescriptor() const
  9747. {
  9748. IConstWorkUnit *workUnit = ctx->queryWorkUnit();
  9749. if (workUnit)
  9750. return workUnit->queryUserDescriptor();
  9751. else
  9752. return NULL;
  9753. }
  9754. virtual bool isOutputTransformed() const { return false; }
  9755. };
  9756. //=================================================================================
  9757. class CRoxieServerCsvWriteActivity : public CRoxieServerDiskWriteActivity
  9758. {
  9759. IHThorCsvWriteArg &csvHelper;
  9760. CSVOutputStream csvOutput;
  9761. public:
  9762. CRoxieServerCsvWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9763. : CRoxieServerDiskWriteActivity(_factory, _probeManager), csvHelper(static_cast<IHThorCsvWriteArg &>(helper))
  9764. {
  9765. csvOutput.init(csvHelper.queryCsvParameters(), false);
  9766. }
  9767. virtual void onExecute()
  9768. {
  9769. OwnedRoxieString header(csvHelper.queryCsvParameters()->getHeader());
  9770. if (header)
  9771. {
  9772. csvOutput.beginLine();
  9773. csvOutput.writeHeaderLn(strlen(header), header);
  9774. diskout->write(csvOutput.length(), csvOutput.str());
  9775. }
  9776. loop
  9777. {
  9778. const void *nextrec = input->nextInGroup();
  9779. if (!nextrec)
  9780. {
  9781. nextrec = input->nextInGroup();
  9782. if (!nextrec)
  9783. break;
  9784. }
  9785. processed++;
  9786. csvOutput.beginLine();
  9787. csvHelper.writeRow((const byte *)nextrec, &csvOutput);
  9788. csvOutput.endLine();
  9789. diskout->write(csvOutput.length(), csvOutput.str());
  9790. ReleaseRoxieRow(nextrec);
  9791. }
  9792. OwnedRoxieString footer(csvHelper.queryCsvParameters()->getFooter());
  9793. if (footer)
  9794. {
  9795. csvOutput.beginLine();
  9796. csvOutput.writeHeaderLn(strlen(footer), footer);
  9797. diskout->write(csvOutput.length(), csvOutput.str());
  9798. }
  9799. }
  9800. virtual void setFileProperties(IFileDescriptor *desc) const
  9801. {
  9802. CRoxieServerDiskWriteActivity::setFileProperties(desc);
  9803. IPropertyTree &props = desc->queryProperties();
  9804. props.setProp("@format","utf8n");
  9805. ICsvParameters *csvParameters = csvHelper.queryCsvParameters();
  9806. StringBuffer separator;
  9807. OwnedRoxieString rs(csvParameters->getSeparator(0));
  9808. const char *s = rs;
  9809. while (s && *s)
  9810. {
  9811. if (',' == *s)
  9812. separator.append("\\,");
  9813. else
  9814. separator.append(*s);
  9815. ++s;
  9816. }
  9817. props.setProp("@csvSeparate", separator.str());
  9818. props.setProp("@csvQuote", rs.setown(csvParameters->getQuote(0)));
  9819. props.setProp("@csvTerminate", rs.setown(csvParameters->getTerminator(0)));
  9820. props.setProp("@csvEscape", rs.setown(csvParameters->getEscape(0)));
  9821. props.setProp("@kind", "csv");
  9822. }
  9823. virtual bool isOutputTransformed() const { return true; }
  9824. };
  9825. class CRoxieServerXmlWriteActivity : public CRoxieServerDiskWriteActivity
  9826. {
  9827. IHThorXmlWriteArg &xmlHelper;
  9828. StringAttr rowTag;
  9829. public:
  9830. CRoxieServerXmlWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9831. : CRoxieServerDiskWriteActivity(_factory, _probeManager), xmlHelper(static_cast<IHThorXmlWriteArg &>(helper))
  9832. {
  9833. }
  9834. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9835. {
  9836. CRoxieServerDiskWriteActivity::start(parentExtractSize, parentExtract, paused);
  9837. OwnedRoxieString xmlpath(xmlHelper.getXmlIteratorPath());
  9838. if (!xmlpath)
  9839. rowTag.set("Row");
  9840. else
  9841. {
  9842. const char *path = xmlpath;
  9843. if (*path == '/') path++;
  9844. if (strchr(path, '/')) UNIMPLEMENTED; // more what do we do with /mydata/row
  9845. rowTag.set(path);
  9846. }
  9847. }
  9848. virtual void onExecute()
  9849. {
  9850. OwnedRoxieString suppliedHeader(xmlHelper.getHeader());
  9851. const char *header = suppliedHeader;
  9852. if (!header) header = "<Dataset>\n";
  9853. diskout->write(strlen(header), header);
  9854. CommonXmlWriter xmlOutput(xmlHelper.getXmlFlags());
  9855. loop
  9856. {
  9857. OwnedConstRoxieRow nextrec = input->nextInGroup();
  9858. if (!nextrec)
  9859. {
  9860. nextrec.setown(input->nextInGroup());
  9861. if (!nextrec)
  9862. break;
  9863. }
  9864. processed++;
  9865. xmlOutput.clear().outputBeginNested(rowTag, false);
  9866. xmlHelper.toXML((const byte *)nextrec.get(), xmlOutput);
  9867. xmlOutput.outputEndNested(rowTag);
  9868. diskout->write(xmlOutput.length(), xmlOutput.str());
  9869. }
  9870. OwnedRoxieString suppliedFooter(xmlHelper.getFooter());
  9871. const char * footer = suppliedFooter;
  9872. if (!footer) footer = "</Dataset>\n";
  9873. diskout->write(strlen(footer), footer);
  9874. }
  9875. virtual void reset()
  9876. {
  9877. CRoxieServerDiskWriteActivity::reset();
  9878. rowTag.clear();
  9879. }
  9880. virtual void setFileProperties(IFileDescriptor *desc) const
  9881. {
  9882. CRoxieServerDiskWriteActivity::setFileProperties(desc);
  9883. desc->queryProperties().setProp("@format","utf8n");
  9884. desc->queryProperties().setProp("@rowTag",rowTag.get());
  9885. desc->queryProperties().setProp("@kind", "xml");
  9886. }
  9887. virtual bool isOutputTransformed() const { return true; }
  9888. };
  9889. class CRoxieServerDiskWriteActivityFactory : public CRoxieServerMultiOutputFactory
  9890. {
  9891. bool isRoot;
  9892. public:
  9893. CRoxieServerDiskWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  9894. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  9895. {
  9896. Owned<IHThorDiskWriteArg> helper = (IHThorDiskWriteArg *) helperFactory();
  9897. setNumOutputs(helper->getTempUsageCount());
  9898. if (_kind!=TAKdiskwrite)
  9899. assertex(numOutputs == 0);
  9900. }
  9901. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  9902. {
  9903. switch (numOutputs)
  9904. {
  9905. case 0:
  9906. switch (kind)
  9907. {
  9908. case TAKdiskwrite: return new CRoxieServerDiskWriteActivity(this, _probeManager);
  9909. case TAKcsvwrite: return new CRoxieServerCsvWriteActivity(this, _probeManager);
  9910. case TAKxmlwrite: return new CRoxieServerXmlWriteActivity(this, _probeManager);
  9911. };
  9912. throwUnexpected();
  9913. case 1:
  9914. return new CRoxieServerSpillWriteActivity(this, _probeManager);
  9915. default:
  9916. return new CRoxieServerThroughSpillActivity(this, _probeManager, numOutputs);
  9917. }
  9918. }
  9919. virtual bool isSink() const
  9920. {
  9921. return numOutputs == 0; // MORE - check with Gavin if this is right if not a temp but reread in same job...
  9922. }
  9923. };
  9924. IRoxieServerActivityFactory *createRoxieServerDiskWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  9925. {
  9926. return new CRoxieServerDiskWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  9927. }
  9928. //=================================================================================
  9929. class CRoxieServerIndexWriteActivity : public CRoxieServerInternalSinkActivity, implements IRoxiePublishCallback
  9930. {
  9931. IHThorIndexWriteArg &helper;
  9932. bool overwrite;
  9933. Owned<ClusterWriteHandler> clusterHandler;
  9934. Owned<IRoxieWriteHandler> writer;
  9935. unsigned __int64 reccount;
  9936. unsigned int fileCrc;
  9937. StringBuffer filename;
  9938. void updateWorkUnitResult()
  9939. {
  9940. 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
  9941. {
  9942. WorkunitUpdate wu = ctx->updateWorkUnit();
  9943. if (wu)
  9944. {
  9945. if (!(helper.getFlags() & TDXtemporary) && helper.getSequence() >= 0)
  9946. {
  9947. Owned<IWUResult> result = wu->updateResultBySequence(helper.getSequence());
  9948. if (result)
  9949. {
  9950. result->setResultTotalRowCount(reccount);
  9951. result->setResultStatus(ResultStatusCalculated);
  9952. result->setResultLogicalName(filename.str());
  9953. }
  9954. }
  9955. if(clusterHandler)
  9956. clusterHandler->finish(writer->queryFile());
  9957. }
  9958. CTXLOG("Created roxie index file %s", filename.str());
  9959. }
  9960. }
  9961. virtual void resolve()
  9962. {
  9963. StringArray clusters;
  9964. unsigned clusterIdx = 0;
  9965. while(true)
  9966. {
  9967. OwnedRoxieString cluster(helper.getCluster(clusterIdx));
  9968. if(!cluster)
  9969. break;
  9970. clusters.append(cluster);
  9971. clusterIdx++;
  9972. }
  9973. if (roxieName.length())
  9974. clusters.append(roxieName.str());
  9975. else
  9976. clusters.append(".");
  9977. OwnedRoxieString fname(helper.getFileName());
  9978. writer.setown(ctx->createLFN(fname, overwrite, false, clusters)); // MORE - if there's a workunit, use if for scope.
  9979. filename.set(writer->queryFile()->queryFilename());
  9980. if (writer->queryFile()->exists())
  9981. {
  9982. if (overwrite)
  9983. {
  9984. CTXLOG("Removing existing %s from DFS",filename.str());
  9985. writer->queryFile()->remove();
  9986. }
  9987. else
  9988. throw MakeStringException(99, "Cannot write index file %s, file already exists (missing OVERWRITE attribute?)", filename.str());
  9989. }
  9990. }
  9991. void buildUserMetadata(Owned<IPropertyTree> & metadata)
  9992. {
  9993. size32_t nameLen;
  9994. char * nameBuff;
  9995. size32_t valueLen;
  9996. char * valueBuff;
  9997. unsigned idx = 0;
  9998. while(helper.getIndexMeta(nameLen, nameBuff, valueLen, valueBuff, idx++))
  9999. {
  10000. StringBuffer name(nameLen, nameBuff);
  10001. StringBuffer value(valueLen, valueBuff);
  10002. if(*nameBuff == '_' && strcmp(name, "_nodeSize") != 0)
  10003. {
  10004. OwnedRoxieString fname(helper.getFileName());
  10005. throw MakeStringException(0, "Invalid name %s in user metadata for index %s (names beginning with underscore are reserved)", name.str(), fname.get());
  10006. }
  10007. if(!validateXMLTag(name.str()))
  10008. {
  10009. OwnedRoxieString fname(helper.getFileName());
  10010. throw MakeStringException(0, "Invalid name %s in user metadata for index %s (not legal XML element name)", name.str(), fname.get());
  10011. }
  10012. if(!metadata)
  10013. metadata.setown(createPTree("metadata"));
  10014. metadata->setProp(name.str(), value.str());
  10015. }
  10016. }
  10017. void buildLayoutMetadata(Owned<IPropertyTree> & metadata)
  10018. {
  10019. if(!metadata)
  10020. metadata.setown(createPTree("metadata"));
  10021. metadata->setProp("_record_ECL", helper.queryRecordECL());
  10022. void * layoutMetaBuff;
  10023. size32_t layoutMetaSize;
  10024. if(helper.getIndexLayout(layoutMetaSize, layoutMetaBuff))
  10025. {
  10026. metadata->setPropBin("_record_layout", layoutMetaSize, layoutMetaBuff);
  10027. rtlFree(layoutMetaBuff);
  10028. }
  10029. }
  10030. public:
  10031. CRoxieServerIndexWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  10032. : CRoxieServerInternalSinkActivity(_factory, _probeManager), helper(static_cast<IHThorIndexWriteArg &>(basehelper))
  10033. {
  10034. overwrite = ((helper.getFlags() & TIWoverwrite) != 0);
  10035. reccount = 0;
  10036. }
  10037. ~CRoxieServerIndexWriteActivity()
  10038. {
  10039. }
  10040. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10041. {
  10042. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  10043. resolve();
  10044. }
  10045. virtual void onExecute()
  10046. {
  10047. bool isVariable = helper.queryDiskRecordSize()->isVariableSize();
  10048. size32_t maxDiskRecordSize;
  10049. if (isVariable)
  10050. maxDiskRecordSize = 0x8000;
  10051. else
  10052. {
  10053. maxDiskRecordSize = helper.queryDiskRecordSize()->getFixedSize();
  10054. if (maxDiskRecordSize > 0x8000)
  10055. throw MakeStringException(99, "Index minimum record length (%d) exceeds 32k internal limit", maxDiskRecordSize);
  10056. }
  10057. OwnedMalloc<char> rowBuffer(maxDiskRecordSize, true);
  10058. unsigned __int64 fileSize = 0;
  10059. fileCrc = -1;
  10060. OwnedRoxieString dsName(helper.getFileName());
  10061. if (dsName.get())
  10062. {
  10063. Owned<const IResolvedFile> dsFileInfo = resolveLFN(dsName, false);
  10064. if (dsFileInfo)
  10065. {
  10066. fileSize = dsFileInfo->getFileSize();
  10067. }
  10068. }
  10069. {
  10070. Owned<IFileIO> io;
  10071. try
  10072. {
  10073. io.setown(writer->queryFile()->open(IFOcreate));
  10074. }
  10075. catch(IException * e)
  10076. {
  10077. e->Release();
  10078. clearKeyStoreCache(false);
  10079. io.setown(writer->queryFile()->open(IFOcreate));
  10080. }
  10081. if(!io)
  10082. throw MakeStringException(errno, "Failed to create file %s for writing", filename.str());
  10083. Owned<IFileIOStream> out = createIOStream(io);
  10084. unsigned flags = COL_PREFIX | HTREE_FULLSORT_KEY;
  10085. if (helper.getFlags() & TIWrowcompress)
  10086. flags |= HTREE_COMPRESSED_KEY|HTREE_QUICK_COMPRESSED_KEY;
  10087. else if (!(helper.getFlags() & TIWnolzwcompress))
  10088. flags |= HTREE_COMPRESSED_KEY;
  10089. if (isVariable)
  10090. flags |= HTREE_VARSIZE;
  10091. Owned<IPropertyTree> metadata;
  10092. buildUserMetadata(metadata);
  10093. buildLayoutMetadata(metadata);
  10094. unsigned nodeSize = metadata ? metadata->getPropInt("_nodeSize", NODESIZE) : NODESIZE;
  10095. Owned<IKeyBuilder> builder = createKeyBuilder(out, flags, maxDiskRecordSize, fileSize, nodeSize, helper.getKeyedSize(), 0);
  10096. class BcWrapper : implements IBlobCreator
  10097. {
  10098. IKeyBuilder *builder;
  10099. public:
  10100. BcWrapper(IKeyBuilder *_builder) : builder(_builder) {}
  10101. virtual unsigned __int64 createBlob(size32_t size, const void * ptr)
  10102. {
  10103. return builder->createBlob(size, (const char *) ptr);
  10104. }
  10105. } bc(builder);
  10106. // Loop thru the results
  10107. loop
  10108. {
  10109. OwnedConstRoxieRow nextrec(input->nextInGroup());
  10110. if (!nextrec)
  10111. {
  10112. nextrec.setown(input->nextInGroup());
  10113. if (!nextrec)
  10114. break;
  10115. }
  10116. try
  10117. {
  10118. unsigned __int64 fpos;
  10119. RtlStaticRowBuilder rowBuilder(rowBuffer, maxDiskRecordSize);
  10120. size32_t thisSize = helper.transform(rowBuilder, nextrec, &bc, fpos);
  10121. builder->processKeyData(rowBuffer, fpos, thisSize);
  10122. }
  10123. catch(IException * e)
  10124. {
  10125. throw makeWrappedException(e);
  10126. }
  10127. reccount++;
  10128. }
  10129. if(metadata)
  10130. builder->finish(metadata,&fileCrc);
  10131. else
  10132. builder->finish(&fileCrc);
  10133. }
  10134. }
  10135. virtual void stop(bool aborting)
  10136. {
  10137. if (writer)
  10138. {
  10139. if (!aborting)
  10140. updateWorkUnitResult();
  10141. writer->finish(!aborting, this);
  10142. writer.clear();
  10143. }
  10144. CRoxieServerActivity::stop(aborting);
  10145. }
  10146. virtual void reset()
  10147. {
  10148. CRoxieServerActivity::reset();
  10149. writer.clear();
  10150. }
  10151. //interface IRoxiePublishCallback
  10152. virtual void setFileProperties(IFileDescriptor *desc) const
  10153. {
  10154. IPropertyTree &partProps = desc->queryPart(0)->queryProperties(); //properties of the first file part.
  10155. IPropertyTree &fileProps = desc->queryProperties(); // properties of the logical file
  10156. // Now publish to name services
  10157. StringBuffer dir,base;
  10158. offset_t indexFileSize = writer->queryFile()->size();
  10159. if(clusterHandler)
  10160. clusterHandler->splitPhysicalFilename(dir, base);
  10161. else
  10162. splitFilename(filename.str(), &dir, &dir, &base, &base);
  10163. desc->setDefaultDir(dir.str());
  10164. //properties of the first file part.
  10165. Owned<IPropertyTree> attrs;
  10166. if(clusterHandler)
  10167. attrs.setown(createPTree("Part")); // clusterHandler is going to set attributes
  10168. else
  10169. {
  10170. // add cluster
  10171. StringBuffer mygroupname;
  10172. desc->setNumParts(1);
  10173. desc->setPartMask(base.str());
  10174. attrs.set(&desc->queryPart(0)->queryProperties());
  10175. }
  10176. attrs->setPropInt64("@size", indexFileSize);
  10177. CDateTime createTime, modifiedTime, accessedTime;
  10178. writer->queryFile()->getTime(&createTime, &modifiedTime, &accessedTime);
  10179. // round file time down to nearest sec. Nanosec accurancy is not preserved elsewhere and can lead to mismatch later.
  10180. unsigned hour, min, sec, nanosec;
  10181. modifiedTime.getTime(hour, min, sec, nanosec);
  10182. modifiedTime.setTime(hour, min, sec, 0);
  10183. StringBuffer timestr;
  10184. modifiedTime.getString(timestr);
  10185. if(timestr.length())
  10186. attrs->setProp("@modified", timestr.str());
  10187. if(clusterHandler)
  10188. clusterHandler->setDescriptorParts(desc, base.str(), attrs);
  10189. // properties of the logical file
  10190. IPropertyTree & properties = desc->queryProperties();
  10191. properties.setProp("@kind", "key");
  10192. properties.setPropInt64("@size", indexFileSize);
  10193. properties.setPropInt64("@recordCount", reccount);
  10194. SCMStringBuffer info;
  10195. WorkunitUpdate workUnit = ctx->updateWorkUnit();
  10196. if (workUnit)
  10197. {
  10198. properties.setProp("@owner", workUnit->getUser(info).str());
  10199. info.clear();
  10200. properties.setProp("@workunit", workUnit->getWuid(info).str());
  10201. info.clear();
  10202. properties.setProp("@job", workUnit->getJobName(info).str());
  10203. }
  10204. char const * rececl = helper.queryRecordECL();
  10205. if(rececl && *rececl)
  10206. properties.setProp("ECL", rececl);
  10207. if (helper.getFlags() & TIWexpires)
  10208. setExpiryTime(properties, helper.getExpiryDays());
  10209. if (helper.getFlags() & TIWupdate)
  10210. {
  10211. unsigned eclCRC;
  10212. unsigned __int64 totalCRC;
  10213. helper.getUpdateCRCs(eclCRC, totalCRC);
  10214. properties.setPropInt("@eclCRC", eclCRC);
  10215. properties.setPropInt64("@totalCRC", totalCRC);
  10216. }
  10217. properties.setPropInt("@fileCrc", fileCrc);
  10218. properties.setPropInt("@formatCrc", helper.getFormatCrc());
  10219. void * layoutMetaBuff;
  10220. size32_t layoutMetaSize;
  10221. if(helper.getIndexLayout(layoutMetaSize, layoutMetaBuff))
  10222. {
  10223. properties.setPropBin("_record_layout", layoutMetaSize, layoutMetaBuff);
  10224. rtlFree(layoutMetaBuff);
  10225. }
  10226. }
  10227. IUserDescriptor *queryUserDescriptor() const
  10228. {
  10229. IConstWorkUnit *workUnit = ctx->queryWorkUnit();
  10230. if (workUnit)
  10231. return workUnit->queryUserDescriptor();
  10232. else
  10233. return NULL;
  10234. }
  10235. };
  10236. //=================================================================================
  10237. class CRoxieServerIndexWriteActivityFactory : public CRoxieServerMultiOutputFactory
  10238. {
  10239. public:
  10240. CRoxieServerIndexWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  10241. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  10242. {
  10243. setNumOutputs(0);
  10244. }
  10245. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  10246. {
  10247. return new CRoxieServerIndexWriteActivity(this, _probeManager);
  10248. }
  10249. virtual bool isSink() const
  10250. {
  10251. return true;
  10252. }
  10253. };
  10254. IRoxieServerActivityFactory *createRoxieServerIndexWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  10255. {
  10256. return new CRoxieServerIndexWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  10257. }
  10258. //=================================================================================
  10259. static inline void getLimitType(unsigned flags, bool & limitFail, bool & limitOnFail)
  10260. {
  10261. if((flags & JFmatchAbortLimitSkips) != 0)
  10262. {
  10263. limitFail = false;
  10264. limitOnFail = false;
  10265. }
  10266. else
  10267. {
  10268. limitOnFail = ((flags & JFonfail) != 0);
  10269. limitFail = !limitOnFail;
  10270. }
  10271. }
  10272. class CRoxieServerJoinActivity : public CRoxieServerTwoInputActivity
  10273. {
  10274. enum { JSfill, JSfillleft, JSfillright, JScollate, JScompare, JSleftonly, JSrightonly } state;
  10275. IHThorJoinArg &helper;
  10276. ICompare * collate;
  10277. ICompare * collateupper;
  10278. ThorActivityKind activityKind;
  10279. bool leftOuterJoin;
  10280. bool rightOuterJoin;
  10281. bool exclude;
  10282. bool limitFail;
  10283. bool limitOnFail;
  10284. unsigned keepLimit;
  10285. unsigned joinLimit;
  10286. unsigned atmostLimit;
  10287. unsigned abortLimit;
  10288. unsigned atmostsTriggered;
  10289. bool betweenjoin;
  10290. OwnedRowArray right;
  10291. const void * left;
  10292. const void * pendingRight;
  10293. unsigned rightIndex;
  10294. BoolArray matchedRight;
  10295. bool matchedLeft;
  10296. Owned<IException> failingLimit;
  10297. ConstPointerArray filteredRight;
  10298. Owned<IRHLimitedCompareHelper> limitedhelper;
  10299. OwnedConstRoxieRow defaultLeft;
  10300. OwnedConstRoxieRow defaultRight;
  10301. Owned<IEngineRowAllocator> defaultLeftAllocator;
  10302. Owned<IEngineRowAllocator> defaultRightAllocator;
  10303. bool cloneLeft;
  10304. void createDefaultLeft()
  10305. {
  10306. if (!defaultLeft)
  10307. {
  10308. if (!defaultLeftAllocator)
  10309. defaultLeftAllocator.setown(ctx->queryCodeContext()->getRowAllocator(input->queryOutputMeta(), activityId));
  10310. RtlDynamicRowBuilder rowBuilder(defaultLeftAllocator);
  10311. size32_t thisSize = helper.createDefaultLeft(rowBuilder);
  10312. defaultLeft.setown(rowBuilder.finalizeRowClear(thisSize));
  10313. }
  10314. }
  10315. void createDefaultRight()
  10316. {
  10317. if (!defaultRight)
  10318. {
  10319. if (!defaultRightAllocator)
  10320. defaultRightAllocator.setown(ctx->queryCodeContext()->getRowAllocator(input1->queryOutputMeta(), activityId));
  10321. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  10322. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  10323. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  10324. }
  10325. }
  10326. public:
  10327. CRoxieServerJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  10328. : CRoxieServerTwoInputActivity(_factory, _probeManager), helper((IHThorJoinArg &)basehelper)
  10329. {
  10330. // MORE - some of this should be done in factory
  10331. unsigned joinFlags = helper.getJoinFlags();
  10332. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  10333. rightOuterJoin = (joinFlags & JFrightouter) != 0;
  10334. exclude = (joinFlags & JFexclude) != 0;
  10335. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  10336. getLimitType(joinFlags, limitFail, limitOnFail);
  10337. if (joinFlags & JFslidingmatch)
  10338. {
  10339. betweenjoin = true;
  10340. collate = helper.queryCompareLeftRightLower();
  10341. collateupper = helper.queryCompareLeftRightUpper();
  10342. }
  10343. else
  10344. {
  10345. betweenjoin = false;
  10346. collate = collateupper = helper.queryCompareLeftRight();
  10347. }
  10348. rightIndex = 0;
  10349. state = JSfill;
  10350. matchedLeft = false;
  10351. joinLimit = 0;
  10352. keepLimit = 0; // wait until ctx available
  10353. atmostLimit = 0; // wait until ctx available
  10354. abortLimit = 0; // wait until ctx available
  10355. atmostsTriggered = 0;
  10356. assertex((joinFlags & (JFfirst | JFfirstleft | JFfirstright)) == 0);
  10357. left = NULL;
  10358. pendingRight = NULL;
  10359. activityKind = _factory->getKind();
  10360. }
  10361. virtual bool needsAllocator() const { return true; }
  10362. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10363. {
  10364. left = NULL;
  10365. rightIndex = 0;
  10366. state = JSfill;
  10367. matchedLeft = false;
  10368. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  10369. keepLimit = helper.getKeepLimit();
  10370. if (keepLimit == 0)
  10371. keepLimit = (unsigned)-1;
  10372. atmostsTriggered = 0;
  10373. atmostLimit = helper.getJoinLimit();
  10374. if(atmostLimit == 0)
  10375. atmostLimit = (unsigned)-1;
  10376. else
  10377. assertex(!rightOuterJoin && !betweenjoin);
  10378. abortLimit = helper.getMatchAbortLimit();
  10379. if (abortLimit == 0)
  10380. abortLimit = (unsigned)-1;
  10381. if (rightOuterJoin)
  10382. createDefaultLeft();
  10383. if ((leftOuterJoin && (activityKind==TAKjoin || activityKind==TAKjoinlight || activityKind==TAKdenormalizegroup)) || limitOnFail)
  10384. createDefaultRight();
  10385. if ((helper.getJoinFlags() & JFlimitedprefixjoin) && helper.getJoinLimit())
  10386. { //limited match join (s[1..n])
  10387. limitedhelper.setown(createRHLimitedCompareHelper());
  10388. limitedhelper->init( helper.getJoinLimit(), input1, collate, helper.queryPrefixCompare() );
  10389. }
  10390. }
  10391. virtual void reset()
  10392. {
  10393. if (atmostsTriggered)
  10394. noteStatistic(STATS_ATMOST, atmostsTriggered, 1);
  10395. right.clear();
  10396. ReleaseClearRoxieRow(left);
  10397. ReleaseClearRoxieRow(pendingRight);
  10398. defaultRight.clear();
  10399. defaultLeft.clear();
  10400. CRoxieServerTwoInputActivity::reset();
  10401. }
  10402. virtual void setInput(unsigned idx, IRoxieInput *_in)
  10403. {
  10404. switch(idx)
  10405. {
  10406. case 0:
  10407. if ((helper.getJoinFlags() & JFparallel) != 0)
  10408. {
  10409. puller.setown(new CRoxieServerReadAheadInput(0)); // MORE - cant ask context for parallelJoinPreload as context is not yet set up.
  10410. puller->setInput(0, _in);
  10411. _in = puller;
  10412. }
  10413. input = _in;
  10414. break;
  10415. case 1:
  10416. input1 = _in;
  10417. break;
  10418. default:
  10419. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  10420. }
  10421. }
  10422. virtual IRoxieInput *queryOutput(unsigned idx)
  10423. {
  10424. if (idx==(unsigned)-1)
  10425. idx = 0;
  10426. return idx ? NULL : this;
  10427. }
  10428. void fillLeft()
  10429. {
  10430. matchedLeft = false;
  10431. left = input->nextInGroup();
  10432. if (!left)
  10433. left = input->nextInGroup();
  10434. if(betweenjoin && left && pendingRight && (collate->docompare(left, pendingRight) >= 0))
  10435. fillRight();
  10436. if (limitedhelper && 0==rightIndex)
  10437. {
  10438. rightIndex = 0;
  10439. right.clear();
  10440. matchedRight.kill();
  10441. if (left)
  10442. {
  10443. limitedhelper->getGroup(right,left);
  10444. ForEachItemIn(idx, right)
  10445. matchedRight.append(false);
  10446. }
  10447. }
  10448. }
  10449. void fillRight()
  10450. {
  10451. if (limitedhelper)
  10452. return;
  10453. failingLimit.clear();
  10454. if(betweenjoin && left)
  10455. {
  10456. aindex_t start = 0;
  10457. while(right.isItem(start) && (collateupper->docompare(left, right.item(start)) > 0))
  10458. start++;
  10459. if(start>0)
  10460. right.clearPart(0, start);
  10461. }
  10462. else
  10463. right.clear();
  10464. rightIndex = 0;
  10465. unsigned groupCount = 0;
  10466. const void * next;
  10467. while(true)
  10468. {
  10469. if(pendingRight)
  10470. {
  10471. next = pendingRight;
  10472. pendingRight = NULL;
  10473. }
  10474. else
  10475. {
  10476. next = input1->nextInGroup();
  10477. }
  10478. if(!rightOuterJoin && next && (!left || (collateupper->docompare(left, next) > 0))) // if right is less than left, and not right outer, can skip group
  10479. {
  10480. while(next)
  10481. {
  10482. ReleaseClearRoxieRow(next);
  10483. next = input1->nextInGroup();
  10484. }
  10485. continue;
  10486. }
  10487. while(next)
  10488. {
  10489. if(groupCount==abortLimit)
  10490. {
  10491. if(limitFail)
  10492. failLimit();
  10493. if (ctx->queryDebugContext())
  10494. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  10495. if(limitOnFail)
  10496. {
  10497. assertex(!failingLimit);
  10498. try
  10499. {
  10500. failLimit();
  10501. }
  10502. catch(IException * except)
  10503. {
  10504. failingLimit.setown(except);
  10505. }
  10506. assertex(failingLimit != NULL);
  10507. }
  10508. right.append(next);
  10509. do
  10510. {
  10511. next = input1->nextInGroup();
  10512. ReleaseRoxieRow(next);
  10513. } while(next);
  10514. break;
  10515. }
  10516. else if(groupCount==atmostLimit)
  10517. {
  10518. atmostsTriggered++;
  10519. right.clear();
  10520. groupCount = 0;
  10521. while(next)
  10522. {
  10523. ReleaseRoxieRow(next);
  10524. next = input1->nextInGroup();
  10525. }
  10526. }
  10527. else
  10528. {
  10529. right.append(next);
  10530. groupCount++;
  10531. }
  10532. next = input1->nextInGroup();
  10533. }
  10534. // 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
  10535. if(betweenjoin && left)
  10536. {
  10537. pendingRight = input1->nextInGroup();
  10538. if(!pendingRight || (collate->docompare(left, pendingRight) < 0))
  10539. break;
  10540. }
  10541. else
  10542. break;
  10543. }
  10544. matchedRight.kill();
  10545. ForEachItemIn(idx, right)
  10546. matchedRight.append(false);
  10547. }
  10548. const void * joinRecords(const void * curLeft, const void * curRight)
  10549. {
  10550. if (cloneLeft)
  10551. {
  10552. LinkRoxieRow(curLeft);
  10553. return curLeft;
  10554. }
  10555. try
  10556. {
  10557. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  10558. size32_t thisSize = helper.transform(rowBuilder, curLeft, curRight);
  10559. if (thisSize)
  10560. return rowBuilder.finalizeRowClear(thisSize);
  10561. else
  10562. return NULL;
  10563. }
  10564. catch (IException *E)
  10565. {
  10566. throw makeWrappedException(E);
  10567. }
  10568. }
  10569. const void * denormalizeRecords(const void * curLeft, ConstPointerArray & rows)
  10570. {
  10571. try
  10572. {
  10573. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  10574. unsigned numRows = rows.ordinality();
  10575. const void * right = numRows ? rows.item(0) : defaultRight.get();
  10576. size32_t thisSize = helper.transform(rowBuilder, curLeft, right, numRows, (const void * *)rows.getArray());
  10577. if (thisSize)
  10578. return rowBuilder.finalizeRowClear(thisSize);
  10579. else
  10580. return NULL;
  10581. }
  10582. catch (IException *E)
  10583. {
  10584. throw makeWrappedException(E);
  10585. }
  10586. }
  10587. const void * joinException(const void * curLeft, IException * except)
  10588. {
  10589. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  10590. size32_t thisSize = helper.onFailTransform(rowBuilder, curLeft, defaultRight, except);
  10591. return rowBuilder.finalizeRowClear(thisSize);
  10592. }
  10593. void failLimit()
  10594. {
  10595. helper.onMatchAbortLimitExceeded();
  10596. CommonXmlWriter xmlwrite(0);
  10597. if (input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  10598. {
  10599. input->queryOutputMeta()->toXML((byte *) left, xmlwrite);
  10600. }
  10601. throw MakeStringException(ROXIE_TOO_MANY_RESULTS, "More than %d match candidates in join %d for row %s", abortLimit, queryId(), xmlwrite.str());
  10602. }
  10603. virtual const void * nextInGroup()
  10604. {
  10605. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  10606. loop
  10607. {
  10608. switch (state)
  10609. {
  10610. case JSfill:
  10611. fillLeft();
  10612. state = JSfillright;
  10613. break;
  10614. case JSfillright:
  10615. fillRight();
  10616. state = JScollate;
  10617. break;
  10618. case JSfillleft:
  10619. fillLeft();
  10620. state = JScollate;
  10621. break;
  10622. case JScollate:
  10623. if (right.ordinality() == 0)
  10624. {
  10625. if (left == NULL)
  10626. return NULL;
  10627. state = JSleftonly;
  10628. }
  10629. else
  10630. {
  10631. if (!left)
  10632. state = JSrightonly;
  10633. else
  10634. {
  10635. int diff;
  10636. if(betweenjoin)
  10637. diff = ((collate->docompare(left, right.item(0)) < 0) ? -1 : ((collateupper->docompare(left, right.item(right.ordinality()-1)) > 0) ? +1 : 0));
  10638. else
  10639. diff = collate->docompare(left, right.item(0));
  10640. bool limitExceeded = right.ordinality()>abortLimit;
  10641. if (diff == 0)
  10642. {
  10643. if (limitExceeded)
  10644. {
  10645. const void * ret = NULL;
  10646. if(failingLimit)
  10647. ret = joinException(left, failingLimit);
  10648. ReleaseRoxieRow(left);
  10649. left = NULL;
  10650. state = JSfillleft;
  10651. ForEachItemIn(idx, right)
  10652. matchedRight.replace(true, idx);
  10653. if(ret)
  10654. {
  10655. processed++;
  10656. return ret;
  10657. }
  10658. }
  10659. else
  10660. {
  10661. state = JScompare;
  10662. joinLimit = keepLimit;
  10663. }
  10664. }
  10665. else if (diff < 0)
  10666. state = JSleftonly;
  10667. else if (limitExceeded)
  10668. {
  10669. // MORE - Roxie code seems to think there should be a destroyRowset(right) here....
  10670. state = JSfillright;
  10671. }
  10672. else
  10673. state = JSrightonly;
  10674. }
  10675. }
  10676. break;
  10677. case JSrightonly:
  10678. if (rightOuterJoin)
  10679. {
  10680. switch (activityKind)
  10681. {
  10682. case TAKjoin:
  10683. {
  10684. while (right.isItem(rightIndex))
  10685. {
  10686. if (!matchedRight.item(rightIndex))
  10687. {
  10688. const void * rhs = right.item(rightIndex++);
  10689. const void *ret = joinRecords(defaultLeft, rhs);
  10690. if (ret)
  10691. {
  10692. processed++;
  10693. return ret;
  10694. }
  10695. }
  10696. rightIndex++;
  10697. }
  10698. break;
  10699. }
  10700. //Probably excessive to implement the following, but possibly useful
  10701. case TAKdenormalize:
  10702. {
  10703. OwnedConstRoxieRow newLeft;
  10704. newLeft.set(defaultLeft);
  10705. unsigned rowSize = 0;
  10706. unsigned leftCount = 0;
  10707. while (right.isItem(rightIndex))
  10708. {
  10709. if (!matchedRight.item(rightIndex))
  10710. {
  10711. const void * rhs = right.item(rightIndex);
  10712. try
  10713. {
  10714. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  10715. unsigned thisSize = helper.transform(rowBuilder, newLeft, rhs, ++leftCount);
  10716. if (thisSize)
  10717. {
  10718. rowSize = thisSize;
  10719. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  10720. }
  10721. }
  10722. catch (IException *E)
  10723. {
  10724. throw makeWrappedException(E);
  10725. }
  10726. }
  10727. rightIndex++;
  10728. }
  10729. state = JSfillright;
  10730. if (rowSize)
  10731. {
  10732. processed++;
  10733. return newLeft.getClear();
  10734. }
  10735. break;
  10736. }
  10737. case TAKdenormalizegroup:
  10738. {
  10739. filteredRight.kill();
  10740. while (right.isItem(rightIndex))
  10741. {
  10742. if (!matchedRight.item(rightIndex))
  10743. filteredRight.append(right.item(rightIndex));
  10744. rightIndex++;
  10745. }
  10746. state = JSfillright;
  10747. if (filteredRight.ordinality())
  10748. {
  10749. const void * ret = denormalizeRecords(defaultLeft, filteredRight);
  10750. filteredRight.kill();
  10751. if (ret)
  10752. {
  10753. processed++;
  10754. return ret;
  10755. }
  10756. }
  10757. break;
  10758. }
  10759. }
  10760. }
  10761. state = JSfillright;
  10762. break;
  10763. case JSleftonly:
  10764. {
  10765. const void * ret = NULL;
  10766. if (!matchedLeft && leftOuterJoin)
  10767. {
  10768. switch (activityKind)
  10769. {
  10770. case TAKjoin:
  10771. ret = joinRecords(left, defaultRight);
  10772. break;
  10773. case TAKdenormalize:
  10774. ret = left;
  10775. left = NULL;
  10776. break;
  10777. case TAKdenormalizegroup:
  10778. filteredRight.kill();
  10779. ret = denormalizeRecords(left, filteredRight);
  10780. break;
  10781. }
  10782. }
  10783. ReleaseRoxieRow(left);
  10784. left = NULL;
  10785. state = JSfillleft;
  10786. if (ret)
  10787. {
  10788. processed++;
  10789. return ret;
  10790. }
  10791. break;
  10792. }
  10793. case JScompare:
  10794. if (joinLimit != 0)
  10795. {
  10796. switch (activityKind)
  10797. {
  10798. case TAKjoin:
  10799. {
  10800. while (right.isItem(rightIndex))
  10801. {
  10802. const void * rhs = right.item(rightIndex++);
  10803. if (helper.match(left, rhs))
  10804. {
  10805. matchedRight.replace(true, rightIndex-1);
  10806. matchedLeft = true;
  10807. if (!exclude)
  10808. {
  10809. const void *ret = joinRecords(left, rhs);
  10810. if (ret)
  10811. {
  10812. processed++;
  10813. joinLimit--;
  10814. return ret;
  10815. }
  10816. }
  10817. }
  10818. }
  10819. break;
  10820. }
  10821. case TAKdenormalize:
  10822. {
  10823. OwnedConstRoxieRow newLeft;
  10824. newLeft.set(left);
  10825. unsigned rowSize = 0;
  10826. unsigned leftCount = 0;
  10827. while (right.isItem(rightIndex) && joinLimit)
  10828. {
  10829. try
  10830. {
  10831. const void * rhs = right.item(rightIndex++);
  10832. if (helper.match(left, rhs))
  10833. {
  10834. matchedRight.replace(true, rightIndex-1);
  10835. matchedLeft = true;
  10836. if (!exclude)
  10837. {
  10838. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  10839. unsigned thisSize = helper.transform(rowBuilder, newLeft, rhs, ++leftCount);
  10840. if (thisSize)
  10841. {
  10842. rowSize = thisSize;
  10843. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  10844. joinLimit--;
  10845. }
  10846. }
  10847. }
  10848. }
  10849. catch (IException *E)
  10850. {
  10851. throw makeWrappedException(E);
  10852. }
  10853. }
  10854. state = JSleftonly;
  10855. rightIndex = 0;
  10856. if (rowSize)
  10857. {
  10858. processed++;
  10859. return newLeft.getClear();
  10860. }
  10861. break;
  10862. }
  10863. case TAKdenormalizegroup:
  10864. {
  10865. filteredRight.kill();
  10866. while (right.isItem(rightIndex))
  10867. {
  10868. const void * rhs = right.item(rightIndex++);
  10869. if (helper.match(left, rhs))
  10870. {
  10871. matchedRight.replace(true, rightIndex-1);
  10872. filteredRight.append(rhs);
  10873. matchedLeft = true;
  10874. if (filteredRight.ordinality()==joinLimit)
  10875. break;
  10876. }
  10877. }
  10878. state = JSleftonly;
  10879. rightIndex = 0;
  10880. if (!exclude && filteredRight.ordinality())
  10881. {
  10882. const void * ret = denormalizeRecords(left, filteredRight);
  10883. filteredRight.kill();
  10884. if (ret)
  10885. {
  10886. processed++;
  10887. return ret;
  10888. }
  10889. }
  10890. break;
  10891. }
  10892. }
  10893. }
  10894. state = JSleftonly;
  10895. rightIndex = 0;
  10896. break;
  10897. }
  10898. }
  10899. }
  10900. };
  10901. class CRoxieServerJoinActivityFactory : public CRoxieServerActivityFactory
  10902. {
  10903. unsigned input2;
  10904. unsigned input2idx;
  10905. public:
  10906. CRoxieServerJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  10907. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  10908. {
  10909. input2 = 0;
  10910. input2idx = 0;
  10911. }
  10912. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  10913. {
  10914. return new CRoxieServerJoinActivity(this, _probeManager);
  10915. }
  10916. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  10917. {
  10918. if (idx==1)
  10919. {
  10920. input2 = source;
  10921. input2idx = sourceidx;
  10922. }
  10923. else
  10924. CRoxieServerActivityFactory::setInput(idx, source, sourceidx);
  10925. }
  10926. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  10927. {
  10928. switch (idx)
  10929. {
  10930. case 1:
  10931. sourceidx = input2idx;
  10932. return input2;
  10933. case 0:
  10934. return CRoxieServerActivityFactory::getInput(idx, sourceidx);
  10935. default:
  10936. return (unsigned) -1;
  10937. }
  10938. }
  10939. virtual unsigned numInputs() const { return 2; }
  10940. };
  10941. IRoxieServerActivityFactory *createRoxieServerJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  10942. {
  10943. return new CRoxieServerJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  10944. }
  10945. //=================================================================================
  10946. #define CONCAT_READAHEAD 1000
  10947. class CRoxieThreadedConcatReader : public CInterface, implements IRecordPullerCallback
  10948. {
  10949. public:
  10950. IMPLEMENT_IINTERFACE;
  10951. CRoxieThreadedConcatReader(InterruptableSemaphore &_ready, bool _grouped)
  10952. : puller(false), grouped(_grouped), atEog(true), ready(_ready), eof(false)
  10953. {
  10954. }
  10955. void start(unsigned parentExtractSize, const byte *parentExtract, bool paused, IRoxieSlaveContext *ctx)
  10956. {
  10957. space.reinit(CONCAT_READAHEAD);
  10958. puller.start(parentExtractSize, parentExtract, paused, ctx->concatPreload(), false, ctx);
  10959. }
  10960. void stop(bool aborting)
  10961. {
  10962. space.interrupt();
  10963. puller.stop(aborting);
  10964. }
  10965. IRoxieInput *queryInput() const
  10966. {
  10967. return puller.queryInput();
  10968. }
  10969. void reset()
  10970. {
  10971. puller.reset();
  10972. ForEachItemIn(idx, buffer)
  10973. ReleaseRoxieRow(buffer.item(idx));
  10974. buffer.clear();
  10975. eof = false;
  10976. atEog = true;
  10977. }
  10978. void setInput(IRoxieInput *_in)
  10979. {
  10980. puller.setInput(this, _in);
  10981. }
  10982. virtual void processRow(const void *row)
  10983. {
  10984. buffer.enqueue(row);
  10985. ready.signal();
  10986. space.wait();
  10987. }
  10988. virtual void processGroup(const ConstPointerArray &rows)
  10989. {
  10990. // We use record-by-record input mode of the puller thread even in grouped mode.
  10991. throwUnexpected();
  10992. }
  10993. virtual void processEOG()
  10994. {
  10995. if (grouped)
  10996. processRow(NULL);
  10997. }
  10998. virtual void processDone()
  10999. {
  11000. processRow(NULL);
  11001. }
  11002. virtual bool fireException(IException *e)
  11003. {
  11004. // called from puller thread on failure
  11005. ready.interrupt(LINK(e));
  11006. space.interrupt(e);
  11007. return true;
  11008. }
  11009. bool peek(const void * &row, bool &anyActive)
  11010. {
  11011. if (!eof)
  11012. {
  11013. if (buffer.ordinality())
  11014. {
  11015. space.signal();
  11016. row = buffer.dequeue();
  11017. if (row==NULL)
  11018. {
  11019. if (atEog)
  11020. {
  11021. eof = true;
  11022. return false;
  11023. }
  11024. else
  11025. atEog = true;
  11026. }
  11027. else if (grouped)
  11028. atEog = false;
  11029. return true;
  11030. }
  11031. anyActive = true;
  11032. }
  11033. return false;
  11034. }
  11035. protected:
  11036. RecordPullerThread puller;
  11037. InterruptableSemaphore space;
  11038. InterruptableSemaphore &ready;
  11039. SafeQueueOf<const void, true> buffer;
  11040. bool atEog;
  11041. bool eof;
  11042. bool grouped;
  11043. };
  11044. MAKEPointerArray(CRoxieThreadedConcatReader, ReaderArray);
  11045. class CRoxieServerThreadedConcatActivity : public CRoxieServerActivity
  11046. {
  11047. InterruptableSemaphore ready;
  11048. ReaderArray pullers;
  11049. unsigned numInputs;
  11050. unsigned nextPuller; // for round robin
  11051. unsigned readyPending;
  11052. bool eof;
  11053. bool inGroup;
  11054. bool grouped;
  11055. public:
  11056. CRoxieServerThreadedConcatActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _grouped, unsigned _numInputs)
  11057. : CRoxieServerActivity(_factory, _probeManager), grouped(_grouped)
  11058. {
  11059. numInputs = _numInputs;
  11060. eof = (numInputs==0);
  11061. nextPuller = 0;
  11062. readyPending = 0;
  11063. for (unsigned i = 0; i < numInputs; i++)
  11064. pullers.append(*new CRoxieThreadedConcatReader(ready, _grouped));
  11065. }
  11066. ~CRoxieServerThreadedConcatActivity()
  11067. {
  11068. ForEachItemIn(idx, pullers)
  11069. delete &pullers.item(idx);
  11070. }
  11071. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11072. {
  11073. eof = (numInputs==0);
  11074. inGroup = false;
  11075. nextPuller = 0;
  11076. readyPending = 0;
  11077. ready.reinit();
  11078. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  11079. ForEachItemIn(idx, pullers)
  11080. {
  11081. pullers.item(idx).start(parentExtractSize, parentExtract, paused, ctx);
  11082. // NOTE - it is ok to start the thread running while parts of the subgraph are still being started, since everything
  11083. // in the part of the subgraph that the thread uses has been started.
  11084. // Note that splitters are supposed to cope with being used when only some outputs have been started.
  11085. }
  11086. }
  11087. virtual void stop(bool aborting)
  11088. {
  11089. ready.interrupt();
  11090. ForEachItemIn(idx, pullers)
  11091. pullers.item(idx).stop(aborting);
  11092. CRoxieServerActivity::stop(aborting);
  11093. }
  11094. virtual unsigned __int64 queryLocalCycles() const
  11095. {
  11096. return 0;
  11097. }
  11098. virtual IRoxieInput *queryInput(unsigned idx) const
  11099. {
  11100. if (pullers.isItem(idx))
  11101. return pullers.item(idx).queryInput();
  11102. else
  11103. return NULL;
  11104. }
  11105. virtual void reset()
  11106. {
  11107. CRoxieServerActivity::reset();
  11108. ForEachItemIn(idx, pullers)
  11109. pullers.item(idx).reset();
  11110. eof = false;
  11111. inGroup = false;
  11112. nextPuller = 0;
  11113. readyPending = 0;
  11114. }
  11115. virtual void setInput(unsigned idx, IRoxieInput *_in)
  11116. {
  11117. if (pullers.isItem(idx))
  11118. pullers.item(idx).setInput(_in);
  11119. else
  11120. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  11121. }
  11122. virtual const void * nextInGroup()
  11123. {
  11124. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  11125. if (eof)
  11126. return NULL;
  11127. loop
  11128. {
  11129. if (readyPending && !inGroup)
  11130. {
  11131. if (readyPending > 1)
  11132. ready.signal(readyPending-1);
  11133. readyPending = 0;
  11134. }
  11135. else
  11136. ready.wait();
  11137. bool anyActive = false;
  11138. ForEachItemIn(unused_index, pullers)
  11139. {
  11140. // NOTE - we round robin not just because it's more efficient, but because it ensures the preservation of grouping information
  11141. const void *ret;
  11142. bool fetched = pullers.item(nextPuller).peek(ret, anyActive);
  11143. if (fetched)
  11144. {
  11145. inGroup = (ret != NULL);
  11146. return ret;
  11147. }
  11148. if (inGroup && grouped)
  11149. {
  11150. // Some other puller has data, but we can't consume it until the group we are reading is complete.
  11151. readyPending++;
  11152. anyActive = true;
  11153. break;
  11154. }
  11155. nextPuller++;
  11156. if (nextPuller==pullers.ordinality())
  11157. nextPuller = 0;
  11158. }
  11159. if (!anyActive)
  11160. break;
  11161. // A ready signal without anything being ready means someone reached end-of-file.
  11162. }
  11163. eof = true;
  11164. return NULL;
  11165. }
  11166. };
  11167. class CRoxieServerOrderedConcatActivity : public CRoxieServerActivity
  11168. {
  11169. IRoxieInput *curInput;
  11170. bool eogSeen;
  11171. bool anyThisGroup;
  11172. bool grouped;
  11173. unsigned numInputs;
  11174. unsigned inputIdx;
  11175. IRoxieInput **inputArray;
  11176. public:
  11177. CRoxieServerOrderedConcatActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _grouped, unsigned _numInputs)
  11178. : CRoxieServerActivity(_factory, _probeManager)
  11179. {
  11180. eogSeen = false;
  11181. anyThisGroup = false;
  11182. grouped = _grouped;
  11183. numInputs = _numInputs;
  11184. inputIdx = 0;
  11185. inputArray = new IRoxieInput*[numInputs];
  11186. for (unsigned i = 0; i < numInputs; i++)
  11187. inputArray[i] = NULL;
  11188. }
  11189. ~CRoxieServerOrderedConcatActivity()
  11190. {
  11191. delete [] inputArray;
  11192. }
  11193. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11194. {
  11195. inputIdx = 0;
  11196. curInput = inputArray[inputIdx];
  11197. eogSeen = false;
  11198. anyThisGroup = false;
  11199. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  11200. for (unsigned i = 0; i < numInputs; i++)
  11201. inputArray[i]->start(parentExtractSize, parentExtract, paused);
  11202. }
  11203. virtual void stop(bool aborting)
  11204. {
  11205. for (unsigned i = 0; i < numInputs; i++)
  11206. inputArray[i]->stop(aborting);
  11207. CRoxieServerActivity::stop(aborting);
  11208. }
  11209. virtual unsigned __int64 queryLocalCycles() const
  11210. {
  11211. return 0;
  11212. }
  11213. virtual IRoxieInput *queryInput(unsigned idx) const
  11214. {
  11215. if (idx < numInputs)
  11216. return inputArray[idx];
  11217. else
  11218. return NULL;
  11219. }
  11220. virtual void reset()
  11221. {
  11222. CRoxieServerActivity::reset();
  11223. for (unsigned i = 0; i < numInputs; i++)
  11224. inputArray[i]->reset();
  11225. }
  11226. virtual void setInput(unsigned idx, IRoxieInput *_in)
  11227. {
  11228. inputArray[idx] = _in;
  11229. }
  11230. virtual const void * nextInGroup()
  11231. {
  11232. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  11233. if (!curInput)
  11234. return NULL; // eof
  11235. const void * next = curInput->nextInGroup();
  11236. if (next)
  11237. {
  11238. anyThisGroup = true;
  11239. eogSeen = false;
  11240. processed++;
  11241. return next;
  11242. }
  11243. else if (!eogSeen)
  11244. {
  11245. eogSeen = true;
  11246. if (grouped)
  11247. {
  11248. if (anyThisGroup)
  11249. {
  11250. anyThisGroup = false;
  11251. return NULL;
  11252. }
  11253. else
  11254. return nextInGroup();
  11255. }
  11256. else
  11257. return nextInGroup();
  11258. }
  11259. else if (inputIdx < numInputs-1)
  11260. {
  11261. inputIdx++;
  11262. curInput = inputArray[inputIdx];
  11263. eogSeen = false;
  11264. return nextInGroup();
  11265. }
  11266. else
  11267. {
  11268. curInput = NULL;
  11269. return NULL;
  11270. }
  11271. }
  11272. };
  11273. class CRoxieServerConcatActivityFactory : public CRoxieServerMultiInputFactory
  11274. {
  11275. bool ordered;
  11276. bool grouped;
  11277. public:
  11278. CRoxieServerConcatActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11279. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  11280. {
  11281. Owned <IHThorFunnelArg> helper = (IHThorFunnelArg *) helperFactory();
  11282. ordered = helper->isOrdered();
  11283. grouped = helper->queryOutputMeta()->isGrouped();
  11284. }
  11285. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  11286. {
  11287. if (ordered || (_probeManager && _probeManager->queryDebugManager()))
  11288. return new CRoxieServerOrderedConcatActivity(this, _probeManager, grouped, numInputs());
  11289. else
  11290. return new CRoxieServerThreadedConcatActivity(this, _probeManager, grouped, numInputs());
  11291. }
  11292. };
  11293. IRoxieServerActivityFactory *createRoxieServerConcatActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11294. {
  11295. return new CRoxieServerConcatActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  11296. }
  11297. //=================================================================================
  11298. class CRoxieServerNonEmptyActivity : public CRoxieServerMultiInputBaseActivity
  11299. {
  11300. IRoxieInput * selectedInput;
  11301. unsigned savedParentExtractSize;
  11302. const byte * savedParentExtract;
  11303. bool foundInput;
  11304. public:
  11305. CRoxieServerNonEmptyActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  11306. : CRoxieServerMultiInputBaseActivity(_factory, _probeManager, _numInputs)
  11307. {
  11308. foundInput = false;
  11309. selectedInput = NULL;
  11310. savedParentExtractSize = 0;;
  11311. savedParentExtract = NULL;
  11312. }
  11313. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11314. {
  11315. //Don't start the inputs yet so we can short-circuit...
  11316. CRoxieServerMultiInputBaseActivity::start(parentExtractSize, parentExtract, paused);
  11317. savedParentExtractSize = parentExtractSize;
  11318. savedParentExtract = parentExtract;
  11319. }
  11320. virtual void stop(bool aborting)
  11321. {
  11322. if (foundInput)
  11323. {
  11324. if (selectedInput)
  11325. selectedInput->stop(aborting);
  11326. }
  11327. else
  11328. {
  11329. for (unsigned i = 0; i < numInputs; i++)
  11330. inputArray[i]->stop(aborting);
  11331. }
  11332. CRoxieServerMultiInputBaseActivity::stop(aborting);
  11333. }
  11334. virtual void reset()
  11335. {
  11336. CRoxieServerMultiInputBaseActivity::reset();
  11337. foundInput = false;
  11338. selectedInput = NULL;
  11339. }
  11340. virtual unsigned __int64 queryLocalCycles() const
  11341. {
  11342. return 0; // Can't easily calcuate anything reliable but local processing is negligible
  11343. }
  11344. virtual const void * nextInGroup()
  11345. {
  11346. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  11347. if (!foundInput)
  11348. {
  11349. foundInput = true;
  11350. //If we get an exception in this loop then stop() will stop any started inputs
  11351. for (unsigned i=0; i < numInputs; i++)
  11352. {
  11353. selectedInput = inputArray[i];
  11354. selectedInput->start(savedParentExtractSize, savedParentExtract, false);
  11355. const void * next = selectedInput->nextInGroup();
  11356. if (next)
  11357. {
  11358. //Found a row so stop remaining
  11359. for (unsigned j=i+1; j < numInputs; j++)
  11360. inputArray[j]->stop(false);
  11361. processed++;
  11362. return next;
  11363. }
  11364. selectedInput->stop(false);
  11365. }
  11366. selectedInput = NULL;
  11367. return NULL;
  11368. }
  11369. if (!selectedInput)
  11370. return NULL;
  11371. const void * next = selectedInput->nextInGroup();
  11372. if (next)
  11373. processed++;
  11374. return next;
  11375. }
  11376. };
  11377. class CRoxieServerNonEmptyActivityFactory : public CRoxieServerMultiInputFactory
  11378. {
  11379. public:
  11380. CRoxieServerNonEmptyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11381. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  11382. {
  11383. }
  11384. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  11385. {
  11386. return new CRoxieServerNonEmptyActivity(this, _probeManager, numInputs());
  11387. }
  11388. };
  11389. IRoxieServerActivityFactory *createRoxieServerNonEmptyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11390. {
  11391. return new CRoxieServerNonEmptyActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  11392. }
  11393. //=================================================================================
  11394. class CRoxieServerMergeActivity : public CRoxieServerActivity
  11395. {
  11396. IHThorMergeArg &helper;
  11397. unsigned *mergeheap;
  11398. unsigned activeInputs;
  11399. unsigned numInputs;
  11400. IRoxieInput **inputArray;
  11401. const void **pending;
  11402. bool first;
  11403. ICompare *compare;
  11404. bool dedup;
  11405. void permute()
  11406. {
  11407. assertex(activeInputs == 0);
  11408. for(unsigned i = 0; i < numInputs; i++)
  11409. if(pullInput(i))
  11410. mergeheap[activeInputs++] = i;
  11411. // the tree structure: element p has children p*2+1 and p*2+2, or element c has parent (unsigned)(c-1)/2
  11412. // the heap property: no element should be smaller than its parent
  11413. // the dedup variant: if(dedup), the top of the heap should also not be equal to either child
  11414. // 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
  11415. if (activeInputs >= 2)
  11416. for(unsigned p = (activeInputs-2)/2; p > 0; --p)
  11417. siftDown(p);
  11418. if(dedup)
  11419. siftDownDedupTop();
  11420. else
  11421. siftDown(0);
  11422. }
  11423. void readNext()
  11424. {
  11425. if(!pullInput(mergeheap[0]))
  11426. if(!promote(0))
  11427. return;
  11428. // we have changed the element at the top of the heap, so need to sift it down to maintain the heap property
  11429. if(dedup)
  11430. siftDownDedupTop();
  11431. else
  11432. siftDown(0);
  11433. }
  11434. bool pullInput(unsigned i)
  11435. {
  11436. const void *next = inputArray[i]->nextInGroup();
  11437. if (!next)
  11438. next = inputArray[i]->nextInGroup();
  11439. pending[i] = next;
  11440. return (next != NULL);
  11441. }
  11442. bool promote(unsigned p)
  11443. {
  11444. activeInputs--;
  11445. if(activeInputs == p)
  11446. return false;
  11447. mergeheap[p] = mergeheap[activeInputs];
  11448. return true;
  11449. }
  11450. bool siftDown(unsigned p)
  11451. {
  11452. // assumimg that all descendents of p form a heap, sift p down to its correct position, and so include it in the heap
  11453. bool nochange = true;
  11454. while(1)
  11455. {
  11456. unsigned c = p*2 + 1;
  11457. if(c >= activeInputs)
  11458. return nochange;
  11459. if(c+1 < activeInputs)
  11460. {
  11461. int childcmp = BuffCompare(c+1, c);
  11462. if((childcmp < 0) || ((childcmp == 0) && (mergeheap[c+1] < mergeheap[c])))
  11463. ++c;
  11464. }
  11465. int cmp = BuffCompare(c, p);
  11466. if((cmp > 0) || ((cmp == 0) && (mergeheap[c] > mergeheap[p])))
  11467. return nochange;
  11468. nochange = false;
  11469. unsigned r = mergeheap[c];
  11470. mergeheap[c] = mergeheap[p];
  11471. mergeheap[p] = r;
  11472. p = c;
  11473. }
  11474. }
  11475. void siftDownDedupTop()
  11476. {
  11477. // same as siftDown(0), except that it also ensures that the top of the heap is not equal to either of its children
  11478. if(activeInputs < 2)
  11479. return;
  11480. unsigned c = 1;
  11481. int childcmp = 1;
  11482. if(activeInputs >= 3)
  11483. {
  11484. childcmp = BuffCompare(2, 1);
  11485. if(childcmp < 0)
  11486. c = 2;
  11487. }
  11488. int cmp = BuffCompare(c, 0);
  11489. if(cmp > 0)
  11490. return;
  11491. // the following loop ensures the correct property holds on the smaller branch, and that childcmp==0 iff the top matches the other branch
  11492. while(cmp <= 0)
  11493. {
  11494. if(cmp == 0)
  11495. {
  11496. if(mergeheap[c] < mergeheap[0])
  11497. {
  11498. unsigned r = mergeheap[c];
  11499. mergeheap[c] = mergeheap[0];
  11500. mergeheap[0] = r;
  11501. }
  11502. ReleaseClearRoxieRow(pending[mergeheap[c]]);
  11503. if(!pullInput(mergeheap[c]))
  11504. if(!promote(c))
  11505. break;
  11506. siftDown(c);
  11507. }
  11508. else
  11509. {
  11510. unsigned r = mergeheap[c];
  11511. mergeheap[c] = mergeheap[0];
  11512. mergeheap[0] = r;
  11513. if(siftDown(c))
  11514. break;
  11515. }
  11516. cmp = BuffCompare(c, 0);
  11517. }
  11518. // the following loop ensures the uniqueness property holds on the other branch too
  11519. c = 3-c;
  11520. if(activeInputs <= c)
  11521. return;
  11522. while(childcmp == 0)
  11523. {
  11524. if(mergeheap[c] < mergeheap[0])
  11525. {
  11526. unsigned r = mergeheap[c];
  11527. mergeheap[c] = mergeheap[0];
  11528. mergeheap[0] = r;
  11529. }
  11530. ReleaseClearRoxieRow(pending[mergeheap[c]]);
  11531. if(!pullInput(mergeheap[c]))
  11532. if(!promote(c))
  11533. break;
  11534. siftDown(c);
  11535. childcmp = BuffCompare(c, 0);
  11536. }
  11537. }
  11538. inline int BuffCompare(unsigned a, unsigned b)
  11539. {
  11540. return compare->docompare(pending[mergeheap[a]], pending[mergeheap[b]]);
  11541. }
  11542. public:
  11543. CRoxieServerMergeActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  11544. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorMergeArg &)basehelper), numInputs(_numInputs)
  11545. {
  11546. activeInputs = 0;
  11547. first = true;
  11548. mergeheap = new unsigned[numInputs];
  11549. inputArray = new IRoxieInput*[numInputs];
  11550. pending = new const void *[numInputs];
  11551. compare = helper.queryCompare();
  11552. dedup = helper.dedup();
  11553. for (unsigned i = 0; i < numInputs; i++)
  11554. {
  11555. inputArray[i] = NULL;
  11556. pending[i] = NULL;
  11557. }
  11558. }
  11559. ~CRoxieServerMergeActivity()
  11560. {
  11561. delete [] mergeheap;
  11562. delete [] inputArray;
  11563. delete [] pending;
  11564. }
  11565. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11566. {
  11567. activeInputs = 0;
  11568. first = true;
  11569. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  11570. for (unsigned i = 0; i < numInputs; i++)
  11571. {
  11572. inputArray[i]->start(parentExtractSize, parentExtract, paused);
  11573. }
  11574. }
  11575. virtual void stop(bool aborting)
  11576. {
  11577. for (unsigned i = 0; i < numInputs; i++)
  11578. {
  11579. inputArray[i]->stop(aborting);
  11580. }
  11581. CRoxieServerActivity::stop(aborting);
  11582. }
  11583. virtual void reset()
  11584. {
  11585. for (unsigned i = 0; i < numInputs; i++)
  11586. {
  11587. ReleaseClearRoxieRow(pending[i]);
  11588. inputArray[i]->reset();
  11589. }
  11590. CRoxieServerActivity::reset();
  11591. }
  11592. virtual void setInput(unsigned idx, IRoxieInput *_in)
  11593. {
  11594. inputArray[idx] = _in;
  11595. }
  11596. virtual const void * nextInGroup()
  11597. {
  11598. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  11599. if (first)
  11600. {
  11601. permute();
  11602. first = false;
  11603. }
  11604. if (activeInputs)
  11605. {
  11606. const void *next = pending[mergeheap[0]];
  11607. readNext();
  11608. if (next)
  11609. processed++;
  11610. return next;
  11611. }
  11612. else
  11613. return NULL;
  11614. }
  11615. };
  11616. class CRoxieServerMergeActivityFactory : public CRoxieServerMultiInputFactory
  11617. {
  11618. public:
  11619. CRoxieServerMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11620. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  11621. {
  11622. }
  11623. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  11624. {
  11625. return new CRoxieServerMergeActivity(this, _probeManager, numInputs());
  11626. }
  11627. };
  11628. IRoxieServerActivityFactory *createRoxieServerMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11629. {
  11630. return new CRoxieServerMergeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  11631. }
  11632. //=================================================================================
  11633. class CRoxieServerRegroupActivity : public CRoxieServerMultiInputActivity
  11634. {
  11635. IHThorRegroupArg &helper;
  11636. unsigned inputIndex;
  11637. bool eof;
  11638. unsigned __int64 numProcessedLastGroup;
  11639. public:
  11640. CRoxieServerRegroupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  11641. : CRoxieServerMultiInputActivity(_factory, _probeManager, _numInputs), helper((IHThorRegroupArg &)basehelper)
  11642. {
  11643. inputIndex = 0;
  11644. eof = false;
  11645. numProcessedLastGroup = 0;
  11646. }
  11647. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11648. {
  11649. inputIndex = 0;
  11650. eof = false;
  11651. numProcessedLastGroup = processed;
  11652. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  11653. }
  11654. const void * nextFromInputs()
  11655. {
  11656. unsigned initialInput = inputIndex;
  11657. while (inputIndex < numInputs)
  11658. {
  11659. const void * next = inputArray[inputIndex]->nextInGroup();
  11660. if (next)
  11661. {
  11662. if ((inputIndex != initialInput) && (inputIndex != initialInput+1))
  11663. {
  11664. ReleaseRoxieRow(next);
  11665. throw MakeStringException(ROXIE_MISMATCH_GROUP_ERROR, "Mismatched groups supplied to Regroup (%d)", factory->queryId());
  11666. }
  11667. return next;
  11668. }
  11669. inputIndex++;
  11670. }
  11671. if ((initialInput != 0) && (initialInput+1 != numInputs))
  11672. throw MakeStringException(ROXIE_MISMATCH_GROUP_ERROR, "Mismatched groups supplied to Regroup (%d)", factory->queryId());
  11673. inputIndex = 0;
  11674. return NULL;
  11675. }
  11676. virtual const void * nextInGroup()
  11677. {
  11678. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  11679. if (eof)
  11680. return NULL;
  11681. const void * ret = nextFromInputs();
  11682. if (ret)
  11683. {
  11684. processed++;
  11685. return ret;
  11686. }
  11687. if (numProcessedLastGroup != processed)
  11688. {
  11689. numProcessedLastGroup = processed;
  11690. return NULL;
  11691. }
  11692. eof = true;
  11693. return NULL;
  11694. }
  11695. #if 0
  11696. virtual void setInput(unsigned idx, IRoxieInput *_in)
  11697. {
  11698. //MORE: RKC: Do we want to do this i) always ii) conditionally iii) never
  11699. if (idx)
  11700. {
  11701. puller.setown(new CRoxieServerReadAheadInput(0)); // MORE - cant ask context for parallelJoinPreload as context is not yet set up.
  11702. puller->setInput(0, _in);
  11703. CRoxieServerMultiInputActivity::setInput(idx, puller);
  11704. }
  11705. else
  11706. CRoxieServerMultiInputActivity::setInput(idx, _in);
  11707. }
  11708. #endif
  11709. };
  11710. class CRoxieServerRegroupActivityFactory : public CRoxieServerMultiInputFactory
  11711. {
  11712. public:
  11713. CRoxieServerRegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11714. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  11715. {
  11716. }
  11717. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  11718. {
  11719. return new CRoxieServerRegroupActivity(this, _probeManager, numInputs());
  11720. }
  11721. };
  11722. IRoxieServerActivityFactory *createRoxieServerRegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11723. {
  11724. return new CRoxieServerRegroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  11725. }
  11726. //=================================================================================
  11727. class CRoxieServerCombineActivity : public CRoxieServerMultiInputActivity
  11728. {
  11729. IHThorCombineArg &helper;
  11730. unsigned __int64 numProcessedLastGroup;
  11731. public:
  11732. CRoxieServerCombineActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  11733. : CRoxieServerMultiInputActivity(_factory, _probeManager, _numInputs), helper((IHThorCombineArg &)basehelper)
  11734. {
  11735. numProcessedLastGroup = 0;
  11736. }
  11737. ~CRoxieServerCombineActivity()
  11738. {
  11739. }
  11740. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11741. {
  11742. numProcessedLastGroup = processed;
  11743. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  11744. }
  11745. void nextInputs(ConstPointerArray & out)
  11746. {
  11747. for (unsigned i=0; i < numInputs; i++)
  11748. {
  11749. const void * next = inputArray[i]->nextInGroup();
  11750. if (next)
  11751. out.append(next);
  11752. }
  11753. }
  11754. virtual bool needsAllocator() const { return true; }
  11755. virtual const void * nextInGroup()
  11756. {
  11757. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  11758. loop
  11759. {
  11760. ConstPointerArray group;
  11761. nextInputs(group);
  11762. if ((group.ordinality() == 0) && (numProcessedLastGroup == processed))
  11763. nextInputs(group);
  11764. if (group.ordinality() == 0)
  11765. {
  11766. numProcessedLastGroup = processed;
  11767. return NULL;
  11768. }
  11769. else if (group.ordinality() != numInputs)
  11770. {
  11771. ReleaseRoxieRowSet(group);
  11772. throw MakeStringException(ROXIE_MISMATCH_GROUP_ERROR, "Mismatched group input for Combine Activity(%d)", factory->queryId());
  11773. }
  11774. try
  11775. {
  11776. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11777. size32_t outSize = helper.transform(rowBuilder, group.ordinality(), group.getArray());
  11778. ReleaseRoxieRowSet(group);
  11779. if (outSize)
  11780. {
  11781. processed++;
  11782. return rowBuilder.finalizeRowClear(outSize);
  11783. }
  11784. }
  11785. catch (IException *E)
  11786. {
  11787. ReleaseRoxieRowSet(group);
  11788. throw makeWrappedException(E);
  11789. }
  11790. }
  11791. }
  11792. };
  11793. class CRoxieServerCombineActivityFactory : public CRoxieServerMultiInputFactory
  11794. {
  11795. public:
  11796. CRoxieServerCombineActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11797. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  11798. {
  11799. }
  11800. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  11801. {
  11802. return new CRoxieServerCombineActivity(this, _probeManager, numInputs());
  11803. }
  11804. };
  11805. IRoxieServerActivityFactory *createRoxieServerCombineActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11806. {
  11807. return new CRoxieServerCombineActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  11808. }
  11809. //=================================================================================
  11810. class CRoxieServerCombineGroupActivity : public CRoxieServerTwoInputActivity
  11811. {
  11812. IHThorCombineGroupArg &helper;
  11813. unsigned __int64 numProcessedLastGroup;
  11814. public:
  11815. CRoxieServerCombineGroupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  11816. : CRoxieServerTwoInputActivity(_factory, _probeManager), helper((IHThorCombineGroupArg &)basehelper)
  11817. {
  11818. numProcessedLastGroup = 0;
  11819. }
  11820. ~CRoxieServerCombineGroupActivity()
  11821. {
  11822. }
  11823. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11824. {
  11825. numProcessedLastGroup = processed;
  11826. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  11827. }
  11828. virtual void setInput(unsigned idx, IRoxieInput *_in)
  11829. {
  11830. switch(idx)
  11831. {
  11832. case 0:
  11833. #if 0
  11834. //MORE: RKC: Do we want to do this i) always ii) conditionally iii) never
  11835. puller.setown(new CRoxieServerReadAheadInput(0)); // MORE - cant ask context for parallelJoinPreload as context is not yet set up.
  11836. puller->setInput(0, _in);
  11837. _in = puller;
  11838. #endif
  11839. input = _in;
  11840. break;
  11841. case 1:
  11842. input1 = _in;
  11843. break;
  11844. default:
  11845. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  11846. }
  11847. }
  11848. virtual IRoxieInput *queryOutput(unsigned idx)
  11849. {
  11850. if (idx==(unsigned)-1)
  11851. idx = 0;
  11852. return idx ? NULL : this;
  11853. }
  11854. virtual bool needsAllocator() const { return true; }
  11855. virtual const void * nextInGroup()
  11856. {
  11857. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  11858. loop
  11859. {
  11860. const void * left = input->nextInGroup();
  11861. if (!left && (numProcessedLastGroup == processed))
  11862. left = input->nextInGroup();
  11863. if (!left)
  11864. {
  11865. if (numProcessedLastGroup == processed)
  11866. {
  11867. const void * nextRight = input1->nextInGroup();
  11868. if (nextRight)
  11869. {
  11870. ReleaseRoxieRow(nextRight);
  11871. throw MakeStringException(ROXIE_MISSING_GROUP_ERROR, "Missing LEFT record for Combine Group (%d)", factory->queryId());
  11872. }
  11873. }
  11874. else
  11875. numProcessedLastGroup = processed;
  11876. return NULL;
  11877. }
  11878. ConstPointerArray group;
  11879. loop
  11880. {
  11881. const void * in = input1->nextInGroup();
  11882. if (!in)
  11883. break;
  11884. group.append(in);
  11885. }
  11886. if (group.ordinality() == 0)
  11887. {
  11888. ReleaseRoxieRow(left);
  11889. ReleaseRoxieRowSet(group);
  11890. throw MakeStringException(ROXIE_MISSING_GROUP_ERROR, "Missing RIGHT group for Combine Group (%d)", factory->queryId());
  11891. }
  11892. try
  11893. {
  11894. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11895. size32_t outSize = helper.transform(rowBuilder, left, group.ordinality(), (const void * *)group.getArray());
  11896. ReleaseRoxieRow(left);
  11897. ReleaseRoxieRowSet(group);
  11898. if (outSize)
  11899. {
  11900. processed++;
  11901. return rowBuilder.finalizeRowClear(outSize);
  11902. }
  11903. }
  11904. catch (IException *E)
  11905. {
  11906. ReleaseRoxieRow(left);
  11907. ReleaseRoxieRowSet(group);
  11908. throw makeWrappedException(E);
  11909. }
  11910. }
  11911. }
  11912. };
  11913. class CRoxieServerCombineGroupActivityFactory : public CRoxieServerActivityFactory
  11914. {
  11915. unsigned input2;
  11916. unsigned input2idx;
  11917. public:
  11918. CRoxieServerCombineGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11919. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  11920. {
  11921. input2 = 0;
  11922. input2idx = 0;
  11923. }
  11924. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  11925. {
  11926. return new CRoxieServerCombineGroupActivity(this, _probeManager);
  11927. }
  11928. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  11929. {
  11930. if (idx==1)
  11931. {
  11932. input2 = source;
  11933. input2idx = sourceidx;
  11934. }
  11935. else
  11936. CRoxieServerActivityFactory::setInput(idx, source, sourceidx);
  11937. }
  11938. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  11939. {
  11940. switch (idx)
  11941. {
  11942. case 1:
  11943. sourceidx = input2idx;
  11944. return input2;
  11945. case 0:
  11946. return CRoxieServerActivityFactory::getInput(idx, sourceidx);
  11947. default:
  11948. return (unsigned) -1;
  11949. }
  11950. }
  11951. virtual unsigned numInputs() const { return 2; }
  11952. };
  11953. IRoxieServerActivityFactory *createRoxieServerCombineGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11954. {
  11955. return new CRoxieServerCombineGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  11956. }
  11957. //=================================================================================
  11958. class CRoxieServerRollupGroupActivity : public CRoxieServerActivity
  11959. {
  11960. IHThorRollupGroupArg &helper;
  11961. bool eof;
  11962. public:
  11963. CRoxieServerRollupGroupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  11964. : CRoxieServerActivity(_factory, _probeManager),
  11965. helper((IHThorRollupGroupArg &)basehelper)
  11966. {
  11967. eof = false;
  11968. }
  11969. ~CRoxieServerRollupGroupActivity()
  11970. {
  11971. }
  11972. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11973. {
  11974. eof = false;
  11975. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  11976. }
  11977. virtual bool needsAllocator() const { return true; }
  11978. virtual const void * nextInGroup()
  11979. {
  11980. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  11981. if (eof)
  11982. return NULL;
  11983. loop
  11984. {
  11985. ConstPointerArray group;
  11986. loop
  11987. {
  11988. const void * in = input->nextInGroup();
  11989. if (!in)
  11990. break;
  11991. group.append(in);
  11992. }
  11993. if (group.ordinality() == 0)
  11994. {
  11995. eof = true;
  11996. return NULL;
  11997. }
  11998. try
  11999. {
  12000. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12001. size32_t outSize = helper.transform(rowBuilder, group.ordinality(), (const void * *)group.getArray());
  12002. ReleaseRoxieRowSet(group);
  12003. if (outSize)
  12004. {
  12005. processed++;
  12006. return rowBuilder.finalizeRowClear(outSize);
  12007. }
  12008. }
  12009. catch (IException * E)
  12010. {
  12011. ReleaseRoxieRowSet(group);
  12012. throw makeWrappedException(E);
  12013. }
  12014. }
  12015. }
  12016. };
  12017. class CRoxieServerRollupGroupActivityFactory : public CRoxieServerActivityFactory
  12018. {
  12019. public:
  12020. CRoxieServerRollupGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  12021. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  12022. {
  12023. }
  12024. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  12025. {
  12026. return new CRoxieServerRollupGroupActivity(this, _probeManager);
  12027. }
  12028. };
  12029. IRoxieServerActivityFactory *createRoxieServerRollupGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  12030. {
  12031. return new CRoxieServerRollupGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  12032. }
  12033. //=================================================================================
  12034. class CRoxieServerFilterProjectActivity : public CRoxieServerLateStartActivity
  12035. {
  12036. IHThorFilterProjectArg &helper;
  12037. unsigned numProcessedLastGroup;
  12038. unsigned __int64 recordCount;
  12039. public:
  12040. CRoxieServerFilterProjectActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  12041. : CRoxieServerLateStartActivity(_factory, _probeManager), helper((IHThorFilterProjectArg &)basehelper)
  12042. {
  12043. numProcessedLastGroup = 0;
  12044. recordCount = 0;
  12045. }
  12046. ~CRoxieServerFilterProjectActivity()
  12047. {
  12048. }
  12049. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12050. {
  12051. numProcessedLastGroup = 0;
  12052. recordCount = 0;
  12053. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  12054. lateStart(parentExtractSize, parentExtract, helper.canMatchAny()); //sets eof
  12055. }
  12056. virtual bool needsAllocator() const { return true; }
  12057. virtual const void * nextInGroup()
  12058. {
  12059. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  12060. if (eof)
  12061. return NULL;
  12062. loop
  12063. {
  12064. const void * in = input->nextInGroup();
  12065. if (!in)
  12066. {
  12067. recordCount = 0;
  12068. if (numProcessedLastGroup == processed)
  12069. in = input->nextInGroup();
  12070. if (!in)
  12071. {
  12072. numProcessedLastGroup = processed;
  12073. return NULL;
  12074. }
  12075. }
  12076. try
  12077. {
  12078. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12079. size32_t outSize = helper.transform(rowBuilder, in, ++recordCount);
  12080. ReleaseRoxieRow(in);
  12081. if (outSize)
  12082. {
  12083. processed++;
  12084. return rowBuilder.finalizeRowClear(outSize);
  12085. }
  12086. }
  12087. catch (IException *E)
  12088. {
  12089. throw makeWrappedException(E);
  12090. }
  12091. }
  12092. }
  12093. };
  12094. class CRoxieServerFilterProjectActivityFactory : public CRoxieServerActivityFactory
  12095. {
  12096. public:
  12097. CRoxieServerFilterProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  12098. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  12099. {
  12100. }
  12101. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  12102. {
  12103. return new CRoxieServerFilterProjectActivity(this, _probeManager);
  12104. }
  12105. };
  12106. IRoxieServerActivityFactory *createRoxieServerFilterProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  12107. {
  12108. return new CRoxieServerFilterProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  12109. }
  12110. //=================================================================================
  12111. class CRoxieServerProjectActivity : public CRoxieServerActivity
  12112. {
  12113. unsigned numProcessedLastGroup;
  12114. bool count;
  12115. unsigned __int64 recordCount;
  12116. public:
  12117. CRoxieServerProjectActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _count)
  12118. : CRoxieServerActivity(_factory, _probeManager),
  12119. count(_count)
  12120. {
  12121. numProcessedLastGroup = 0;
  12122. recordCount = 0;
  12123. }
  12124. ~CRoxieServerProjectActivity()
  12125. {
  12126. }
  12127. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12128. {
  12129. numProcessedLastGroup = 0;
  12130. recordCount = 0;
  12131. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  12132. }
  12133. virtual bool needsAllocator() const { return true; }
  12134. virtual const void * nextInGroup()
  12135. {
  12136. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  12137. loop
  12138. {
  12139. OwnedConstRoxieRow in = input->nextInGroup();
  12140. if (!in)
  12141. {
  12142. recordCount = 0;
  12143. if (numProcessedLastGroup == processed)
  12144. in.setown(input->nextInGroup());
  12145. if (!in)
  12146. {
  12147. numProcessedLastGroup = processed;
  12148. return NULL;
  12149. }
  12150. }
  12151. try
  12152. {
  12153. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12154. size32_t outSize;
  12155. if (count)
  12156. outSize = ((IHThorCountProjectArg &) basehelper).transform(rowBuilder, in, ++recordCount);
  12157. else
  12158. outSize = ((IHThorProjectArg &) basehelper).transform(rowBuilder, in);
  12159. if (outSize)
  12160. {
  12161. processed++;
  12162. return rowBuilder.finalizeRowClear(outSize);
  12163. }
  12164. }
  12165. catch (IException *E)
  12166. {
  12167. throw makeWrappedException(E);
  12168. }
  12169. }
  12170. }
  12171. };
  12172. class CRoxieServerProjectActivityFactory : public CRoxieServerActivityFactory
  12173. {
  12174. protected:
  12175. bool count;
  12176. public:
  12177. CRoxieServerProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  12178. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  12179. {
  12180. count = (_kind==TAKcountproject || _kind==TAKprefetchcountproject);
  12181. }
  12182. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  12183. {
  12184. return new CRoxieServerProjectActivity(this, _probeManager, count);
  12185. }
  12186. };
  12187. IRoxieServerActivityFactory *createRoxieServerProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  12188. {
  12189. return new CRoxieServerProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  12190. }
  12191. //=================================================================================
  12192. class CRoxieServerPrefetchProjectActivity : public CRoxieServerActivity, implements IRecordPullerCallback
  12193. {
  12194. unsigned numProcessedLastGroup;
  12195. bool count;
  12196. bool eof;
  12197. bool allPulled;
  12198. bool isThreaded;
  12199. unsigned preload;
  12200. unsigned __int64 recordCount;
  12201. IHThorPrefetchProjectArg &helper;
  12202. RecordPullerThread puller;
  12203. InterruptableSemaphore ready;
  12204. InterruptableSemaphore space;
  12205. class PrefetchInfo : public CInterface
  12206. {
  12207. public:
  12208. inline PrefetchInfo(IHThorPrefetchProjectArg &helper, const void *_in, unsigned __int64 _recordCount)
  12209. {
  12210. if (helper.preTransform(extract, _in, _recordCount))
  12211. {
  12212. in.setown(_in);
  12213. recordCount = _recordCount;
  12214. }
  12215. else
  12216. ReleaseRoxieRow(_in);
  12217. }
  12218. OwnedConstRoxieRow in;
  12219. unsigned __int64 recordCount;
  12220. rtlRowBuilder extract;
  12221. };
  12222. QueueOf<PrefetchInfo, true> pulled;
  12223. CriticalSection pulledCrit;
  12224. public:
  12225. CRoxieServerPrefetchProjectActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _count)
  12226. : CRoxieServerActivity(_factory, _probeManager),
  12227. helper((IHThorPrefetchProjectArg &) basehelper),
  12228. puller(false),
  12229. count(_count)
  12230. {
  12231. numProcessedLastGroup = 0;
  12232. recordCount = 0;
  12233. eof = false;
  12234. allPulled = false;
  12235. isThreaded = (helper.getFlags() & PPFparallel) != 0;
  12236. preload = 0;
  12237. }
  12238. ~CRoxieServerPrefetchProjectActivity()
  12239. {
  12240. while (pulled.ordinality())
  12241. ::Release(pulled.dequeue());
  12242. }
  12243. virtual void setInput(unsigned idx, IRoxieInput *_in)
  12244. {
  12245. if (idx)
  12246. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  12247. puller.setInput(this, _in);
  12248. }
  12249. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12250. {
  12251. numProcessedLastGroup = 0;
  12252. recordCount = 0;
  12253. eof = false;
  12254. allPulled = false;
  12255. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  12256. preload = helper.getLookahead();
  12257. if (!preload)
  12258. preload = ctx->prefetchProjectPreload();
  12259. space.reinit(preload);
  12260. ready.reinit();
  12261. puller.start(parentExtractSize, parentExtract, paused, preload, !isThreaded, ctx);
  12262. }
  12263. virtual void stop(bool aborting)
  12264. {
  12265. space.interrupt();
  12266. ready.interrupt();
  12267. CRoxieServerActivity::stop(aborting);
  12268. puller.stop(aborting);
  12269. }
  12270. virtual void reset()
  12271. {
  12272. CRoxieServerActivity::reset();
  12273. puller.reset();
  12274. allPulled = false;
  12275. while (pulled.ordinality())
  12276. ::Release(pulled.dequeue());
  12277. }
  12278. virtual PrefetchInfo *readNextRecord()
  12279. {
  12280. if (!isThreaded)
  12281. {
  12282. if (!allPulled) // This looks like it's thread unsafe but we are inside the if(!isThreaded) so should be ok
  12283. puller.pullRecords(1);
  12284. }
  12285. else
  12286. ready.wait();
  12287. CriticalBlock b(pulledCrit);
  12288. PrefetchInfo *ret = pulled.ordinality() ? pulled.dequeue() : NULL;
  12289. space.signal();
  12290. return ret;
  12291. }
  12292. virtual bool needsAllocator() const { return true; }
  12293. virtual const void * nextInGroup()
  12294. {
  12295. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  12296. if (eof)
  12297. return NULL;
  12298. loop
  12299. {
  12300. Owned<PrefetchInfo> in = readNextRecord();
  12301. if (!in)
  12302. {
  12303. recordCount = 0;
  12304. if (numProcessedLastGroup == processed)
  12305. in.setown(readNextRecord());
  12306. if (!in)
  12307. {
  12308. numProcessedLastGroup = processed;
  12309. eof = true;
  12310. return NULL;
  12311. }
  12312. }
  12313. try
  12314. {
  12315. if (in->in)
  12316. {
  12317. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12318. size32_t outSize;
  12319. IThorChildGraph *child = helper.queryChild();
  12320. Owned<IEclGraphResults> results;
  12321. if (child)
  12322. results.setown(child->evaluate(in->extract.size(), in->extract.getbytes()));
  12323. outSize = helper.transform(rowBuilder, in->in, results, in->recordCount);
  12324. if (outSize)
  12325. {
  12326. processed++;
  12327. return rowBuilder.finalizeRowClear(outSize);
  12328. }
  12329. }
  12330. }
  12331. catch (IException *E)
  12332. {
  12333. throw makeWrappedException(E);
  12334. }
  12335. }
  12336. }
  12337. // interface IExceptionHandler
  12338. virtual bool fireException(IException *e)
  12339. {
  12340. // called from puller thread on failure
  12341. ready.interrupt(LINK(e));
  12342. space.interrupt(e);
  12343. return true;
  12344. }
  12345. // interface IRecordPullerCallback
  12346. virtual void processRow(const void *row)
  12347. {
  12348. {
  12349. CriticalBlock b(pulledCrit);
  12350. pulled.enqueue(new PrefetchInfo(helper, row, ++recordCount));
  12351. }
  12352. if (isThreaded)
  12353. {
  12354. ready.signal();
  12355. space.wait();
  12356. }
  12357. }
  12358. virtual void processEOG()
  12359. {
  12360. {
  12361. CriticalBlock b(pulledCrit);
  12362. pulled.enqueue(NULL);
  12363. }
  12364. if (isThreaded)
  12365. {
  12366. ready.signal();
  12367. space.wait();
  12368. }
  12369. }
  12370. virtual void processGroup(const ConstPointerArray &rows)
  12371. {
  12372. throwUnexpected();
  12373. }
  12374. virtual void processDone()
  12375. {
  12376. CriticalBlock b(pulledCrit);
  12377. allPulled = true;
  12378. if (isThreaded)
  12379. ready.signal();
  12380. }
  12381. };
  12382. class CRoxieServerPrefetchProjectActivityFactory : public CRoxieServerProjectActivityFactory
  12383. {
  12384. public:
  12385. CRoxieServerPrefetchProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  12386. : CRoxieServerProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  12387. {
  12388. }
  12389. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  12390. {
  12391. return new CRoxieServerPrefetchProjectActivity(this, _probeManager, count);
  12392. }
  12393. };
  12394. extern IRoxieServerActivityFactory *createRoxieServerPrefetchProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  12395. {
  12396. return new CRoxieServerPrefetchProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  12397. }
  12398. //=================================================================================
  12399. class CPointerArrayRoxieInput : public CPseudoRoxieInput
  12400. {
  12401. public:
  12402. CPointerArrayRoxieInput()
  12403. {
  12404. rowset = NULL;
  12405. rowcount = 0;
  12406. curRow = 0;
  12407. }
  12408. void init(size32_t _rowcount, byte **_rowset)
  12409. {
  12410. rowset = _rowset;
  12411. rowcount = _rowcount;
  12412. curRow = 0;
  12413. }
  12414. virtual const void * nextInGroup()
  12415. {
  12416. if (curRow < rowcount)
  12417. {
  12418. const void * ret = rowset[curRow];
  12419. if (ret)
  12420. LinkRoxieRow(ret);
  12421. curRow++;
  12422. return ret;
  12423. }
  12424. return NULL;
  12425. }
  12426. protected:
  12427. byte **rowset;
  12428. size32_t rowcount;
  12429. size32_t curRow;
  12430. };
  12431. class CRoxieServerLoopActivity : public CRoxieServerActivity
  12432. {
  12433. protected:
  12434. IHThorLoopArg &helper;
  12435. ThorActivityKind activityKind;
  12436. unsigned maxIterations;
  12437. bool finishedLooping;
  12438. unsigned flags;
  12439. bool eof;
  12440. rtlRowBuilder loopExtractBuilder;
  12441. unsigned loopGraphId;
  12442. Linked<IOutputMetaData> counterMeta;
  12443. public:
  12444. CRoxieServerLoopActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _loopGraphId, IOutputMetaData * _counterMeta)
  12445. : CRoxieServerActivity(_factory, _probeManager),
  12446. helper((IHThorLoopArg &)basehelper), loopGraphId(_loopGraphId), counterMeta(_counterMeta)
  12447. {
  12448. eof = false;
  12449. finishedLooping = false;
  12450. activityKind = factory->getKind();
  12451. flags = helper.getFlags();
  12452. maxIterations = 0;
  12453. }
  12454. virtual bool needsAllocator() const { return true; }
  12455. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12456. {
  12457. eof = false;
  12458. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  12459. int iterations = (int) helper.numIterations();
  12460. maxIterations = (iterations >= 0) ? iterations : 0;
  12461. finishedLooping = ((activityKind == TAKloopcount) && (maxIterations == 0));
  12462. if ((flags & IHThorLoopArg::LFnewloopagain) && !helper.loopFirstTime())
  12463. finishedLooping = true;
  12464. loopExtractBuilder.clear();
  12465. helper.createParentExtract(loopExtractBuilder); // could possibly delay this until execution actually happens
  12466. }
  12467. virtual void stop(bool aborting)
  12468. {
  12469. CRoxieServerActivity::stop(aborting);
  12470. loopExtractBuilder.clear();
  12471. }
  12472. void createCounterResult(IRoxieServerChildGraph * graph, unsigned counter)
  12473. {
  12474. if (flags & IHThorLoopArg::LFcounter)
  12475. {
  12476. void * counterRow = ctx->queryRowManager().allocate(sizeof(thor_loop_counter_t), activityId);
  12477. *((thor_loop_counter_t *)counterRow) = counter;
  12478. RtlLinkedDatasetBuilder builder(rowAllocator);
  12479. builder.appendOwn(counterRow);
  12480. Owned<CGraphResult> counterResult = new CGraphResult(builder.getcount(), builder.linkrows());
  12481. graph->setInputResult(2, counterResult);
  12482. }
  12483. }
  12484. };
  12485. //=================================================================================
  12486. class CRoxieServerSequentialLoopActivity : public CRoxieServerLoopActivity
  12487. {
  12488. Owned<IActivityGraph> loopQuery;
  12489. Owned<IRoxieServerChildGraph> loopGraph;
  12490. IRoxieInput * curInput;
  12491. RtlLinkedDatasetBuilder *loopInputBuilder;
  12492. CPointerArrayRoxieInput arrayInput;
  12493. Linked<IRoxieInput> resultInput;
  12494. unsigned loopCounter;
  12495. public:
  12496. CRoxieServerSequentialLoopActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _loopGraphId, IOutputMetaData * _counterMeta)
  12497. : CRoxieServerLoopActivity(_factory, _probeManager, _loopGraphId, _counterMeta)
  12498. {
  12499. curInput = NULL;
  12500. loopCounter = 0;
  12501. loopInputBuilder = NULL;
  12502. }
  12503. virtual bool needsAllocator() const { return true; }
  12504. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  12505. {
  12506. CRoxieServerLoopActivity::onCreate(_ctx, _colocalParent);
  12507. loopQuery.set(_ctx->queryChildGraph(loopGraphId));
  12508. }
  12509. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12510. {
  12511. curInput = input;
  12512. loopCounter = 1;
  12513. CRoxieServerLoopActivity::start(parentExtractSize, parentExtract, paused);
  12514. //MORE: Not sure about this, should IRoxieServerChildGraph be combined with IActivityGraph?
  12515. loopGraph.set(loopQuery->queryLoopGraph());
  12516. loopInputBuilder = new RtlLinkedDatasetBuilder(rowAllocator);
  12517. }
  12518. virtual void stop(bool aborting)
  12519. {
  12520. delete loopInputBuilder;
  12521. loopInputBuilder = NULL;
  12522. CRoxieServerLoopActivity::stop(aborting);
  12523. }
  12524. virtual const void * nextInGroup()
  12525. {
  12526. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  12527. if (eof)
  12528. return NULL;
  12529. unsigned emptyIterations = 0;
  12530. loop
  12531. {
  12532. loop
  12533. {
  12534. const void * ret = curInput->nextInGroup();
  12535. if (!ret)
  12536. {
  12537. ret = curInput->nextInGroup(); // more cope with groups somehow....
  12538. if (!ret)
  12539. {
  12540. if (finishedLooping)
  12541. {
  12542. eof = true;
  12543. return NULL;
  12544. }
  12545. break;
  12546. }
  12547. }
  12548. if (finishedLooping ||
  12549. ((flags & IHThorLoopArg::LFfiltered) && !helper.sendToLoop(loopCounter, ret)))
  12550. {
  12551. processed++;
  12552. return ret;
  12553. }
  12554. loopInputBuilder->appendOwn(ret);
  12555. }
  12556. switch (activityKind)
  12557. {
  12558. case TAKloopdataset:
  12559. {
  12560. if (!(flags & IHThorLoopArg::LFnewloopagain))
  12561. {
  12562. if (!helper.loopAgain(loopCounter, loopInputBuilder->getcount(), (const void**) loopInputBuilder->queryrows()))
  12563. {
  12564. if (loopInputBuilder->getcount() == 0)
  12565. {
  12566. eof = true;
  12567. return NULL;
  12568. }
  12569. arrayInput.init(loopInputBuilder->getcount(), loopInputBuilder->linkrows());
  12570. // MORE - should builder be cleared here?
  12571. curInput = &arrayInput;
  12572. finishedLooping = true;
  12573. continue; // back to the input loop again
  12574. }
  12575. }
  12576. break;
  12577. }
  12578. case TAKlooprow:
  12579. if (!loopInputBuilder->getcount())
  12580. {
  12581. finishedLooping = true;
  12582. eof = true;
  12583. return NULL;
  12584. }
  12585. break;
  12586. }
  12587. if (loopInputBuilder->getcount())
  12588. emptyIterations = 0;
  12589. else
  12590. {
  12591. //note: any outputs which didn't go around the loop again, would return the record, reinitializing emptyIterations
  12592. emptyIterations++;
  12593. if (emptyIterations > maxEmptyLoopIterations)
  12594. throw MakeStringException(ROXIE_TOO_MANY_EMPTY_LOOP, "Executed LOOP with empty input and output %u times", emptyIterations);
  12595. if (emptyIterations % 32 == 0)
  12596. CTXLOG("Executing LOOP with empty input and output %u times", emptyIterations);
  12597. }
  12598. checkAbort();
  12599. try
  12600. {
  12601. Owned<IRoxieGraphResults> results = executeIteration(loopExtractBuilder.size(), loopExtractBuilder.getbytes(), loopCounter);
  12602. resultInput.setown(results->createIterator(0));
  12603. if (flags & IHThorLoopArg::LFnewloopagain)
  12604. {
  12605. Owned<IRoxieInput> againResult = results->createIterator(helper.loopAgainResult());
  12606. OwnedConstRoxieRow row = againResult->nextInGroup();
  12607. assertex(row);
  12608. //Result is a row which contains a single boolean field.
  12609. if (!((const bool *)row.get())[0])
  12610. finishedLooping = true;
  12611. }
  12612. }
  12613. catch (IException *E)
  12614. {
  12615. throw makeWrappedException(E);
  12616. }
  12617. curInput = resultInput.get();
  12618. loopCounter++;
  12619. if ((activityKind == TAKloopcount) && (loopCounter > maxIterations))
  12620. finishedLooping = true;
  12621. }
  12622. }
  12623. IRoxieGraphResults * executeIteration(unsigned parentExtractSize, const byte *parentExtract, unsigned counter)
  12624. {
  12625. try
  12626. {
  12627. loopGraph->beforeExecute();
  12628. Owned<IGraphResult> inputRowsResult = new CGraphResult(loopInputBuilder->getcount(), loopInputBuilder->linkrows());
  12629. loopInputBuilder->clear();
  12630. loopGraph->setInputResult(1, inputRowsResult);
  12631. createCounterResult(loopGraph, counter);
  12632. Owned<IRoxieGraphResults> ret = loopGraph->execute(parentExtractSize, parentExtract);
  12633. loopGraph->afterExecute();
  12634. return ret.getClear();
  12635. }
  12636. catch (...)
  12637. {
  12638. CTXLOG("Exception thrown in loop body - cleaning up");
  12639. loopGraph->afterExecute();
  12640. throw;
  12641. }
  12642. }
  12643. };
  12644. //=================================================================================
  12645. typedef SafeQueueOf<const void, true> SafeRowQueue;
  12646. class CRowQueuePseudoInput : public CPseudoRoxieInput
  12647. {
  12648. public:
  12649. CRowQueuePseudoInput(SafeRowQueue & _input) :
  12650. input(_input)
  12651. {
  12652. eof = false;
  12653. }
  12654. virtual const void * nextInGroup()
  12655. {
  12656. if (eof)
  12657. return NULL;
  12658. const void * ret = input.dequeue();
  12659. if (!ret)
  12660. eof = true;
  12661. return ret;
  12662. }
  12663. protected:
  12664. SafeRowQueue & input;
  12665. bool eof;
  12666. };
  12667. class CRoxieServerParallelLoopActivity;
  12668. class LoopFilterPseudoInput : public CIndirectRoxieInput
  12669. {
  12670. public:
  12671. LoopFilterPseudoInput(CRoxieServerParallelLoopActivity * _activity, IRoxieInput * _input, unsigned _counter) :
  12672. CIndirectRoxieInput(_input), activity(_activity), counter(_counter)
  12673. {
  12674. }
  12675. virtual const void * nextInGroup();
  12676. protected:
  12677. CRoxieServerParallelLoopActivity * activity;
  12678. unsigned counter;
  12679. };
  12680. class LoopExecutorThread : public RestartableThread
  12681. {
  12682. protected:
  12683. Owned<IRoxieInput> safeInput;
  12684. CRoxieServerParallelLoopActivity * activity;
  12685. bool eof;
  12686. CriticalSection crit;
  12687. unsigned flags;
  12688. SafeRowQueue tempResults[2];
  12689. unsigned savedParentExtractSize;
  12690. const byte * savedParentExtract;
  12691. IArrayOf<IActivityGraph> cachedGraphs;
  12692. IRoxieSlaveContext *ctx;
  12693. public:
  12694. LoopExecutorThread()
  12695. : RestartableThread("LoopExecutorThread")
  12696. {
  12697. activity = NULL;
  12698. eof = false;
  12699. flags = 0;
  12700. ctx = NULL;
  12701. savedParentExtract = NULL;
  12702. savedParentExtractSize = 0;
  12703. }
  12704. virtual IRoxieInput *queryInput(unsigned idx) const
  12705. {
  12706. return safeInput->queryInput(idx);
  12707. }
  12708. void setInput(CRoxieServerParallelLoopActivity * _activity, IRoxieInput *_input, unsigned _flags)
  12709. {
  12710. activity = _activity;
  12711. flags = _flags;
  12712. // 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.
  12713. safeInput.setown(new CSafeRoxieInput(_input));
  12714. }
  12715. IRoxieInput *queryInput() const
  12716. {
  12717. return safeInput;
  12718. }
  12719. void onCreate(IRoxieSlaveContext * _ctx);
  12720. void start(unsigned parentExtractSize, const byte *parentExtract, bool paused);
  12721. void stop(bool aborting);
  12722. void reset();
  12723. virtual int run();
  12724. protected:
  12725. void executeLoop();
  12726. void executeLoopInstance(unsigned counter, unsigned numIterations, IRoxieInput * input, SafeRowQueue * spillOutput);
  12727. IRoxieInput * createLoopIterationGraph(unsigned i, IRoxieInput * input, unsigned counter);
  12728. };
  12729. class CRoxieServerParallelLoopActivity : public CRoxieServerLoopActivity
  12730. {
  12731. friend class LoopFilterPseudoInput;
  12732. friend class LoopExecutorThread;
  12733. QueueOf<const void, true> ready;
  12734. CriticalSection helperCS;
  12735. CriticalSection cs;
  12736. size32_t sizeNumParallel;
  12737. rtlDataAttr listNumParallel;
  12738. unsigned defaultNumParallel;
  12739. LoopExecutorThread executor;
  12740. IProbeManager* probeManager;
  12741. CriticalSection canAccess;
  12742. CriticalSection scrit;
  12743. InterruptableSemaphore readySpace;
  12744. InterruptableSemaphore recordsReady;
  12745. protected:
  12746. bool includeInLoop(unsigned counter, const void * row)
  12747. {
  12748. CriticalBlock b(helperCS);
  12749. return helper.sendToLoop(counter, row);
  12750. }
  12751. public:
  12752. CRoxieServerParallelLoopActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _loopGraphId, IOutputMetaData * _counterMeta)
  12753. : CRoxieServerLoopActivity(_factory, _probeManager, _loopGraphId, _counterMeta),
  12754. readySpace(parallelLoopFlowLimit)
  12755. {
  12756. probeManager = _probeManager;
  12757. defaultNumParallel = 0;
  12758. }
  12759. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  12760. {
  12761. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  12762. executor.onCreate(_ctx);
  12763. }
  12764. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12765. {
  12766. CriticalBlock b(scrit); // can stop while still starting, if unlucky...
  12767. readySpace.reinit(parallelLoopFlowLimit);
  12768. recordsReady.reinit();
  12769. CRoxieServerLoopActivity::start(parentExtractSize, parentExtract, paused);
  12770. defaultNumParallel = helper.defaultParallelIterations();
  12771. if (!defaultNumParallel)
  12772. defaultNumParallel = DEFAULT_PARALLEL_LOOP_THREADS;
  12773. helper.numParallelIterations(sizeNumParallel, listNumParallel.refdata());
  12774. //MORE: If numIterations <= number of parallel iterations[1],
  12775. //then we don't need to create a separate thread to do the processing, and the results will also avoid
  12776. //being transferred via a queue
  12777. executor.start(parentExtractSize, parentExtract, paused);
  12778. }
  12779. virtual void setInput(unsigned idx, IRoxieInput *_in)
  12780. {
  12781. if (idx)
  12782. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  12783. executor.setInput(this, _in, flags);
  12784. }
  12785. virtual void stop(bool aborting)
  12786. {
  12787. CriticalBlock b(scrit); // can stop while still starting, if unlucky...
  12788. readySpace.interrupt();
  12789. recordsReady.interrupt();
  12790. executor.join(); // MORE - may not be needed given stop/reset split
  12791. CRoxieServerLoopActivity::stop(aborting);
  12792. }
  12793. virtual void reset()
  12794. {
  12795. while (ready.ordinality())
  12796. ReleaseRoxieRow(ready.dequeue());
  12797. executor.reset();
  12798. CRoxieServerActivity::reset();
  12799. }
  12800. virtual const void * nextInGroup()
  12801. {
  12802. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  12803. loop
  12804. {
  12805. if (eof)
  12806. return NULL;
  12807. recordsReady.wait();
  12808. CriticalBlock procedure(canAccess);
  12809. if (ready.ordinality())
  12810. {
  12811. const void *result = ready.dequeue();
  12812. readySpace.signal();
  12813. if (result)
  12814. processed++;
  12815. return result;
  12816. }
  12817. else
  12818. eof = true;
  12819. }
  12820. }
  12821. unsigned getNumParallel(unsigned iter)
  12822. {
  12823. if (iter * sizeof(unsigned) >= sizeNumParallel)
  12824. return defaultNumParallel;
  12825. return ((unsigned *)listNumParallel.getdata())[iter];
  12826. }
  12827. inline void enqueueResult(const void * row)
  12828. {
  12829. try
  12830. {
  12831. while(!readySpace.wait(1000))
  12832. {
  12833. CTXLOG("Blocked waiting for space in loop %p activity id: %d output queue: %d records in queue", this, queryId(), ready.ordinality());
  12834. }
  12835. }
  12836. catch (...)
  12837. {
  12838. ReleaseRoxieRow(row);
  12839. throw;
  12840. }
  12841. CriticalBlock b2(canAccess);
  12842. ready.enqueue(row);
  12843. recordsReady.signal();
  12844. }
  12845. inline void finishResults()
  12846. {
  12847. recordsReady.signal();
  12848. }
  12849. virtual bool fireException(IException *e)
  12850. {
  12851. readySpace.interrupt(LINK(e));
  12852. recordsReady.interrupt(e);
  12853. return true;
  12854. }
  12855. IActivityGraph * createChildGraphInstance()
  12856. {
  12857. return factory->createChildGraph(ctx, &helper, loopGraphId, this, probeManager, *this);
  12858. }
  12859. IActivityGraph * queryChildGraph()
  12860. {
  12861. return ctx->queryChildGraph(loopGraphId);
  12862. }
  12863. };
  12864. //=================================================================================
  12865. const void * LoopFilterPseudoInput::nextInGroup()
  12866. {
  12867. loop
  12868. {
  12869. const void * next = input->nextInGroup();
  12870. if (!next || activity->includeInLoop(counter, next))
  12871. return next;
  12872. activity->enqueueResult(next);
  12873. }
  12874. }
  12875. void LoopExecutorThread::onCreate(IRoxieSlaveContext * _ctx)
  12876. {
  12877. //Initialise the cached graph list with the child instance that will always be created. Other iterations will be created on demand.
  12878. ctx = _ctx;
  12879. cachedGraphs.append(*LINK(activity->queryChildGraph()));
  12880. }
  12881. void LoopExecutorThread::start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12882. {
  12883. savedParentExtractSize = parentExtractSize;
  12884. savedParentExtract = parentExtract;
  12885. eof = false;
  12886. StringBuffer logPrefix("[");
  12887. ctx->getLogPrefix(logPrefix).append("] ");
  12888. RestartableThread::start(logPrefix);
  12889. }
  12890. int LoopExecutorThread::run()
  12891. {
  12892. try
  12893. {
  12894. executeLoop();
  12895. }
  12896. catch (IException *e)
  12897. {
  12898. activity->fireException(e);
  12899. }
  12900. catch (...)
  12901. {
  12902. activity->fireException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unexpected exception caught in LoopExecutorThread::run"));
  12903. }
  12904. return 0;
  12905. }
  12906. void LoopExecutorThread::stop(bool aborting)
  12907. {
  12908. safeInput->stop(aborting);
  12909. RestartableThread::join();
  12910. }
  12911. void LoopExecutorThread::reset()
  12912. {
  12913. safeInput->reset();
  12914. }
  12915. void LoopExecutorThread::executeLoop()
  12916. {
  12917. unsigned iterations = 0;
  12918. unsigned counter = 0;
  12919. unsigned outputIndex = 0;
  12920. //Note, activities don't link inputs, so need to be careful that special inputs remain linked while the activity is executing.
  12921. loop
  12922. {
  12923. if (activity->activityKind == TAKloopcount)
  12924. {
  12925. if (counter == activity->maxIterations)
  12926. break;
  12927. }
  12928. else
  12929. {
  12930. //This condition isn't quite right because it needs to be whether the filtered
  12931. //input is empty. May be ok if we include that in the semantics,
  12932. if (tempResults[1-outputIndex].ordinality() == 0)
  12933. break;
  12934. }
  12935. unsigned numParallel = activity->getNumParallel(iterations);
  12936. Linked<IRoxieInput> curInput;
  12937. if (iterations == 0)
  12938. curInput.set(safeInput);
  12939. else
  12940. {
  12941. SafeRowQueue & inputQueue = tempResults[1-outputIndex];
  12942. inputQueue.enqueue(NULL);
  12943. curInput.setown(new CRowQueuePseudoInput(inputQueue));
  12944. }
  12945. SafeRowQueue * curOutput = NULL;
  12946. if (counter+numParallel > activity->maxIterations)
  12947. numParallel = activity->maxIterations - counter;
  12948. else if (counter+numParallel < activity->maxIterations)
  12949. curOutput = &tempResults[outputIndex];
  12950. executeLoopInstance(counter, numParallel, curInput, curOutput);
  12951. outputIndex = 1-outputIndex;
  12952. counter += numParallel;
  12953. iterations++;
  12954. }
  12955. //Check for TAKlooprow, where end of loop couldn't be determined ahead of time
  12956. SafeRowQueue & inputQueue = tempResults[1-outputIndex];
  12957. while (inputQueue.ordinality())
  12958. {
  12959. const void * next = inputQueue.dequeue();
  12960. activity->enqueueResult(next);
  12961. }
  12962. activity->finishResults();
  12963. }
  12964. void LoopExecutorThread::executeLoopInstance(unsigned counter, unsigned numIterations, IRoxieInput * input, SafeRowQueue * spillOutput)
  12965. {
  12966. IArrayOf<IRoxieInput> savedInputs; // activities don't link their inputs, so this list keeps filters alive.
  12967. Linked<IRoxieInput> curInput = input;
  12968. unsigned i;
  12969. for (i= 0; i != numIterations; i++)
  12970. {
  12971. unsigned thisCounter = counter+i+1;
  12972. IRoxieInput * filtered = curInput;
  12973. if (flags & IHThorLoopArg::LFfiltered)
  12974. {
  12975. filtered = new LoopFilterPseudoInput(activity, curInput, thisCounter);
  12976. savedInputs.append(*filtered);
  12977. }
  12978. //graph is kept, so new curInput will be guaranteed to exist
  12979. curInput.setown(createLoopIterationGraph(i, filtered, thisCounter));
  12980. }
  12981. try
  12982. {
  12983. curInput->start(savedParentExtractSize, savedParentExtract, false);
  12984. if (spillOutput)
  12985. {
  12986. loop
  12987. {
  12988. const void * next = curInput->nextInGroup();
  12989. if (!next)
  12990. break;
  12991. spillOutput->enqueue(next);
  12992. }
  12993. }
  12994. else
  12995. {
  12996. loop
  12997. {
  12998. const void * next = curInput->nextInGroup();
  12999. if (!next)
  13000. break;
  13001. activity->enqueueResult(next);
  13002. }
  13003. }
  13004. }
  13005. catch (IException *E)
  13006. {
  13007. ctx->notifyAbort(E);
  13008. for (i= 0; i != numIterations; i++)
  13009. {
  13010. cachedGraphs.item(i).queryLoopGraph()->afterExecute();
  13011. }
  13012. curInput->stop(true);
  13013. curInput->reset();
  13014. throw;
  13015. }
  13016. for (i= 0; i != numIterations; i++)
  13017. {
  13018. cachedGraphs.item(i).queryLoopGraph()->afterExecute();
  13019. }
  13020. curInput->stop(false);
  13021. curInput->reset();
  13022. }
  13023. IRoxieInput * LoopExecutorThread::createLoopIterationGraph(unsigned i, IRoxieInput * input, unsigned counter)
  13024. {
  13025. if (!cachedGraphs.isItem(i))
  13026. cachedGraphs.append(*activity->createChildGraphInstance());
  13027. Linked<IRoxieServerChildGraph> loopGraph = cachedGraphs.item(i).queryLoopGraph();
  13028. loopGraph->beforeExecute();
  13029. if (!loopGraph->querySetInputResult(1, input))
  13030. throwUnexpected(); // a loop which doesn't use the value from the previous iteration. Should probably handle even if daft.
  13031. activity->createCounterResult(loopGraph, counter);
  13032. return loopGraph->selectOutput(0);
  13033. }
  13034. //=================================================================================
  13035. class CCounterRowMetaData : public CInterface, implements IOutputMetaData
  13036. {
  13037. public:
  13038. IMPLEMENT_IINTERFACE
  13039. virtual size32_t getRecordSize(const void *) { return sizeof(thor_loop_counter_t); }
  13040. virtual size32_t getMinRecordSize() const { return sizeof(thor_loop_counter_t); }
  13041. virtual size32_t getFixedSize() const { return sizeof(thor_loop_counter_t); }
  13042. virtual void toXML(const byte * self, IXmlWriter & out) { }
  13043. virtual unsigned getVersion() const { return OUTPUTMETADATA_VERSION; }
  13044. virtual unsigned getMetaFlags() { return 0; }
  13045. virtual void destruct(byte * self) {}
  13046. virtual IOutputRowSerializer * createDiskSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  13047. virtual IOutputRowDeserializer * createDiskDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  13048. virtual ISourceRowPrefetcher * createDiskPrefetcher(ICodeContext * ctx, unsigned activityId) { return NULL; }
  13049. virtual IOutputMetaData * querySerializedDiskMeta() { return this; }
  13050. virtual IOutputRowSerializer * createInternalSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  13051. virtual IOutputRowDeserializer * createInternalDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  13052. virtual void walkIndirectMembers(const byte * self, IIndirectMemberVisitor & visitor) {}
  13053. virtual IOutputMetaData * queryChildMeta(unsigned i) { return NULL; }
  13054. };
  13055. class CRoxieServerLoopActivityFactory : public CRoxieServerActivityFactory
  13056. {
  13057. unsigned loopGraphId;
  13058. unsigned flags;
  13059. Linked<IOutputMetaData> counterMeta;
  13060. public:
  13061. CRoxieServerLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _loopGraphId)
  13062. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), loopGraphId(_loopGraphId)
  13063. {
  13064. Owned<IHThorLoopArg> helper = (IHThorLoopArg *) helperFactory();
  13065. flags = helper->getFlags();
  13066. counterMeta.setown(new CCounterRowMetaData);
  13067. }
  13068. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  13069. {
  13070. if (flags & IHThorLoopArg::LFparallel)
  13071. return new CRoxieServerParallelLoopActivity(this, _probeManager, loopGraphId, counterMeta);
  13072. else
  13073. return new CRoxieServerSequentialLoopActivity(this, _probeManager, loopGraphId, counterMeta);
  13074. }
  13075. };
  13076. IRoxieServerActivityFactory *createRoxieServerLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _loopGraphId)
  13077. {
  13078. return new CRoxieServerLoopActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _loopGraphId);
  13079. }
  13080. //=================================================================================
  13081. class CRoxieServerGraphLoopActivity : public CRoxieServerActivity
  13082. {
  13083. protected:
  13084. IHThorGraphLoopArg &helper;
  13085. unsigned maxIterations;
  13086. unsigned flags;
  13087. rtlRowBuilder GraphExtractBuilder;
  13088. unsigned loopGraphId;
  13089. Linked<IOutputMetaData> counterMeta;
  13090. public:
  13091. CRoxieServerGraphLoopActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _GraphGraphId, IOutputMetaData * _counterMeta)
  13092. : CRoxieServerActivity(_factory, _probeManager),
  13093. helper((IHThorGraphLoopArg &)basehelper), loopGraphId(_GraphGraphId), counterMeta(_counterMeta)
  13094. {
  13095. flags = helper.getFlags();
  13096. maxIterations = 0;
  13097. }
  13098. virtual bool needsAllocator() const { return true; }
  13099. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13100. {
  13101. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  13102. int iterations = (int) helper.numIterations();
  13103. maxIterations = (iterations >= 0) ? iterations : 0;
  13104. if (maxIterations > maxGraphLoopIterations)
  13105. throw MakeStringException(ROXIE_TOO_MANY_GRAPH_LOOP, "Attempt to execute graph %u times", maxIterations);
  13106. if (maxIterations != 0)
  13107. {
  13108. GraphExtractBuilder.clear();
  13109. helper.createParentExtract(GraphExtractBuilder);
  13110. }
  13111. }
  13112. virtual void stop(bool aborting)
  13113. {
  13114. CRoxieServerActivity::stop(aborting);
  13115. GraphExtractBuilder.clear();
  13116. }
  13117. void createCounterResult(IRoxieServerChildGraph * graph, unsigned counter)
  13118. {
  13119. if (flags & IHThorGraphLoopArg::GLFcounter)
  13120. {
  13121. void * counterRow = ctx->queryRowManager().allocate(sizeof(thor_loop_counter_t), activityId);
  13122. *((thor_loop_counter_t *)counterRow) = counter;
  13123. RtlLinkedDatasetBuilder builder(rowAllocator);
  13124. builder.appendOwn(counterRow);
  13125. Owned<CGraphResult> counterResult = new CGraphResult(builder.getcount(), builder.linkrows());
  13126. graph->setInputResult(0, counterResult);
  13127. }
  13128. }
  13129. };
  13130. //=================================================================================
  13131. class CRoxieServerSequentialGraphLoopActivity : public CRoxieServerGraphLoopActivity
  13132. {
  13133. Owned<IActivityGraph> GraphQuery;
  13134. Owned<IRoxieServerChildGraph> loopGraph;
  13135. Linked<IRoxieInput> resultInput;
  13136. bool evaluated;
  13137. public:
  13138. CRoxieServerSequentialGraphLoopActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _GraphGraphId, IOutputMetaData * _counterMeta)
  13139. : CRoxieServerGraphLoopActivity(_factory, _probeManager, _GraphGraphId, _counterMeta)
  13140. {
  13141. evaluated = false;
  13142. }
  13143. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  13144. {
  13145. CRoxieServerGraphLoopActivity::onCreate(_ctx, _colocalParent);
  13146. GraphQuery.set(_ctx->queryChildGraph(loopGraphId));
  13147. }
  13148. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13149. {
  13150. CRoxieServerGraphLoopActivity::start(parentExtractSize, parentExtract, paused);
  13151. //MORE: Not sure about this, should IRoxieServerChildGraph be combined with IActivityGraph?
  13152. loopGraph.set(GraphQuery->queryLoopGraph());
  13153. evaluated = false;
  13154. }
  13155. virtual void stop(bool aborting)
  13156. {
  13157. if (loopGraph)
  13158. loopGraph->clearGraphLoopResults();
  13159. CRoxieServerGraphLoopActivity::stop(aborting);
  13160. }
  13161. virtual const void * nextInGroup()
  13162. {
  13163. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  13164. if (!evaluated)
  13165. {
  13166. executeEntireGraph();
  13167. evaluated = true;
  13168. }
  13169. const void * ret = resultInput->nextInGroup();
  13170. if (ret)
  13171. processed++;
  13172. return ret;
  13173. }
  13174. void executeIteration(unsigned parentExtractSize, const byte *parentExtract, unsigned counter)
  13175. {
  13176. try
  13177. {
  13178. loopGraph->beforeExecute();
  13179. createCounterResult(loopGraph, counter);
  13180. loopGraph->executeGraphLoop(parentExtractSize, parentExtract);
  13181. loopGraph->afterExecute();
  13182. }
  13183. catch (...)
  13184. {
  13185. CTXLOG("Exception thrown in graph body - cleaning up");
  13186. loopGraph->afterExecute();
  13187. throw;
  13188. }
  13189. }
  13190. void createInitialGraphInput()
  13191. {
  13192. loopGraph->clearGraphLoopResults();
  13193. RtlLinkedDatasetBuilder builder(rowAllocator);
  13194. input->readAll(builder);
  13195. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  13196. loopGraph->setGraphLoopResult(0, result);
  13197. }
  13198. void executeEntireGraph()
  13199. {
  13200. createInitialGraphInput();
  13201. for (unsigned loopCounter=1; loopCounter <= maxIterations; loopCounter++)
  13202. {
  13203. executeIteration(GraphExtractBuilder.size(), GraphExtractBuilder.getbytes(), loopCounter);
  13204. }
  13205. resultInput.setown(loopGraph->getGraphLoopResult(maxIterations));
  13206. }
  13207. };
  13208. //=================================================================================
  13209. struct GraphOutputSplitterArg : public ccdserver_hqlhelper::CThorSplitArg
  13210. {
  13211. public:
  13212. virtual unsigned numBranches()
  13213. {
  13214. return 0;
  13215. }
  13216. virtual IOutputMetaData * queryOutputMeta()
  13217. {
  13218. return NULL;// get it from the parent..
  13219. }
  13220. };
  13221. extern "C" IHThorArg * createGraphOutputSplitter() { return new GraphOutputSplitterArg; }
  13222. class CGraphIterationInfo : public CInterface
  13223. {
  13224. private:
  13225. Owned<IRoxieServerActivityFactory> factory; // Note - before sourceAct, so destroyed last
  13226. unsigned sourceIdx;
  13227. Linked<IRoxieServerActivity> sourceAct;
  13228. Linked<IRoxieInput> sourceInput;
  13229. unsigned numUses;
  13230. unsigned iteration;
  13231. public:
  13232. CGraphIterationInfo(IRoxieServerActivity * _sourceAct, IRoxieInput *_input, unsigned _sourceIdx, unsigned _iteration)
  13233. : sourceAct(_sourceAct), sourceInput(_input), sourceIdx(_sourceIdx), iteration(_iteration)
  13234. {
  13235. numUses = 0;
  13236. }
  13237. inline void noteUsed()
  13238. {
  13239. numUses++;
  13240. }
  13241. void createSplitter(IRoxieSlaveContext *ctx, IProbeManager *probeManager)
  13242. {
  13243. if (numUses > 1)
  13244. {
  13245. factory.setown(createRoxieServerThroughSpillActivityFactory(sourceAct->queryFactory()->queryQueryFactory(), createGraphOutputSplitter, numUses));
  13246. IRoxieServerActivity *splitter = factory->createActivity(NULL);
  13247. splitter->onCreate(ctx, NULL);
  13248. IRoxieInput *input = sourceAct->queryOutput(sourceIdx);
  13249. if (probeManager)
  13250. {
  13251. IInputBase * inputBase = probeManager->createProbe(static_cast<IInputBase*>(input), sourceAct, splitter, sourceIdx, 0, iteration);
  13252. input = static_cast<IRoxieInput*>(inputBase);
  13253. // MORE - shouldn't this be added to probes?
  13254. }
  13255. sourceAct.setown(splitter);
  13256. sourceAct->setInput(0, input);
  13257. sourceIdx = 0;
  13258. sourceInput.clear();
  13259. }
  13260. }
  13261. IRoxieInput *connectOutput(IProbeManager *probeManager, IArrayOf<IRoxieInput> &probes, IRoxieServerActivity *targetAct, unsigned targetIdx)
  13262. {
  13263. // MORE - not really necessary to create splitters in separate pass, is it?
  13264. if (factory) // we created a splitter....
  13265. sourceInput.set(sourceAct->queryOutput(sourceIdx));
  13266. IRoxieInput *ret = sourceInput;
  13267. if (probeManager)
  13268. {
  13269. IInputBase *inputBase = probeManager->createProbe(ret, sourceAct, targetAct, sourceIdx, targetIdx, iteration);
  13270. ret = static_cast<IRoxieInput *>(inputBase);
  13271. probes.append(*LINK(ret));
  13272. }
  13273. if (factory) // we created a splitter....
  13274. sourceIdx++;
  13275. return ret;
  13276. }
  13277. };
  13278. class CRoxieServerParallelGraphLoopActivity : public CRoxieServerGraphLoopActivity, implements IRoxieServerLoopResultProcessor
  13279. {
  13280. Owned<IActivityGraph> childGraph;
  13281. IRoxieInput * resultInput;
  13282. CIArrayOf<CGraphIterationInfo> outputs;
  13283. IArrayOf<IRoxieServerChildGraph> iterationGraphs;
  13284. Owned<CExtractMapperInput> inputExtractMapper;
  13285. IProbeManager *probeManager;
  13286. unsigned createLoopCounter;
  13287. IArrayOf<IRoxieInput> probes;
  13288. public:
  13289. CRoxieServerParallelGraphLoopActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _GraphGraphId, IOutputMetaData * _counterMeta)
  13290. : CRoxieServerGraphLoopActivity(_factory, _probeManager, _GraphGraphId, _counterMeta), probeManager(_probeManager)
  13291. {
  13292. inputExtractMapper.setown(new CExtractMapperInput);
  13293. resultInput = NULL;
  13294. createLoopCounter = 0;
  13295. }
  13296. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  13297. {
  13298. CRoxieServerGraphLoopActivity::onCreate(_ctx, _colocalParent);
  13299. childGraph.set(_ctx->queryChildGraph(loopGraphId));
  13300. }
  13301. virtual void setInput(unsigned idx, IRoxieInput *_in)
  13302. {
  13303. //Input needs to be handled very carefully.....
  13304. //We don't want to call onStart on the input unless it is actually used, so don't use the base CRoxieServerActivity implementation.
  13305. //This activity's input needs to be started with (parentExtractSize, parentExtract), but the elements in the graph need to be started with the
  13306. //GraphExtractBuilder parent extract. So we need to wrap the input in a pseudo-input (inputExtractMapper) that passes through a different
  13307. //parentExtract. Something very similar will be needed for query library calls with streaming inputs when they are implemented.
  13308. assertex(idx == 0);
  13309. inputExtractMapper->setInput(_in);
  13310. }
  13311. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13312. {
  13313. CRoxieServerGraphLoopActivity::start(parentExtractSize, parentExtract, paused); // initialises GraphExtractBuilder
  13314. inputExtractMapper->setParentExtract(parentExtractSize, parentExtract);
  13315. createExpandedGraph(GraphExtractBuilder.size(), GraphExtractBuilder.getbytes(), probeManager);
  13316. resultInput->start(GraphExtractBuilder.size(), GraphExtractBuilder.getbytes(), paused);
  13317. }
  13318. virtual void stop(bool aborting)
  13319. {
  13320. if (resultInput)
  13321. resultInput->stop(aborting);
  13322. CRoxieServerGraphLoopActivity::stop(aborting);
  13323. }
  13324. virtual void reset()
  13325. {
  13326. if (resultInput)
  13327. resultInput->reset();
  13328. resultInput = NULL;
  13329. iterationGraphs.kill();
  13330. outputs.kill();
  13331. if (probeManager)
  13332. {
  13333. probeManager->deleteGraph(NULL, (IArrayOf<IInputBase>*)&probes);
  13334. probes.kill();
  13335. }
  13336. CRoxieServerGraphLoopActivity::reset();
  13337. }
  13338. virtual const void * nextInGroup()
  13339. {
  13340. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  13341. const void * ret = resultInput->nextInGroup();
  13342. if (ret)
  13343. processed++;
  13344. return ret;
  13345. }
  13346. void createExpandedGraph(unsigned parentExtractSize, const byte *parentExtract, IProbeManager *probeManager)
  13347. {
  13348. //result(0) is the input to the graph.
  13349. resultInput = inputExtractMapper;
  13350. outputs.append(* new CGraphIterationInfo(resultInput->queryActivity(), resultInput, 0, 1));
  13351. for (createLoopCounter=1; createLoopCounter <= maxIterations; createLoopCounter++)
  13352. {
  13353. IRoxieServerChildGraph * graph = childGraph->createGraphLoopInstance(createLoopCounter, parentExtractSize, parentExtract, *this);
  13354. graph->beforeExecute();
  13355. iterationGraphs.append(*graph);
  13356. graph->gatherIterationUsage(*this);
  13357. CGraphIterationInfo *iteration = graph->selectGraphLoopOutput();
  13358. outputs.append(*iteration);
  13359. }
  13360. createLoopCounter = 0;
  13361. createSplitters(probeManager);
  13362. ForEachItemIn(i2, iterationGraphs)
  13363. iterationGraphs.item(i2).associateIterationOutputs(*this);
  13364. resultInput = outputs.tos().connectOutput(probeManager, probes, this, 0);
  13365. }
  13366. void createSplitters(IProbeManager *probeManager)
  13367. {
  13368. ForEachItemIn(i, outputs)
  13369. {
  13370. CGraphIterationInfo & next = outputs.item(i);
  13371. next.createSplitter(ctx, probeManager);
  13372. }
  13373. }
  13374. //IRoxieServerLoopResultProcessor
  13375. virtual void noteUseIteration(unsigned _whichIteration)
  13376. {
  13377. int whichIteration = (int) _whichIteration; // May go negative - API is unsigned for historical reasons
  13378. if (whichIteration >= 0)
  13379. {
  13380. if (!outputs.isItem(whichIteration))
  13381. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Error reading graph result %d from iteration %d", whichIteration, createLoopCounter);
  13382. outputs.item(whichIteration).noteUsed();
  13383. }
  13384. }
  13385. virtual IRoxieInput * connectIterationOutput(unsigned whichIteration, IProbeManager *probeManager, IArrayOf<IRoxieInput> &probes, IRoxieServerActivity *targetAct, unsigned targetIdx)
  13386. {
  13387. if (outputs.isItem(whichIteration))
  13388. {
  13389. CGraphIterationInfo & next = outputs.item(whichIteration);
  13390. return next.connectOutput(probeManager, probes, targetAct, targetIdx);
  13391. }
  13392. return NULL;
  13393. }
  13394. };
  13395. //=================================================================================
  13396. class CRoxieServerGraphLoopActivityFactory : public CRoxieServerActivityFactory
  13397. {
  13398. unsigned loopGraphId;
  13399. unsigned flags;
  13400. Linked<IOutputMetaData> counterMeta;
  13401. public:
  13402. CRoxieServerGraphLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _loopGraphId)
  13403. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), loopGraphId(_loopGraphId)
  13404. {
  13405. Owned<IHThorGraphLoopArg> helper = (IHThorGraphLoopArg *) helperFactory();
  13406. flags = helper->getFlags();
  13407. counterMeta.setown(new CCounterRowMetaData);
  13408. }
  13409. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  13410. {
  13411. if (kind == TAKparallelgraphloop)
  13412. return new CRoxieServerParallelGraphLoopActivity(this, _probeManager, loopGraphId, counterMeta);
  13413. else
  13414. return new CRoxieServerSequentialGraphLoopActivity(this, _probeManager, loopGraphId, counterMeta);
  13415. }
  13416. };
  13417. IRoxieServerActivityFactory *createRoxieServerGraphLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _loopGraphId)
  13418. {
  13419. return new CRoxieServerGraphLoopActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _loopGraphId);
  13420. }
  13421. //=====================================================================================================
  13422. class CRoxieServerLibraryCallActivity : public CRoxieServerActivity
  13423. {
  13424. class OutputAdaptor : public CExtractMapperInput
  13425. {
  13426. bool stopped;
  13427. public:
  13428. CRoxieServerLibraryCallActivity *parent;
  13429. unsigned oid;
  13430. unsigned processed;
  13431. public:
  13432. IMPLEMENT_IINTERFACE;
  13433. OutputAdaptor() : CExtractMapperInput(NULL)
  13434. {
  13435. parent = NULL;
  13436. oid = 0;
  13437. init();
  13438. }
  13439. void init()
  13440. {
  13441. processed = 0;
  13442. stopped = false;
  13443. }
  13444. virtual unsigned queryId() const
  13445. {
  13446. return parent->queryId();
  13447. }
  13448. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13449. {
  13450. parent->start(oid, parentExtractSize, parentExtract, paused);
  13451. CExtractMapperInput::start(parentExtractSize, parentExtract, paused);
  13452. }
  13453. virtual void stop(bool aborting)
  13454. {
  13455. if (!stopped)
  13456. {
  13457. stopped = true;
  13458. parent->stop(oid, aborting); // parent code relies on stop being called exactly once per adaptor, so make sure it is!
  13459. CExtractMapperInput::stop(aborting);
  13460. }
  13461. };
  13462. virtual void reset()
  13463. {
  13464. parent->reset(oid, processed);
  13465. CExtractMapperInput::reset();
  13466. init();
  13467. };
  13468. virtual void checkAbort()
  13469. {
  13470. parent->checkAbort();
  13471. }
  13472. };
  13473. IHThorLibraryCallArg &helper;
  13474. unsigned numInputs;
  13475. unsigned numOutputs;
  13476. unsigned numActiveOutputs;
  13477. bool started;
  13478. OutputAdaptor* outputAdaptors;
  13479. CExtractMapperInput * * inputAdaptors;
  13480. bool * inputUsed;
  13481. bool * outputUsed;
  13482. Owned<IException> error;
  13483. CriticalSection crit;
  13484. rtlRowBuilder libraryExtractBuilder;
  13485. Owned<IActivityGraph> libraryGraph;
  13486. const LibraryCallFactoryExtra & extra;
  13487. public:
  13488. CRoxieServerLibraryCallActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs, unsigned _numOutputs, const LibraryCallFactoryExtra & _extra)
  13489. : CRoxieServerActivity(_factory, _probeManager),
  13490. helper((IHThorLibraryCallArg &)basehelper), extra(_extra)
  13491. {
  13492. numInputs = _numInputs;
  13493. numOutputs = _numOutputs;
  13494. numActiveOutputs = numOutputs;
  13495. inputAdaptors = new CExtractMapperInput*[numInputs];
  13496. inputUsed = new bool[numInputs];
  13497. for (unsigned i1 = 0; i1 < numInputs; i1++)
  13498. {
  13499. inputAdaptors[i1] = new CExtractMapperInput;
  13500. inputUsed[i1] = false;
  13501. }
  13502. outputAdaptors = new OutputAdaptor[numOutputs];
  13503. outputUsed = new bool[numOutputs];
  13504. for (unsigned i2 = 0; i2 < numOutputs; i2++)
  13505. {
  13506. outputAdaptors[i2].parent = this;
  13507. outputAdaptors[i2].oid = i2;
  13508. outputUsed[i2] = false;
  13509. }
  13510. started = false;
  13511. }
  13512. ~CRoxieServerLibraryCallActivity()
  13513. {
  13514. for (unsigned i1 = 0; i1 < numInputs; i1++)
  13515. ::Release(inputAdaptors[i1]);
  13516. delete [] inputAdaptors;
  13517. delete [] inputUsed;
  13518. delete [] outputAdaptors;
  13519. delete [] outputUsed;
  13520. }
  13521. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  13522. {
  13523. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  13524. libraryGraph.setown(_ctx->getLibraryGraph(extra, this));
  13525. libraryGraph->onCreate(_ctx, _colocalParent);
  13526. //Now map the inputs and outputs to the adapters
  13527. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  13528. for (unsigned i1=0; i1<numInputs; i1++)
  13529. inputUsed[i1] = graph->querySetInputResult(i1, inputAdaptors[i1]);
  13530. for (unsigned i2=0; i2<numOutputs; i2++)
  13531. {
  13532. unsigned outputIndex = extra.outputs.item(i2);
  13533. Owned<IRoxieInput> output = graph->selectOutput(numInputs+outputIndex);
  13534. outputAdaptors[i2].setInput(output);
  13535. }
  13536. }
  13537. virtual void start(unsigned oid, unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13538. {
  13539. CriticalBlock b(crit);
  13540. if (error)
  13541. throw error.getLink();
  13542. if (factory)
  13543. factory->noteStarted(oid);
  13544. if (!started)
  13545. {
  13546. // even though it is not complete, we don't want to run this again if it fails.
  13547. started = true;
  13548. //see notes on splitter above
  13549. try
  13550. {
  13551. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  13552. }
  13553. catch (IException *E)
  13554. {
  13555. #ifdef TRACE_SPLIT
  13556. CTXLOG("spill %d caught exception in start", activityId);
  13557. #endif
  13558. error.set(E);
  13559. throw;
  13560. }
  13561. catch (...)
  13562. {
  13563. IException *E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught in CRoxieServerLibraryCallActivity::start");
  13564. error.set(E);
  13565. throw E;
  13566. }
  13567. //recreate the parent extract, and use it to reinitialize the graphs...
  13568. libraryExtractBuilder.clear();
  13569. helper.createParentExtract(libraryExtractBuilder);
  13570. // 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
  13571. // some inputs before we see start on others.
  13572. for (unsigned i1 = 0; i1 < numInputs; i1++)
  13573. {
  13574. if (inputUsed[i1])
  13575. inputAdaptors[i1]->setParentExtract(parentExtractSize, parentExtract);
  13576. else
  13577. inputAdaptors[i1]->stop(false);
  13578. }
  13579. for (unsigned i2 = 0; i2 < numOutputs; i2++)
  13580. outputAdaptors[i2].setParentExtract(libraryExtractBuilder.size(), libraryExtractBuilder.getbytes());
  13581. //call stop on all the unused inputs.
  13582. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  13583. graph->beforeExecute();
  13584. ForEachItemIn(i3, extra.unusedOutputs)
  13585. {
  13586. Owned<IRoxieInput> output = graph->selectOutput(numInputs+extra.unusedOutputs.item(i3));
  13587. output->stop(false);
  13588. }
  13589. }
  13590. }
  13591. virtual void stop(unsigned oid, bool aborting)
  13592. {
  13593. CriticalBlock b(crit);
  13594. if (--numActiveOutputs == 0)
  13595. {
  13596. //call stop on all the unused inputs.
  13597. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  13598. graph->beforeExecute();
  13599. ForEachItemIn(i3, extra.unusedOutputs)
  13600. {
  13601. Owned<IRoxieInput> output = graph->selectOutput(numInputs+extra.unusedOutputs.item(i3));
  13602. output->stop(false);
  13603. }
  13604. CRoxieServerActivity::stop(aborting);
  13605. }
  13606. }
  13607. void reset(unsigned oid, unsigned _processed)
  13608. {
  13609. noteProcessed(oid, _processed, 0, 0);
  13610. started = false;
  13611. error.clear();
  13612. numActiveOutputs = numOutputs;
  13613. if (state != STATEreset) // make sure input is only reset once
  13614. {
  13615. CRoxieServerActivity::reset();
  13616. libraryGraph->reset();
  13617. //Call reset on all unused outputs from the graph - no one else will.
  13618. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  13619. ForEachItemIn(i3, extra.unusedOutputs)
  13620. {
  13621. Owned<IRoxieInput> output = graph->selectOutput(numInputs+extra.unusedOutputs.item(i3));
  13622. output->reset();
  13623. }
  13624. }
  13625. };
  13626. virtual void setInput(unsigned idx, IRoxieInput *_in)
  13627. {
  13628. inputAdaptors[idx]->setInput(_in);
  13629. }
  13630. public:
  13631. virtual const void *nextInGroup()
  13632. {
  13633. throwUnexpected(); // Internal logic error - we are not anybody's input
  13634. }
  13635. virtual IOutputMetaData * queryOutputMeta() const
  13636. {
  13637. throwUnexpected(); // should be called on outputs instead
  13638. }
  13639. virtual IRoxieInput *queryOutput(unsigned idx)
  13640. {
  13641. assertex(idx!=(unsigned)-1);
  13642. assertex(!outputUsed[idx]);
  13643. outputUsed[idx] = true;
  13644. return &outputAdaptors[idx];
  13645. }
  13646. };
  13647. void LibraryCallFactoryExtra::set(const LibraryCallFactoryExtra & _other)
  13648. {
  13649. ForEachItemIn(i1, _other.outputs)
  13650. outputs.append(_other.outputs.item(i1));
  13651. ForEachItemIn(i2, _other.unusedOutputs)
  13652. unusedOutputs.append(_other.unusedOutputs.item(i2));
  13653. maxOutputs = _other.maxOutputs;
  13654. graphid = _other.graphid;
  13655. libraryName.set(_other.libraryName);
  13656. interfaceHash = _other.interfaceHash;
  13657. embedded = _other.embedded;
  13658. }
  13659. void LibraryCallFactoryExtra::calcUnused()
  13660. {
  13661. for (unsigned i=0; i < maxOutputs; i++)
  13662. if (!outputs.contains(i))
  13663. unusedOutputs.append(i);
  13664. }
  13665. class CRoxieServerLibraryCallActivityFactory : public CRoxieServerMultiOutputFactory
  13666. {
  13667. private:
  13668. CRoxieServerMultiInputInfo inputs;
  13669. LibraryCallFactoryExtra extra;
  13670. public:
  13671. CRoxieServerLibraryCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, LibraryCallFactoryExtra & _extra)
  13672. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  13673. {
  13674. extra.set(_extra);
  13675. extra.calcUnused();
  13676. setNumOutputs(extra.outputs.ordinality());
  13677. }
  13678. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  13679. {
  13680. return new CRoxieServerLibraryCallActivity(this, _probeManager, numInputs(), numOutputs, extra);
  13681. }
  13682. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  13683. {
  13684. inputs.set(idx, source, sourceidx);
  13685. }
  13686. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  13687. {
  13688. return inputs.get(idx, sourceidx);
  13689. }
  13690. virtual unsigned numInputs() const { return inputs.ordinality(); }
  13691. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  13692. {
  13693. addXrefLibraryInfo(reply, extra.libraryName);
  13694. }
  13695. };
  13696. IRoxieServerActivityFactory *createRoxieServerLibraryCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, LibraryCallFactoryExtra & _extra)
  13697. {
  13698. return new CRoxieServerLibraryCallActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _extra);
  13699. }
  13700. //=====================================================================================================
  13701. class CRoxieServerNWayInputActivity : public CRoxieServerActivity
  13702. {
  13703. IHThorNWayInputArg & helper;
  13704. IRoxieInput ** inputs;
  13705. PointerArrayOf<IRoxieInput> selectedInputs;
  13706. unsigned numInputs;
  13707. public:
  13708. CRoxieServerNWayInputActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  13709. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorNWayInputArg &)basehelper), numInputs(_numInputs)
  13710. {
  13711. inputs = new IRoxieInput*[numInputs];
  13712. for (unsigned i = 0; i < numInputs; i++)
  13713. inputs[i] = NULL;
  13714. }
  13715. ~CRoxieServerNWayInputActivity()
  13716. {
  13717. delete [] inputs;
  13718. }
  13719. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13720. {
  13721. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  13722. bool selectionIsAll;
  13723. size32_t selectionLen;
  13724. rtlDataAttr selection;
  13725. helper.getInputSelection(selectionIsAll, selectionLen, selection.refdata());
  13726. selectedInputs.kill();
  13727. if (selectionIsAll)
  13728. {
  13729. for (unsigned i=0; i < numInputs; i++)
  13730. selectedInputs.append(inputs[i]);
  13731. }
  13732. else
  13733. {
  13734. const size32_t * selections = (const size32_t *)selection.getdata();
  13735. unsigned max = selectionLen/sizeof(size32_t);
  13736. for (unsigned i = 0; i < max; i++)
  13737. {
  13738. unsigned nextIndex = selections[i];
  13739. //Check there are no duplicates..... Assumes there are a fairly small number of inputs, so n^2 search is ok.
  13740. for (unsigned j=i+1; j < max; j++)
  13741. {
  13742. if (nextIndex == selections[j])
  13743. throw MakeStringException(ROXIE_NWAY_INPUT_ERROR, "Selection list for nway input can not contain duplicates");
  13744. }
  13745. if (nextIndex > numInputs)
  13746. throw MakeStringException(ROXIE_NWAY_INPUT_ERROR, "Index %d in RANGE selection list is out of range", nextIndex);
  13747. selectedInputs.append(inputs[nextIndex-1]);
  13748. }
  13749. }
  13750. ForEachItemIn(i2, selectedInputs)
  13751. selectedInputs.item(i2)->start(parentExtractSize, parentExtract, paused);
  13752. }
  13753. virtual void stop(bool aborting)
  13754. {
  13755. ForEachItemIn(i2, selectedInputs)
  13756. selectedInputs.item(i2)->stop(aborting);
  13757. CRoxieServerActivity::stop(aborting);
  13758. }
  13759. virtual unsigned __int64 queryLocalCycles() const
  13760. {
  13761. __int64 localCycles = totalCycles;
  13762. ForEachItemIn(i, selectedInputs)
  13763. {
  13764. localCycles -= selectedInputs.item(i)->queryTotalCycles();
  13765. }
  13766. if (localCycles < 0)
  13767. localCycles = 0;
  13768. return localCycles;
  13769. }
  13770. virtual IRoxieInput *queryInput(unsigned idx) const
  13771. {
  13772. if (selectedInputs.isItem(idx))
  13773. return selectedInputs.item(idx);
  13774. else
  13775. return NULL;
  13776. }
  13777. virtual void reset()
  13778. {
  13779. ForEachItemIn(i, selectedInputs)
  13780. selectedInputs.item(i)->reset();
  13781. selectedInputs.kill();
  13782. CRoxieServerActivity::reset();
  13783. }
  13784. virtual void setInput(unsigned idx, IRoxieInput *_in)
  13785. {
  13786. assertex(idx < numInputs);
  13787. inputs[idx] = _in;
  13788. }
  13789. virtual const void * nextInGroup()
  13790. {
  13791. throwUnexpected();
  13792. }
  13793. virtual unsigned numConcreteOutputs() const
  13794. {
  13795. return selectedInputs.ordinality();
  13796. }
  13797. virtual IRoxieInput * queryConcreteInput(unsigned idx)
  13798. {
  13799. if (selectedInputs.isItem(idx))
  13800. return selectedInputs.item(idx);
  13801. return NULL;
  13802. }
  13803. };
  13804. class CRoxieServerNWayInputActivityFactory : public CRoxieServerMultiInputFactory
  13805. {
  13806. // bool ordered;
  13807. public:
  13808. CRoxieServerNWayInputActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  13809. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  13810. {
  13811. }
  13812. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  13813. {
  13814. return new CRoxieServerNWayInputActivity(this, _probeManager, numInputs());
  13815. }
  13816. };
  13817. IRoxieServerActivityFactory *createRoxieServerNWayInputActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  13818. {
  13819. return new CRoxieServerNWayInputActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  13820. }
  13821. //=====================================================================================================
  13822. class CRoxieServerNWayGraphLoopResultReadActivity : public CRoxieServerActivity
  13823. {
  13824. IHThorNWayGraphLoopResultReadArg & helper;
  13825. CIArrayOf<CRoxieServerActivity> resultReaders;
  13826. PointerArrayOf<IRoxieInput> inputs;
  13827. unsigned graphId;
  13828. bool grouped;
  13829. bool selectionIsAll;
  13830. size32_t selectionLen;
  13831. rtlDataAttr selection;
  13832. public:
  13833. CRoxieServerNWayGraphLoopResultReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId)
  13834. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorNWayGraphLoopResultReadArg &)basehelper)
  13835. {
  13836. grouped = helper.isGrouped();
  13837. graphId = _graphId;
  13838. selectionIsAll = false;
  13839. }
  13840. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13841. {
  13842. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  13843. if (inputs.ordinality() == 0)
  13844. {
  13845. initInputSelection();
  13846. unsigned max = selectionLen / sizeof(size32_t);
  13847. const size32_t * selections = (const size32_t *)selection.getdata();
  13848. IProbeManager * probeManager = NULL; // MORE!!
  13849. for (unsigned i = 0; i < max; i++)
  13850. {
  13851. CRoxieServerActivity * resultInput = new CRoxieServerInternalGraphLoopResultReadActivity(factory, probeManager, graphId, selections[i]);
  13852. resultReaders.append(*resultInput);
  13853. inputs.append(resultInput->queryOutput(0));
  13854. resultInput->onCreate(ctx, colocalParent);
  13855. resultInput->start(parentExtractSize, parentExtract, paused);
  13856. }
  13857. }
  13858. else
  13859. {
  13860. ForEachItemIn(i, inputs)
  13861. inputs.item(i)->start(parentExtractSize, parentExtract, paused);
  13862. }
  13863. }
  13864. virtual void stop(bool aborting)
  13865. {
  13866. ForEachItemIn(i, inputs)
  13867. inputs.item(i)->stop(aborting);
  13868. CRoxieServerActivity::stop(aborting);
  13869. }
  13870. virtual void reset()
  13871. {
  13872. ForEachItemIn(i, inputs)
  13873. inputs.item(i)->reset();
  13874. inputs.kill();
  13875. resultReaders.kill();
  13876. CRoxieServerActivity::reset();
  13877. }
  13878. virtual void setInput(unsigned idx, IRoxieInput *_in)
  13879. {
  13880. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for nway graph result read");
  13881. }
  13882. virtual const void * nextInGroup()
  13883. {
  13884. throwUnexpected();
  13885. }
  13886. virtual unsigned numConcreteOutputs() const
  13887. {
  13888. return inputs.ordinality();
  13889. }
  13890. virtual IRoxieInput * queryConcreteInput(unsigned idx)
  13891. {
  13892. if (inputs.isItem(idx))
  13893. return inputs.item(idx);
  13894. return NULL;
  13895. }
  13896. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract)
  13897. {
  13898. ensureCreated();
  13899. basehelper.onStart(parentExtract, NULL);
  13900. initInputSelection();
  13901. unsigned max = selectionLen / sizeof(size32_t);
  13902. const size32_t * selections = (const size32_t *)selection.getdata();
  13903. for (unsigned i = 0; i < max; i++)
  13904. processor.noteUseIteration(selections[i]);
  13905. }
  13906. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract, IProbeManager *probeManager, IArrayOf<IRoxieInput> &probes)
  13907. {
  13908. //selection etc. already initialised from the gratherIterationUsage() call.
  13909. unsigned max = selectionLen / sizeof(size32_t);
  13910. const size32_t * selections = (const size32_t *)selection.getdata();
  13911. for (unsigned i = 0; i < max; i++)
  13912. inputs.append(processor.connectIterationOutput(selections[i], probeManager, probes, this, i));
  13913. }
  13914. protected:
  13915. void initInputSelection()
  13916. {
  13917. helper.getInputSelection(selectionIsAll, selectionLen, selection.refdata());
  13918. if (selectionIsAll)
  13919. throw MakeStringException(ROXIE_NWAY_INPUT_ERROR, "ALL not yet supported for NWay graph inputs");
  13920. }
  13921. };
  13922. class CRoxieServerNWayGraphLoopResultReadActivityFactory : public CRoxieServerActivityFactory
  13923. {
  13924. unsigned graphId;
  13925. public:
  13926. CRoxieServerNWayGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _graphId)
  13927. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), graphId(_graphId)
  13928. {
  13929. }
  13930. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  13931. {
  13932. return new CRoxieServerNWayGraphLoopResultReadActivity(this, _probeManager, graphId);
  13933. }
  13934. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  13935. {
  13936. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for NWay GraphLoopResultRead activity");
  13937. }
  13938. };
  13939. IRoxieServerActivityFactory *createRoxieServerNWayGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned graphId)
  13940. {
  13941. return new CRoxieServerNWayGraphLoopResultReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, graphId);
  13942. }
  13943. //=================================================================================
  13944. class RoxieSteppedInput : public CInterface, implements ISteppedInput
  13945. {
  13946. public:
  13947. RoxieSteppedInput(IRoxieInput * _input) { input = _input; }
  13948. IMPLEMENT_IINTERFACE
  13949. protected:
  13950. virtual const void * nextInputRow()
  13951. {
  13952. #ifdef TRACE_SEEK_REQUESTS
  13953. IRoxieContextLogger * logger = input->queryActivity();
  13954. const void * ret = doNextInputRow();
  13955. {
  13956. CommonXmlWriter xmlwrite(XWFtrim|XWFopt|XWFnoindent);
  13957. if (!ret)
  13958. xmlwrite.outputBool(true,"eof");
  13959. else if (input->queryOutputMeta()->hasXML())
  13960. input->queryOutputMeta()->toXML((byte *) ret, xmlwrite);
  13961. logger->CTXLOG("next() returns (%s)", xmlwrite.str());
  13962. }
  13963. return ret;
  13964. #else
  13965. return doNextInputRow();
  13966. #endif
  13967. }
  13968. virtual const void * nextInputRowGE(const void * seek, unsigned numFields, bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  13969. {
  13970. #ifdef TRACE_SEEK_REQUESTS
  13971. IRoxieContextLogger * logger = input->queryActivity();
  13972. {
  13973. CommonXmlWriter xmlwrite(XWFtrim|XWFopt|XWFnoindent);
  13974. if (input->queryOutputMeta()->hasXML())
  13975. input->queryOutputMeta()->toXML((byte *) seek, xmlwrite);
  13976. logger->CTXLOG("nextInputRowGE(%d, %s%s%s, %s) seek(%s)",
  13977. numFields,
  13978. stepExtra.readAheadManyResults() ? "readahead " : "",
  13979. stepExtra.returnMismatches() ? "mismatch" : "exact",
  13980. stepExtra.onlyReturnFirstSeekMatch() ? " single-match" : "",
  13981. stepExtra.queryExtraSeeks() ? "multi-seek":"",
  13982. xmlwrite.str());
  13983. }
  13984. const void * ret = doNextInputRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  13985. {
  13986. CommonXmlWriter xmlwrite(XWFtrim|XWFopt|XWFnoindent);
  13987. if (!ret)
  13988. xmlwrite.outputBool(true,"eof");
  13989. else if (input->queryOutputMeta()->hasXML())
  13990. input->queryOutputMeta()->toXML((byte *) ret, xmlwrite);
  13991. logger->CTXLOG("nextInputRowGE(%d, %s%s%s, %s) result(%s)",
  13992. numFields,
  13993. stepExtra.readAheadManyResults() ? "readahead " : "",
  13994. stepExtra.returnMismatches() ? "mismatch" : "exact",
  13995. stepExtra.onlyReturnFirstSeekMatch() ? " single-match" : "",
  13996. stepExtra.queryExtraSeeks() ? "multi-seek":"",
  13997. xmlwrite.str());
  13998. }
  13999. return ret;
  14000. #else
  14001. return doNextInputRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  14002. #endif
  14003. }
  14004. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  14005. {
  14006. return input->gatherConjunctions(collector);
  14007. }
  14008. virtual void resetEOF()
  14009. {
  14010. input->resetEOF();
  14011. }
  14012. virtual IInputSteppingMeta * queryInputSteppingMeta()
  14013. {
  14014. return input->querySteppingMeta();
  14015. }
  14016. inline const void * doNextInputRow()
  14017. {
  14018. const void * ret = input->nextInGroup();
  14019. if (!ret)
  14020. ret = input->nextInGroup();
  14021. return ret;
  14022. }
  14023. inline const void * doNextInputRowGE(const void * seek, unsigned numFields, bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  14024. {
  14025. assertex(wasCompleteMatch);
  14026. return input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  14027. }
  14028. protected:
  14029. IRoxieInput * input;
  14030. };
  14031. //=================================================================================
  14032. class CRoxieServerNaryActivity : public CRoxieServerMultiInputActivity
  14033. {
  14034. public:
  14035. CRoxieServerNaryActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14036. : CRoxieServerMultiInputActivity(_factory, _probeManager, _numInputs)
  14037. {
  14038. }
  14039. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14040. {
  14041. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  14042. for (unsigned i=0; i < numInputs; i++)
  14043. {
  14044. IRoxieInput * cur = inputArray[i];
  14045. unsigned numRealInputs = cur->numConcreteOutputs();
  14046. for (unsigned j = 0; j < numRealInputs; j++)
  14047. {
  14048. IRoxieInput * curReal = cur->queryConcreteInput(j);
  14049. expandedInputs.append(curReal);
  14050. }
  14051. }
  14052. }
  14053. virtual void reset()
  14054. {
  14055. expandedInputs.kill();
  14056. CRoxieServerMultiInputActivity::reset();
  14057. }
  14058. protected:
  14059. PointerArrayOf<IRoxieInput> expandedInputs;
  14060. };
  14061. //=================================================================================
  14062. class CRoxieStreamMerger : public CStreamMerger
  14063. {
  14064. public:
  14065. CRoxieStreamMerger() : CStreamMerger(true) {}
  14066. void initInputs(unsigned _numInputs, IRoxieInput ** _inputArray)
  14067. {
  14068. CStreamMerger::initInputs(_numInputs);
  14069. inputArray = _inputArray;
  14070. }
  14071. virtual bool pullInput(unsigned i, const void * seek, unsigned numFields, const SmartStepExtra * stepExtra)
  14072. {
  14073. const void * next;
  14074. bool matches = true;
  14075. if (seek)
  14076. next = inputArray[i]->nextSteppedGE(seek, numFields, matches, *stepExtra);
  14077. else
  14078. next = nextUngrouped(inputArray[i]);
  14079. pending[i] = next;
  14080. pendingMatches[i] = matches;
  14081. return (next != NULL);
  14082. }
  14083. virtual void releaseRow(const void * row)
  14084. {
  14085. ReleaseRoxieRow(row);
  14086. }
  14087. protected:
  14088. IRoxieInput **inputArray;
  14089. };
  14090. class CRoxieServerNWayMergeActivity : public CRoxieServerNaryActivity
  14091. {
  14092. public:
  14093. CRoxieServerNWayMergeActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14094. : CRoxieServerNaryActivity(_factory, _probeManager, _numInputs),
  14095. helper((IHThorNWayMergeArg &)basehelper)
  14096. {
  14097. initializedMeta = false;
  14098. }
  14099. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14100. {
  14101. CRoxieServerNaryActivity::start(parentExtractSize, parentExtract, paused);
  14102. merger.init(helper.queryCompare(), helper.dedup(), helper.querySteppingMeta()->queryCompare());
  14103. merger.initInputs(expandedInputs.length(), expandedInputs.getArray());
  14104. }
  14105. virtual void stop(bool aborting)
  14106. {
  14107. merger.done();
  14108. CRoxieServerNaryActivity::stop(aborting);
  14109. }
  14110. virtual void reset()
  14111. {
  14112. merger.cleanup();
  14113. CRoxieServerNaryActivity::reset();
  14114. initializedMeta = false;
  14115. }
  14116. virtual const void * nextInGroup()
  14117. {
  14118. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  14119. const void * next = merger.nextRow();
  14120. if (next)
  14121. processed++;
  14122. return next;
  14123. }
  14124. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  14125. {
  14126. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  14127. const void * next = merger.nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  14128. if (next)
  14129. processed++;
  14130. return next;
  14131. }
  14132. virtual IInputSteppingMeta * querySteppingMeta()
  14133. {
  14134. if (expandedInputs.ordinality() == 0)
  14135. return NULL;
  14136. if (!initializedMeta)
  14137. {
  14138. meta.init(helper.querySteppingMeta(), false);
  14139. ForEachItemIn(i, expandedInputs)
  14140. {
  14141. if (meta.getNumFields() == 0)
  14142. break;
  14143. IInputSteppingMeta * inputMeta = expandedInputs.item(i)->querySteppingMeta();
  14144. meta.intersect(inputMeta);
  14145. }
  14146. initializedMeta = true;
  14147. }
  14148. if (meta.getNumFields() == 0)
  14149. return NULL;
  14150. return &meta;
  14151. }
  14152. protected:
  14153. IHThorNWayMergeArg &helper;
  14154. CRoxieStreamMerger merger;
  14155. CSteppingMeta meta;
  14156. bool initializedMeta;
  14157. };
  14158. class CRoxieServerNWayMergeActivityFactory : public CRoxieServerMultiInputFactory
  14159. {
  14160. public:
  14161. CRoxieServerNWayMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14162. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  14163. {
  14164. }
  14165. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14166. {
  14167. return new CRoxieServerNWayMergeActivity(this, _probeManager, numInputs());
  14168. }
  14169. };
  14170. IRoxieServerActivityFactory *createRoxieServerNWayMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14171. {
  14172. return new CRoxieServerNWayMergeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  14173. }
  14174. //=================================================================================
  14175. class CRoxieServerNWayMergeJoinActivity : public CRoxieServerNaryActivity
  14176. {
  14177. public:
  14178. CRoxieServerNWayMergeJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs, CMergeJoinProcessor & _processor)
  14179. : CRoxieServerNaryActivity(_factory, _probeManager, _numInputs),processor(_processor),
  14180. helper((IHThorNWayMergeJoinArg &)basehelper)
  14181. {
  14182. }
  14183. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14184. {
  14185. CRoxieServerNaryActivity::start(parentExtractSize, parentExtract, paused);
  14186. ForEachItemIn(i1, expandedInputs)
  14187. {
  14188. IRoxieInput * cur = expandedInputs.item(i1);
  14189. Owned<RoxieSteppedInput> stepInput = new RoxieSteppedInput(cur);
  14190. processor.addInput(stepInput);
  14191. }
  14192. ICodeContext * codectx = ctx->queryCodeContext();
  14193. Owned<IEngineRowAllocator> inputAllocator = codectx->getRowAllocator(helper.queryInputMeta(), activityId);
  14194. Owned<IEngineRowAllocator> outputAllocator = codectx->getRowAllocator(helper.queryOutputMeta(), activityId);
  14195. processor.beforeProcessing(inputAllocator, outputAllocator);
  14196. }
  14197. virtual void stop(bool aborting)
  14198. {
  14199. processor.afterProcessing();
  14200. CRoxieServerNaryActivity::stop(aborting);
  14201. }
  14202. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  14203. {
  14204. return processor.gatherConjunctions(collector);
  14205. }
  14206. virtual void resetEOF()
  14207. {
  14208. processor.queryResetEOF();
  14209. }
  14210. virtual const void * nextInGroup()
  14211. {
  14212. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  14213. const void * next = processor.nextInGroup();
  14214. if (next)
  14215. processed++;
  14216. return next;
  14217. }
  14218. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  14219. {
  14220. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  14221. const void * next = processor.nextGE(seek, numFields, wasCompleteMatch, stepExtra);
  14222. if (next)
  14223. processed++;
  14224. return next;
  14225. }
  14226. virtual IInputSteppingMeta * querySteppingMeta()
  14227. {
  14228. return processor.queryInputSteppingMeta();
  14229. }
  14230. protected:
  14231. IHThorNWayMergeJoinArg & helper;
  14232. CMergeJoinProcessor & processor;
  14233. };
  14234. class CRoxieServerAndMergeJoinActivity : public CRoxieServerNWayMergeJoinActivity
  14235. {
  14236. public:
  14237. CRoxieServerAndMergeJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14238. : CRoxieServerNWayMergeJoinActivity(_factory, _probeManager, _numInputs, andProcessor), andProcessor(helper)
  14239. {
  14240. }
  14241. protected:
  14242. CAndMergeJoinProcessor andProcessor;
  14243. };
  14244. class CRoxieServerAndLeftMergeJoinActivity : public CRoxieServerNWayMergeJoinActivity
  14245. {
  14246. public:
  14247. CRoxieServerAndLeftMergeJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14248. : CRoxieServerNWayMergeJoinActivity(_factory, _probeManager, _numInputs, andLeftProcessor), andLeftProcessor(helper)
  14249. {
  14250. }
  14251. protected:
  14252. CAndLeftMergeJoinProcessor andLeftProcessor;
  14253. };
  14254. class CRoxieServerMofNMergeJoinActivity : public CRoxieServerNWayMergeJoinActivity
  14255. {
  14256. public:
  14257. CRoxieServerMofNMergeJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14258. : CRoxieServerNWayMergeJoinActivity(_factory, _probeManager, _numInputs, mofnProcessor), mofnProcessor(helper)
  14259. {
  14260. }
  14261. protected:
  14262. CMofNMergeJoinProcessor mofnProcessor;
  14263. };
  14264. class CRoxieServerProximityJoinActivity : public CRoxieServerNWayMergeJoinActivity
  14265. {
  14266. public:
  14267. CRoxieServerProximityJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14268. : CRoxieServerNWayMergeJoinActivity(_factory, _probeManager, _numInputs, proximityProcessor), proximityProcessor(helper)
  14269. {
  14270. }
  14271. protected:
  14272. CProximityJoinProcessor proximityProcessor;
  14273. };
  14274. class CRoxieServerNWayMergeJoinActivityFactory : public CRoxieServerMultiInputFactory
  14275. {
  14276. unsigned flags;
  14277. public:
  14278. CRoxieServerNWayMergeJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14279. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  14280. {
  14281. Owned<IHThorNWayMergeJoinArg> helper = (IHThorNWayMergeJoinArg *) helperFactory();
  14282. flags = helper->getJoinFlags();
  14283. }
  14284. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14285. {
  14286. if (flags & IHThorNWayMergeJoinArg::MJFhasrange)
  14287. return new CRoxieServerProximityJoinActivity(this, _probeManager, numInputs());
  14288. switch (flags & IHThorNWayMergeJoinArg::MJFkindmask)
  14289. {
  14290. case IHThorNWayMergeJoinArg::MJFinner:
  14291. return new CRoxieServerAndMergeJoinActivity(this, _probeManager, numInputs());
  14292. case IHThorNWayMergeJoinArg::MJFleftonly:
  14293. case IHThorNWayMergeJoinArg::MJFleftouter:
  14294. return new CRoxieServerAndLeftMergeJoinActivity(this, _probeManager, numInputs());
  14295. case IHThorNWayMergeJoinArg::MJFmofn:
  14296. return new CRoxieServerMofNMergeJoinActivity(this, _probeManager, numInputs());
  14297. default:
  14298. throwUnexpected();
  14299. }
  14300. }
  14301. };
  14302. IRoxieServerActivityFactory *createRoxieServerNWayMergeJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14303. {
  14304. return new CRoxieServerNWayMergeJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  14305. }
  14306. //=================================================================================
  14307. class CRoxieServerNWaySelectActivity : public CRoxieServerMultiInputActivity
  14308. {
  14309. IHThorNWaySelectArg &helper;
  14310. public:
  14311. CRoxieServerNWaySelectActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14312. : CRoxieServerMultiInputActivity(_factory, _probeManager, _numInputs),
  14313. helper((IHThorNWaySelectArg &)basehelper)
  14314. {
  14315. }
  14316. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14317. {
  14318. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  14319. unsigned whichInput = helper.getInputIndex();
  14320. selectedInput = NULL;
  14321. if (whichInput--)
  14322. {
  14323. for (unsigned i=0; i < numInputs; i++)
  14324. {
  14325. IRoxieInput * cur = inputArray[i];
  14326. unsigned numRealInputs = cur->numConcreteOutputs();
  14327. if (whichInput < numRealInputs)
  14328. {
  14329. selectedInput = cur->queryConcreteInput(whichInput);
  14330. break;
  14331. }
  14332. whichInput -= numRealInputs;
  14333. }
  14334. }
  14335. }
  14336. virtual void reset()
  14337. {
  14338. selectedInput = NULL;
  14339. CRoxieServerMultiInputActivity::reset();
  14340. }
  14341. const void * nextInGroup()
  14342. {
  14343. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  14344. if (!selectedInput)
  14345. return NULL;
  14346. return selectedInput->nextInGroup();
  14347. }
  14348. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  14349. {
  14350. if (!selectedInput)
  14351. return false;
  14352. return selectedInput->gatherConjunctions(collector);
  14353. }
  14354. virtual void resetEOF()
  14355. {
  14356. if (selectedInput)
  14357. selectedInput->resetEOF();
  14358. }
  14359. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  14360. {
  14361. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  14362. if (!selectedInput)
  14363. return NULL;
  14364. return selectedInput->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  14365. }
  14366. IInputSteppingMeta * querySteppingMeta()
  14367. {
  14368. if (selectedInput)
  14369. return selectedInput->querySteppingMeta();
  14370. return NULL;
  14371. }
  14372. protected:
  14373. IRoxieInput * selectedInput;
  14374. };
  14375. class CRoxieServerNWaySelectActivityFactory : public CRoxieServerMultiInputFactory
  14376. {
  14377. public:
  14378. CRoxieServerNWaySelectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14379. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  14380. {
  14381. }
  14382. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14383. {
  14384. return new CRoxieServerNWaySelectActivity(this, _probeManager, numInputs());
  14385. }
  14386. };
  14387. IRoxieServerActivityFactory *createRoxieServerNWaySelectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14388. {
  14389. return new CRoxieServerNWaySelectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  14390. }
  14391. //=================================================================================
  14392. class CRoxieServerRemoteActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler
  14393. {
  14394. protected:
  14395. IHThorRemoteArg &helper;
  14396. CRemoteResultAdaptor remote;
  14397. public:
  14398. CRoxieServerRemoteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteID)
  14399. : CRoxieServerActivity(_factory, _probeManager),
  14400. helper((IHThorRemoteArg &)basehelper),
  14401. remote(_remoteID, meta.queryOriginal(), helper, *this, false, false) // MORE - if they need it stable we'll have to think!
  14402. {
  14403. }
  14404. virtual const IResolvedFile *queryVarFileInfo() const
  14405. {
  14406. return NULL;
  14407. }
  14408. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  14409. {
  14410. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  14411. remote.onCreate(this, this, _ctx, _colocalParent);
  14412. }
  14413. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14414. {
  14415. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14416. remote.onStart(parentExtractSize, parentExtract);
  14417. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  14418. unsigned fileNo = 0; // MORE - superfiles require us to do this per file part... maybe (needs thought)
  14419. remote.getMem(0, fileNo, 0); // the cached context is all we need to send
  14420. remote.flush();
  14421. remote.senddone();
  14422. }
  14423. virtual void setInput(unsigned idx, IRoxieInput *_in)
  14424. {
  14425. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  14426. }
  14427. virtual IRoxieInput *queryOutput(unsigned idx)
  14428. {
  14429. if (idx==(unsigned)-1)
  14430. idx = 0;
  14431. return idx ? NULL: &remote;
  14432. }
  14433. virtual void reset()
  14434. {
  14435. processed = remote.processed;
  14436. remote.processed = 0;
  14437. CRoxieServerActivity::reset();
  14438. }
  14439. virtual void onLimitExceeded(bool isKeyed)
  14440. {
  14441. if (traceLevel > 4)
  14442. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  14443. helper.onLimitExceeded();
  14444. }
  14445. virtual const void *createLimitFailRow(bool isKeyed)
  14446. {
  14447. UNIMPLEMENTED; // MORE - is there an ONFAIL for a limit folded into a remote?
  14448. }
  14449. virtual const void *nextInGroup()
  14450. {
  14451. throwUnexpected(); // I am nobody's input
  14452. }
  14453. };
  14454. class CRoxieServerRemoteActivityFactory : public CRoxieServerActivityFactory
  14455. {
  14456. public:
  14457. RemoteActivityId remoteId;
  14458. bool isRoot;
  14459. CRoxieServerRemoteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, bool _isRoot)
  14460. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), remoteId(_remoteId), isRoot(_isRoot)
  14461. {
  14462. }
  14463. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14464. {
  14465. return new CRoxieServerRemoteActivity(this, _probeManager, remoteId);
  14466. }
  14467. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  14468. {
  14469. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  14470. }
  14471. virtual bool isSink() const
  14472. {
  14473. //I don't think the action version of this is implemented - but this would be the code
  14474. return isRoot && !meta.queryOriginal();
  14475. }
  14476. };
  14477. IRoxieServerActivityFactory *createRoxieServerRemoteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, bool _isRoot)
  14478. {
  14479. return new CRoxieServerRemoteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _isRoot);
  14480. }
  14481. //=================================================================================
  14482. class CRoxieServerIterateActivity : public CRoxieServerActivity
  14483. {
  14484. IHThorIterateArg &helper;
  14485. OwnedConstRoxieRow defaultRecord;
  14486. OwnedConstRoxieRow left;
  14487. OwnedConstRoxieRow right;
  14488. unsigned counter;
  14489. public:
  14490. CRoxieServerIterateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  14491. : CRoxieServerActivity(_factory, _probeManager),
  14492. helper((IHThorIterateArg &)basehelper)
  14493. {
  14494. counter = 0;
  14495. }
  14496. virtual bool needsAllocator() const { return true; }
  14497. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14498. {
  14499. counter = 0;
  14500. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14501. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  14502. size32_t thisSize = helper.createDefault(rowBuilder);
  14503. defaultRecord.setown(rowBuilder.finalizeRowClear(thisSize));
  14504. }
  14505. virtual void reset()
  14506. {
  14507. defaultRecord.clear();
  14508. right.clear();
  14509. left.clear();
  14510. CRoxieServerActivity::reset();
  14511. }
  14512. virtual const void * nextInGroup()
  14513. {
  14514. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  14515. loop
  14516. {
  14517. right.setown(input->nextInGroup());
  14518. if (!right)
  14519. {
  14520. bool skippedGroup = (left == NULL) && (counter > 0); //we have just skipped entire group, but shouldn't output a double null
  14521. left.clear();
  14522. counter = 0;
  14523. if (skippedGroup) continue;
  14524. return NULL;
  14525. }
  14526. try
  14527. {
  14528. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  14529. unsigned outSize = helper.transform(rowBuilder, left ? left : defaultRecord, right, ++counter);
  14530. if (outSize)
  14531. {
  14532. left.setown(rowBuilder.finalizeRowClear(outSize));
  14533. processed++;
  14534. return left.getLink();
  14535. }
  14536. }
  14537. catch (IException *E)
  14538. {
  14539. throw makeWrappedException(E);
  14540. }
  14541. }
  14542. }
  14543. };
  14544. class CRoxieServerIterateActivityFactory : public CRoxieServerActivityFactory
  14545. {
  14546. public:
  14547. CRoxieServerIterateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14548. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  14549. {
  14550. }
  14551. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14552. {
  14553. return new CRoxieServerIterateActivity(this, _probeManager);
  14554. }
  14555. };
  14556. IRoxieServerActivityFactory *createRoxieServerIterateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14557. {
  14558. return new CRoxieServerIterateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  14559. }
  14560. //=================================================================================
  14561. class CRoxieServerProcessActivity : public CRoxieServerActivity
  14562. {
  14563. IHThorProcessArg &helper;
  14564. OwnedConstRoxieRow curRight;
  14565. OwnedConstRoxieRow initialRight;
  14566. unsigned counter;
  14567. Owned<IEngineRowAllocator> rightRowAllocator;
  14568. public:
  14569. CRoxieServerProcessActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  14570. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorProcessArg &)basehelper)
  14571. {
  14572. counter = 0;
  14573. }
  14574. virtual bool needsAllocator() const { return true; }
  14575. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  14576. {
  14577. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  14578. rightRowAllocator.setown(ctx->queryCodeContext()->getRowAllocator(QUERYINTERFACE(helper.queryRightRecordSize(), IOutputMetaData), activityId));
  14579. }
  14580. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14581. {
  14582. counter = 0;
  14583. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14584. RtlDynamicRowBuilder rowBuilder(rightRowAllocator);
  14585. size32_t thisSize = helper.createInitialRight(rowBuilder);
  14586. initialRight.setown(rowBuilder.finalizeRowClear(thisSize));
  14587. curRight.set(initialRight);
  14588. }
  14589. virtual const void * nextInGroup()
  14590. {
  14591. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  14592. try
  14593. {
  14594. loop
  14595. {
  14596. const void * in = input->nextInGroup();
  14597. if (!in)
  14598. {
  14599. bool eog = (curRight != initialRight); // processed any records?
  14600. counter = 0;
  14601. curRight.set(initialRight);
  14602. if (eog)
  14603. return NULL;
  14604. in = input->nextInGroup();
  14605. if (!in)
  14606. return NULL;
  14607. }
  14608. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  14609. RtlDynamicRowBuilder rightRowBuilder(rightRowAllocator);
  14610. size32_t outSize = helper.transform(rowBuilder, rightRowBuilder, in, curRight, ++counter);
  14611. ReleaseRoxieRow(in);
  14612. if (outSize)
  14613. {
  14614. //MORE: This should be returned...
  14615. size32_t rightSize = rightRowAllocator->queryOutputMeta()->getRecordSize(rightRowBuilder.getSelf());
  14616. curRight.setown(rightRowBuilder.finalizeRowClear(rightSize));
  14617. processed++;
  14618. return rowBuilder.finalizeRowClear(outSize);
  14619. }
  14620. }
  14621. }
  14622. catch (IException *E)
  14623. {
  14624. throw makeWrappedException(E);
  14625. }
  14626. }
  14627. };
  14628. class CRoxieServerProcessActivityFactory : public CRoxieServerActivityFactory
  14629. {
  14630. public:
  14631. CRoxieServerProcessActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14632. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  14633. {
  14634. }
  14635. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14636. {
  14637. return new CRoxieServerProcessActivity(this, _probeManager);
  14638. }
  14639. };
  14640. IRoxieServerActivityFactory *createRoxieServerProcessActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14641. {
  14642. return new CRoxieServerProcessActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  14643. }
  14644. //=================================================================================
  14645. class CRoxieServerGroupActivity : public CRoxieServerActivity
  14646. {
  14647. IHThorGroupArg &helper;
  14648. bool endPending;
  14649. bool eof;
  14650. bool first;
  14651. const void *next;
  14652. public:
  14653. CRoxieServerGroupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  14654. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorGroupArg &)basehelper)
  14655. {
  14656. next = NULL;
  14657. endPending = false;
  14658. eof = false;
  14659. first = true;
  14660. }
  14661. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14662. {
  14663. endPending = false;
  14664. eof = false;
  14665. first = true;
  14666. assertex(next == NULL);
  14667. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14668. }
  14669. virtual void reset()
  14670. {
  14671. ReleaseClearRoxieRow(next);
  14672. CRoxieServerActivity::reset();
  14673. }
  14674. virtual const void * nextInGroup()
  14675. {
  14676. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  14677. if (first)
  14678. {
  14679. next = input->nextInGroup();
  14680. first = false;
  14681. }
  14682. if (eof || endPending)
  14683. {
  14684. endPending = false;
  14685. return NULL;
  14686. }
  14687. const void * prev = next;
  14688. next = input->nextInGroup();
  14689. if (!next)
  14690. next = input->nextInGroup();
  14691. if (next)
  14692. {
  14693. assertex(prev);
  14694. if (!helper.isSameGroup(prev, next))
  14695. endPending = true;
  14696. }
  14697. else
  14698. eof = true;
  14699. if (prev)
  14700. processed++;
  14701. return prev;
  14702. }
  14703. };
  14704. class CRoxieServerGroupActivityFactory : public CRoxieServerActivityFactory
  14705. {
  14706. public:
  14707. CRoxieServerGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14708. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  14709. {
  14710. }
  14711. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14712. {
  14713. return new CRoxieServerGroupActivity(this, _probeManager);
  14714. }
  14715. };
  14716. IRoxieServerActivityFactory *createRoxieServerGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14717. {
  14718. return new CRoxieServerGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  14719. }
  14720. //=================================================================================
  14721. class CRoxieServerFirstNActivity : public CRoxieServerLateStartActivity
  14722. {
  14723. unsigned __int64 limit;
  14724. unsigned __int64 skip;
  14725. unsigned doneThisGroup;
  14726. IHThorFirstNArg &helper;
  14727. public:
  14728. CRoxieServerFirstNActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  14729. : CRoxieServerLateStartActivity(_factory, _probeManager), helper((IHThorFirstNArg &)basehelper)
  14730. {
  14731. doneThisGroup = 0;
  14732. limit = 0;
  14733. skip = 0;
  14734. }
  14735. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14736. {
  14737. doneThisGroup = 0;
  14738. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  14739. limit = helper.getLimit();
  14740. skip = helper.numToSkip();
  14741. lateStart(parentExtractSize, parentExtract, limit > 0);
  14742. if (limit + skip >= limit)
  14743. limit += skip;
  14744. }
  14745. const void * nextInGroup()
  14746. {
  14747. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  14748. if (eof)
  14749. return NULL;
  14750. const void *ret;
  14751. loop
  14752. {
  14753. ret = input->nextInGroup();
  14754. if (!ret)
  14755. {
  14756. if (meta.isGrouped())
  14757. {
  14758. if (doneThisGroup > skip)
  14759. {
  14760. doneThisGroup = 0;
  14761. return NULL;
  14762. }
  14763. doneThisGroup = 0;
  14764. }
  14765. ret = input->nextInGroup();
  14766. if (!ret)
  14767. {
  14768. eof = true;
  14769. return NULL;
  14770. }
  14771. }
  14772. doneThisGroup++;
  14773. if (doneThisGroup > skip)
  14774. break;
  14775. ReleaseRoxieRow(ret);
  14776. }
  14777. if (doneThisGroup <= limit)
  14778. {
  14779. processed++;
  14780. return ret;
  14781. }
  14782. ReleaseRoxieRow(ret);
  14783. if (meta.isGrouped())
  14784. {
  14785. while ((ret = input->nextInGroup()) != NULL)
  14786. ReleaseRoxieRow(ret);
  14787. doneThisGroup = 0;
  14788. }
  14789. else
  14790. eof = true;
  14791. return NULL;
  14792. }
  14793. };
  14794. class CRoxieServerFirstNActivityFactory : public CRoxieServerActivityFactory
  14795. {
  14796. public:
  14797. CRoxieServerFirstNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14798. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  14799. {
  14800. }
  14801. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14802. {
  14803. return new CRoxieServerFirstNActivity(this, _probeManager);
  14804. }
  14805. };
  14806. IRoxieServerActivityFactory *createRoxieServerFirstNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14807. {
  14808. return new CRoxieServerFirstNActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  14809. }
  14810. //=================================================================================
  14811. class CRoxieServerSelectNActivity : public CRoxieServerActivity
  14812. {
  14813. bool done;
  14814. IHThorSelectNArg &helper;
  14815. public:
  14816. CRoxieServerSelectNActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  14817. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorSelectNArg &)basehelper)
  14818. {
  14819. done = false;
  14820. }
  14821. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14822. {
  14823. done = false;
  14824. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14825. }
  14826. const void *defaultRow()
  14827. {
  14828. if (!rowAllocator)
  14829. createRowAllocator(); // We delay as often not needed...
  14830. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  14831. size32_t thisSize = helper.createDefault(rowBuilder);
  14832. return rowBuilder.finalizeRowClear(thisSize);
  14833. }
  14834. virtual const void * nextInGroup()
  14835. {
  14836. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  14837. if (done)
  14838. return NULL;
  14839. done = true;
  14840. processed++; // always going to return a row!
  14841. unsigned __int64 index = helper.getRowToSelect();
  14842. while (--index)
  14843. {
  14844. const void * next = input->nextInGroup();
  14845. if (!next)
  14846. next = input->nextInGroup();
  14847. if (!next)
  14848. return defaultRow();
  14849. ReleaseRoxieRow(next);
  14850. }
  14851. const void * next = input->nextInGroup();
  14852. if (!next)
  14853. next = input->nextInGroup();
  14854. if (!next)
  14855. next = defaultRow();
  14856. return next;
  14857. }
  14858. };
  14859. class CRoxieServerSelectNActivityFactory : public CRoxieServerActivityFactory
  14860. {
  14861. public:
  14862. CRoxieServerSelectNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14863. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  14864. {
  14865. }
  14866. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14867. {
  14868. return new CRoxieServerSelectNActivity(this, _probeManager);
  14869. }
  14870. };
  14871. IRoxieServerActivityFactory *createRoxieServerSelectNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14872. {
  14873. return new CRoxieServerSelectNActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  14874. }
  14875. //=================================================================================
  14876. class CRoxieServerSelfJoinActivity : public CRoxieServerActivity
  14877. {
  14878. IHThorJoinArg &helper;
  14879. ICompare *collate;
  14880. OwnedRowArray group;
  14881. bool matchedLeft;
  14882. BoolArray matchedRight;
  14883. bool eof;
  14884. bool first;
  14885. unsigned leftIndex;
  14886. unsigned rightIndex;
  14887. unsigned rightOuterIndex;
  14888. unsigned joinLimit;
  14889. unsigned atmostLimit;
  14890. unsigned atmostsTriggered;
  14891. unsigned abortLimit;
  14892. unsigned keepLimit;
  14893. bool leftOuterJoin;
  14894. bool rightOuterJoin;
  14895. bool exclude;
  14896. bool limitFail;
  14897. bool limitOnFail;
  14898. bool cloneLeft;
  14899. OwnedConstRoxieRow defaultLeft;
  14900. OwnedConstRoxieRow defaultRight;
  14901. OwnedConstRoxieRow lhs;
  14902. Owned<IException> failingLimit;
  14903. bool failingOuterAtmost;
  14904. Owned<IEngineRowAllocator> defaultAllocator;
  14905. Owned<IRHLimitedCompareHelper> limitedhelper;
  14906. Owned<CRHDualCache> dualcache;
  14907. IInputBase *dualCacheInput;
  14908. bool fillGroup()
  14909. {
  14910. group.clear();
  14911. matchedLeft = false;
  14912. matchedRight.kill();
  14913. failingOuterAtmost = false;
  14914. const void * next;
  14915. unsigned groupCount = 0;
  14916. while((next = input->nextInGroup()) != NULL)
  14917. {
  14918. if(groupCount==abortLimit)
  14919. {
  14920. if(limitFail)
  14921. failLimit(next);
  14922. if (ctx->queryDebugContext())
  14923. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  14924. if(limitOnFail)
  14925. {
  14926. assertex(!failingLimit);
  14927. try
  14928. {
  14929. failLimit(next);
  14930. }
  14931. catch(IException * except)
  14932. {
  14933. failingLimit.setown(except);
  14934. }
  14935. assertex(failingLimit != NULL);
  14936. group.append(next);
  14937. groupCount++;
  14938. break;
  14939. }
  14940. group.clear();
  14941. groupCount = 0;
  14942. while(next)
  14943. {
  14944. ReleaseRoxieRow(next);
  14945. next = input->nextInGroup();
  14946. }
  14947. }
  14948. else if(groupCount==atmostLimit)
  14949. {
  14950. atmostsTriggered++;
  14951. if(leftOuterJoin)
  14952. {
  14953. group.append(next);
  14954. groupCount++;
  14955. failingOuterAtmost = true;
  14956. break;
  14957. }
  14958. else
  14959. {
  14960. group.clear();
  14961. groupCount = 0;
  14962. while (next)
  14963. {
  14964. ReleaseRoxieRow(next);
  14965. next = input->nextInGroup();
  14966. }
  14967. }
  14968. }
  14969. else
  14970. {
  14971. group.append(next);
  14972. groupCount++;
  14973. }
  14974. }
  14975. if(group.ordinality()==0)
  14976. {
  14977. eof = true;
  14978. return false;
  14979. }
  14980. leftIndex = 0;
  14981. rightIndex = 0;
  14982. rightOuterIndex = 0;
  14983. joinLimit = keepLimit;
  14984. ForEachItemIn(idx, group)
  14985. matchedRight.append(false);
  14986. return true;
  14987. }
  14988. void failLimit(const void * next)
  14989. {
  14990. helper.onMatchAbortLimitExceeded();
  14991. CommonXmlWriter xmlwrite(XWFtrim|XWFopt );
  14992. if (!ctx->isBlind() && input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  14993. {
  14994. input->queryOutputMeta()->toXML((byte *) next, xmlwrite);
  14995. }
  14996. throw MakeStringException(ROXIE_TOO_MANY_RESULTS, "More than %d match candidates in self-join %d for row %s", abortLimit, queryId(), xmlwrite.str());
  14997. }
  14998. virtual bool needsAllocator() const { return true; }
  14999. const void *joinRecords(const void * curLeft, const void * curRight, IException * except = NULL)
  15000. {
  15001. try
  15002. {
  15003. if (cloneLeft && !except)
  15004. {
  15005. LinkRoxieRow(curLeft);
  15006. return curLeft;
  15007. }
  15008. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15009. size32_t outsize = except ? helper.onFailTransform(rowBuilder, curLeft, curRight, except) : helper.transform(rowBuilder, curLeft, curRight);
  15010. if (outsize)
  15011. return rowBuilder.finalizeRowClear(outsize);
  15012. else
  15013. return NULL;
  15014. }
  15015. catch (IException *E)
  15016. {
  15017. throw makeWrappedException(E);
  15018. }
  15019. }
  15020. void createDefaultLeft()
  15021. {
  15022. if (!defaultLeft)
  15023. {
  15024. if (!defaultAllocator)
  15025. defaultAllocator.setown(ctx->queryCodeContext()->getRowAllocator(input->queryOutputMeta(), activityId));
  15026. RtlDynamicRowBuilder rowBuilder(defaultAllocator);
  15027. size32_t thisSize = helper.createDefaultLeft(rowBuilder);
  15028. defaultLeft.setown(rowBuilder.finalizeRowClear(thisSize));
  15029. }
  15030. }
  15031. void createDefaultRight()
  15032. {
  15033. if (!defaultRight)
  15034. {
  15035. if (!defaultAllocator)
  15036. defaultAllocator.setown(ctx->queryCodeContext()->getRowAllocator(input->queryOutputMeta(), activityId));
  15037. RtlDynamicRowBuilder rowBuilder(defaultAllocator);
  15038. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  15039. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  15040. }
  15041. }
  15042. public:
  15043. CRoxieServerSelfJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  15044. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorJoinArg &)basehelper)
  15045. {
  15046. collate = helper.queryCompareLeftRight();
  15047. eof = false;
  15048. first = true;
  15049. keepLimit = 0;
  15050. atmostLimit = 0;
  15051. atmostsTriggered = 0;
  15052. unsigned joinFlags = helper.getJoinFlags();
  15053. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  15054. rightOuterJoin = (joinFlags & JFrightouter) != 0;
  15055. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  15056. exclude = (joinFlags & JFexclude) != 0;
  15057. abortLimit = 0;
  15058. joinLimit = 0;
  15059. assertex((joinFlags & (JFfirst | JFfirstleft | JFfirstright)) == 0); // no longer supported
  15060. getLimitType(joinFlags, limitFail, limitOnFail);
  15061. if((joinFlags & JFslidingmatch) != 0)
  15062. throw MakeStringException(ROXIE_UNIMPLEMENTED_ERROR, "Internal Error: Sliding self join not supported");
  15063. failingOuterAtmost = false;
  15064. matchedLeft = false;
  15065. leftIndex = 0;
  15066. rightIndex = 0;
  15067. rightOuterIndex = 0;
  15068. dualCacheInput = NULL;
  15069. }
  15070. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15071. {
  15072. eof = false;
  15073. first = true;
  15074. failingLimit.clear();
  15075. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  15076. keepLimit = helper.getKeepLimit();
  15077. if(keepLimit == 0)
  15078. keepLimit = (unsigned)-1;
  15079. atmostsTriggered = 0;
  15080. atmostLimit = helper.getJoinLimit();
  15081. if(atmostLimit == 0)
  15082. atmostLimit = (unsigned)-1;
  15083. else
  15084. assertex(!rightOuterJoin);
  15085. abortLimit = helper.getMatchAbortLimit();
  15086. if (abortLimit == 0)
  15087. abortLimit = (unsigned)-1;
  15088. if (rightOuterJoin)
  15089. createDefaultLeft();
  15090. if (leftOuterJoin || limitOnFail)
  15091. createDefaultRight();
  15092. if ((helper.getJoinFlags() & JFlimitedprefixjoin) && helper.getJoinLimit())
  15093. { //limited match join (s[1..n])
  15094. dualcache.setown(new CRHDualCache());
  15095. dualcache->init(CRoxieServerActivity::input);
  15096. dualCacheInput = dualcache->queryOut1();
  15097. failingOuterAtmost = false;
  15098. matchedLeft = false;
  15099. leftIndex = 0;
  15100. rightOuterIndex = 0;
  15101. limitedhelper.setown(createRHLimitedCompareHelper());
  15102. limitedhelper->init( helper.getJoinLimit(), dualcache->queryOut2(), collate, helper.queryPrefixCompare() );
  15103. }
  15104. }
  15105. virtual void reset()
  15106. {
  15107. if (atmostsTriggered)
  15108. noteStatistic(STATS_ATMOST, atmostsTriggered, 1);
  15109. group.clear();
  15110. CRoxieServerActivity::reset();
  15111. defaultLeft.clear();
  15112. defaultRight.clear();
  15113. }
  15114. virtual const void * nextInGroup()
  15115. {
  15116. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  15117. if (limitedhelper)
  15118. {
  15119. while(!eof) //limited match join
  15120. {
  15121. if (!group.isItem(rightIndex))
  15122. {
  15123. lhs.setown(dualCacheInput->nextInGroup());
  15124. if (lhs)
  15125. {
  15126. rightIndex = 0;
  15127. group.clear();
  15128. limitedhelper->getGroup(group,lhs);
  15129. }
  15130. else
  15131. {
  15132. eof = true;
  15133. }
  15134. }
  15135. if (group.isItem(rightIndex))
  15136. {
  15137. const void * rhs = group.item(rightIndex++);
  15138. if(helper.match(lhs, rhs))
  15139. {
  15140. const void * ret = joinRecords(lhs, rhs);
  15141. return ret;
  15142. }
  15143. }
  15144. }
  15145. return NULL;
  15146. }
  15147. else
  15148. {
  15149. if (first)
  15150. {
  15151. first = false;
  15152. fillGroup();
  15153. }
  15154. while(!eof)
  15155. {
  15156. if(failingOuterAtmost)
  15157. while(group.isItem(leftIndex))
  15158. {
  15159. const void * ret = joinRecords(group.item(leftIndex++), defaultRight);
  15160. if(ret)
  15161. {
  15162. processed++;
  15163. return ret;
  15164. }
  15165. }
  15166. if((joinLimit == 0) || !group.isItem(rightIndex))
  15167. {
  15168. if(leftOuterJoin && !matchedLeft && !failingLimit)
  15169. {
  15170. const void * ret = joinRecords(group.item(leftIndex), defaultRight);
  15171. if(ret)
  15172. {
  15173. matchedLeft = true;
  15174. processed++;
  15175. return ret;
  15176. }
  15177. }
  15178. leftIndex++;
  15179. matchedLeft = false;
  15180. rightIndex = 0;
  15181. joinLimit = keepLimit;
  15182. }
  15183. if(!group.isItem(leftIndex))
  15184. {
  15185. if(failingLimit || failingOuterAtmost)
  15186. {
  15187. const void * lhs;
  15188. while((lhs = input->nextInGroup()) != NULL) // dualCache never active here
  15189. {
  15190. const void * ret = joinRecords(lhs, defaultRight, failingLimit);
  15191. ReleaseRoxieRow(lhs);
  15192. if(ret)
  15193. {
  15194. processed++;
  15195. return ret;
  15196. }
  15197. }
  15198. failingLimit.clear();
  15199. }
  15200. if(rightOuterJoin && !failingLimit)
  15201. while(group.isItem(rightOuterIndex))
  15202. if(!matchedRight.item(rightOuterIndex++))
  15203. {
  15204. const void * ret = joinRecords(defaultLeft, group.item(rightOuterIndex-1));
  15205. if(ret)
  15206. {
  15207. processed++;
  15208. return ret;
  15209. }
  15210. }
  15211. if(!fillGroup())
  15212. return NULL;
  15213. continue;
  15214. }
  15215. const void * lhs = group.item(leftIndex);
  15216. if(failingLimit)
  15217. {
  15218. leftIndex++;
  15219. const void * ret = joinRecords(lhs, defaultRight, failingLimit);
  15220. if(ret)
  15221. {
  15222. processed++;
  15223. return ret;
  15224. }
  15225. }
  15226. else
  15227. {
  15228. const void * rhs = group.item(rightIndex++);
  15229. if(helper.match(lhs, rhs))
  15230. {
  15231. matchedLeft = true;
  15232. matchedRight.replace(true, rightIndex-1);
  15233. if(!exclude)
  15234. {
  15235. const void * ret = joinRecords(lhs, rhs);
  15236. if(ret)
  15237. {
  15238. processed++;
  15239. joinLimit--;
  15240. return ret;
  15241. }
  15242. }
  15243. }
  15244. }
  15245. }
  15246. return NULL;
  15247. }
  15248. }
  15249. };
  15250. class CRoxieServerSelfJoinActivityFactory : public CRoxieServerActivityFactory
  15251. {
  15252. public:
  15253. CRoxieServerSelfJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  15254. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  15255. {
  15256. }
  15257. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  15258. {
  15259. return new CRoxieServerSelfJoinActivity(this, _probeManager);
  15260. }
  15261. };
  15262. IRoxieServerActivityFactory *createRoxieServerSelfJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  15263. {
  15264. return new CRoxieServerSelfJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  15265. }
  15266. //=====================================================================================================
  15267. class CRoxieServerLookupJoinActivity : public CRoxieServerTwoInputActivity
  15268. {
  15269. private:
  15270. class LookupTable : public CInterface
  15271. {
  15272. public:
  15273. LookupTable(unsigned _size, ICompare * _leftRightCompare, ICompare * _rightCompare, IHash * _leftHash, IHash * _rightHash, bool _dedupOnAdd)
  15274. : leftRightCompare(_leftRightCompare), rightCompare(_rightCompare), leftHash(_leftHash), rightHash(_rightHash), dedupOnAdd(_dedupOnAdd)
  15275. {
  15276. unsigned minsize = (4*_size)/3;
  15277. size = 2;
  15278. while((minsize >>= 1) > 0)
  15279. size <<= 1;
  15280. mask = size - 1;
  15281. table = (const void * *)calloc(size, sizeof(void *));
  15282. findex = BadIndex;
  15283. }
  15284. ~LookupTable()
  15285. {
  15286. unsigned i;
  15287. for(i=0; i<size; i++)
  15288. ReleaseRoxieRow(table[i]);
  15289. free(table);
  15290. }
  15291. void add(const void * right)
  15292. {
  15293. findex = BadIndex;
  15294. unsigned start = rightHash->hash(right) & mask;
  15295. unsigned index = start;
  15296. while(table[index])
  15297. {
  15298. if(dedupOnAdd && (rightCompare->docompare(table[index], right) == 0))
  15299. {
  15300. ReleaseRoxieRow(right);
  15301. return;
  15302. }
  15303. index++;
  15304. if(index==size)
  15305. index = 0;
  15306. if(index==start)
  15307. throwUnexpected(); //table is full, should never happen
  15308. }
  15309. table[index] = right;
  15310. }
  15311. const void *find(const void * left) const
  15312. {
  15313. fstart = leftHash->hash(left) & mask;
  15314. findex = fstart;
  15315. return doFind(left);
  15316. }
  15317. const void *findNext(const void * left) const
  15318. {
  15319. if(findex == BadIndex)
  15320. return NULL;
  15321. advance();
  15322. return doFind(left);
  15323. }
  15324. void advance() const
  15325. {
  15326. findex++;
  15327. if(findex==size)
  15328. findex = 0;
  15329. if(findex==fstart)
  15330. throw MakeStringException(ROXIE_JOIN_ERROR, "Internal error hthor lookup join activity (hash table full on lookup)");
  15331. }
  15332. const void *doFind(const void * left) const
  15333. {
  15334. while(table[findex])
  15335. {
  15336. if(leftRightCompare->docompare(left, table[findex]) == 0)
  15337. return table[findex];
  15338. advance();
  15339. }
  15340. findex = BadIndex;
  15341. return NULL;
  15342. }
  15343. private:
  15344. ICompare * leftRightCompare;
  15345. ICompare * rightCompare;
  15346. IHash * leftHash;
  15347. IHash * rightHash;
  15348. unsigned size;
  15349. unsigned mask;
  15350. const void * * table;
  15351. bool dedupOnAdd;
  15352. unsigned mutable fstart;
  15353. unsigned mutable findex;
  15354. static unsigned const BadIndex;
  15355. };
  15356. IHThorHashJoinArg &helper;
  15357. bool leftOuterJoin;
  15358. bool exclude;
  15359. bool eog;
  15360. bool many;
  15361. bool dedupRHS;
  15362. bool matchedGroup;
  15363. const void *left;
  15364. OwnedConstRoxieRow defaultRight;
  15365. Owned<LookupTable> table;
  15366. unsigned keepLimit;
  15367. unsigned atmostLimit;
  15368. unsigned atmostsTriggered;
  15369. unsigned limitLimit;
  15370. bool limitFail;
  15371. bool limitOnFail;
  15372. bool hasGroupLimit;
  15373. bool isSmartJoin;
  15374. unsigned keepCount;
  15375. bool gotMatch;
  15376. bool cloneLeft;
  15377. ConstPointerArray rightGroup;
  15378. aindex_t rightGroupIndex;
  15379. Owned<IException> failingLimit;
  15380. ConstPointerArray filteredRight;
  15381. ThorActivityKind activityKind;
  15382. Owned<IEngineRowAllocator> defaultRightAllocator;
  15383. void createDefaultRight()
  15384. {
  15385. if (!defaultRight)
  15386. {
  15387. if (!defaultRightAllocator)
  15388. defaultRightAllocator.setown(ctx->queryCodeContext()->getRowAllocator(input1->queryOutputMeta(), activityId));
  15389. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  15390. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  15391. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  15392. }
  15393. }
  15394. public:
  15395. CRoxieServerLookupJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  15396. : CRoxieServerTwoInputActivity(_factory, _probeManager), helper((IHThorHashJoinArg &)basehelper)
  15397. {
  15398. unsigned joinFlags = helper.getJoinFlags();
  15399. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  15400. assertex((joinFlags & JFrightouter) == 0);
  15401. exclude = (joinFlags & JFexclude) != 0;
  15402. many = (joinFlags & JFmanylookup) != 0;
  15403. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  15404. dedupRHS = (joinFlags & (JFmanylookup | JFmatchrequired | JFtransformMaySkip)) == 0; // optimisation: can implicitly dedup RHS unless is many lookup, or match required, or transform may skip
  15405. left = NULL;
  15406. activityKind = factory->getKind();
  15407. eog = false;
  15408. matchedGroup = false;
  15409. gotMatch = false;
  15410. keepLimit = 0;
  15411. keepCount = 0;
  15412. atmostLimit = 0;
  15413. atmostsTriggered = 0;
  15414. limitLimit = 0;
  15415. hasGroupLimit = false;
  15416. isSmartJoin = (joinFlags & JFsmart) != 0;
  15417. getLimitType(joinFlags, limitFail, limitOnFail);
  15418. }
  15419. void loadRight()
  15420. {
  15421. ConstPointerArray rightset;
  15422. unsigned i = 0;
  15423. try
  15424. {
  15425. const void * next;
  15426. while(true)
  15427. {
  15428. next = input1->nextInGroup();
  15429. if(!next)
  15430. next = input1->nextInGroup();
  15431. if(!next)
  15432. break;
  15433. rightset.append(next);
  15434. }
  15435. unsigned rightord = rightset.ordinality();
  15436. table.setown(new LookupTable(rightord, helper.queryCompareLeftRight(), helper.queryCompareRight(), helper.queryHashLeft(), helper.queryHashRight(), dedupRHS));
  15437. for(i=0; i<rightord; i++)
  15438. table->add(rightset.item(i));
  15439. }
  15440. catch (...)
  15441. {
  15442. unsigned rightord = rightset.ordinality();
  15443. for ( ; i<rightord; i++)
  15444. ReleaseRoxieRow(rightset.item(i));
  15445. throw;
  15446. }
  15447. };
  15448. virtual void reset()
  15449. {
  15450. if (atmostsTriggered)
  15451. noteStatistic(STATS_ATMOST, atmostsTriggered, 1);
  15452. CRoxieServerTwoInputActivity::reset();
  15453. ReleaseClearRoxieRow(left);
  15454. defaultRight.clear();
  15455. table.clear();
  15456. }
  15457. virtual bool needsAllocator() const { return true; }
  15458. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15459. {
  15460. eog = false;
  15461. matchedGroup = false;
  15462. left = NULL;
  15463. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  15464. keepLimit = helper.getKeepLimit();
  15465. if(keepLimit==0) keepLimit = static_cast<unsigned>(-1);
  15466. atmostsTriggered = 0;
  15467. atmostLimit = helper.getJoinLimit();
  15468. limitLimit = helper.getMatchAbortLimit();
  15469. hasGroupLimit = ((atmostLimit > 0) || (limitLimit > 0));
  15470. if(atmostLimit==0) atmostLimit = static_cast<unsigned>(-1);
  15471. if(limitLimit==0) limitLimit = static_cast<unsigned>(-1);
  15472. getLimitType(helper.getJoinFlags(), limitFail, limitOnFail);
  15473. switch (activityKind)
  15474. {
  15475. case TAKlookupjoin:
  15476. case TAKlookupdenormalizegroup:
  15477. case TAKsmartjoin:
  15478. case TAKsmartdenormalizegroup:
  15479. if (leftOuterJoin)
  15480. createDefaultRight();
  15481. break;
  15482. }
  15483. if (limitOnFail)
  15484. createDefaultRight();
  15485. }
  15486. virtual void setInput(unsigned idx, IRoxieInput *_in)
  15487. {
  15488. if (idx==1)
  15489. input1 = _in;
  15490. else
  15491. {
  15492. if ((helper.getJoinFlags() & JFparallel) != 0)
  15493. {
  15494. puller.setown(new CRoxieServerReadAheadInput(0)); // MORE - cant ask context for parallelJoinPreload as context is not yet set up.
  15495. puller->setInput(0, _in);
  15496. _in = puller;
  15497. }
  15498. CRoxieServerActivity::setInput(idx, _in);
  15499. }
  15500. }
  15501. virtual const void * nextInGroup()
  15502. {
  15503. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  15504. if(!table)
  15505. loadRight();
  15506. switch (activityKind)
  15507. {
  15508. case TAKlookupjoin:
  15509. case TAKsmartjoin:
  15510. return nextInGroupJoin();
  15511. case TAKlookupdenormalize:
  15512. case TAKlookupdenormalizegroup:
  15513. case TAKsmartdenormalize:
  15514. case TAKsmartdenormalizegroup:
  15515. return nextInGroupDenormalize();
  15516. }
  15517. throwUnexpected();
  15518. }
  15519. private:
  15520. const void * nextInGroupJoin()
  15521. {
  15522. if(!table)
  15523. loadRight();
  15524. while(true)
  15525. {
  15526. const void * right = NULL;
  15527. if(!left)
  15528. {
  15529. left = input->nextInGroup();
  15530. keepCount = keepLimit;
  15531. if(!left)
  15532. {
  15533. if (isSmartJoin)
  15534. left = input->nextInGroup();
  15535. if (!left)
  15536. {
  15537. if(matchedGroup || eog)
  15538. {
  15539. matchedGroup = false;
  15540. eog = true;
  15541. return NULL;
  15542. }
  15543. eog = true;
  15544. continue;
  15545. }
  15546. }
  15547. eog = false;
  15548. gotMatch = false;
  15549. right = getRightFirst();
  15550. }
  15551. else
  15552. right = getRightNext();
  15553. const void * ret = NULL;
  15554. if(failingLimit)
  15555. {
  15556. ret = joinException(left, failingLimit);
  15557. }
  15558. else
  15559. {
  15560. while(right)
  15561. {
  15562. if(helper.match(left, right))
  15563. {
  15564. gotMatch = true;
  15565. if(exclude)
  15566. break;
  15567. ret = joinRecords(left, right);
  15568. if(ret)
  15569. break;
  15570. }
  15571. right = getRightNext();
  15572. ret = NULL;
  15573. }
  15574. if(leftOuterJoin && !gotMatch)
  15575. {
  15576. ret = joinRecords(left, defaultRight);
  15577. gotMatch = true;
  15578. }
  15579. }
  15580. if(ret)
  15581. {
  15582. matchedGroup = true;
  15583. processed++;
  15584. if(!many || (--keepCount == 0) || failingLimit)
  15585. {
  15586. ReleaseClearRoxieRow(left);
  15587. failingLimit.clear();
  15588. }
  15589. return ret;
  15590. }
  15591. ReleaseClearRoxieRow(left);
  15592. }
  15593. }
  15594. const void * nextInGroupDenormalize()
  15595. {
  15596. while(true)
  15597. {
  15598. left = input->nextInGroup();
  15599. if(!left)
  15600. {
  15601. if (!matchedGroup || isSmartJoin)
  15602. left = input->nextInGroup();
  15603. if (!left)
  15604. {
  15605. matchedGroup = false;
  15606. return NULL;
  15607. }
  15608. }
  15609. gotMatch = false;
  15610. const void * right = getRightFirst();
  15611. const void * ret = NULL;
  15612. if (failingLimit)
  15613. ret = joinException(left, failingLimit);
  15614. else if (activityKind == TAKlookupdenormalize || activityKind == TAKsmartdenormalize)
  15615. {
  15616. OwnedConstRoxieRow newLeft;
  15617. newLeft.set(left);
  15618. unsigned rowSize = 0;
  15619. unsigned leftCount = 0;
  15620. keepCount = keepLimit;
  15621. while (right)
  15622. {
  15623. try
  15624. {
  15625. if (helper.match(left, right))
  15626. {
  15627. gotMatch = true;
  15628. if (exclude)
  15629. break;
  15630. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15631. unsigned thisSize = helper.transform(rowBuilder, newLeft, right, ++leftCount);
  15632. if (thisSize)
  15633. {
  15634. rowSize = thisSize;
  15635. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  15636. }
  15637. if(!many || (--keepCount == 0))
  15638. break;
  15639. }
  15640. right = getRightNext();
  15641. }
  15642. catch (IException *E)
  15643. {
  15644. throw makeWrappedException(E);
  15645. }
  15646. }
  15647. if (rowSize)
  15648. ret = newLeft.getClear();
  15649. else if (leftOuterJoin && !gotMatch)
  15650. {
  15651. ret = left;
  15652. left = NULL;
  15653. }
  15654. }
  15655. else
  15656. {
  15657. filteredRight.kill();
  15658. keepCount = keepLimit;
  15659. while (right)
  15660. {
  15661. if (helper.match(left, right))
  15662. {
  15663. gotMatch = true;
  15664. if(exclude)
  15665. break;
  15666. filteredRight.append(right);
  15667. if(!many || (--keepCount == 0))
  15668. break;
  15669. }
  15670. right = getRightNext();
  15671. }
  15672. if((filteredRight.ordinality() > 0) || (leftOuterJoin && !gotMatch))
  15673. ret = denormalizeRecords(left, filteredRight);
  15674. filteredRight.kill();
  15675. }
  15676. ReleaseRoxieRow(left);
  15677. left = NULL;
  15678. failingLimit.clear();
  15679. if(ret)
  15680. {
  15681. matchedGroup = true;
  15682. processed++;
  15683. return ret;
  15684. }
  15685. }
  15686. }
  15687. const void * joinRecords(const void * left, const void * right)
  15688. {
  15689. if (cloneLeft)
  15690. {
  15691. LinkRoxieRow(left);
  15692. return left;
  15693. }
  15694. try
  15695. {
  15696. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15697. unsigned outSize = helper.transform(rowBuilder, left, right);
  15698. if (outSize)
  15699. return rowBuilder.finalizeRowClear(outSize);
  15700. else
  15701. return NULL;
  15702. }
  15703. catch (IException *E)
  15704. {
  15705. throw makeWrappedException(E);
  15706. }
  15707. }
  15708. const void * joinException(const void * left, IException * except)
  15709. {
  15710. try
  15711. {
  15712. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15713. unsigned outSize = helper.onFailTransform(rowBuilder, left, defaultRight, except);
  15714. if (outSize)
  15715. return rowBuilder.finalizeRowClear(outSize);
  15716. else
  15717. return NULL;
  15718. }
  15719. catch (IException *E)
  15720. {
  15721. throw makeWrappedException(E);
  15722. }
  15723. }
  15724. const void * denormalizeRecords(const void * left, ConstPointerArray & rows)
  15725. {
  15726. try
  15727. {
  15728. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15729. unsigned numRows = rows.ordinality();
  15730. const void * right = numRows ? rows.item(0) : defaultRight.get();
  15731. unsigned outSize = helper.transform(rowBuilder, left, right, numRows, (const void * *)rows.getArray());
  15732. if (outSize)
  15733. return rowBuilder.finalizeRowClear(outSize);
  15734. else
  15735. return NULL;
  15736. }
  15737. catch (IException *E)
  15738. {
  15739. throw makeWrappedException(E);
  15740. }
  15741. }
  15742. const void * getRightFirst() { if(hasGroupLimit) return fillRightGroup(); else return table->find(left); }
  15743. const void * getRightNext() { if(hasGroupLimit) return readRightGroup(); else return table->findNext(left); }
  15744. const void * readRightGroup() { if(rightGroup.isItem(rightGroupIndex)) return rightGroup.item(rightGroupIndex++); else return NULL; }
  15745. const void *fillRightGroup()
  15746. {
  15747. rightGroup.kill();
  15748. for(const void * right = table->find(left); right; right = table->findNext(left))
  15749. {
  15750. rightGroup.append(right);
  15751. if(rightGroup.ordinality() > limitLimit)
  15752. {
  15753. if(limitFail)
  15754. failLimit();
  15755. gotMatch = true;
  15756. if (ctx->queryDebugContext())
  15757. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  15758. if(limitOnFail)
  15759. {
  15760. assertex(!failingLimit);
  15761. try
  15762. {
  15763. failLimit();
  15764. }
  15765. catch(IException * e)
  15766. {
  15767. failingLimit.setown(e);
  15768. }
  15769. assertex(failingLimit != NULL);
  15770. }
  15771. else
  15772. {
  15773. rightGroup.kill();
  15774. }
  15775. break;
  15776. }
  15777. if(rightGroup.ordinality() > atmostLimit)
  15778. {
  15779. atmostsTriggered++;
  15780. rightGroup.kill();
  15781. break;
  15782. }
  15783. }
  15784. rightGroupIndex = 0;
  15785. return readRightGroup();
  15786. }
  15787. void failLimit()
  15788. {
  15789. helper.onMatchAbortLimitExceeded();
  15790. CommonXmlWriter xmlwrite(XWFtrim|XWFopt );
  15791. if(!ctx->isBlind() && input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  15792. {
  15793. input->queryOutputMeta()->toXML(static_cast<const unsigned char *>(left), xmlwrite);
  15794. }
  15795. throw MakeStringException(ROXIE_TOO_MANY_RESULTS, "More than %u match candidates in join %d for row %s", limitLimit, queryId(), xmlwrite.str());
  15796. }
  15797. };
  15798. unsigned const CRoxieServerLookupJoinActivity::LookupTable::BadIndex(static_cast<unsigned>(-1));
  15799. class CRoxieServerLookupJoinActivityFactory : public CRoxieServerJoinActivityFactory
  15800. {
  15801. public:
  15802. CRoxieServerLookupJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  15803. : CRoxieServerJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  15804. {
  15805. Owned<IHThorHashJoinArg> helper = (IHThorHashJoinArg *) helperFactory();
  15806. if((helper->getJoinFlags() & (JFfirst | JFfirstleft | JFfirstright | JFslidingmatch)) != 0)
  15807. throw MakeStringException(ROXIE_INVALID_FLAGS, "Invalid flags for lookup join activity"); // code generator should never create such an activity
  15808. }
  15809. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  15810. {
  15811. return new CRoxieServerLookupJoinActivity(this, _probeManager);
  15812. }
  15813. };
  15814. IRoxieServerActivityFactory *createRoxieServerLookupJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  15815. {
  15816. return new CRoxieServerLookupJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  15817. }
  15818. //=====================================================================================================
  15819. class CRoxieServerAllJoinActivity : public CRoxieServerTwoInputActivity
  15820. {
  15821. private:
  15822. IHThorAllJoinArg &helper;
  15823. bool leftOuterJoin;
  15824. bool rightOuterJoin;
  15825. bool exclude;
  15826. OwnedConstRoxieRow defaultRight;
  15827. OwnedConstRoxieRow defaultLeft;
  15828. Owned<IEngineRowAllocator> defaultRightAllocator;
  15829. Owned<IEngineRowAllocator> defaultLeftAllocator;
  15830. const void *left;
  15831. unsigned countForLeft;
  15832. ConstPointerArray rightset;
  15833. BoolArray matchedRight; // MORE - could use a bitset...
  15834. unsigned keepLimit;
  15835. bool started;
  15836. bool eog;
  15837. bool eos;
  15838. bool matchedLeft;
  15839. bool matchedGroup;
  15840. bool leftIsGrouped;
  15841. bool cloneLeft;
  15842. unsigned rightIndex;
  15843. unsigned rightOrdinality;
  15844. ThorActivityKind activityKind;
  15845. ConstPointerArray filteredRight;
  15846. void createDefaultLeft()
  15847. {
  15848. if (!defaultLeft)
  15849. {
  15850. if (!defaultLeftAllocator)
  15851. defaultLeftAllocator.setown(ctx->queryCodeContext()->getRowAllocator(input->queryOutputMeta(), activityId));
  15852. RtlDynamicRowBuilder rowBuilder(defaultLeftAllocator);
  15853. size32_t thisSize = helper.createDefaultLeft(rowBuilder);
  15854. defaultLeft.setown(rowBuilder.finalizeRowClear(thisSize));
  15855. }
  15856. }
  15857. void createDefaultRight()
  15858. {
  15859. if (!defaultRight)
  15860. {
  15861. if (!defaultRightAllocator)
  15862. defaultRightAllocator.setown(ctx->queryCodeContext()->getRowAllocator(input1->queryOutputMeta(), activityId));
  15863. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  15864. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  15865. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  15866. }
  15867. }
  15868. public:
  15869. CRoxieServerAllJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  15870. : CRoxieServerTwoInputActivity(_factory, _probeManager), helper((IHThorAllJoinArg &)basehelper)
  15871. {
  15872. unsigned joinFlags = helper.getJoinFlags();
  15873. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  15874. rightOuterJoin = (joinFlags & JFrightouter) != 0;
  15875. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  15876. keepLimit = (unsigned) -1;
  15877. exclude = (joinFlags & JFexclude) != 0;
  15878. left = NULL;
  15879. started = true;
  15880. eog = false;
  15881. eos = false;
  15882. matchedLeft = false;
  15883. matchedGroup = false;
  15884. activityKind = factory->getKind();
  15885. rightIndex = 0;
  15886. rightOrdinality = 0;
  15887. leftIsGrouped = false;
  15888. countForLeft = 0;
  15889. }
  15890. virtual void reset()
  15891. {
  15892. defaultRight.clear();
  15893. defaultLeft.clear();
  15894. ReleaseRoxieRowSet(rightset);
  15895. matchedRight.kill();
  15896. CRoxieServerTwoInputActivity::reset();
  15897. }
  15898. virtual bool needsAllocator() const { return true; }
  15899. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15900. {
  15901. eog = false;
  15902. eos = false;
  15903. matchedLeft = false;
  15904. matchedGroup = false;
  15905. started = false;
  15906. left = NULL;
  15907. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  15908. keepLimit = helper.getKeepLimit();
  15909. if(keepLimit==0)
  15910. keepLimit = (unsigned) -1;
  15911. countForLeft = keepLimit;
  15912. leftIsGrouped = input->queryOutputMeta()->isGrouped();
  15913. if((activityKind==TAKalljoin || activityKind==TAKalldenormalizegroup) && leftOuterJoin)
  15914. createDefaultRight();
  15915. if(rightOuterJoin)
  15916. createDefaultLeft();
  15917. }
  15918. void loadRight()
  15919. {
  15920. const void * next;
  15921. while(true)
  15922. {
  15923. next = input1->nextInGroup();
  15924. if(!next)
  15925. next = input1->nextInGroup();
  15926. if(!next)
  15927. break;
  15928. rightset.append(next);
  15929. matchedRight.append(false);
  15930. }
  15931. rightIndex = 0;
  15932. rightOrdinality = rightset.ordinality();
  15933. }
  15934. virtual void setInput(unsigned idx, IRoxieInput *_in)
  15935. {
  15936. if (idx==1)
  15937. input1 = _in;
  15938. else
  15939. {
  15940. if ((helper.getJoinFlags() & JFparallel) != 0)
  15941. {
  15942. puller.setown(new CRoxieServerReadAheadInput(0)); // MORE - cant ask context for parallelJoinPreload as context is not yet set up.
  15943. puller->setInput(0, _in);
  15944. _in = puller;
  15945. }
  15946. CRoxieServerActivity::setInput(idx, _in);
  15947. }
  15948. }
  15949. const void * joinRecords(const void * left, const void * right)
  15950. {
  15951. // MORE - could share some code with lookup join
  15952. if (cloneLeft)
  15953. {
  15954. LinkRoxieRow(left);
  15955. return left;
  15956. }
  15957. try
  15958. {
  15959. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15960. unsigned outSize = helper.transform(rowBuilder, left, right);
  15961. if (outSize)
  15962. return rowBuilder.finalizeRowClear(outSize);
  15963. else
  15964. return NULL;
  15965. }
  15966. catch (IException *E)
  15967. {
  15968. throw makeWrappedException(E);
  15969. }
  15970. }
  15971. const void * denormalizeRecords(const void * curLeft, ConstPointerArray & rows)
  15972. {
  15973. try
  15974. {
  15975. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15976. unsigned numRows = rows.ordinality();
  15977. const void * right = numRows ? rows.item(0) : defaultRight.get();
  15978. unsigned outSize = helper.transform(rowBuilder, curLeft, right, numRows, rows.getArray());
  15979. if (outSize)
  15980. return rowBuilder.finalizeRowClear(outSize);
  15981. else
  15982. return NULL;
  15983. }
  15984. catch (IException *E)
  15985. {
  15986. throw makeWrappedException(E);
  15987. }
  15988. }
  15989. virtual const void *nextInGroup()
  15990. {
  15991. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  15992. if(!started)
  15993. {
  15994. started = true;
  15995. left = input->nextInGroup();
  15996. matchedLeft = false;
  15997. countForLeft = keepLimit;
  15998. if(left == NULL)
  15999. {
  16000. eos = true;
  16001. return NULL;
  16002. }
  16003. loadRight();
  16004. }
  16005. const void * ret;
  16006. const void * right;
  16007. if(eos)
  16008. return NULL;
  16009. while(true)
  16010. {
  16011. ret = NULL;
  16012. if((rightIndex == rightOrdinality) || (countForLeft==0))
  16013. {
  16014. if(leftOuterJoin && left && !matchedLeft)
  16015. {
  16016. switch(activityKind)
  16017. {
  16018. case TAKalljoin:
  16019. ret = joinRecords(left, defaultRight);
  16020. break;
  16021. case TAKalldenormalize:
  16022. ret = left;
  16023. left = NULL;
  16024. break;
  16025. case TAKalldenormalizegroup:
  16026. filteredRight.kill();
  16027. ret = denormalizeRecords(left, filteredRight);
  16028. break;
  16029. default:
  16030. throwUnexpected();
  16031. }
  16032. }
  16033. rightIndex = 0;
  16034. ReleaseRoxieRow(left);
  16035. left = NULL;
  16036. if(ret)
  16037. {
  16038. matchedGroup = true;
  16039. processed++;
  16040. return ret;
  16041. }
  16042. }
  16043. if(!left)
  16044. {
  16045. left = input->nextInGroup();
  16046. matchedLeft = false;
  16047. countForLeft = keepLimit;
  16048. }
  16049. if(!left)
  16050. {
  16051. if(eog)
  16052. {
  16053. eos = true;
  16054. matchedGroup = false;
  16055. return NULL;
  16056. }
  16057. eog = true;
  16058. if (matchedGroup && leftIsGrouped)
  16059. {
  16060. matchedGroup = false;
  16061. return NULL;
  16062. }
  16063. matchedGroup = false;
  16064. continue;
  16065. }
  16066. eog = false;
  16067. switch(activityKind)
  16068. {
  16069. case TAKalljoin:
  16070. while(rightIndex < rightOrdinality)
  16071. {
  16072. right = rightset.item(rightIndex);
  16073. if(helper.match(left, right))
  16074. {
  16075. matchedLeft = true;
  16076. matchedRight.replace(true, rightIndex);
  16077. if(!exclude)
  16078. ret = joinRecords(left, right);
  16079. }
  16080. rightIndex++;
  16081. if(ret)
  16082. {
  16083. countForLeft--;
  16084. matchedGroup = true;
  16085. processed++;
  16086. return ret;
  16087. }
  16088. }
  16089. break;
  16090. case TAKalldenormalize:
  16091. {
  16092. OwnedConstRoxieRow newLeft;
  16093. newLeft.set(left);
  16094. unsigned rowSize = 0;
  16095. unsigned leftCount = 0;
  16096. while((rightIndex < rightOrdinality) && countForLeft)
  16097. {
  16098. right = rightset.item(rightIndex);
  16099. if(helper.match(left, right))
  16100. {
  16101. matchedLeft = true;
  16102. matchedRight.replace(true, rightIndex);
  16103. if(!exclude)
  16104. {
  16105. try
  16106. {
  16107. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16108. unsigned thisSize = helper.transform(rowBuilder, newLeft, right, ++leftCount);
  16109. if(thisSize)
  16110. {
  16111. rowSize = thisSize;
  16112. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  16113. --countForLeft;
  16114. }
  16115. }
  16116. catch (IException *e)
  16117. {
  16118. throw makeWrappedException(e);
  16119. }
  16120. }
  16121. }
  16122. rightIndex++;
  16123. }
  16124. if(rowSize)
  16125. {
  16126. processed++;
  16127. return newLeft.getClear();
  16128. }
  16129. }
  16130. break;
  16131. case TAKalldenormalizegroup:
  16132. filteredRight.kill();
  16133. while((rightIndex < rightOrdinality) && countForLeft)
  16134. {
  16135. right = rightset.item(rightIndex);
  16136. if(helper.match(left, right))
  16137. {
  16138. matchedLeft = true;
  16139. matchedRight.replace(true, rightIndex);
  16140. filteredRight.append(right);
  16141. --countForLeft;
  16142. }
  16143. ++rightIndex;
  16144. }
  16145. if(!exclude && filteredRight.ordinality())
  16146. {
  16147. ret = denormalizeRecords(left, filteredRight);
  16148. filteredRight.kill();
  16149. if(ret)
  16150. {
  16151. processed++;
  16152. return ret;
  16153. }
  16154. }
  16155. break;
  16156. default:
  16157. throwUnexpected();
  16158. }
  16159. }
  16160. }
  16161. };
  16162. class CRoxieServerAllJoinActivityFactory : public CRoxieServerJoinActivityFactory
  16163. {
  16164. public:
  16165. CRoxieServerAllJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16166. : CRoxieServerJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  16167. {
  16168. Owned<IHThorAllJoinArg> helper = (IHThorAllJoinArg *) helperFactory();
  16169. if((helper->getJoinFlags() & (JFfirst | JFfirstleft | JFfirstright)) != 0)
  16170. throw MakeStringException(ROXIE_INVALID_FLAGS, "Invalid flags for join all activity"); // code generator should never create such an activity
  16171. }
  16172. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  16173. {
  16174. return new CRoxieServerAllJoinActivity(this, _probeManager);
  16175. }
  16176. };
  16177. IRoxieServerActivityFactory *createRoxieServerAllJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16178. {
  16179. return new CRoxieServerAllJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  16180. }
  16181. //=====================================================================================================
  16182. class CRoxieServerTopNActivity : public CRoxieServerLateStartActivity
  16183. {
  16184. unsigned limit;
  16185. bool hasBest;
  16186. bool eoi;
  16187. const void **sorted;
  16188. unsigned sortedCount;
  16189. unsigned curIndex;
  16190. IHThorTopNArg &helper;
  16191. ICompare &compare;
  16192. public:
  16193. CRoxieServerTopNActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  16194. : CRoxieServerLateStartActivity(_factory, _probeManager), helper((IHThorTopNArg &)basehelper), compare(*helper.queryCompare())
  16195. {
  16196. sorted = NULL;
  16197. sortedCount = 0;
  16198. curIndex = 0;
  16199. limit = 0;
  16200. eoi = false;
  16201. hasBest = false;
  16202. }
  16203. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16204. {
  16205. assertex(sorted == NULL);
  16206. sortedCount = 0;
  16207. curIndex = 0;
  16208. eoi = false;
  16209. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  16210. limit = (unsigned) helper.getLimit();
  16211. hasBest = helper.hasBest();
  16212. lateStart(parentExtractSize, parentExtract, limit > 0);
  16213. // MORE - should we use an expanding array instead?
  16214. if (limit > 0)
  16215. sorted = (const void **) ctx->queryRowManager().allocate((limit+1) * sizeof(const void *), activityId);
  16216. }
  16217. virtual void reset()
  16218. {
  16219. if (sorted)
  16220. {
  16221. while(curIndex < sortedCount)
  16222. ReleaseRoxieRow(sorted[curIndex++]);
  16223. ReleaseRoxieRow(sorted);
  16224. }
  16225. sorted = NULL;
  16226. CRoxieServerLateStartActivity::reset();
  16227. }
  16228. bool abortEarly()
  16229. {
  16230. if (hasBest && (sortedCount == limit))
  16231. {
  16232. int compare = helper.compareBest(sorted[sortedCount-1]);
  16233. if (compare == 0)
  16234. {
  16235. if (meta.isGrouped())
  16236. {
  16237. //MORE: This would be more efficient if we had a away of skipping to the end of the incoming group.
  16238. const void * next;
  16239. while ((next = input->nextInGroup()) != NULL)
  16240. ReleaseRoxieRow(next);
  16241. }
  16242. else
  16243. eoi = true;
  16244. return true;
  16245. }
  16246. //This only checks the lowest element - we could check all elements inserted, but it would increase the number of compares
  16247. if (compare < 0)
  16248. throw MakeStringException(ROXIE_TOPN_ROW_ERROR, "TOPN: row found that exceeds the best value");
  16249. }
  16250. return false;
  16251. }
  16252. void getSorted()
  16253. {
  16254. curIndex = 0;
  16255. sortedCount = 0;
  16256. if(eoi)
  16257. return;
  16258. const void * next;
  16259. while ((next = input->nextInGroup()) != NULL)
  16260. {
  16261. if (sortedCount < limit)
  16262. {
  16263. binary_vec_insert_stable(next, sorted, sortedCount, compare);
  16264. sortedCount++;
  16265. if(abortEarly())
  16266. return;
  16267. }
  16268. else
  16269. {
  16270. if(limit && compare.docompare(sorted[sortedCount-1], next) > 0) // MORE - if stability is an issue, need to consider whether this should be > or >=
  16271. {
  16272. binary_vec_insert_stable(next, sorted, sortedCount, compare); // MORE - not sure this is stable!
  16273. ReleaseRoxieRow(sorted[sortedCount]);
  16274. if(abortEarly())
  16275. return;
  16276. }
  16277. else
  16278. {
  16279. ReleaseRoxieRow(next); // do not bother with insertion sort if we know next will fall off the end
  16280. }
  16281. }
  16282. }
  16283. }
  16284. virtual const void * nextInGroup()
  16285. {
  16286. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  16287. if (eof)
  16288. return NULL;
  16289. if (curIndex >= sortedCount)
  16290. {
  16291. bool eog = sortedCount != 0;
  16292. getSorted();
  16293. if(sortedCount == 0)
  16294. {
  16295. eof = true;
  16296. return NULL;
  16297. }
  16298. if (eog)
  16299. return NULL;
  16300. }
  16301. processed++;
  16302. return sorted[curIndex++];
  16303. }
  16304. };
  16305. class CRoxieServerTopNActivityFactory : public CRoxieServerActivityFactory
  16306. {
  16307. public:
  16308. CRoxieServerTopNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16309. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  16310. {
  16311. }
  16312. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  16313. {
  16314. return new CRoxieServerTopNActivity(this, _probeManager);
  16315. }
  16316. };
  16317. IRoxieServerActivityFactory *createRoxieServerTopNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16318. {
  16319. return new CRoxieServerTopNActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  16320. }
  16321. //=================================================================================
  16322. class CRoxieServerLimitActivity : public CRoxieServerActivity
  16323. {
  16324. protected:
  16325. unsigned __int64 rowLimit;
  16326. IHThorLimitArg &helper;
  16327. public:
  16328. CRoxieServerLimitActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  16329. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorLimitArg &)basehelper)
  16330. {
  16331. rowLimit = 0;
  16332. }
  16333. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16334. {
  16335. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  16336. rowLimit = helper.getRowLimit(); // could conceivably depend on context so should not compute any earlier than this
  16337. }
  16338. virtual const void *nextInGroup()
  16339. {
  16340. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  16341. const void * ret = input->nextInGroup();
  16342. if (ret)
  16343. {
  16344. processed++;
  16345. if (processed > rowLimit)
  16346. {
  16347. ReleaseRoxieRow(ret);
  16348. if (traceLevel > 4)
  16349. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  16350. helper.onLimitExceeded();
  16351. }
  16352. }
  16353. return ret;
  16354. }
  16355. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  16356. {
  16357. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  16358. const void * ret = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  16359. if (ret)
  16360. {
  16361. if (wasCompleteMatch)
  16362. processed++;
  16363. if (processed > rowLimit)
  16364. {
  16365. ReleaseRoxieRow(ret);
  16366. if (traceLevel > 4)
  16367. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  16368. helper.onLimitExceeded();
  16369. }
  16370. }
  16371. return ret;
  16372. }
  16373. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  16374. {
  16375. return input->gatherConjunctions(collector);
  16376. }
  16377. virtual void resetEOF()
  16378. {
  16379. //Do not reset the rowLimit
  16380. input->resetEOF();
  16381. }
  16382. IInputSteppingMeta * querySteppingMeta()
  16383. {
  16384. return input->querySteppingMeta();
  16385. }
  16386. };
  16387. class CRoxieServerLimitActivityFactory : public CRoxieServerActivityFactory
  16388. {
  16389. public:
  16390. CRoxieServerLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16391. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  16392. {
  16393. }
  16394. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  16395. {
  16396. return new CRoxieServerLimitActivity(this, _probeManager);
  16397. }
  16398. };
  16399. IRoxieServerActivityFactory *createRoxieServerLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16400. {
  16401. return new CRoxieServerLimitActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  16402. }
  16403. //=====================================================================================================
  16404. class CRoxieServerSkipLimitActivity : public CRoxieServerLimitActivity
  16405. {
  16406. ConstPointerArray buff;
  16407. bool started;
  16408. unsigned index;
  16409. IHThorLimitTransformExtra * transformExtra;
  16410. public:
  16411. CRoxieServerSkipLimitActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _onFail)
  16412. : CRoxieServerLimitActivity(_factory, _probeManager)
  16413. {
  16414. transformExtra = NULL;
  16415. started = false;
  16416. index = 0;
  16417. if (_onFail)
  16418. transformExtra = static_cast<IHThorLimitTransformExtra *>(helper.selectInterface(TAIlimittransformextra_1));
  16419. }
  16420. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16421. {
  16422. started = false;
  16423. index = 0;
  16424. CRoxieServerLimitActivity::start(parentExtractSize, parentExtract, paused);
  16425. }
  16426. virtual void reset()
  16427. {
  16428. while (buff.isItem(index))
  16429. ReleaseRoxieRow(buff.item(index++));
  16430. buff.kill();
  16431. started = false;
  16432. CRoxieServerLimitActivity::reset();
  16433. }
  16434. virtual const void *nextInGroup()
  16435. {
  16436. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  16437. if (!started)
  16438. pullInput();
  16439. if (buff.isItem(index))
  16440. {
  16441. const void * next = buff.item(index++);
  16442. if(next)
  16443. processed++;
  16444. return next;
  16445. }
  16446. return NULL;
  16447. }
  16448. protected:
  16449. void pullInput()
  16450. {
  16451. unsigned count = 0;
  16452. loop
  16453. {
  16454. const void * next = input->nextInGroup();
  16455. if (next == NULL)
  16456. {
  16457. next = input->nextInGroup();
  16458. if(next == NULL)
  16459. break;
  16460. buff.append(NULL);
  16461. }
  16462. count++;
  16463. if (count > rowLimit)
  16464. {
  16465. ReleaseRoxieRow(next);
  16466. ReleaseRoxieRowSet(buff);
  16467. if (ctx->queryDebugContext())
  16468. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  16469. if (transformExtra)
  16470. {
  16471. createRowAllocator();
  16472. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16473. size32_t outSize = transformExtra->transformOnLimitExceeded(rowBuilder);
  16474. if (outSize)
  16475. buff.append(rowBuilder.finalizeRowClear(outSize));
  16476. }
  16477. break;
  16478. }
  16479. buff.append(next);
  16480. }
  16481. started = true;
  16482. }
  16483. };
  16484. class CRoxieServerSkipLimitActivityFactory : public CRoxieServerActivityFactory
  16485. {
  16486. public:
  16487. CRoxieServerSkipLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16488. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  16489. {
  16490. }
  16491. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  16492. {
  16493. return new CRoxieServerSkipLimitActivity(this, _probeManager, kind==TAKcreaterowlimit);
  16494. }
  16495. };
  16496. IRoxieServerActivityFactory *createRoxieServerSkipLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16497. {
  16498. return new CRoxieServerSkipLimitActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  16499. }
  16500. //=================================================================================
  16501. class CRoxieServerCatchActivity : public CRoxieServerActivity
  16502. {
  16503. IHThorCatchArg &helper;
  16504. public:
  16505. CRoxieServerCatchActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  16506. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorCatchArg &)basehelper)
  16507. {
  16508. }
  16509. virtual const void *nextInGroup()
  16510. {
  16511. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  16512. try
  16513. {
  16514. const void *ret = input->nextInGroup();
  16515. if (ret)
  16516. processed++;
  16517. return ret;
  16518. }
  16519. catch (IException *E)
  16520. {
  16521. E->Release();
  16522. helper.onExceptionCaught();
  16523. }
  16524. catch (...)
  16525. {
  16526. helper.onExceptionCaught();
  16527. }
  16528. throwUnexpected(); // onExceptionCaught should have thrown something
  16529. }
  16530. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  16531. {
  16532. try
  16533. {
  16534. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  16535. const void * ret = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  16536. if (ret && wasCompleteMatch)
  16537. processed++;
  16538. return ret;
  16539. }
  16540. catch (IException *E)
  16541. {
  16542. E->Release();
  16543. helper.onExceptionCaught();
  16544. }
  16545. catch (...)
  16546. {
  16547. helper.onExceptionCaught();
  16548. }
  16549. throwUnexpected(); // onExceptionCaught should have thrown something
  16550. }
  16551. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  16552. {
  16553. return input->gatherConjunctions(collector);
  16554. }
  16555. virtual void resetEOF()
  16556. {
  16557. input->resetEOF(); // MORE - why not in base class?
  16558. }
  16559. IInputSteppingMeta * querySteppingMeta()
  16560. {
  16561. return input->querySteppingMeta();
  16562. }
  16563. };
  16564. class CRoxieServerSkipCatchActivity : public CRoxieServerActivity
  16565. {
  16566. ConstPointerArray buff;
  16567. bool started;
  16568. unsigned index;
  16569. IHThorCatchArg &helper;
  16570. bool createRow;
  16571. public:
  16572. CRoxieServerSkipCatchActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _createRow)
  16573. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorCatchArg &)basehelper), createRow(_createRow)
  16574. {
  16575. started = false;
  16576. index = 0;
  16577. }
  16578. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16579. {
  16580. started = false;
  16581. index = 0;
  16582. try
  16583. {
  16584. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  16585. }
  16586. catch (IException *E)
  16587. {
  16588. onException(E);
  16589. started = true;
  16590. }
  16591. catch (...)
  16592. {
  16593. onException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught"));
  16594. started = true;
  16595. }
  16596. }
  16597. virtual void reset()
  16598. {
  16599. while (buff.isItem(index))
  16600. ReleaseRoxieRow(buff.item(index++));
  16601. buff.kill();
  16602. started = false;
  16603. CRoxieServerActivity::reset();
  16604. }
  16605. virtual const void *nextInGroup()
  16606. {
  16607. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  16608. if (!started)
  16609. pullInput();
  16610. if (buff.isItem(index))
  16611. {
  16612. const void * next = buff.item(index++);
  16613. if(next)
  16614. processed++;
  16615. return next;
  16616. }
  16617. return NULL;
  16618. }
  16619. protected:
  16620. void onException(IException *E)
  16621. {
  16622. input->stop(true);
  16623. ReleaseRoxieRowSet(buff);
  16624. if (createRow)
  16625. {
  16626. createRowAllocator();
  16627. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16628. size32_t outSize = helper.transformOnExceptionCaught(rowBuilder, E);
  16629. if (outSize)
  16630. buff.append(rowBuilder.finalizeRowClear(outSize));
  16631. }
  16632. E->Release();
  16633. }
  16634. void pullInput()
  16635. {
  16636. try
  16637. {
  16638. bool EOGseen = false;
  16639. loop
  16640. {
  16641. const void * next = input->nextInGroup();
  16642. buff.append(next);
  16643. if (next == NULL)
  16644. {
  16645. if (EOGseen)
  16646. break;
  16647. EOGseen = true;
  16648. }
  16649. else
  16650. EOGseen = false;
  16651. }
  16652. }
  16653. catch (IException *E)
  16654. {
  16655. onException(E);
  16656. }
  16657. catch (...)
  16658. {
  16659. onException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught"));
  16660. }
  16661. started = true;
  16662. }
  16663. };
  16664. class CRoxieServerCatchActivityFactory : public CRoxieServerActivityFactory
  16665. {
  16666. public:
  16667. CRoxieServerCatchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16668. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  16669. {
  16670. }
  16671. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  16672. {
  16673. switch (kind)
  16674. {
  16675. case TAKcatch:
  16676. return new CRoxieServerCatchActivity(this, _probeManager);
  16677. case TAKskipcatch:
  16678. return new CRoxieServerSkipCatchActivity(this, _probeManager, false);
  16679. case TAKcreaterowcatch:
  16680. return new CRoxieServerSkipCatchActivity(this, _probeManager, true);
  16681. default:
  16682. throwUnexpected();
  16683. }
  16684. }
  16685. };
  16686. IRoxieServerActivityFactory *createRoxieServerCatchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16687. {
  16688. return new CRoxieServerCatchActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  16689. }
  16690. //=================================================================================
  16691. class CRoxieServerCaseActivity : public CRoxieServerActivity
  16692. {
  16693. IHThorCaseArg &helper;
  16694. IRoxieInput **inputs;
  16695. unsigned cond;
  16696. bool unusedStopped;
  16697. IRoxieInput *in;
  16698. unsigned numInputs;
  16699. public:
  16700. CRoxieServerCaseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  16701. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorCaseArg &)basehelper), numInputs(_numInputs)
  16702. {
  16703. unusedStopped = false;
  16704. cond = 0;
  16705. inputs = new IRoxieInput*[numInputs];
  16706. for (unsigned i = 0; i < numInputs; i++)
  16707. inputs[i] = NULL;
  16708. in = NULL;
  16709. }
  16710. ~CRoxieServerCaseActivity()
  16711. {
  16712. delete [] inputs;
  16713. }
  16714. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16715. {
  16716. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  16717. cond = helper.getBranch();
  16718. //CHOOSE defaults to the last argument if out of range.
  16719. if (cond >= numInputs)
  16720. cond = numInputs - 1;
  16721. inputs[cond]->start(parentExtractSize, parentExtract, paused);
  16722. for (unsigned idx = 0; idx < numInputs; idx++)
  16723. {
  16724. if (idx!=cond)
  16725. inputs[idx]->stop(false); // Note: stopping unused branches early helps us avoid buffering splits too long.
  16726. }
  16727. in = inputs[cond];
  16728. unusedStopped = true;
  16729. }
  16730. virtual void stop(bool aborting)
  16731. {
  16732. for (unsigned idx = 0; idx < numInputs; idx++)
  16733. {
  16734. if (idx==cond || !unusedStopped)
  16735. inputs[idx]->stop(aborting);
  16736. }
  16737. CRoxieServerActivity::stop(aborting);
  16738. }
  16739. virtual void reset()
  16740. {
  16741. for (unsigned idx = 0; idx < numInputs; idx++)
  16742. {
  16743. inputs[idx]->reset();
  16744. }
  16745. unusedStopped = false;
  16746. in = NULL;
  16747. CRoxieServerActivity::reset();
  16748. }
  16749. virtual void setInput(unsigned idx, IRoxieInput *_in)
  16750. {
  16751. assertex(idx < numInputs);
  16752. inputs[idx] = _in;
  16753. }
  16754. virtual const void *nextInGroup()
  16755. {
  16756. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  16757. if (in)
  16758. {
  16759. const void *ret = in->nextInGroup();
  16760. if (ret)
  16761. processed++;
  16762. return ret;
  16763. }
  16764. return NULL;
  16765. }
  16766. };
  16767. class CRoxieServerCaseActivityFactory : public CRoxieServerMultiInputFactory
  16768. {
  16769. bool graphInvariant;
  16770. public:
  16771. CRoxieServerCaseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _graphInvariant)
  16772. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  16773. {
  16774. graphInvariant = _graphInvariant;
  16775. }
  16776. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  16777. {
  16778. return new CRoxieServerCaseActivity(this, _probeManager, numInputs());
  16779. }
  16780. virtual bool isGraphInvariant() const
  16781. {
  16782. return graphInvariant;
  16783. }
  16784. };
  16785. IRoxieServerActivityFactory *createRoxieServerCaseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _graphInvariant)
  16786. {
  16787. return new CRoxieServerCaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphInvariant);
  16788. }
  16789. //=================================================================================
  16790. class CRoxieServerIfActivity : public CRoxieServerActivity
  16791. {
  16792. IHThorIfArg &helper;
  16793. IRoxieInput *inputTrue;
  16794. IRoxieInput *inputFalse;
  16795. bool cond;
  16796. bool unusedStopped;
  16797. public:
  16798. CRoxieServerIfActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  16799. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorIfArg &)basehelper)
  16800. {
  16801. inputFalse = NULL;
  16802. inputTrue = NULL;
  16803. unusedStopped = false;
  16804. cond = false;
  16805. }
  16806. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16807. {
  16808. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  16809. cond = helper.getCondition();
  16810. if (cond)
  16811. {
  16812. inputTrue->start(parentExtractSize, parentExtract, paused);
  16813. if (inputFalse)
  16814. inputFalse->stop(false); // Note: stopping unused branches early helps us avoid buffering splits too long.
  16815. }
  16816. else
  16817. {
  16818. if (inputFalse)
  16819. inputFalse->start(parentExtractSize, parentExtract, paused);
  16820. inputTrue->stop(false);
  16821. }
  16822. unusedStopped = true;
  16823. }
  16824. virtual void stop(bool aborting)
  16825. {
  16826. if (!unusedStopped || cond)
  16827. inputTrue->stop(aborting);
  16828. if (inputFalse && (!unusedStopped || !cond))
  16829. inputFalse->stop(aborting);
  16830. CRoxieServerActivity::stop(aborting);
  16831. }
  16832. virtual unsigned __int64 queryLocalCycles() const
  16833. {
  16834. __int64 localCycles = totalCycles;
  16835. localCycles -= inputTrue->queryTotalCycles();
  16836. if (inputFalse)
  16837. localCycles -= inputFalse->queryTotalCycles();
  16838. if (localCycles < 0)
  16839. localCycles = 0;
  16840. return localCycles;
  16841. }
  16842. virtual IRoxieInput *queryInput(unsigned idx) const
  16843. {
  16844. switch (idx)
  16845. {
  16846. case 0:
  16847. return inputTrue;
  16848. case 1:
  16849. return inputFalse;
  16850. default:
  16851. return NULL;
  16852. }
  16853. }
  16854. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  16855. {
  16856. IRoxieInput *in = cond ? inputTrue : inputFalse;
  16857. if (in)
  16858. return in->queryIndexReadActivity();
  16859. return NULL;
  16860. }
  16861. virtual void reset()
  16862. {
  16863. CRoxieServerActivity::reset();
  16864. inputTrue->reset();
  16865. if (inputFalse)
  16866. inputFalse->reset();
  16867. unusedStopped = false;
  16868. }
  16869. virtual void setInput(unsigned idx, IRoxieInput *_in)
  16870. {
  16871. if (idx==1)
  16872. inputFalse = _in;
  16873. else
  16874. {
  16875. assertex(!idx);
  16876. inputTrue = _in;
  16877. }
  16878. }
  16879. virtual const void *nextInGroup()
  16880. {
  16881. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  16882. IRoxieInput *in = cond ? inputTrue : inputFalse;
  16883. if (in)
  16884. {
  16885. const void * ret;
  16886. if ((ret = in->nextInGroup()) != NULL)
  16887. processed++;
  16888. return ret;
  16889. }
  16890. return NULL;
  16891. }
  16892. };
  16893. class CRoxieServerIfActivityFactory : public CRoxieServerActivityFactory
  16894. {
  16895. unsigned input2;
  16896. unsigned input2idx;
  16897. bool graphInvariant;
  16898. public:
  16899. CRoxieServerIfActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _graphInvariant)
  16900. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  16901. {
  16902. graphInvariant = _graphInvariant;
  16903. input2 = (unsigned)-1;
  16904. input2idx = (unsigned)-1;
  16905. }
  16906. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  16907. {
  16908. return new CRoxieServerIfActivity(this, _probeManager);
  16909. }
  16910. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  16911. {
  16912. if (idx==1)
  16913. {
  16914. input2 = source;
  16915. input2idx = sourceidx;
  16916. }
  16917. else
  16918. CRoxieServerActivityFactory::setInput(idx, source, sourceidx);
  16919. }
  16920. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  16921. {
  16922. switch (idx)
  16923. {
  16924. case 1:
  16925. sourceidx = input2idx;
  16926. return input2;
  16927. case 0:
  16928. return CRoxieServerActivityFactory::getInput(idx, sourceidx);
  16929. default:
  16930. return (unsigned) -1;
  16931. }
  16932. }
  16933. virtual unsigned numInputs() const { return (input2 == (unsigned)-1) ? 1 : 2; }
  16934. virtual bool isGraphInvariant() const
  16935. {
  16936. return graphInvariant;
  16937. }
  16938. };
  16939. IRoxieServerActivityFactory *createRoxieServerIfActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _graphInvariant)
  16940. {
  16941. return new CRoxieServerIfActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphInvariant);
  16942. }
  16943. //=================================================================================
  16944. class CRoxieServerActionBaseActivity : public CRoxieServerActivity
  16945. {
  16946. CriticalSection ecrit;
  16947. Owned<IException> exception;
  16948. bool executed;
  16949. public:
  16950. CRoxieServerActionBaseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  16951. : CRoxieServerActivity(_factory, _probeManager)
  16952. {
  16953. executed = false;
  16954. }
  16955. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract) = 0;
  16956. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  16957. {
  16958. CriticalBlock b(ecrit);
  16959. if (exception)
  16960. throw(exception.getLink());
  16961. if (!executed)
  16962. {
  16963. try
  16964. {
  16965. executed = true;
  16966. start(parentExtractSize, parentExtract, false);
  16967. doExecuteAction(parentExtractSize, parentExtract);
  16968. stop(false);
  16969. }
  16970. catch (IException * E)
  16971. {
  16972. ctx->notifyAbort(E);
  16973. stop(true);
  16974. exception.set(E);
  16975. throw;
  16976. }
  16977. }
  16978. }
  16979. virtual void reset()
  16980. {
  16981. executed = false;
  16982. exception.clear();
  16983. CRoxieServerActivity::reset();
  16984. }
  16985. virtual unsigned __int64 queryLocalCycles() const
  16986. {
  16987. return totalCycles;
  16988. }
  16989. virtual const void *nextInGroup()
  16990. {
  16991. throwUnexpected(); // I am nobody's input
  16992. }
  16993. virtual IRoxieInput *queryInput(unsigned idx) const
  16994. {
  16995. throwUnexpected(); // I am nobody's input
  16996. }
  16997. };
  16998. class CRoxieServerIfActionActivity : public CRoxieServerActionBaseActivity
  16999. {
  17000. IHThorIfArg &helper;
  17001. public:
  17002. CRoxieServerIfActionActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17003. : CRoxieServerActionBaseActivity(_factory, _probeManager), helper((IHThorIfArg &)basehelper)
  17004. {
  17005. }
  17006. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  17007. {
  17008. int controlId;
  17009. {
  17010. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  17011. controlId = helper.getCondition() ? 1 : 2;
  17012. }
  17013. executeDependencies(parentExtractSize, parentExtract, controlId);
  17014. }
  17015. };
  17016. class CRoxieServerIfActionActivityFactory : public CRoxieServerActivityFactory
  17017. {
  17018. bool isRoot;
  17019. public:
  17020. CRoxieServerIfActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  17021. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  17022. {
  17023. }
  17024. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  17025. {
  17026. return new CRoxieServerIfActionActivity(this, _probeManager);
  17027. }
  17028. virtual bool isSink() const
  17029. {
  17030. return isRoot;
  17031. }
  17032. };
  17033. IRoxieServerActivityFactory *createRoxieServerIfActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  17034. {
  17035. return new CRoxieServerIfActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  17036. }
  17037. //=================================================================================
  17038. class CRoxieServerParallelActionActivity : public CRoxieServerActionBaseActivity
  17039. {
  17040. public:
  17041. CRoxieServerParallelActionActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17042. : CRoxieServerActionBaseActivity(_factory, _probeManager)
  17043. {
  17044. }
  17045. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  17046. {
  17047. #ifdef PARALLEL_EXECUTE
  17048. CParallelActivityExecutor afor(dependencies, parentExtractSize, parentExtract);
  17049. afor.For(dependencies.ordinality(), dependencies.ordinality(), true);
  17050. #else
  17051. ForEachItemIn(idx, dependencies)
  17052. {
  17053. dependencies.item(idx).execute(parentExtractSize, parentExtract);
  17054. }
  17055. #endif
  17056. }
  17057. };
  17058. class CRoxieServerParallelActionActivityFactory : public CRoxieServerActivityFactory
  17059. {
  17060. bool isRoot;
  17061. public:
  17062. CRoxieServerParallelActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  17063. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  17064. {
  17065. assertex(!isRoot); // non-internal should be expanded out..
  17066. }
  17067. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  17068. {
  17069. return new CRoxieServerParallelActionActivity(this, _probeManager);
  17070. }
  17071. virtual bool isSink() const
  17072. {
  17073. return isRoot;
  17074. }
  17075. };
  17076. IRoxieServerActivityFactory *createRoxieServerParallelActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  17077. {
  17078. return new CRoxieServerParallelActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  17079. }
  17080. //=================================================================================
  17081. class CRoxieServerSequentialActionActivity : public CRoxieServerActionBaseActivity
  17082. {
  17083. IHThorSequentialArg &helper;
  17084. public:
  17085. CRoxieServerSequentialActionActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17086. : CRoxieServerActionBaseActivity(_factory, _probeManager), helper((IHThorSequentialArg &)basehelper)
  17087. {
  17088. }
  17089. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  17090. {
  17091. unsigned numBranches = helper.numBranches();
  17092. for (unsigned branch=1; branch <= numBranches; branch++)
  17093. executeDependencies(parentExtractSize, parentExtract, branch);
  17094. }
  17095. };
  17096. class CRoxieServerSequentialActionActivityFactory : public CRoxieServerActivityFactory
  17097. {
  17098. bool isRoot;
  17099. public:
  17100. CRoxieServerSequentialActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  17101. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  17102. {
  17103. }
  17104. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  17105. {
  17106. return new CRoxieServerSequentialActionActivity(this, _probeManager);
  17107. }
  17108. virtual bool isSink() const
  17109. {
  17110. return isRoot;
  17111. }
  17112. };
  17113. IRoxieServerActivityFactory *createRoxieServerSequentialActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  17114. {
  17115. return new CRoxieServerSequentialActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  17116. }
  17117. //=================================================================================
  17118. class CRoxieServerWhenActivity : public CRoxieServerActivity
  17119. {
  17120. public:
  17121. CRoxieServerWhenActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17122. : CRoxieServerActivity(_factory, _probeManager)
  17123. {
  17124. savedExtractSize = 0;
  17125. savedExtract = NULL;
  17126. }
  17127. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17128. {
  17129. savedExtractSize = parentExtractSize;
  17130. savedExtract = parentExtract;
  17131. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  17132. executeDependencies(parentExtractSize, parentExtract, WhenParallelId); // MORE: This should probably be done in parallel!
  17133. }
  17134. virtual void stop(bool aborting)
  17135. {
  17136. if (state != STATEstopped)
  17137. executeDependencies(savedExtractSize, savedExtract, aborting ? WhenFailureId : WhenSuccessId);
  17138. CRoxieServerActivity::stop(aborting);
  17139. }
  17140. virtual const void *nextInGroup()
  17141. {
  17142. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext()); // bit of a waste of time....
  17143. return input->nextInGroup();
  17144. }
  17145. protected:
  17146. unsigned savedExtractSize;
  17147. const byte *savedExtract;
  17148. };
  17149. class CRoxieServerWhenActivityFactory : public CRoxieServerActivityFactory
  17150. {
  17151. public:
  17152. CRoxieServerWhenActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  17153. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  17154. {
  17155. }
  17156. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  17157. {
  17158. return new CRoxieServerWhenActivity(this, _probeManager);
  17159. }
  17160. };
  17161. extern IRoxieServerActivityFactory *createRoxieServerWhenActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  17162. {
  17163. return new CRoxieServerWhenActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  17164. }
  17165. //=================================================================================
  17166. class CRoxieServerWhenActionActivity : public CRoxieServerActionBaseActivity
  17167. {
  17168. public:
  17169. CRoxieServerWhenActionActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17170. : CRoxieServerActionBaseActivity(_factory, _probeManager)
  17171. {
  17172. savedExtractSize = 0;
  17173. savedExtract = NULL;
  17174. }
  17175. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17176. {
  17177. savedExtractSize = parentExtractSize;
  17178. savedExtract = parentExtract;
  17179. CRoxieServerActionBaseActivity::start(parentExtractSize, parentExtract, paused);
  17180. executeDependencies(parentExtractSize, parentExtract, WhenParallelId); // MORE: This should probably be done in parallel!
  17181. }
  17182. virtual void stop(bool aborting)
  17183. {
  17184. if (state != STATEstopped)
  17185. executeDependencies(savedExtractSize, savedExtract, aborting ? WhenFailureId : WhenSuccessId);
  17186. CRoxieServerActionBaseActivity::stop(aborting);
  17187. }
  17188. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  17189. {
  17190. executeDependencies(parentExtractSize, parentExtract, 1);
  17191. }
  17192. protected:
  17193. unsigned savedExtractSize;
  17194. const byte *savedExtract;
  17195. };
  17196. class CRoxieServerWhenActionActivityFactory : public CRoxieServerActivityFactory
  17197. {
  17198. public:
  17199. CRoxieServerWhenActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  17200. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  17201. {
  17202. }
  17203. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  17204. {
  17205. return new CRoxieServerWhenActionActivity(this, _probeManager);
  17206. }
  17207. virtual bool isSink() const
  17208. {
  17209. return isRoot;
  17210. }
  17211. private:
  17212. bool isRoot;
  17213. };
  17214. extern IRoxieServerActivityFactory *createRoxieServerWhenActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  17215. {
  17216. return new CRoxieServerWhenActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  17217. }
  17218. //=================================================================================
  17219. class CRoxieServerParseActivity : public CRoxieServerActivity, implements IMatchedAction
  17220. {
  17221. IHThorParseArg &helper;
  17222. INlpParser * parser;
  17223. INlpResultIterator * rowIter;
  17224. const void * in;
  17225. char * curSearchText;
  17226. INlpParseAlgorithm * algorithm;
  17227. size32_t curSearchTextLen;
  17228. bool anyThisGroup;
  17229. bool processRecord(const void * inRec)
  17230. {
  17231. if (helper.searchTextNeedsFree())
  17232. rtlFree(curSearchText);
  17233. curSearchTextLen = 0;
  17234. curSearchText = NULL;
  17235. helper.getSearchText(curSearchTextLen, curSearchText, inRec);
  17236. return parser->performMatch(*this, in, curSearchTextLen, curSearchText);
  17237. }
  17238. public:
  17239. CRoxieServerParseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, INlpParseAlgorithm * _algorithm)
  17240. : CRoxieServerActivity(_factory, _probeManager),
  17241. helper((IHThorParseArg &)basehelper), algorithm(_algorithm)
  17242. {
  17243. parser = NULL;
  17244. rowIter = NULL;
  17245. in = NULL;
  17246. curSearchText = NULL;
  17247. anyThisGroup = false;
  17248. curSearchTextLen = 0;
  17249. }
  17250. ~CRoxieServerParseActivity()
  17251. {
  17252. ::Release(parser);
  17253. }
  17254. virtual bool needsAllocator() const { return true; }
  17255. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  17256. {
  17257. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  17258. parser = algorithm->createParser(_ctx->queryCodeContext(), activityId, helper.queryHelper(), &helper);
  17259. rowIter = parser->queryResultIter();
  17260. }
  17261. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17262. {
  17263. anyThisGroup = false;
  17264. curSearchTextLen = 0;
  17265. curSearchText = NULL;
  17266. in = NULL;
  17267. parser->reset();
  17268. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  17269. }
  17270. virtual void reset()
  17271. {
  17272. if (helper.searchTextNeedsFree())
  17273. rtlFree(curSearchText);
  17274. curSearchText = NULL;
  17275. ReleaseClearRoxieRow(in);
  17276. CRoxieServerActivity::reset();
  17277. }
  17278. virtual unsigned onMatch(ARowBuilder & self, const void * curRecord, IMatchedResults * results, IMatchWalker * walker)
  17279. {
  17280. try
  17281. {
  17282. return helper.transform(self, curRecord, results, walker);
  17283. }
  17284. catch (IException *E)
  17285. {
  17286. throw makeWrappedException(E);
  17287. }
  17288. }
  17289. virtual const void * nextInGroup()
  17290. {
  17291. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  17292. loop
  17293. {
  17294. if (rowIter->isValid())
  17295. {
  17296. anyThisGroup = true;
  17297. OwnedConstRoxieRow out = rowIter->getRow();
  17298. rowIter->next();
  17299. processed++;
  17300. return out.getClear();
  17301. }
  17302. ReleaseClearRoxieRow(in);
  17303. in = input->nextInGroup();
  17304. if (!in)
  17305. {
  17306. if (anyThisGroup)
  17307. {
  17308. anyThisGroup = false;
  17309. return NULL;
  17310. }
  17311. in = input->nextInGroup();
  17312. if (!in)
  17313. return NULL;
  17314. }
  17315. processRecord(in);
  17316. rowIter->first();
  17317. }
  17318. }
  17319. };
  17320. class CRoxieServerParseActivityFactory : public CRoxieServerActivityFactory
  17321. {
  17322. Owned<INlpParseAlgorithm> algorithm;
  17323. Owned<IHThorParseArg> helper;
  17324. public:
  17325. CRoxieServerParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IResourceContext *rc)
  17326. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  17327. {
  17328. helper.setown((IHThorParseArg *) helperFactory());
  17329. algorithm.setown(createThorParser(rc, *helper));
  17330. }
  17331. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  17332. {
  17333. return new CRoxieServerParseActivity(this, _probeManager, algorithm);
  17334. }
  17335. };
  17336. IRoxieServerActivityFactory *createRoxieServerParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IResourceContext *rc)
  17337. {
  17338. return new CRoxieServerParseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, rc);
  17339. }
  17340. //=====================================================================================================
  17341. class CRoxieServerWorkUnitWriteActivity : public CRoxieServerInternalSinkActivity
  17342. {
  17343. IHThorWorkUnitWriteArg &helper;
  17344. bool isReread;
  17345. bool grouped;
  17346. IRoxieServerContext *serverContext;
  17347. public:
  17348. CRoxieServerWorkUnitWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _isReread)
  17349. : CRoxieServerInternalSinkActivity(_factory, _probeManager), helper((IHThorWorkUnitWriteArg &)basehelper), isReread(_isReread)
  17350. {
  17351. grouped = (helper.getFlags() & POFgrouped) != 0;
  17352. serverContext = NULL;
  17353. }
  17354. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  17355. {
  17356. CRoxieServerInternalSinkActivity::onCreate(_ctx, _colocalParent);
  17357. serverContext = ctx->queryServerContext();
  17358. if (!serverContext)
  17359. {
  17360. throw MakeStringException(ROXIE_PIPE_ERROR, "Pipe output activity cannot be executed in slave context");
  17361. }
  17362. }
  17363. virtual bool needsAllocator() const { return true; }
  17364. virtual void onExecute()
  17365. {
  17366. int sequence = helper.getSequence();
  17367. const char *storedName = helper.queryName();
  17368. if (!storedName)
  17369. storedName = "Dataset";
  17370. MemoryBuffer result;
  17371. FlushingStringBuffer *response = NULL;
  17372. bool saveInContext = (int) sequence < 0 || isReread;
  17373. if (!meta.queryOriginal()) // this is a bit of a hack - don't know why no meta on an output....
  17374. meta.set(input->queryOutputMeta());
  17375. Owned<IOutputRowSerializer> rowSerializer;
  17376. Owned<IXmlWriter> writer;
  17377. if ((int) sequence >= 0)
  17378. {
  17379. response = serverContext->queryResult(sequence);
  17380. if (response)
  17381. {
  17382. response->startDataset("Dataset", helper.queryName(), sequence, (helper.getFlags() & POFextend) != 0);
  17383. if (response->mlFmt==MarkupFmt_XML || response->mlFmt==MarkupFmt_JSON)
  17384. {
  17385. unsigned int writeFlags = serverContext->getXmlFlags();
  17386. if (response->mlFmt==MarkupFmt_JSON)
  17387. writeFlags |= XWFnoindent;
  17388. writer.setown(createIXmlWriter(writeFlags, 1, response, (response->mlFmt==MarkupFmt_JSON) ? WTJSON : WTStandard));
  17389. writer->outputBeginArray("Row");
  17390. }
  17391. }
  17392. }
  17393. if (serverContext->outputResultsToWorkUnit()||(response && response->isRaw))
  17394. {
  17395. createRowAllocator();
  17396. rowSerializer.setown(rowAllocator->createDiskSerializer(ctx->queryCodeContext()));
  17397. }
  17398. __int64 initialProcessed = processed;
  17399. RtlLinkedDatasetBuilder builder(rowAllocator);
  17400. loop
  17401. {
  17402. const void *row = input->nextInGroup();
  17403. if (saveInContext)
  17404. {
  17405. if (row || grouped)
  17406. builder.append(row);
  17407. }
  17408. if (grouped && (processed != initialProcessed))
  17409. {
  17410. if (serverContext->outputResultsToWorkUnit())
  17411. result.append(row == NULL);
  17412. if (response)
  17413. {
  17414. if (response->isRaw)
  17415. response->append(row == NULL);
  17416. else
  17417. {
  17418. response->append("<Row __GroupBreak__=\"1\"/>"); // sensible, but need to handle on input
  17419. }
  17420. }
  17421. }
  17422. if (!row)
  17423. {
  17424. row = input->nextInGroup();
  17425. if (!row)
  17426. break;
  17427. if (saveInContext)
  17428. builder.append(row);
  17429. }
  17430. processed++;
  17431. if (serverContext->outputResultsToWorkUnit())
  17432. {
  17433. CThorDemoRowSerializer serializerTarget(result);
  17434. rowSerializer->serialize(serializerTarget, (const byte *) row);
  17435. }
  17436. if (response)
  17437. {
  17438. if (response->isRaw)
  17439. {
  17440. // MORE - should be able to serialize straight to the response...
  17441. MemoryBuffer rowbuff;
  17442. CThorDemoRowSerializer serializerTarget(rowbuff);
  17443. rowSerializer->serialize(serializerTarget, (const byte *) row);
  17444. response->append(rowbuff.length(), rowbuff.toByteArray());
  17445. }
  17446. else if (writer)
  17447. {
  17448. writer->outputBeginNested("Row", false);
  17449. helper.serializeXml((byte *) row, *writer);
  17450. writer->outputEndNested("Row");
  17451. }
  17452. else
  17453. {
  17454. SimpleOutputWriter x;
  17455. helper.serializeXml((byte *) row, x);
  17456. x.newline();
  17457. response->append(x.str());
  17458. }
  17459. response->incrementRowCount();
  17460. response->flush(false);
  17461. }
  17462. ReleaseRoxieRow(row);
  17463. }
  17464. if (writer)
  17465. writer->outputEndArray("Row");
  17466. if (saveInContext)
  17467. serverContext->appendResultDeserialized(storedName, sequence, builder.getcount(), builder.linkrows(), (helper.getFlags() & POFextend) != 0, LINK(meta.queryOriginal()));
  17468. if (serverContext->outputResultsToWorkUnit())
  17469. serverContext->appendResultRawContext(storedName, sequence, result.length(), result.toByteArray(), processed, (helper.getFlags() & POFextend) != 0, false); // MORE - shame to do extra copy...
  17470. }
  17471. };
  17472. class CRoxieServerWorkUnitWriteActivityFactory : public CRoxieServerInternalSinkFactory
  17473. {
  17474. bool isReread;
  17475. public:
  17476. CRoxieServerWorkUnitWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  17477. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot)
  17478. {
  17479. isReread = usageCount > 0;
  17480. Owned<IHThorWorkUnitWriteArg> helper = (IHThorWorkUnitWriteArg *) helperFactory();
  17481. isInternal = (helper->getSequence()==ResultSequenceInternal);
  17482. }
  17483. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  17484. {
  17485. return new CRoxieServerWorkUnitWriteActivity(this, _probeManager, isReread);
  17486. }
  17487. };
  17488. IRoxieServerActivityFactory *createRoxieServerWorkUnitWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  17489. {
  17490. return new CRoxieServerWorkUnitWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot);
  17491. }
  17492. //=====================================================================================================
  17493. class CRoxieServerWorkUnitWriteDictActivity : public CRoxieServerInternalSinkActivity
  17494. {
  17495. IHThorDictionaryWorkUnitWriteArg &helper;
  17496. IRoxieServerContext *serverContext;
  17497. public:
  17498. CRoxieServerWorkUnitWriteDictActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17499. : CRoxieServerInternalSinkActivity(_factory, _probeManager), helper((IHThorDictionaryWorkUnitWriteArg &)basehelper)
  17500. {
  17501. serverContext = NULL;
  17502. }
  17503. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  17504. {
  17505. CRoxieServerInternalSinkActivity::onCreate(_ctx, _colocalParent);
  17506. serverContext = ctx->queryServerContext();
  17507. if (!serverContext)
  17508. {
  17509. throw MakeStringException(ROXIE_PIPE_ERROR, "Write Dictionary activity cannot be executed in slave context");
  17510. }
  17511. }
  17512. virtual bool needsAllocator() const { return true; }
  17513. virtual void onExecute()
  17514. {
  17515. int sequence = helper.getSequence();
  17516. const char *storedName = helper.queryName();
  17517. assertex(storedName && *storedName);
  17518. assertex(sequence < 0);
  17519. RtlLinkedDictionaryBuilder builder(rowAllocator, helper.queryHashLookupInfo());
  17520. loop
  17521. {
  17522. const void *row = input->nextInGroup();
  17523. if (!row)
  17524. {
  17525. row = input->nextInGroup();
  17526. if (!row)
  17527. break;
  17528. }
  17529. builder.appendOwn(row);
  17530. processed++;
  17531. }
  17532. serverContext->appendResultDeserialized(storedName, sequence, builder.getcount(), builder.linkrows(), (helper.getFlags() & POFextend) != 0, LINK(meta.queryOriginal()));
  17533. }
  17534. };
  17535. class CRoxieServerWorkUnitWriteDictActivityFactory : public CRoxieServerInternalSinkFactory
  17536. {
  17537. public:
  17538. CRoxieServerWorkUnitWriteDictActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  17539. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot)
  17540. {
  17541. Owned<IHThorDictionaryWorkUnitWriteArg> helper = (IHThorDictionaryWorkUnitWriteArg *) helperFactory();
  17542. isInternal = (helper->getSequence()==ResultSequenceInternal);
  17543. }
  17544. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  17545. {
  17546. return new CRoxieServerWorkUnitWriteDictActivity(this, _probeManager);
  17547. }
  17548. };
  17549. IRoxieServerActivityFactory *createRoxieServerWorkUnitWriteDictActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  17550. {
  17551. return new CRoxieServerWorkUnitWriteDictActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot);
  17552. }
  17553. //=================================================================================
  17554. class CRoxieServerRemoteResultActivity : public CRoxieServerInternalSinkActivity
  17555. {
  17556. IHThorRemoteResultArg &helper;
  17557. public:
  17558. CRoxieServerRemoteResultActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17559. : CRoxieServerInternalSinkActivity(_factory, _probeManager), helper((IHThorRemoteResultArg &)basehelper)
  17560. {
  17561. }
  17562. virtual void onExecute()
  17563. {
  17564. OwnedConstRoxieRow row = input->nextInGroup();
  17565. helper.sendResult(row); // should be only one row or something has gone wrong!
  17566. }
  17567. };
  17568. class CRoxieServerRemoteResultActivityFactory : public CRoxieServerInternalSinkFactory
  17569. {
  17570. public:
  17571. CRoxieServerRemoteResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  17572. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot)
  17573. {
  17574. Owned<IHThorRemoteResultArg> helper = (IHThorRemoteResultArg *) helperFactory();
  17575. isInternal = (helper->getSequence()==ResultSequenceInternal);
  17576. }
  17577. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  17578. {
  17579. return new CRoxieServerRemoteResultActivity(this, _probeManager);
  17580. }
  17581. };
  17582. IRoxieServerActivityFactory *createRoxieServerRemoteResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  17583. {
  17584. return new CRoxieServerRemoteResultActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot);
  17585. }
  17586. //=================================================================================
  17587. class CRoxieServerXmlParseActivity : public CRoxieServerActivity, implements IXMLSelect
  17588. {
  17589. IHThorXmlParseArg &helper;
  17590. Owned<IXMLParse> xmlParser;
  17591. const void * in;
  17592. char * srchStr;
  17593. unsigned numProcessedLastGroup;
  17594. bool srchStrNeedsFree;
  17595. Owned<IColumnProvider> lastMatch;
  17596. public:
  17597. IMPLEMENT_IINTERFACE;
  17598. CRoxieServerXmlParseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17599. : CRoxieServerActivity(_factory, _probeManager),
  17600. helper((IHThorXmlParseArg &)basehelper)
  17601. {
  17602. srchStrNeedsFree = helper.searchTextNeedsFree();
  17603. numProcessedLastGroup = 0;
  17604. srchStr = NULL;
  17605. in = NULL;
  17606. }
  17607. ~CRoxieServerXmlParseActivity()
  17608. {
  17609. }
  17610. virtual bool needsAllocator() const { return true; }
  17611. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17612. {
  17613. numProcessedLastGroup = 0;
  17614. srchStr = NULL;
  17615. in = NULL;
  17616. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  17617. }
  17618. virtual void reset()
  17619. {
  17620. if (helper.searchTextNeedsFree())
  17621. rtlFree(srchStr);
  17622. srchStr = NULL;
  17623. ReleaseClearRoxieRow(in);
  17624. xmlParser.clear();
  17625. CRoxieServerActivity::reset();
  17626. }
  17627. virtual void match(IColumnProvider &entry, offset_t startOffset, offset_t endOffset)
  17628. {
  17629. lastMatch.set(&entry);
  17630. }
  17631. virtual const void *nextInGroup()
  17632. {
  17633. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  17634. loop
  17635. {
  17636. if(xmlParser)
  17637. {
  17638. loop
  17639. {
  17640. if(!xmlParser->next())
  17641. {
  17642. if (srchStrNeedsFree)
  17643. {
  17644. rtlFree(srchStr);
  17645. srchStr = NULL;
  17646. }
  17647. xmlParser.clear();
  17648. break;
  17649. }
  17650. if(lastMatch)
  17651. {
  17652. try
  17653. {
  17654. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17655. size32_t outSize = helper.transform(rowBuilder, in, lastMatch);
  17656. lastMatch.clear();
  17657. if (outSize)
  17658. {
  17659. processed++;
  17660. return rowBuilder.finalizeRowClear(outSize);
  17661. }
  17662. }
  17663. catch (IException *E)
  17664. {
  17665. throw makeWrappedException(E);
  17666. }
  17667. }
  17668. }
  17669. }
  17670. ReleaseClearRoxieRow(in);
  17671. in = input->nextInGroup();
  17672. if(!in)
  17673. {
  17674. if(numProcessedLastGroup == processed)
  17675. in = input->nextInGroup();
  17676. if(!in)
  17677. {
  17678. numProcessedLastGroup = processed;
  17679. return NULL;
  17680. }
  17681. }
  17682. size32_t srchLen;
  17683. helper.getSearchText(srchLen, srchStr, in);
  17684. OwnedRoxieString xmlIteratorPath(helper.getXmlIteratorPath());
  17685. xmlParser.setown(createXMLParse(srchStr, srchLen, xmlIteratorPath, *this));
  17686. }
  17687. }
  17688. };
  17689. class CRoxieServerXmlParseActivityFactory : public CRoxieServerActivityFactory
  17690. {
  17691. public:
  17692. CRoxieServerXmlParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  17693. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  17694. {
  17695. }
  17696. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  17697. {
  17698. return new CRoxieServerXmlParseActivity(this, _probeManager);
  17699. }
  17700. };
  17701. IRoxieServerActivityFactory *createRoxieServerXmlParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  17702. {
  17703. return new CRoxieServerXmlParseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  17704. }
  17705. //=====================================================================================================
  17706. class CRoxieServerDiskReadBaseActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler, implements IIndexReadContext
  17707. {
  17708. protected:
  17709. IHThorDiskReadBaseArg &helper;
  17710. IHThorCompoundExtra * compoundHelper;
  17711. RemoteActivityId remoteId; // Note we copy it rather than reference
  17712. Owned<CSkippableRemoteResultAdaptor> remote;
  17713. unsigned numParts;
  17714. unsigned __int64 rowLimit;
  17715. unsigned __int64 stopAfter;
  17716. Linked<IInMemoryIndexManager> manager;
  17717. Owned<IInMemoryIndexCursor> cursor;
  17718. Owned<IDirectReader> reader;
  17719. CThorContiguousRowBuffer deserializeSource;
  17720. Owned<ISourceRowPrefetcher> prefetcher;
  17721. bool eof;
  17722. bool isKeyed;
  17723. bool variableFileName;
  17724. bool isOpt;
  17725. bool sorted;
  17726. bool maySkip;
  17727. bool isLocal;
  17728. CachedOutputMetaData diskSize;
  17729. Owned<const IResolvedFile> varFileInfo;
  17730. Owned<IFileIOArray> varFiles;
  17731. inline bool useRemote()
  17732. {
  17733. return remote != NULL && numParts > 1;
  17734. }
  17735. public:
  17736. IMPLEMENT_IINTERFACE;
  17737. CRoxieServerDiskReadBaseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager)
  17738. : CRoxieServerActivity(_factory, _probeManager),
  17739. helper((IHThorDiskReadBaseArg &)basehelper),
  17740. numParts(_numParts),
  17741. remoteId(_remoteId),
  17742. manager(_manager),
  17743. isLocal(_isLocal),
  17744. sorted(_sorted),
  17745. maySkip(_maySkip),
  17746. deserializeSource(NULL)
  17747. {
  17748. if (numParts != 1 && !isLocal) // NOTE : when numParts == 0 (variable case) we create, even though we may not use
  17749. remote.setown(new CSkippableRemoteResultAdaptor(remoteId, meta.queryOriginal(), helper, *this, sorted, false, _maySkip));
  17750. compoundHelper = NULL;
  17751. eof = false;
  17752. rowLimit = (unsigned __int64) -1;
  17753. isKeyed = false;
  17754. stopAfter = I64C(0x7FFFFFFFFFFFFFFF);
  17755. diskSize.set(helper.queryDiskRecordSize());
  17756. variableFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getFlags() & (TDXvarfilename|TDXdynamicfilename)) != 0);
  17757. isOpt = (helper.getFlags() & TDRoptional) != 0;
  17758. }
  17759. virtual const IResolvedFile *queryVarFileInfo() const
  17760. {
  17761. return varFileInfo;
  17762. }
  17763. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  17764. {
  17765. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  17766. if (remote)
  17767. remote->onCreate(this, this, _ctx, _colocalParent);
  17768. }
  17769. virtual bool needsAllocator() const { return true; }
  17770. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17771. {
  17772. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  17773. if (compoundHelper)
  17774. {
  17775. rowLimit = compoundHelper->getRowLimit();
  17776. stopAfter = compoundHelper->getChooseNLimit();
  17777. }
  17778. if (!helper.canMatchAny())
  17779. eof = true;
  17780. else
  17781. {
  17782. if (variableFileName)
  17783. {
  17784. OwnedRoxieString fileName(helper.getFileName());
  17785. varFileInfo.setown(resolveLFN(fileName, isOpt));
  17786. numParts = 0;
  17787. if (varFileInfo)
  17788. {
  17789. Owned<IFilePartMap> map = varFileInfo->getFileMap();
  17790. if (map)
  17791. numParts = map->getNumParts();
  17792. }
  17793. }
  17794. if (!numParts)
  17795. {
  17796. eof = true;
  17797. }
  17798. else if (useRemote())
  17799. {
  17800. remote->onStart(parentExtractSize, parentExtract);
  17801. remote->setLimits(rowLimit, (unsigned __int64) -1, stopAfter);
  17802. unsigned fileNo = 0; // MORE - superfiles require us to do this per file part... maybe (needs thought)
  17803. // Translation into a message per channel done elsewhere....
  17804. remote->getMem(0, fileNo, 0);
  17805. remote->flush();
  17806. remote->senddone();
  17807. }
  17808. else
  17809. {
  17810. if (variableFileName)
  17811. {
  17812. unsigned channel = isLocal ? factory->queryQueryFactory().queryChannel() : 0;
  17813. varFiles.setown(varFileInfo->getIFileIOArray(isOpt, channel));
  17814. manager.setown(varFileInfo->getIndexManager(isOpt, channel, varFiles, diskSize, false, 0));
  17815. }
  17816. assertex(manager != NULL);
  17817. helper.createSegmentMonitors(this);
  17818. if (cursor)
  17819. {
  17820. isKeyed = cursor->selectKey();
  17821. cursor->reset();
  17822. }
  17823. if (!isKeyed)
  17824. {
  17825. reader.setown(manager->createReader(0, 0, 1));
  17826. deserializeSource.setStream(reader);
  17827. prefetcher.setown(diskSize.queryOriginal()->createDiskPrefetcher(ctx->queryCodeContext(), activityId));
  17828. }
  17829. helper.setCallback(reader ? reader->queryThorDiskCallback() : cursor);
  17830. }
  17831. }
  17832. }
  17833. virtual void append(IKeySegmentMonitor *segment)
  17834. {
  17835. if (!segment->isWild())
  17836. {
  17837. if (!cursor)
  17838. cursor.setown(manager->createCursor());
  17839. cursor->append(segment);
  17840. }
  17841. }
  17842. virtual unsigned ordinality() const
  17843. {
  17844. return cursor ? cursor->ordinality() : 0;
  17845. }
  17846. virtual IKeySegmentMonitor *item(unsigned idx) const
  17847. {
  17848. return cursor ? cursor->item(idx) : 0;
  17849. }
  17850. virtual void setMergeBarrier(unsigned barrierOffset)
  17851. {
  17852. // no merging so no issue...
  17853. }
  17854. virtual void stop(bool aborting)
  17855. {
  17856. if (useRemote())
  17857. remote->onStop(aborting);
  17858. CRoxieServerActivity::stop(aborting);
  17859. }
  17860. virtual void reset()
  17861. {
  17862. if (useRemote())
  17863. {
  17864. processed = remote->processed;
  17865. remote->processed = 0;
  17866. remote->onReset();
  17867. }
  17868. varFileInfo.clear();
  17869. eof = false;
  17870. if (cursor)
  17871. cursor->reset();
  17872. deserializeSource.clearStream();
  17873. CRoxieServerActivity::reset();
  17874. }
  17875. virtual void setInput(unsigned idx, IRoxieInput *_in)
  17876. {
  17877. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  17878. }
  17879. virtual void onLimitExceeded(bool isKeyed)
  17880. {
  17881. if (traceLevel > 4)
  17882. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  17883. assertex(compoundHelper);
  17884. if (isKeyed) // MORE does this exist for diskread? should it?
  17885. {
  17886. if (helper.getFlags() & (TDRkeyedlimitskips|TDRkeyedlimitcreates))
  17887. {
  17888. if (ctx->queryDebugContext())
  17889. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  17890. throw makeLimitSkipException(true);
  17891. }
  17892. else
  17893. {
  17894. UNIMPLEMENTED;
  17895. //compoundHelper->onKeyedLimitExceeded(); Doesn't exist - though the flags do... interesting...
  17896. }
  17897. }
  17898. else
  17899. {
  17900. if (helper.getFlags() & (TDRlimitskips|TDRlimitcreates))
  17901. {
  17902. if (ctx->queryDebugContext())
  17903. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  17904. throw makeLimitSkipException(false);
  17905. }
  17906. else
  17907. compoundHelper->onLimitExceeded();
  17908. }
  17909. }
  17910. virtual const void * createLimitFailRow(bool isKeyed)
  17911. {
  17912. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17913. IHThorSourceLimitTransformExtra *limitTransformExtra = static_cast<IHThorSourceLimitTransformExtra *>(helper.selectInterface(TAIsourcelimittransformextra_1));
  17914. assertex(limitTransformExtra);
  17915. size32_t outSize = isKeyed ? limitTransformExtra->transformOnKeyedLimitExceeded(rowBuilder) : limitTransformExtra->transformOnLimitExceeded(rowBuilder);
  17916. if (outSize)
  17917. return rowBuilder.finalizeRowClear(outSize);
  17918. return NULL;
  17919. }
  17920. };
  17921. class CRoxieServerDiskReadActivity : public CRoxieServerDiskReadBaseActivity
  17922. {
  17923. IHThorCompoundReadExtra * readHelper;
  17924. ConstPointerArray readrows;
  17925. bool readAheadDone;
  17926. unsigned readIndex;
  17927. public:
  17928. CRoxieServerDiskReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager)
  17929. : CRoxieServerDiskReadBaseActivity(_factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, _maySkip, _manager)
  17930. {
  17931. compoundHelper = (IHThorDiskReadArg *)&helper;
  17932. readHelper = (IHThorDiskReadArg *)&helper;
  17933. readAheadDone = false;
  17934. readIndex = 0;
  17935. }
  17936. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17937. {
  17938. rowLimit = compoundHelper->getRowLimit();
  17939. stopAfter = compoundHelper->getChooseNLimit();
  17940. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  17941. readAheadDone = false;
  17942. readIndex = 0;
  17943. }
  17944. virtual void reset()
  17945. {
  17946. while (readrows.isItem(readIndex))
  17947. ReleaseRoxieRow(readrows.item(readIndex++));
  17948. readrows.kill();
  17949. readAheadDone = false;
  17950. readIndex = 0;
  17951. CRoxieServerDiskReadBaseActivity::reset();
  17952. }
  17953. virtual const void *nextInGroup()
  17954. {
  17955. if (eof)
  17956. return NULL;
  17957. else if (useRemote())
  17958. return remote->nextInGroup();
  17959. else if (maySkip)
  17960. {
  17961. if (!readAheadDone)
  17962. {
  17963. unsigned preprocessed = 0;
  17964. while (!eof)
  17965. {
  17966. const void *row = _nextInGroup();
  17967. if (row)
  17968. preprocessed++;
  17969. if (preprocessed > rowLimit)
  17970. {
  17971. ReleaseRoxieRow(row);
  17972. while (readrows.isItem(readIndex))
  17973. ReleaseRoxieRow(readrows.item(readIndex++));
  17974. readrows.kill();
  17975. eof = true;
  17976. if (ctx->queryDebugContext())
  17977. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  17978. if (helper.getFlags() & TDRlimitskips)
  17979. return NULL;
  17980. else if (helper.getFlags() & TDRlimitcreates)
  17981. return createLimitFailRow(false);
  17982. else
  17983. throwUnexpected();
  17984. }
  17985. if (preprocessed > stopAfter) // MORE - bit of a strange place to check
  17986. {
  17987. eof = true;
  17988. ReleaseRoxieRow(row);
  17989. break;
  17990. }
  17991. readrows.append(row);
  17992. }
  17993. readAheadDone = true;
  17994. }
  17995. if (readrows.isItem(readIndex))
  17996. {
  17997. const void *ret = readrows.item(readIndex++);
  17998. if (ret)
  17999. processed++;
  18000. return ret;
  18001. }
  18002. else
  18003. {
  18004. eof = true;
  18005. return NULL;
  18006. }
  18007. }
  18008. else
  18009. {
  18010. const void *ret = _nextInGroup();
  18011. if (ret)
  18012. {
  18013. processed++;
  18014. if (processed > rowLimit)
  18015. {
  18016. if (traceLevel > 4)
  18017. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  18018. ReleaseRoxieRow(ret);
  18019. compoundHelper->onLimitExceeded();
  18020. throwUnexpected(); // onLimitExceeded is not supposed to return
  18021. }
  18022. if (processed > stopAfter) // MORE - bit of a strange place to check
  18023. {
  18024. eof = true;
  18025. ReleaseRoxieRow(ret);
  18026. return NULL;
  18027. }
  18028. }
  18029. return ret;
  18030. }
  18031. }
  18032. const void *_nextInGroup()
  18033. {
  18034. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  18035. unsigned transformedSize = 0;
  18036. if (isKeyed)
  18037. {
  18038. loop
  18039. {
  18040. const void *nextCandidate = cursor->nextMatch();
  18041. if (!nextCandidate)
  18042. {
  18043. eof = true;
  18044. return NULL;
  18045. }
  18046. transformedSize = readHelper->transform(rowBuilder, nextCandidate);
  18047. if (transformedSize)
  18048. break;
  18049. }
  18050. }
  18051. else // use reader...
  18052. {
  18053. assertex(reader != NULL);
  18054. loop
  18055. {
  18056. if (deserializeSource.eos())
  18057. {
  18058. eof = true;
  18059. return NULL;
  18060. }
  18061. prefetcher->readAhead(deserializeSource);
  18062. const byte *nextRec = deserializeSource.queryRow();
  18063. if (cursor && cursor->isFiltered(nextRec))
  18064. transformedSize = 0;
  18065. else
  18066. transformedSize = readHelper->transform(rowBuilder, nextRec);
  18067. deserializeSource.finishedRow();
  18068. if (transformedSize)
  18069. break;
  18070. }
  18071. }
  18072. return rowBuilder.finalizeRowClear(transformedSize);
  18073. }
  18074. };
  18075. class CRoxieServerXmlReadActivity : public CRoxieServerDiskReadBaseActivity, implements IXMLSelect
  18076. {
  18077. IHThorXmlReadArg * readHelper;
  18078. Owned<IXmlToRowTransformer> rowTransformer;
  18079. Owned<IXMLParse> xmlParser;
  18080. Owned<IColumnProvider> lastMatch;
  18081. unsigned __int64 localOffset;
  18082. public:
  18083. IMPLEMENT_IINTERFACE;
  18084. CRoxieServerXmlReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager)
  18085. : CRoxieServerDiskReadBaseActivity(_factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, _maySkip, _manager)
  18086. {
  18087. compoundHelper = NULL;
  18088. readHelper = (IHThorXmlReadArg *)&helper;
  18089. localOffset = 0;
  18090. }
  18091. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18092. {
  18093. rowLimit = readHelper->getRowLimit();
  18094. stopAfter = readHelper->getChooseNLimit();
  18095. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  18096. if (!useRemote())
  18097. {
  18098. rowTransformer.set(readHelper->queryTransformer());
  18099. assertex(reader != NULL);
  18100. OwnedRoxieString xmlIterator(readHelper->getXmlIteratorPath());
  18101. xmlParser.setown(createXMLParse(*reader->querySimpleStream(), xmlIterator, *this, (0 != (TDRxmlnoroot & readHelper->getFlags()))?ptr_noRoot:ptr_none, (readHelper->getFlags() & TDRusexmlcontents) != 0));
  18102. }
  18103. }
  18104. virtual void reset()
  18105. {
  18106. CRoxieServerDiskReadBaseActivity::reset();
  18107. rowTransformer.clear();
  18108. xmlParser.clear();
  18109. }
  18110. virtual void match(IColumnProvider &entry, offset_t startOffset, offset_t endOffset)
  18111. {
  18112. localOffset = startOffset;
  18113. lastMatch.set(&entry);
  18114. }
  18115. virtual const void *nextInGroup()
  18116. {
  18117. if (eof)
  18118. return NULL;
  18119. else if (useRemote())
  18120. return remote->nextInGroup();
  18121. assertex(xmlParser != NULL);
  18122. try
  18123. {
  18124. while (!eof)
  18125. {
  18126. //call to next() will callback on the IXmlSelect interface
  18127. bool gotNext = false;
  18128. gotNext = xmlParser->next();
  18129. if(!gotNext)
  18130. eof = true;
  18131. else if (lastMatch)
  18132. {
  18133. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  18134. unsigned sizeGot = rowTransformer->transform(rowBuilder, lastMatch, reader->queryThorDiskCallback());
  18135. lastMatch.clear();
  18136. localOffset = 0;
  18137. if (sizeGot)
  18138. {
  18139. OwnedConstRoxieRow ret = rowBuilder.finalizeRowClear(sizeGot);
  18140. if (processed > rowLimit)
  18141. {
  18142. if (traceLevel > 4)
  18143. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  18144. readHelper->onLimitExceeded();
  18145. throwUnexpected(); // onLimitExceeded is not supposed to return
  18146. }
  18147. processed++;
  18148. if (processed > stopAfter) // MORE - bit of a strange place to check
  18149. {
  18150. eof = true;
  18151. return NULL;
  18152. }
  18153. return ret.getClear();
  18154. }
  18155. }
  18156. }
  18157. return NULL;
  18158. }
  18159. catch(IException *E)
  18160. {
  18161. throw makeWrappedException(E);
  18162. }
  18163. }
  18164. };
  18165. class CRoxieServerCsvReadActivity : public CRoxieServerDiskReadBaseActivity
  18166. {
  18167. IHThorCsvReadArg *readHelper;
  18168. ICsvParameters * csvInfo;
  18169. unsigned headerLines;
  18170. unsigned maxDiskSize;
  18171. CSVSplitter csvSplitter;
  18172. unsigned __int64 localOffset;
  18173. const char *quotes;
  18174. const char *separators;
  18175. const char *terminators;
  18176. const char *escapes;
  18177. public:
  18178. CRoxieServerCsvReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  18179. unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager,
  18180. const char *_quotes, const char *_separators, const char *_terminators, const char *_escapes)
  18181. : CRoxieServerDiskReadBaseActivity(_factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, _maySkip, _manager),
  18182. quotes(_quotes), separators(_separators), terminators(_terminators), escapes(_escapes)
  18183. {
  18184. compoundHelper = NULL;
  18185. readHelper = (IHThorCsvReadArg *)&helper;
  18186. rowLimit = readHelper->getRowLimit();
  18187. stopAfter = readHelper->getChooseNLimit();
  18188. csvInfo = readHelper->queryCsvParameters();
  18189. maxDiskSize = csvInfo->queryMaxSize();
  18190. localOffset = 0;
  18191. headerLines = 0;
  18192. }
  18193. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18194. {
  18195. rowLimit = readHelper->getRowLimit();
  18196. stopAfter = readHelper->getChooseNLimit();
  18197. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  18198. if (!useRemote())
  18199. {
  18200. headerLines = csvInfo->queryHeaderLen();
  18201. if (headerLines && isLocal && reader->queryFilePart() != 1)
  18202. 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...
  18203. if (!eof)
  18204. {
  18205. if (varFileInfo)
  18206. {
  18207. const IPropertyTree *options = varFileInfo->queryProperties();
  18208. if (options)
  18209. {
  18210. quotes = options->queryProp("@csvQuote");
  18211. separators = options->queryProp("@csvSeparate");
  18212. terminators = options->queryProp("@csvTerminate");
  18213. escapes = options->queryProp("@csvEscape");
  18214. }
  18215. }
  18216. csvSplitter.init(readHelper->getMaxColumns(), csvInfo, quotes, separators, terminators, escapes);
  18217. }
  18218. }
  18219. }
  18220. virtual const void *nextInGroup()
  18221. {
  18222. if (eof)
  18223. return NULL;
  18224. else if (useRemote())
  18225. return remote->nextInGroup();
  18226. try
  18227. {
  18228. while (!eof)
  18229. {
  18230. if (reader->eos())
  18231. {
  18232. eof = true;
  18233. break;
  18234. }
  18235. // MORE - there are rumours of a csvSplitter that operates on a stream... if/when it exists, this should use it
  18236. size32_t rowSize = 4096; // MORE - make configurable
  18237. size32_t maxRowSize = 10*1024*1024; // MORE - make configurable
  18238. size32_t thisLineLength;
  18239. loop
  18240. {
  18241. size32_t avail;
  18242. const void *peek = reader->peek(rowSize, avail);
  18243. thisLineLength = csvSplitter.splitLine(avail, (const byte *)peek);
  18244. if (thisLineLength < rowSize || avail < rowSize)
  18245. break;
  18246. if (rowSize == maxRowSize)
  18247. throw MakeStringException(0, "Row too big");
  18248. if (rowSize >= maxRowSize/2)
  18249. rowSize = maxRowSize;
  18250. else
  18251. rowSize += rowSize;
  18252. }
  18253. if (headerLines)
  18254. {
  18255. headerLines--;
  18256. reader->skip(thisLineLength);
  18257. }
  18258. else
  18259. {
  18260. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  18261. unsigned transformedSize = readHelper->transform(rowBuilder, csvSplitter.queryLengths(), (const char * *)csvSplitter.queryData());
  18262. reader->skip(thisLineLength);
  18263. if (transformedSize)
  18264. {
  18265. OwnedConstRoxieRow ret = rowBuilder.finalizeRowClear(transformedSize);
  18266. if (processed > rowLimit)
  18267. {
  18268. readHelper->onLimitExceeded();
  18269. throwUnexpected(); // onLimitExceeded is not supposed to return
  18270. }
  18271. processed++;
  18272. if (processed > stopAfter) // MORE - bit of a strange place to check
  18273. {
  18274. eof = true;
  18275. return NULL;
  18276. }
  18277. return ret.getClear();
  18278. }
  18279. }
  18280. }
  18281. return NULL;
  18282. }
  18283. catch(IException *E)
  18284. {
  18285. throw makeWrappedException(E);
  18286. }
  18287. }
  18288. virtual void reset()
  18289. {
  18290. CRoxieServerDiskReadBaseActivity::reset();
  18291. csvSplitter.reset();
  18292. localOffset = 0;
  18293. }
  18294. virtual unsigned __int64 getFilePosition(const void * row)
  18295. {
  18296. UNIMPLEMENTED; // we know offset in the reader but not sure it helps us much
  18297. }
  18298. virtual unsigned __int64 getLocalFilePosition(const void * row)
  18299. {
  18300. UNIMPLEMENTED;
  18301. }
  18302. };
  18303. class CRoxieServerDiskNormalizeActivity : public CRoxieServerDiskReadBaseActivity
  18304. {
  18305. IHThorDiskNormalizeArg *normalizeHelper;
  18306. bool firstPending;
  18307. public:
  18308. CRoxieServerDiskNormalizeActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, IInMemoryIndexManager *_manager)
  18309. : CRoxieServerDiskReadBaseActivity(_factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, false, _manager)
  18310. {
  18311. compoundHelper = (IHThorDiskNormalizeArg *)&helper;
  18312. normalizeHelper = (IHThorDiskNormalizeArg *)&helper;
  18313. firstPending = true;
  18314. }
  18315. virtual void reset()
  18316. {
  18317. firstPending = true;
  18318. CRoxieServerDiskReadBaseActivity::reset();
  18319. }
  18320. virtual const void *nextInGroup()
  18321. {
  18322. if (eof)
  18323. return NULL;
  18324. else if (useRemote())
  18325. return remote->nextInGroup();
  18326. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  18327. unsigned transformedSize = 0;
  18328. if (isKeyed)
  18329. {
  18330. loop
  18331. {
  18332. while (firstPending)
  18333. {
  18334. const void *nextCandidate = cursor->nextMatch();
  18335. if (!nextCandidate)
  18336. {
  18337. eof = true;
  18338. return NULL;
  18339. }
  18340. if (normalizeHelper->first(nextCandidate))
  18341. {
  18342. firstPending = false;
  18343. break;
  18344. }
  18345. }
  18346. transformedSize = normalizeHelper->transform(rowBuilder);
  18347. firstPending = !normalizeHelper->next();
  18348. if (transformedSize)
  18349. break;
  18350. }
  18351. }
  18352. else
  18353. {
  18354. assertex(reader != NULL);
  18355. loop
  18356. {
  18357. while (firstPending)
  18358. {
  18359. if (deserializeSource.eos())
  18360. {
  18361. eof = true;
  18362. return NULL;
  18363. }
  18364. prefetcher->readAhead(deserializeSource);
  18365. const byte *nextRec = deserializeSource.queryRow();
  18366. if (!cursor || !cursor->isFiltered(nextRec))
  18367. {
  18368. if (normalizeHelper->first(nextRec))
  18369. firstPending = false;
  18370. }
  18371. deserializeSource.finishedRow();
  18372. }
  18373. transformedSize = normalizeHelper->transform(rowBuilder);
  18374. firstPending = !normalizeHelper->next();
  18375. if (transformedSize)
  18376. break;
  18377. }
  18378. }
  18379. OwnedConstRoxieRow recBuffer = rowBuilder.finalizeRowClear(transformedSize);
  18380. processed++;
  18381. if (processed > rowLimit)
  18382. {
  18383. compoundHelper->onLimitExceeded();
  18384. throwUnexpected(); // onLimitExceeded is not supposed to return
  18385. }
  18386. if (processed > stopAfter) // MORE - bit of a strange place to check
  18387. {
  18388. eof = true;
  18389. return NULL;
  18390. }
  18391. return recBuffer.getClear();
  18392. }
  18393. };
  18394. class CRoxieServerDiskAggregateBaseActivity : public CRoxieServerDiskReadBaseActivity
  18395. {
  18396. protected:
  18397. bool done;
  18398. public:
  18399. CRoxieServerDiskAggregateBaseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager)
  18400. : CRoxieServerDiskReadBaseActivity(_factory, _probeManager, _remoteId, _numParts, _isLocal, false, false, _manager),
  18401. done(false)
  18402. {
  18403. }
  18404. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18405. {
  18406. done = false;
  18407. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  18408. }
  18409. virtual IRoxieInput *queryOutput(unsigned idx)
  18410. {
  18411. if (idx==(unsigned)-1)
  18412. idx = 0;
  18413. return idx ? NULL: this;
  18414. }
  18415. };
  18416. class CRoxieServerDiskCountActivity : public CRoxieServerDiskAggregateBaseActivity
  18417. {
  18418. IHThorDiskCountArg & countHelper;
  18419. unsigned __int64 choosenLimit;
  18420. IHThorSourceCountLimit *limitHelper;
  18421. unsigned __int64 getSkippedCount()
  18422. {
  18423. unsigned flags = countHelper.getFlags();
  18424. if (flags & TDRlimitskips)
  18425. return 0;
  18426. else if (flags & TDRlimitcreates)
  18427. return 1;
  18428. else
  18429. {
  18430. assertex(limitHelper);
  18431. if (traceLevel > 4)
  18432. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  18433. limitHelper->onLimitExceeded();
  18434. throwUnexpected(); // onLimitExceeded should always throw exception
  18435. }
  18436. }
  18437. public:
  18438. CRoxieServerDiskCountActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager)
  18439. : CRoxieServerDiskAggregateBaseActivity(_factory, _probeManager, _remoteId, _numParts, _isLocal, _manager),
  18440. countHelper((IHThorDiskCountArg &)basehelper)
  18441. {
  18442. limitHelper = static_cast<IHThorSourceCountLimit *>(basehelper.selectInterface(TAIsourcecountlimit_1));
  18443. choosenLimit = 0;
  18444. }
  18445. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18446. {
  18447. choosenLimit = countHelper.getChooseNLimit();
  18448. if (limitHelper)
  18449. {
  18450. rowLimit = limitHelper->getRowLimit();
  18451. // keyedLimit = limitHelper->getKeyedLimit(); // more - should there be one?
  18452. }
  18453. CRoxieServerDiskAggregateBaseActivity::start(parentExtractSize, parentExtract, paused);
  18454. }
  18455. virtual const void *nextInGroup()
  18456. {
  18457. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  18458. if (done) return NULL;
  18459. done = true;
  18460. unsigned __int64 totalCount = 0;
  18461. if (helper.canMatchAny() && !eof)
  18462. {
  18463. if (useRemote())
  18464. {
  18465. loop
  18466. {
  18467. const void * next = remote->nextInGroup();
  18468. if (!next)
  18469. break;
  18470. if (meta.getFixedSize() == 1)
  18471. totalCount += *(byte *)next;
  18472. else
  18473. totalCount += *(unsigned __int64 *)next;
  18474. ReleaseRoxieRow(next);
  18475. if (totalCount > rowLimit)
  18476. {
  18477. totalCount = getSkippedCount();
  18478. break;
  18479. }
  18480. else if (totalCount >= choosenLimit)
  18481. {
  18482. totalCount = choosenLimit;
  18483. break;
  18484. }
  18485. }
  18486. }
  18487. else
  18488. {
  18489. if (isKeyed)
  18490. {
  18491. loop
  18492. {
  18493. const void *nextCandidate = cursor->nextMatch();
  18494. if (!nextCandidate)
  18495. break;
  18496. totalCount += countHelper.numValid(nextCandidate);
  18497. if (totalCount > rowLimit)
  18498. {
  18499. totalCount = getSkippedCount();
  18500. break;
  18501. }
  18502. else if (totalCount >= choosenLimit)
  18503. {
  18504. totalCount = choosenLimit;
  18505. break;
  18506. }
  18507. }
  18508. }
  18509. else
  18510. {
  18511. assertex(reader != NULL);
  18512. while (!deserializeSource.eos())
  18513. {
  18514. prefetcher->readAhead(deserializeSource);
  18515. const byte *nextRec = deserializeSource.queryRow();
  18516. if (!cursor || !cursor->isFiltered(nextRec))
  18517. {
  18518. totalCount += countHelper.numValid(nextRec);
  18519. }
  18520. deserializeSource.finishedRow();
  18521. if (totalCount > rowLimit)
  18522. {
  18523. totalCount = getSkippedCount();
  18524. break;
  18525. }
  18526. else if (totalCount >= choosenLimit)
  18527. {
  18528. totalCount = choosenLimit;
  18529. break;
  18530. }
  18531. }
  18532. }
  18533. }
  18534. }
  18535. size32_t rowSize = meta.getFixedSize();
  18536. void * result = rowAllocator->createRow();
  18537. if (rowSize == 1)
  18538. *(byte *)result = (byte)totalCount;
  18539. else
  18540. {
  18541. assertex(rowSize == sizeof(unsigned __int64));
  18542. *(unsigned __int64 *)result = totalCount;
  18543. }
  18544. return rowAllocator->finalizeRow(rowSize, result, rowSize);
  18545. }
  18546. };
  18547. class CRoxieServerDiskAggregateActivity : public CRoxieServerDiskAggregateBaseActivity
  18548. {
  18549. IHThorCompoundAggregateExtra & aggregateHelper;
  18550. public:
  18551. CRoxieServerDiskAggregateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  18552. unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager)
  18553. : CRoxieServerDiskAggregateBaseActivity(_factory, _probeManager, _remoteId, _numParts, _isLocal, _manager),
  18554. aggregateHelper((IHThorDiskAggregateArg &)basehelper)
  18555. {
  18556. }
  18557. const void * gatherMerged()
  18558. {
  18559. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  18560. size32_t finalSize = 0;
  18561. if (useRemote())
  18562. {
  18563. const void * firstRow = remote->nextInGroup();
  18564. if (!firstRow)
  18565. {
  18566. rowBuilder.ensureRow();
  18567. finalSize = aggregateHelper.clearAggregate(rowBuilder);
  18568. }
  18569. else
  18570. {
  18571. // NOTE need to clone this because going to modify below, could special case 1 row only
  18572. finalSize = cloneRow(rowBuilder, firstRow, meta);
  18573. ReleaseRoxieRow(firstRow);
  18574. }
  18575. loop
  18576. {
  18577. const void * next = remote->nextInGroup();
  18578. if (!next)
  18579. break;
  18580. finalSize = aggregateHelper.mergeAggregate(rowBuilder, next);
  18581. ReleaseRoxieRow(next);
  18582. }
  18583. }
  18584. else
  18585. {
  18586. aggregateHelper.clearAggregate(rowBuilder);
  18587. if (helper.canMatchAny() && !eof)
  18588. {
  18589. if (isKeyed)
  18590. {
  18591. loop
  18592. {
  18593. const void *next = cursor->nextMatch();
  18594. if (!next)
  18595. break;
  18596. aggregateHelper.processRow(rowBuilder, next);
  18597. }
  18598. }
  18599. else
  18600. {
  18601. assertex(reader != NULL);
  18602. while (!deserializeSource.eos())
  18603. {
  18604. prefetcher->readAhead(deserializeSource);
  18605. const byte *nextRec = deserializeSource.queryRow();
  18606. if (!cursor || !cursor->isFiltered(nextRec))
  18607. {
  18608. aggregateHelper.processRow(rowBuilder, nextRec);
  18609. }
  18610. deserializeSource.finishedRow();
  18611. }
  18612. }
  18613. }
  18614. finalSize = meta.getRecordSize(rowBuilder.getSelf());
  18615. }
  18616. return rowBuilder.finalizeRowClear(finalSize);
  18617. }
  18618. virtual const void *nextInGroup()
  18619. {
  18620. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  18621. if (done) return NULL;
  18622. const void * ret = gatherMerged();
  18623. done = true;
  18624. return ret;
  18625. }
  18626. };
  18627. class CRoxieServerDiskGroupAggregateActivity : public CRoxieServerDiskAggregateBaseActivity
  18628. {
  18629. IHThorDiskGroupAggregateArg & aggregateHelper;
  18630. RowAggregator resultAggregator;
  18631. bool gathered;
  18632. public:
  18633. IMPLEMENT_IINTERFACE;
  18634. CRoxieServerDiskGroupAggregateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager)
  18635. : CRoxieServerDiskAggregateBaseActivity(_factory, _probeManager, _remoteId, _numParts, _isLocal, _manager),
  18636. aggregateHelper((IHThorDiskGroupAggregateArg &)basehelper),
  18637. resultAggregator(aggregateHelper, aggregateHelper),
  18638. gathered(false)
  18639. {
  18640. }
  18641. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18642. {
  18643. gathered= false;
  18644. CRoxieServerDiskAggregateBaseActivity::start(parentExtractSize, parentExtract, paused);
  18645. resultAggregator.start(rowAllocator);
  18646. }
  18647. virtual void reset()
  18648. {
  18649. resultAggregator.reset();
  18650. CRoxieServerDiskAggregateBaseActivity::reset();
  18651. }
  18652. void gatherMerged()
  18653. {
  18654. if (useRemote())
  18655. {
  18656. loop
  18657. {
  18658. const void * next = remote->nextInGroup();
  18659. if (!next)
  18660. break;
  18661. resultAggregator.mergeElement(next);
  18662. ReleaseRoxieRow(next);
  18663. }
  18664. }
  18665. else
  18666. {
  18667. if (helper.canMatchAny() && !eof)
  18668. {
  18669. Owned<IInMemoryFileProcessor> processor = isKeyed ?
  18670. createKeyedGroupAggregateRecordProcessor(cursor, resultAggregator, aggregateHelper) :
  18671. createUnkeyedGroupAggregateRecordProcessor(cursor, resultAggregator, aggregateHelper, manager->createReader(0, 0, 1),
  18672. ctx->queryCodeContext(), activityId);
  18673. processor->doQuery(NULL, 0, 0, 0);
  18674. }
  18675. }
  18676. gathered = true;
  18677. }
  18678. virtual const void *nextInGroup()
  18679. {
  18680. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  18681. if (done)
  18682. return NULL;
  18683. if (!gathered)
  18684. gatherMerged();
  18685. Owned<AggregateRowBuilder> next = resultAggregator.nextResult();
  18686. if (next)
  18687. {
  18688. processed++;
  18689. return next->finalizeRowClear();
  18690. }
  18691. done = true;
  18692. return NULL;
  18693. }
  18694. };
  18695. class CRoxieServerDiskReadActivityFactory : public CRoxieServerActivityFactory
  18696. {
  18697. public:
  18698. RemoteActivityId remoteId;
  18699. bool isLocal;
  18700. bool sorted;
  18701. bool maySkip;
  18702. bool variableFileName;
  18703. Owned<IFilePartMap> map;
  18704. Owned<IFileIOArray> files;
  18705. Owned<IInMemoryIndexManager> manager;
  18706. Owned<const IResolvedFile> datafile;
  18707. const char *quotes;
  18708. const char *separators;
  18709. const char *terminators;
  18710. const char *escapes;
  18711. CRoxieServerDiskReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  18712. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), remoteId(_remoteId)
  18713. {
  18714. isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  18715. Owned<IHThorDiskReadBaseArg> helper = (IHThorDiskReadBaseArg *) helperFactory();
  18716. sorted = (helper->getFlags() & TDRunsorted) == 0;
  18717. variableFileName = allFilesDynamic || _queryFactory.isDynamic() || ((helper->getFlags() & (TDXvarfilename|TDXdynamicfilename)) != 0);
  18718. maySkip = (helper->getFlags() & (TDRkeyedlimitskips|TDRkeyedlimitcreates|TDRlimitskips|TDRlimitcreates)) != 0;
  18719. quotes = separators = terminators = escapes = NULL;
  18720. if (!variableFileName)
  18721. {
  18722. bool isOpt = (helper->getFlags() & TDRoptional) != 0;
  18723. OwnedRoxieString fileName(helper->getFileName());
  18724. datafile.setown(_queryFactory.queryPackage().lookupFileName(fileName, isOpt, true, true, _queryFactory.queryWorkUnit()));
  18725. if (datafile)
  18726. map.setown(datafile->getFileMap());
  18727. bool isSimple = (map && map->getNumParts()==1 && !_queryFactory.getDebugValueBool("disableLocalOptimizations", false));
  18728. if (isLocal || isSimple)
  18729. {
  18730. if (datafile)
  18731. {
  18732. unsigned channel = isLocal ? queryFactory.queryChannel() : 0;
  18733. files.setown(datafile->getIFileIOArray(isOpt, channel));
  18734. manager.setown(datafile->getIndexManager(isOpt, channel, files, helper->queryDiskRecordSize(), _graphNode.getPropBool("att[@name=\"preload\"]/@value", false), _graphNode.getPropInt("att[@name=\"_preloadSize\"]/@value", 0)));
  18735. const IPropertyTree *options = datafile->queryProperties();
  18736. if (options)
  18737. {
  18738. quotes = options->queryProp("@csvQuote");
  18739. separators = options->queryProp("@csvSeparate");
  18740. terminators = options->queryProp("@csvTerminate");
  18741. escapes = options->queryProp("@csvEscape");
  18742. }
  18743. }
  18744. else
  18745. manager.setown(getEmptyIndexManager());
  18746. }
  18747. }
  18748. }
  18749. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  18750. {
  18751. unsigned numParts = map ? map->getNumParts() : 0;
  18752. switch (kind)
  18753. {
  18754. case TAKcsvread:
  18755. return new CRoxieServerCsvReadActivity(this, _probeManager, remoteId, numParts, isLocal, sorted, maySkip, manager,
  18756. quotes, separators, terminators, escapes);
  18757. case TAKxmlread:
  18758. return new CRoxieServerXmlReadActivity(this, _probeManager, remoteId, numParts, isLocal, sorted, maySkip, manager);
  18759. case TAKdiskread:
  18760. return new CRoxieServerDiskReadActivity(this, _probeManager, remoteId, numParts, isLocal, sorted, maySkip, manager);
  18761. case TAKdisknormalize:
  18762. return new CRoxieServerDiskNormalizeActivity(this, _probeManager, remoteId, numParts, isLocal, sorted, manager);
  18763. case TAKdiskcount:
  18764. return new CRoxieServerDiskCountActivity(this, _probeManager, remoteId, numParts, isLocal, manager);
  18765. case TAKdiskaggregate:
  18766. return new CRoxieServerDiskAggregateActivity(this, _probeManager, remoteId, numParts, isLocal, manager);
  18767. case TAKdiskgroupaggregate:
  18768. return new CRoxieServerDiskGroupAggregateActivity(this, _probeManager, remoteId, numParts, isLocal, manager);
  18769. }
  18770. throwUnexpected();
  18771. }
  18772. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  18773. {
  18774. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  18775. }
  18776. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  18777. {
  18778. if (datafile)
  18779. addXrefFileInfo(reply, datafile);
  18780. }
  18781. };
  18782. IRoxieServerActivityFactory *createRoxieServerDiskReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  18783. {
  18784. return new CRoxieServerDiskReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode);
  18785. }
  18786. //=================================================================================
  18787. class CRoxieServerIndexActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler
  18788. {
  18789. protected:
  18790. IHThorIndexReadBaseArg &indexHelper;
  18791. IHThorSteppedSourceExtra * steppedExtra;
  18792. Linked<IKeyArray> keySet;
  18793. Linked<TranslatorArray> translators;
  18794. CSkippableRemoteResultAdaptor remote;
  18795. CIndexTransformCallback callback;
  18796. bool sorted;
  18797. bool variableFileName;
  18798. bool variableInfoPending;
  18799. bool isOpt;
  18800. bool isLocal;
  18801. unsigned __int64 rowLimit;
  18802. unsigned __int64 keyedLimit;
  18803. unsigned __int64 choosenLimit;
  18804. unsigned accepted;
  18805. unsigned rejected;
  18806. unsigned seekGEOffset;
  18807. Owned<IKeyManager> tlk;
  18808. Owned<const IResolvedFile> varFileInfo;
  18809. const RemoteActivityId &remoteId;
  18810. void setVariableFileInfo()
  18811. {
  18812. OwnedRoxieString indexName(indexHelper.getFileName());
  18813. varFileInfo.setown(resolveLFN(indexName, isOpt));
  18814. if (varFileInfo)
  18815. {
  18816. translators.setown(new TranslatorArray) ;
  18817. keySet.setown(varFileInfo->getKeyArray(factory->queryActivityMeta(), translators, isOpt, isLocal ? factory->queryQueryFactory().queryChannel() : 0, factory->queryQueryFactory().getEnableFieldTranslation()));
  18818. }
  18819. variableInfoPending = false;
  18820. }
  18821. public:
  18822. CRoxieServerIndexActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  18823. IKeyArray * _keySet, TranslatorArray *_translators, bool _sorted, bool _isLocal, bool _maySkip)
  18824. : CRoxieServerActivity(_factory, _probeManager),
  18825. keySet(_keySet),
  18826. translators(_translators),
  18827. indexHelper((IHThorIndexReadBaseArg &)basehelper),
  18828. remote(_remoteId, meta.queryOriginal(), indexHelper, *this, _sorted, false, _maySkip),
  18829. remoteId(_remoteId),
  18830. sorted(_sorted),
  18831. isLocal(_isLocal)
  18832. {
  18833. indexHelper.setCallback(&callback);
  18834. steppedExtra = static_cast<IHThorSteppedSourceExtra *>(indexHelper.selectInterface(TAIsteppedsourceextra_1));
  18835. variableFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((indexHelper.getFlags() & (TIRvarfilename|TIRdynamicfilename)) != 0);
  18836. variableInfoPending = false;
  18837. isOpt = (indexHelper.getFlags() & TIRoptional) != 0;
  18838. seekGEOffset = 0;
  18839. // started = false;
  18840. rejected = accepted = 0;
  18841. rowLimit = choosenLimit = keyedLimit = 0;
  18842. }
  18843. virtual const IResolvedFile *queryVarFileInfo() const
  18844. {
  18845. return varFileInfo;
  18846. }
  18847. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  18848. {
  18849. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  18850. remote.onCreate(this, this, _ctx, _colocalParent);
  18851. }
  18852. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18853. {
  18854. accepted = 0;
  18855. rejected = 0;
  18856. rowLimit = (unsigned __int64) -1;
  18857. keyedLimit = (unsigned __int64 ) -1;
  18858. choosenLimit = I64C(0x7fffffffffffffff);
  18859. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  18860. remote.onStart(parentExtractSize, parentExtract);
  18861. variableInfoPending = variableFileName;
  18862. }
  18863. void processAllKeys()
  18864. {
  18865. try
  18866. {
  18867. if (indexHelper.canMatchAny())
  18868. {
  18869. if (variableInfoPending)
  18870. setVariableFileInfo();
  18871. remote.setLimits(rowLimit, keyedLimit, choosenLimit);
  18872. if (keySet)
  18873. {
  18874. // MORE - this recreates the segmonitors per part but not per fileno (which is a little backwards).
  18875. // 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
  18876. // However order is probably better to iterate fileno's inside partnos
  18877. // MORE - also not properly supporting STEPPED I fear.
  18878. // A superkey that mixes single and multipart or tlk and roroot keys might be hard
  18879. for (unsigned partNo = 0; partNo < keySet->length(); partNo++)
  18880. {
  18881. IKeyIndexBase *thisBase = keySet->queryKeyPart(partNo);
  18882. if (thisBase)
  18883. {
  18884. unsigned fileNo = 0;
  18885. IKeyIndex *thisKey = thisBase->queryPart(fileNo);
  18886. if (!thisKey->isTopLevelKey())
  18887. {
  18888. if (keyedLimit != (unsigned __int64) -1)
  18889. {
  18890. if ((indexHelper.getFlags() & TIRcountkeyedlimit) != 0)
  18891. {
  18892. Owned<IKeyManager> countKey;
  18893. countKey.setown(createKeyManager(thisKey, 0, this));
  18894. countKey->setLayoutTranslator(translators->item(fileNo));
  18895. createSegmentMonitors(countKey);
  18896. unsigned __int64 count = countKey->checkCount(keyedLimit);
  18897. if (count > keyedLimit)
  18898. {
  18899. if (traceLevel > 4)
  18900. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  18901. onLimitExceeded(true);
  18902. }
  18903. }
  18904. }
  18905. }
  18906. if (seekGEOffset && !thisKey->isTopLevelKey())
  18907. {
  18908. tlk.setown(createSingleKeyMerger(thisKey, 0, seekGEOffset, this));
  18909. }
  18910. else
  18911. {
  18912. tlk.setown(createKeyManager(thisKey, 0, this));
  18913. tlk->setLayoutTranslator(translators->item(fileNo));
  18914. }
  18915. createSegmentMonitors(tlk);
  18916. if (queryTraceLevel() > 3 || ctx->queryProbeManager())
  18917. {
  18918. StringBuffer out;
  18919. printKeyedValues(out, tlk, indexHelper.queryDiskRecordSize());
  18920. CTXLOG("Using filter %s", out.str());
  18921. if (ctx->queryProbeManager())
  18922. ctx->queryProbeManager()->setNodeProperty(this, "filter", out.str());
  18923. }
  18924. tlk->reset();
  18925. loop // for each file part
  18926. {
  18927. //block for TransformCallbackAssociation
  18928. {
  18929. TransformCallbackAssociation associate(callback, tlk);
  18930. if (thisKey->isTopLevelKey())
  18931. {
  18932. if (thisKey->isFullySorted())
  18933. {
  18934. while (tlk->lookup(false))
  18935. {
  18936. unsigned slavePart = (unsigned) tlk->queryFpos();
  18937. if (slavePart)
  18938. {
  18939. accepted++;
  18940. remote.getMem(slavePart, fileNo, 0); // the cached context is all we need to send
  18941. if (sorted && numChannels>1)
  18942. remote.flush(); // don't combine parts if we need result sorted, except on a 1-way
  18943. }
  18944. }
  18945. }
  18946. else
  18947. {
  18948. // MORE - we could check whether there are any matching parts if we wanted.
  18949. // If people are in the habit of sending null values that would be worthwhile
  18950. remote.getMem(0, fileNo, 0);
  18951. }
  18952. }
  18953. else
  18954. {
  18955. if (processSingleKey(thisKey, translators->item(fileNo)))
  18956. break;
  18957. }
  18958. }
  18959. if (++fileNo < thisBase->numParts())
  18960. {
  18961. thisKey = thisBase->queryPart(fileNo);
  18962. tlk->setKey(thisKey);
  18963. tlk->setLayoutTranslator(translators->item(fileNo));
  18964. tlk->reset();
  18965. }
  18966. else
  18967. break;
  18968. }
  18969. tlk->releaseSegmentMonitors();
  18970. tlk->setKey(NULL);
  18971. }
  18972. }
  18973. }
  18974. }
  18975. remote.flush();
  18976. remote.senddone();
  18977. }
  18978. catch (IException *E)
  18979. {
  18980. remote.setException(E);
  18981. }
  18982. }
  18983. virtual void createSegmentMonitors(IKeyManager *key)
  18984. {
  18985. indexHelper.createSegmentMonitors(key);
  18986. key->finishSegmentMonitors();
  18987. }
  18988. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans) = 0;
  18989. virtual void reset()
  18990. {
  18991. if (accepted)
  18992. noteStatistic(STATS_ACCEPTED, accepted, 1);
  18993. if (rejected)
  18994. noteStatistic(STATS_REJECTED, rejected, 1);
  18995. remote.onReset();
  18996. CRoxieServerActivity::reset();
  18997. if (varFileInfo)
  18998. {
  18999. keySet.clear();
  19000. varFileInfo.clear();
  19001. }
  19002. variableInfoPending = false;
  19003. }
  19004. virtual void stop(bool aborting)
  19005. {
  19006. remote.onStop(aborting);
  19007. CRoxieServerActivity::stop(aborting);
  19008. }
  19009. virtual void setInput(unsigned idx, IRoxieInput *_in)
  19010. {
  19011. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  19012. }
  19013. };
  19014. class CRoxieServerIndexReadBaseActivity : public CRoxieServerIndexActivity
  19015. {
  19016. IHThorSourceLimitTransformExtra * limitTransformExtra;
  19017. public:
  19018. CRoxieServerIndexReadBaseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  19019. IKeyArray * _keySet, TranslatorArray *_translators, bool _sorted, bool _isLocal, bool _maySkip)
  19020. : CRoxieServerIndexActivity(_factory, _probeManager, _remoteId, _keySet, _translators, _sorted, _isLocal, _maySkip)
  19021. {
  19022. limitTransformExtra = static_cast<IHThorSourceLimitTransformExtra *>(indexHelper.selectInterface(TAIsourcelimittransformextra_1));
  19023. }
  19024. virtual void reset()
  19025. {
  19026. remote.onReset();
  19027. CRoxieServerIndexActivity::reset();
  19028. }
  19029. virtual const void *nextInGroup()
  19030. {
  19031. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  19032. try
  19033. {
  19034. const void *ret = remote.nextInGroup();
  19035. if (ret)
  19036. processed++;
  19037. return ret;
  19038. }
  19039. catch (IException *E)
  19040. {
  19041. throw makeWrappedException(E);
  19042. }
  19043. }
  19044. protected:
  19045. virtual const void * createLimitFailRow(bool isKeyed)
  19046. {
  19047. createRowAllocator();
  19048. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  19049. size32_t outSize = isKeyed ? limitTransformExtra->transformOnKeyedLimitExceeded(rowBuilder) : limitTransformExtra->transformOnLimitExceeded(rowBuilder);
  19050. if (outSize)
  19051. return rowBuilder.finalizeRowClear(outSize);
  19052. return NULL;
  19053. }
  19054. };
  19055. class CRoxieServerIndexReadActivity : public CRoxieServerIndexReadBaseActivity, implements IIndexReadActivityInfo
  19056. {
  19057. protected:
  19058. IHThorCompoundReadExtra & readHelper;
  19059. ISteppingMeta *rawMeta;
  19060. CSteppingMeta steppingMeta;
  19061. unsigned * seekSizes;
  19062. bool optimizeSteppedPostFilter;
  19063. ISteppingMeta * projectedMeta;
  19064. unsigned maxSeekLookahead;
  19065. public:
  19066. CRoxieServerIndexReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  19067. IKeyArray * _keySet, TranslatorArray *_translators, bool _sorted, bool _isLocal, bool _maySkip, unsigned _maxSeekLookahead)
  19068. : CRoxieServerIndexReadBaseActivity(_factory, _probeManager, _remoteId, _keySet, _translators, _sorted, _isLocal, _maySkip),
  19069. readHelper((IHThorIndexReadArg &)basehelper)
  19070. {
  19071. rawMeta = readHelper.queryRawSteppingMeta();
  19072. unsigned flags = indexHelper.getFlags();
  19073. optimizeSteppedPostFilter = (flags & TIRunfilteredtransform) != 0;
  19074. seekSizes = NULL;
  19075. maxSeekLookahead = _maxSeekLookahead;
  19076. if (rawMeta)
  19077. {
  19078. const CFieldOffsetSize * fields = rawMeta->queryFields();
  19079. unsigned maxFields = rawMeta->getNumFields();
  19080. seekGEOffset = fields[0].offset;
  19081. seekSizes = new unsigned[maxFields];
  19082. seekSizes[0] = fields[0].size;
  19083. for (unsigned i=1; i < maxFields; i++)
  19084. seekSizes[i] = seekSizes[i-1] + fields[i].size;
  19085. projectedMeta = readHelper.queryProjectedSteppingMeta();
  19086. ISteppingMeta *useMeta = projectedMeta ? projectedMeta : rawMeta;
  19087. remote.setMergeInfo(useMeta); // also need to consider superfile case where there is a mix of multiway and singleparts.. ?
  19088. bool hasPostFilter = readHelper.transformMayFilter() && optimizeSteppedPostFilter;
  19089. steppingMeta.init(useMeta, hasPostFilter);
  19090. }
  19091. }
  19092. ~CRoxieServerIndexReadActivity()
  19093. {
  19094. delete [] seekSizes;
  19095. }
  19096. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19097. {
  19098. CRoxieServerIndexReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  19099. steppingMeta.setDistributed();
  19100. if (steppedExtra)
  19101. steppingMeta.setExtra(steppedExtra);
  19102. rowLimit = readHelper.getRowLimit();
  19103. keyedLimit = readHelper.getKeyedLimit();
  19104. choosenLimit = readHelper.getChooseNLimit();
  19105. if (!paused)
  19106. processAllKeys();
  19107. }
  19108. class LazyLocalKeyReader : public CInterface, implements IMessageResult, implements IMessageUnpackCursor
  19109. {
  19110. public:
  19111. IMPLEMENT_IINTERFACE;
  19112. virtual IMessageUnpackCursor *getCursor(roxiemem::IRowManager *rowMgr) const
  19113. {
  19114. Link();
  19115. return const_cast<LazyLocalKeyReader*> (this);
  19116. }
  19117. virtual const void *getMessageHeader(unsigned &length) const
  19118. {
  19119. length = 0;
  19120. return NULL;
  19121. }
  19122. virtual const void *getMessageMetadata(unsigned &length) const
  19123. {
  19124. length = 0;
  19125. return NULL;
  19126. }
  19127. virtual void discard() const
  19128. {
  19129. // nothing to do.
  19130. }
  19131. unsigned keyedCount;
  19132. unsigned matched;
  19133. bool EOFseen;
  19134. Owned<IKeyIndexSet> keySet;
  19135. Owned<IKeyManager> tlk;
  19136. CRoxieServerIndexReadActivity &owner;
  19137. LazyLocalKeyReader(CRoxieServerIndexReadActivity &_owner, IKeyIndex *key, IRecordLayoutTranslator * trans)
  19138. : owner(_owner)
  19139. {
  19140. keyedCount = 0;
  19141. matched = 0;
  19142. EOFseen = false;
  19143. keySet.setown(createKeyIndexSet());
  19144. keySet->addIndex(LINK(key));
  19145. if (owner.seekGEOffset)
  19146. tlk.setown(createKeyMerger(keySet, 0, owner.seekGEOffset, &owner));
  19147. else
  19148. tlk.setown(createKeyManager(keySet->queryPart(0), 0, &owner));
  19149. tlk->setLayoutTranslator(trans);
  19150. owner.indexHelper.createSegmentMonitors(tlk);
  19151. tlk->finishSegmentMonitors();
  19152. tlk->reset();
  19153. }
  19154. virtual const void *getNext(int length)
  19155. {
  19156. TransformCallbackAssociation associate(owner.callback, tlk);
  19157. while (tlk->lookup(true))
  19158. {
  19159. keyedCount++;
  19160. if (keyedCount > owner.keyedLimit)
  19161. {
  19162. owner.onLimitExceeded(true); // Should throw exception
  19163. throwUnexpected();
  19164. }
  19165. size32_t transformedSize;
  19166. RtlDynamicRowBuilder rowBuilder(owner.rowAllocator);
  19167. byte const * keyRow = tlk->queryKeyBuffer(owner.callback.getFPosRef());
  19168. try
  19169. {
  19170. transformedSize = owner.readHelper.transform(rowBuilder, keyRow);
  19171. owner.callback.finishedRow();
  19172. }
  19173. catch (IException *E)
  19174. {
  19175. throw owner.makeWrappedException(E);
  19176. }
  19177. if (transformedSize)
  19178. {
  19179. OwnedConstRoxieRow result = rowBuilder.finalizeRowClear(transformedSize);
  19180. matched++;
  19181. if (matched > owner.rowLimit)
  19182. {
  19183. owner.onLimitExceeded(false); // Should throw exception
  19184. throwUnexpected();
  19185. }
  19186. if (matched > owner.choosenLimit) // MORE - bit of a strange place to check
  19187. {
  19188. break;
  19189. }
  19190. owner.accepted++;
  19191. return result.getClear();
  19192. }
  19193. else
  19194. owner.rejected++;
  19195. }
  19196. EOFseen = true;
  19197. return NULL;
  19198. }
  19199. virtual bool atEOF() const
  19200. {
  19201. return EOFseen;
  19202. }
  19203. virtual bool isSerialized() const
  19204. {
  19205. return false;
  19206. }
  19207. };
  19208. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
  19209. {
  19210. createRowAllocator();
  19211. remote.injectResult(new LazyLocalKeyReader(*this, key, trans));
  19212. return false;
  19213. }
  19214. virtual void onLimitExceeded(bool isKeyed)
  19215. {
  19216. if (traceLevel > 4)
  19217. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  19218. if (isKeyed)
  19219. {
  19220. if (indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates))
  19221. {
  19222. if (ctx->queryDebugContext())
  19223. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  19224. throw makeLimitSkipException(true);
  19225. }
  19226. else
  19227. readHelper.onKeyedLimitExceeded();
  19228. }
  19229. else
  19230. {
  19231. if (indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates))
  19232. {
  19233. if (ctx->queryDebugContext())
  19234. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  19235. throw makeLimitSkipException(false);
  19236. }
  19237. else
  19238. readHelper.onLimitExceeded();
  19239. }
  19240. }
  19241. virtual void serializeSkipInfo(MemoryBuffer &out, unsigned seekLen, const void *rawSeek, unsigned numFields, const void * seek, const SmartStepExtra &stepExtra) const
  19242. {
  19243. out.append((unsigned short) numFields);
  19244. out.append((unsigned short) seekLen);
  19245. out.append((unsigned short) stepExtra.queryFlags());
  19246. IMultipleStepSeekInfo *seeks = stepExtra.queryExtraSeeks();
  19247. if (seeks)
  19248. {
  19249. unsigned lookahead = 40000/seekLen;
  19250. if (maxSeekLookahead && (lookahead > maxSeekLookahead))
  19251. lookahead = maxSeekLookahead;
  19252. seeks->ensureFilled(seek, numFields, lookahead);
  19253. out.append(lookahead != seeks->ordinality()); // seeksAreEof flag
  19254. unsigned serialized = 1; // rawseek is always serialized...
  19255. unsigned patchLength = out.length();
  19256. out.append(serialized); // NOTE - we come back and patch with the actual value...
  19257. out.append(seekLen, rawSeek);
  19258. if (seeks->ordinality())
  19259. {
  19260. const void *lastSeek = rawSeek;
  19261. byte *nextSeek = NULL;
  19262. if (projectedMeta)
  19263. nextSeek = (byte *) alloca(seekLen);
  19264. for (unsigned i = 0; i < seeks->ordinality(); i++)
  19265. {
  19266. if (projectedMeta)
  19267. {
  19268. RtlStaticRowBuilder rowBuilder(nextSeek-seekGEOffset, seekGEOffset+seekLen);
  19269. readHelper.mapOutputToInput(rowBuilder, seeks->querySeek(i), numFields); // NOTE - weird interface to mapOutputToInput means that it STARTS writing at seekGEOffset...
  19270. }
  19271. else
  19272. nextSeek = (byte *) seeks->querySeek(i)+seekGEOffset;
  19273. int diff = memcmp(nextSeek, lastSeek, seekLen);
  19274. if (diff > 0)
  19275. {
  19276. serialized++;
  19277. out.append(seekLen, nextSeek);
  19278. lastSeek = (const byte *) out.reserve(0) - seekLen;
  19279. }
  19280. }
  19281. unsigned length = out.length();
  19282. out.setWritePos(patchLength);
  19283. out.append(serialized);
  19284. out.setWritePos(length);
  19285. }
  19286. }
  19287. else
  19288. {
  19289. out.append(false);
  19290. out.append(1);
  19291. out.append(seekLen, rawSeek);
  19292. }
  19293. }
  19294. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  19295. {
  19296. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  19297. try
  19298. {
  19299. unsigned seeklen = 0;
  19300. const void *rawSeek = NULL;
  19301. if (seek && numFields)
  19302. {
  19303. seeklen = seekSizes[numFields-1];
  19304. rawSeek = (const byte *)seek + seekGEOffset;
  19305. if (projectedMeta)
  19306. {
  19307. byte * temp = (byte *) alloca(seeklen);
  19308. RtlStaticRowBuilder rawBuilder(temp-seekGEOffset, seekGEOffset+seeklen);
  19309. readHelper.mapOutputToInput(rawBuilder, seek, numFields); // NOTE - weird interface to mapOutputToInput means that it STARTS writing at seekGEOffset...
  19310. rawSeek = (byte *)temp;
  19311. }
  19312. }
  19313. const void *ret = remote.nextSteppedGE(seek, rawSeek, numFields, seeklen, wasCompleteMatch, stepExtra);
  19314. if (ret && wasCompleteMatch) // GH pleas confirm the wasCompleteMatch I just added here is right
  19315. processed++;
  19316. return ret;
  19317. }
  19318. catch (IException *E)
  19319. {
  19320. throw makeWrappedException(E);
  19321. }
  19322. }
  19323. virtual IInputSteppingMeta * querySteppingMeta()
  19324. {
  19325. if (rawMeta && steppingEnabled && ((indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates|TIRkeyedlimitskips|TIRkeyedlimitcreates)) == 0))
  19326. return &steppingMeta;
  19327. return NULL;
  19328. }
  19329. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  19330. {
  19331. if (variableInfoPending)
  19332. setVariableFileInfo();
  19333. return this;
  19334. }
  19335. virtual IKeyArray *getKeySet() const
  19336. {
  19337. return keySet.getLink();
  19338. }
  19339. virtual const IResolvedFile *getVarFileInfo() const
  19340. {
  19341. return varFileInfo.getLink();
  19342. }
  19343. virtual TranslatorArray *getTranslators() const
  19344. {
  19345. return translators.getLink();
  19346. }
  19347. virtual void mergeSegmentMonitors(IIndexReadContext *irc) const
  19348. {
  19349. indexHelper.createSegmentMonitors(irc); // NOTE: they will merge
  19350. }
  19351. virtual IRoxieServerActivity *queryActivity() { return this; }
  19352. virtual const RemoteActivityId& queryRemoteId() const
  19353. {
  19354. return remoteId;
  19355. }
  19356. };
  19357. class CRoxieServerSimpleIndexReadActivity : public CRoxieServerActivity, implements IIndexReadActivityInfo
  19358. {
  19359. IHThorCompoundReadExtra & readHelper;
  19360. IHThorIndexReadBaseArg & indexHelper;
  19361. IHThorSourceLimitTransformExtra * limitTransformExtra;
  19362. IHThorSteppedSourceExtra * steppedExtra;
  19363. bool eof;
  19364. Linked<IKeyArray>keySet;
  19365. Owned<IKeyIndexSet>keyIndexSet;
  19366. Owned<IKeyManager> tlk;
  19367. Linked<TranslatorArray> translators;
  19368. CIndexTransformCallback callback;
  19369. unsigned __int64 keyedLimit;
  19370. unsigned rowLimit;
  19371. unsigned chooseNLimit;
  19372. unsigned accepted;
  19373. unsigned rejected;
  19374. unsigned keyedCount;
  19375. ISteppingMeta * rawMeta;
  19376. ISteppingMeta * projectedMeta;
  19377. size32_t seekGEOffset;
  19378. unsigned * seekSizes;
  19379. CSteppingMeta steppingMeta;
  19380. Owned<const IResolvedFile> varFileInfo;
  19381. const RemoteActivityId &remoteId;
  19382. bool firstRead;
  19383. bool variableFileName;
  19384. bool variableInfoPending;
  19385. bool isOpt;
  19386. bool isLocal;
  19387. bool optimizeSteppedPostFilter;
  19388. // MORE there may be enough in common between this and CRoxieServerIndexActivity to warrant some refactoring
  19389. void initKeySet()
  19390. {
  19391. if ((keySet->length() > 1 || rawMeta != NULL) && translators->needsTranslation())
  19392. {
  19393. throw MakeStringException(ROXIE_UNIMPLEMENTED_ERROR, "Layout translation is not available when merging key parts or smart-stepping, as it may change record order");
  19394. }
  19395. keyIndexSet.setown(createKeyIndexSet());
  19396. for (unsigned part = 0; part < keySet->length(); part++)
  19397. {
  19398. IKeyIndexBase *kib = keySet->queryKeyPart(part);
  19399. if (kib)
  19400. {
  19401. for (unsigned subpart = 0; subpart < kib->numParts(); subpart++)
  19402. {
  19403. IKeyIndex *k = kib->queryPart(subpart);
  19404. if (k)
  19405. {
  19406. assertex(!k->isTopLevelKey());
  19407. keyIndexSet->addIndex(LINK(k));
  19408. }
  19409. }
  19410. }
  19411. }
  19412. }
  19413. void setVariableFileInfo()
  19414. {
  19415. OwnedRoxieString indexName(indexHelper.getFileName());
  19416. varFileInfo.setown(resolveLFN(indexName, isOpt));
  19417. translators.setown(new TranslatorArray) ;
  19418. keySet.setown(varFileInfo->getKeyArray(factory->queryActivityMeta(), translators, isOpt, isLocal ? factory->queryQueryFactory().queryChannel() : 0, factory->queryQueryFactory().getEnableFieldTranslation()));
  19419. initKeySet();
  19420. variableInfoPending = false;
  19421. }
  19422. void onEOF()
  19423. {
  19424. callback.setManager(NULL);
  19425. eof = true;
  19426. tlk.clear();
  19427. }
  19428. public:
  19429. CRoxieServerSimpleIndexReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  19430. IKeyArray *_keyArray, TranslatorArray *_translatorArray, bool _isLocal)
  19431. : CRoxieServerActivity(_factory, _probeManager),
  19432. readHelper((IHThorIndexReadArg &)basehelper),
  19433. indexHelper((IHThorIndexReadArg &)basehelper),
  19434. translators(_translatorArray),
  19435. keySet(_keyArray),
  19436. isLocal(_isLocal),
  19437. remoteId(_remoteId)
  19438. {
  19439. rowLimit = 0;
  19440. keyedLimit = 0;
  19441. chooseNLimit = 0;
  19442. indexHelper.setCallback(&callback);
  19443. steppedExtra = static_cast<IHThorSteppedSourceExtra *>(indexHelper.selectInterface(TAIsteppedsourceextra_1));
  19444. limitTransformExtra = static_cast<IHThorSourceLimitTransformExtra *>(indexHelper.selectInterface(TAIsourcelimittransformextra_1));
  19445. unsigned flags = indexHelper.getFlags();
  19446. variableFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((flags & (TIRvarfilename|TIRdynamicfilename)) != 0);
  19447. variableInfoPending = false;
  19448. isOpt = (flags & TIRoptional) != 0;
  19449. optimizeSteppedPostFilter = (flags & TIRunfilteredtransform) != 0;
  19450. firstRead = true;
  19451. accepted = 0;
  19452. rejected = 0;
  19453. keyedCount = 0;
  19454. eof = false;
  19455. rawMeta = readHelper.queryRawSteppingMeta();
  19456. projectedMeta = readHelper.queryProjectedSteppingMeta();
  19457. seekGEOffset = 0;
  19458. seekSizes = NULL;
  19459. if (rawMeta)
  19460. {
  19461. // MORE - should check all keys in maxFields list can actually be keyed.
  19462. const CFieldOffsetSize * fields = rawMeta->queryFields();
  19463. unsigned maxFields = rawMeta->getNumFields();
  19464. seekGEOffset = fields[0].offset;
  19465. seekSizes = new unsigned[maxFields];
  19466. seekSizes[0] = fields[0].size;
  19467. for (unsigned i=1; i < maxFields; i++)
  19468. seekSizes[i] = seekSizes[i-1] + fields[i].size;
  19469. bool hasPostFilter = readHelper.transformMayFilter() && optimizeSteppedPostFilter;
  19470. if (projectedMeta)
  19471. steppingMeta.init(projectedMeta, hasPostFilter);
  19472. else
  19473. steppingMeta.init(rawMeta, hasPostFilter);
  19474. }
  19475. }
  19476. virtual const IResolvedFile *queryVarFileInfo() const
  19477. {
  19478. return varFileInfo;
  19479. }
  19480. ~CRoxieServerSimpleIndexReadActivity()
  19481. {
  19482. delete [] seekSizes;
  19483. }
  19484. virtual bool needsAllocator() const { return true; }
  19485. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19486. {
  19487. firstRead = true;
  19488. accepted = 0;
  19489. rejected = 0;
  19490. keyedCount = 0;
  19491. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  19492. if (steppedExtra)
  19493. steppingMeta.setExtra(steppedExtra);
  19494. eof = !indexHelper.canMatchAny();
  19495. if (variableFileName)
  19496. variableInfoPending = true;
  19497. else
  19498. {
  19499. variableInfoPending = false;
  19500. if (!keyIndexSet)
  19501. initKeySet();
  19502. }
  19503. }
  19504. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  19505. {
  19506. if (variableInfoPending)
  19507. setVariableFileInfo();
  19508. return this;
  19509. }
  19510. virtual IKeyArray *getKeySet() const
  19511. {
  19512. return keySet.getLink();
  19513. }
  19514. virtual const IResolvedFile *getVarFileInfo() const
  19515. {
  19516. return varFileInfo.getLink();
  19517. }
  19518. virtual TranslatorArray *getTranslators() const
  19519. {
  19520. return translators.getLink();
  19521. }
  19522. virtual void mergeSegmentMonitors(IIndexReadContext *irc) const
  19523. {
  19524. indexHelper.createSegmentMonitors(irc); // NOTE: they will merge
  19525. }
  19526. virtual IRoxieServerActivity *queryActivity() { return this; }
  19527. virtual const RemoteActivityId& queryRemoteId() const
  19528. {
  19529. return remoteId;
  19530. }
  19531. const void *nextInGroup()
  19532. {
  19533. bool matched = true;
  19534. return nextSteppedGE(NULL, 0, matched, dummySmartStepExtra);
  19535. }
  19536. virtual const void *nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  19537. {
  19538. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  19539. if (eof)
  19540. return NULL;
  19541. if (firstRead)
  19542. {
  19543. if (variableInfoPending)
  19544. setVariableFileInfo();
  19545. rowLimit = (unsigned) readHelper.getRowLimit();
  19546. chooseNLimit = (unsigned) readHelper.getChooseNLimit();
  19547. unsigned numParts = keyIndexSet->numParts();
  19548. if (!numParts)
  19549. {
  19550. onEOF();
  19551. return NULL;
  19552. }
  19553. if (numParts > 1 || seekGEOffset)
  19554. {
  19555. tlk.setown(createKeyMerger(keyIndexSet, 0, seekGEOffset, this));
  19556. // note that we don't set up translator because we don't support it. If that ever changes...
  19557. }
  19558. else
  19559. {
  19560. tlk.setown(createKeyManager(keyIndexSet->queryPart(0), 0, this));
  19561. tlk->setLayoutTranslator(translators->item(0));
  19562. }
  19563. indexHelper.createSegmentMonitors(tlk);
  19564. tlk->finishSegmentMonitors();
  19565. if (queryTraceLevel() > 3 || ctx->queryProbeManager())
  19566. {
  19567. StringBuffer out;
  19568. printKeyedValues(out, tlk, indexHelper.queryDiskRecordSize());
  19569. CTXLOG("Using filter %s", out.str());
  19570. if (ctx->queryProbeManager())
  19571. ctx->queryProbeManager()->setNodeProperty(this, "filter", out.str());
  19572. }
  19573. tlk->reset();
  19574. callback.setManager(tlk);
  19575. keyedLimit = readHelper.getKeyedLimit();
  19576. if (keyedLimit != (unsigned __int64) -1)
  19577. {
  19578. if ((indexHelper.getFlags() & TIRcountkeyedlimit) != 0)
  19579. {
  19580. unsigned __int64 count = tlk->checkCount(keyedLimit);
  19581. if (count > keyedLimit)
  19582. {
  19583. if ((indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates)) == 0)
  19584. readHelper.onKeyedLimitExceeded();
  19585. const void * ret = NULL;
  19586. if (indexHelper.getFlags() & TIRkeyedlimitcreates)
  19587. ret = createKeyedLimitOnFailRow();
  19588. onEOF();
  19589. return ret;
  19590. }
  19591. tlk->reset();
  19592. keyedLimit = (unsigned __int64) -1;
  19593. }
  19594. }
  19595. firstRead = false;
  19596. }
  19597. if (accepted == chooseNLimit)
  19598. {
  19599. onEOF();
  19600. return NULL;
  19601. }
  19602. const byte * rawSeek = NULL;
  19603. unsigned seekSize = 0;
  19604. if (seek)
  19605. {
  19606. seekSize = seekSizes[numFields-1];
  19607. rawSeek = (const byte *)seek + seekGEOffset;
  19608. if (projectedMeta)
  19609. {
  19610. byte *temp = (byte *) alloca(seekSize);
  19611. RtlStaticRowBuilder rawBuilder(temp-seekGEOffset, seekGEOffset+seekSize);
  19612. readHelper.mapOutputToInput(rawBuilder, seek, numFields);// NOTE - weird interface to mapOutputToInput means that it STARTS writing at seekGEOffset...
  19613. rawSeek = (byte *)temp;
  19614. }
  19615. #ifdef _DEBUG
  19616. // StringBuffer seekStr;
  19617. // for (unsigned i = 0; i < seekSize; i++)
  19618. // {
  19619. // seekStr.appendf("%02x ", ((unsigned char *) rawSeek)[i]);
  19620. // }
  19621. // DBGLOG("nextSteppedGE can skip offset %d size %d value %s", seekGEOffset, seekSize, seekStr.str());
  19622. #endif
  19623. }
  19624. const byte * originalRawSeek = rawSeek;
  19625. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  19626. while (rawSeek ? tlk->lookupSkip(rawSeek, seekGEOffset, seekSize) : tlk->lookup(true))
  19627. {
  19628. checkAbort();
  19629. keyedCount++;
  19630. if (keyedCount > keyedLimit)
  19631. {
  19632. readHelper.onKeyedLimitExceeded();
  19633. break;
  19634. }
  19635. byte const * keyRow = tlk->queryKeyBuffer(callback.getFPosRef());
  19636. #ifdef _DEBUG
  19637. // StringBuffer recstr;
  19638. // unsigned size = (tlk->queryRecordSize()<80) ? tlk->queryRecordSize() : 80;
  19639. // for (unsigned i = 0; i < size; i++)
  19640. // {
  19641. // recstr.appendf("%02x ", ((unsigned char *) keyRow)[i]);
  19642. // }
  19643. // DBGLOG("nextSteppedGE Got %s", recstr.str());
  19644. if (originalRawSeek && memcmp(keyRow + seekGEOffset, originalRawSeek, seekSize) < 0)
  19645. assertex(!"smart seek failure");
  19646. #endif
  19647. size32_t transformedSize;
  19648. rowBuilder.ensureRow();
  19649. try
  19650. {
  19651. transformedSize = readHelper.transform(rowBuilder, keyRow);
  19652. //if the post filter causes a mismatch, and the stepping condition no longer matches
  19653. //then return a mismatch record - so the join code can start seeking on the other input.
  19654. if (transformedSize == 0 && optimizeSteppedPostFilter && stepExtra.returnMismatches())
  19655. {
  19656. if (memcmp(keyRow + seekGEOffset, originalRawSeek, seekSize) != 0)
  19657. {
  19658. transformedSize = readHelper.unfilteredTransform(rowBuilder, keyRow);
  19659. if (transformedSize != 0)
  19660. wasCompleteMatch = false;
  19661. }
  19662. }
  19663. callback.finishedRow();
  19664. }
  19665. catch (IException *E)
  19666. {
  19667. throw makeWrappedException(E);
  19668. }
  19669. if (transformedSize)
  19670. {
  19671. accepted++;
  19672. if (accepted > rowLimit)
  19673. {
  19674. if ((indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates)) != 0)
  19675. {
  19676. throwUnexpected(); // should not have used simple variant if maySkip set...
  19677. }
  19678. if (traceLevel > 4)
  19679. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  19680. readHelper.onLimitExceeded();
  19681. break;
  19682. }
  19683. processed++;
  19684. #ifdef _DEBUG
  19685. // const byte *ret = (const byte *) out.get();
  19686. // CommonXmlWriter xmlwrite(XWFnoindent|XWFtrim|XWFopt);
  19687. // queryOutputMeta()->toXML(ret, xmlwrite);
  19688. // DBGLOG("ROW: {%p} %s", ret, xmlwrite.str());
  19689. #endif
  19690. return rowBuilder.finalizeRowClear(transformedSize);
  19691. }
  19692. else
  19693. rejected++;
  19694. rawSeek = NULL;
  19695. }
  19696. onEOF();
  19697. return NULL;
  19698. }
  19699. virtual void reset()
  19700. {
  19701. onEOF();
  19702. if (accepted)
  19703. noteStatistic(STATS_ACCEPTED, accepted, 1);
  19704. if (rejected)
  19705. noteStatistic(STATS_REJECTED, rejected, 1);
  19706. if (variableFileName)
  19707. {
  19708. varFileInfo.clear();
  19709. translators.clear();
  19710. }
  19711. variableInfoPending = false;
  19712. CRoxieServerActivity::reset();
  19713. }
  19714. virtual void setInput(unsigned idx, IRoxieInput *_in)
  19715. {
  19716. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  19717. }
  19718. virtual IInputSteppingMeta * querySteppingMeta()
  19719. {
  19720. if (rawMeta && steppingEnabled && ((indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates|TIRkeyedlimitskips|TIRkeyedlimitcreates)) == 0))
  19721. return &steppingMeta;
  19722. return NULL;
  19723. }
  19724. protected:
  19725. const void * createKeyedLimitOnFailRow()
  19726. {
  19727. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  19728. size32_t outSize = limitTransformExtra->transformOnKeyedLimitExceeded(rowBuilder);
  19729. if (outSize)
  19730. return rowBuilder.finalizeRowClear(outSize);
  19731. return NULL;
  19732. }
  19733. };
  19734. class CRoxieServerBaseIndexActivityFactory : public CRoxieServerActivityFactory
  19735. {
  19736. public:
  19737. Owned<IKeyArray> keySet;
  19738. Owned<TranslatorArray> translatorArray;
  19739. Owned<IDefRecordMeta> activityMeta;
  19740. RemoteActivityId remoteId;
  19741. bool isSimple;
  19742. bool isLocal;
  19743. bool maySkip;
  19744. bool sorted;
  19745. bool variableFileName;
  19746. bool enableFieldTranslation;
  19747. unsigned maxSeekLookahead;
  19748. Owned<const IResolvedFile> indexfile;
  19749. CRoxieServerSideCache *cache;
  19750. CRoxieServerBaseIndexActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  19751. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), remoteId(_remoteId)
  19752. {
  19753. Owned<IHThorIndexReadBaseArg> indexHelper = (IHThorIndexReadBaseArg *) helperFactory();
  19754. unsigned flags = indexHelper->getFlags();
  19755. sorted = (flags & TIRunordered) == 0;
  19756. isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  19757. rtlDataAttr indexLayoutMeta;
  19758. size32_t indexLayoutSize;
  19759. if(!indexHelper->getIndexLayout(indexLayoutSize, indexLayoutMeta.refdata()))
  19760. assertex(indexLayoutSize==0);
  19761. MemoryBuffer m;
  19762. m.setBuffer(indexLayoutSize, indexLayoutMeta.getdata());
  19763. activityMeta.setown(deserializeRecordMeta(m, true));
  19764. enableFieldTranslation = queryFactory.getEnableFieldTranslation();
  19765. translatorArray.setown(new TranslatorArray);
  19766. variableFileName = allFilesDynamic || _queryFactory.isDynamic() || ((flags & (TIRvarfilename|TIRdynamicfilename)) != 0);
  19767. if (!variableFileName)
  19768. {
  19769. bool isOpt = (flags & TIRoptional) != 0;
  19770. OwnedRoxieString indexName(indexHelper->getFileName());
  19771. indexfile.setown(queryFactory.queryPackage().lookupFileName(indexName, isOpt, true, true, queryFactory.queryWorkUnit()));
  19772. if (indexfile)
  19773. keySet.setown(indexfile->getKeyArray(activityMeta, translatorArray, isOpt, isLocal ? queryFactory.queryChannel() : 0, enableFieldTranslation));
  19774. }
  19775. isSimple = isLocal;
  19776. maySkip = (flags & (TIRkeyedlimitskips|TIRlimitskips|TIRlimitcreates|TIRkeyedlimitcreates)) != 0;
  19777. if (keySet && keySet->length()==1 && !isLocal && (flags & (TIRlimitskips|TIRlimitcreates|TIRkeyedlimitskips|TIRkeyedlimitcreates))==0)
  19778. {
  19779. IKeyIndexBase *thisBase = keySet->queryKeyPart(0);
  19780. if (thisBase->numParts()==1 && !thisBase->queryPart(0)->isTopLevelKey() && !_queryFactory.getDebugValueBool("disableLocalOptimizations", false))
  19781. isSimple = true;
  19782. }
  19783. int cacheSize = _graphNode.getPropInt("hint[@name='cachehits']/@value", serverSideCacheSize);
  19784. cache = cacheSize ? new CRoxieServerSideCache(cacheSize) : NULL;
  19785. maxSeekLookahead = _graphNode.getPropInt("hint[@name='maxseeklookahead']/@value", 0);
  19786. }
  19787. ~CRoxieServerBaseIndexActivityFactory()
  19788. {
  19789. delete cache;
  19790. }
  19791. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  19792. {
  19793. if (indexfile)
  19794. addXrefFileInfo(reply, indexfile);
  19795. }
  19796. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  19797. {
  19798. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for indexread activity");
  19799. }
  19800. virtual IRoxieServerSideCache *queryServerSideCache() const
  19801. {
  19802. return cache;
  19803. }
  19804. virtual bool getEnableFieldTranslation() const
  19805. {
  19806. return enableFieldTranslation;
  19807. }
  19808. virtual IDefRecordMeta *queryActivityMeta() const
  19809. {
  19810. return activityMeta;
  19811. }
  19812. };
  19813. class CRoxieServerIndexReadActivityFactory : public CRoxieServerBaseIndexActivityFactory
  19814. {
  19815. public:
  19816. CRoxieServerIndexReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  19817. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode)
  19818. {
  19819. }
  19820. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  19821. {
  19822. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  19823. return new CRoxieServerNullActivity(this, _probeManager);
  19824. else if (isSimple && !maySkip)
  19825. return new CRoxieServerSimpleIndexReadActivity(this, _probeManager, remoteId, keySet, translatorArray, isLocal);
  19826. else
  19827. return new CRoxieServerIndexReadActivity(this, _probeManager, remoteId, keySet, translatorArray, sorted, isLocal, maySkip, maxSeekLookahead);
  19828. }
  19829. };
  19830. IRoxieServerActivityFactory *createRoxieServerIndexReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  19831. {
  19832. return new CRoxieServerIndexReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode);
  19833. }
  19834. //--------------------------------------------------------------------------------------------------------------------------
  19835. class CRoxieServerNullCountActivity : public CRoxieServerActivity
  19836. {
  19837. bool done;
  19838. public:
  19839. CRoxieServerNullCountActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  19840. : CRoxieServerActivity(_factory, _probeManager)
  19841. {
  19842. done = false;
  19843. }
  19844. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19845. {
  19846. done = false;
  19847. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  19848. }
  19849. virtual bool needsAllocator() const { return true; }
  19850. virtual const void *nextInGroup()
  19851. {
  19852. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  19853. if (done) return NULL;
  19854. done = true;
  19855. size32_t rowSize = meta.getFixedSize();
  19856. void * nullRow = rowAllocator->createRow();
  19857. if (rowSize == 1)
  19858. *(byte *)nullRow = 0;
  19859. else
  19860. {
  19861. assertex(rowSize == sizeof(unsigned __int64));
  19862. *(unsigned __int64 *)nullRow = 0;
  19863. }
  19864. return rowAllocator->finalizeRow(rowSize, nullRow, rowSize);
  19865. }
  19866. };
  19867. class CRoxieServerIndexCountActivity : public CRoxieServerIndexActivity
  19868. {
  19869. IHThorCompoundCountExtra & countHelper;
  19870. IHThorSourceCountLimit * limitHelper;
  19871. bool done;
  19872. public:
  19873. CRoxieServerIndexCountActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IKeyArray * _keySet, TranslatorArray *_translators, bool _isLocal)
  19874. : CRoxieServerIndexActivity(_factory, _probeManager, _remoteId, _keySet, _translators, false, _isLocal, false),
  19875. countHelper((IHThorIndexCountArg &)basehelper),
  19876. done(false)
  19877. {
  19878. limitHelper = static_cast<IHThorSourceCountLimit *>(basehelper.selectInterface(TAIsourcecountlimit_1));
  19879. }
  19880. virtual bool needsAllocator() const { return true; }
  19881. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19882. {
  19883. done = false;
  19884. CRoxieServerIndexActivity::start(parentExtractSize, parentExtract, paused);
  19885. choosenLimit = countHelper.getChooseNLimit();
  19886. if (limitHelper)
  19887. {
  19888. rowLimit = limitHelper->getRowLimit();
  19889. keyedLimit = limitHelper->getKeyedLimit();
  19890. }
  19891. if (!paused)
  19892. processAllKeys();
  19893. }
  19894. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
  19895. {
  19896. unsigned __int64 count = 0;
  19897. if (countHelper.hasFilter())
  19898. {
  19899. while (tlk->lookup(true))
  19900. {
  19901. try
  19902. {
  19903. count += countHelper.numValid(tlk->queryKeyBuffer(callback.getFPosRef()));
  19904. callback.finishedRow();
  19905. }
  19906. catch (IException *E)
  19907. {
  19908. throw makeWrappedException(E);
  19909. }
  19910. accepted++;
  19911. if (count >= choosenLimit) // MORE - what about limit?
  19912. break;
  19913. }
  19914. }
  19915. else
  19916. count = tlk->getCount(); //MORE: GH->RKC There should be value in providing a max limit to getCount()
  19917. if (count)
  19918. {
  19919. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), false);
  19920. if (count > choosenLimit)
  19921. count = choosenLimit;
  19922. void * recBuffer = rowAllocator->createRow();
  19923. if (meta.getFixedSize() == 1)
  19924. *(byte *)recBuffer = (byte)count;
  19925. else
  19926. {
  19927. assertex(meta.getFixedSize() == sizeof(unsigned __int64));
  19928. *(unsigned __int64 *)recBuffer = count;
  19929. }
  19930. recBuffer = rowAllocator->finalizeRow(meta.getFixedSize(), recBuffer, meta.getFixedSize());
  19931. result->append(recBuffer);
  19932. remote.injectResult(result.getClear());
  19933. //GH->RKC for count(,choosen)/exists passing in the previous count would short-circuit this much earlier
  19934. if (count >= choosenLimit)
  19935. return true;
  19936. }
  19937. return false;
  19938. }
  19939. virtual void onLimitExceeded(bool isKeyed)
  19940. {
  19941. if (traceLevel > 4)
  19942. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  19943. if (isKeyed)
  19944. {
  19945. if (indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates))
  19946. {
  19947. if (ctx->queryDebugContext())
  19948. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  19949. throw makeLimitSkipException(true);
  19950. }
  19951. else
  19952. {
  19953. assertex(limitHelper); // Should not be able to generate exception if there was not one...
  19954. limitHelper->onKeyedLimitExceeded();
  19955. }
  19956. }
  19957. else
  19958. {
  19959. if (indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates))
  19960. {
  19961. if (ctx->queryDebugContext())
  19962. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  19963. throw makeLimitSkipException(false);
  19964. }
  19965. else
  19966. {
  19967. assertex(limitHelper);
  19968. limitHelper->onLimitExceeded();
  19969. }
  19970. }
  19971. }
  19972. virtual const void *createLimitFailRow(bool isKeyed)
  19973. {
  19974. throwUnexpected();
  19975. }
  19976. virtual const void *nextInGroup()
  19977. {
  19978. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  19979. if (done) return NULL;
  19980. done = true;
  19981. unsigned __int64 totalCount = 0;
  19982. bool hasLimit = rowLimit != (unsigned __int64) -1;
  19983. try
  19984. {
  19985. loop
  19986. {
  19987. const void * next = remote.nextInGroup();
  19988. if (!next)
  19989. break;
  19990. if (meta.getFixedSize() == 1)
  19991. totalCount += *(byte *)next;
  19992. else
  19993. totalCount += *(unsigned __int64 *) next;
  19994. ReleaseRoxieRow(next);
  19995. if (totalCount > rowLimit || (totalCount > choosenLimit && !hasLimit)) // can't break out early if there is a possibility of later slave throwing limit exception
  19996. break;
  19997. }
  19998. if (totalCount > rowLimit)
  19999. {
  20000. unsigned flags = indexHelper.getFlags();
  20001. if (flags & TIRlimitskips)
  20002. totalCount = 0;
  20003. else if (flags & TIRlimitcreates)
  20004. totalCount = 1;
  20005. else
  20006. {
  20007. assertex(limitHelper);
  20008. limitHelper->onLimitExceeded();
  20009. }
  20010. }
  20011. else if (totalCount > choosenLimit)
  20012. totalCount = choosenLimit;
  20013. }
  20014. catch (IException *E)
  20015. {
  20016. if (QUERYINTERFACE(E, LimitSkipException))
  20017. {
  20018. totalCount = 0;
  20019. unsigned flags = indexHelper.getFlags();
  20020. if (E->errorCode() == KeyedLimitSkipErrorCode)
  20021. {
  20022. if (flags & TIRkeyedlimitcreates)
  20023. totalCount++;
  20024. }
  20025. else
  20026. {
  20027. if (flags & TIRlimitcreates)
  20028. totalCount++;
  20029. }
  20030. if (totalCount > choosenLimit)
  20031. totalCount = choosenLimit; // would have to be weird code (and escape the optimizer...)
  20032. E->Release();
  20033. }
  20034. else
  20035. throw ;
  20036. }
  20037. void * result = rowAllocator->createRow();
  20038. if (meta.getFixedSize() == 1)
  20039. *(byte *)result = (byte)totalCount;
  20040. else
  20041. {
  20042. assertex(meta.getFixedSize() == sizeof(unsigned __int64));
  20043. *(unsigned __int64 *)result = totalCount;
  20044. }
  20045. return rowAllocator->finalizeRow(meta.getFixedSize(), result, meta.getFixedSize());
  20046. }
  20047. };
  20048. class CRoxieServerIndexCountActivityFactory : public CRoxieServerBaseIndexActivityFactory
  20049. {
  20050. public:
  20051. CRoxieServerIndexCountActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  20052. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode)
  20053. {
  20054. }
  20055. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  20056. {
  20057. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  20058. return new CRoxieServerNullCountActivity(this, _probeManager);
  20059. // else if (isSimple)
  20060. // return new CRoxieServerSimpleIndexCountActivity(this, keySet->queryKeyPart(0)->queryPart(0));
  20061. else
  20062. return new CRoxieServerIndexCountActivity(this, _probeManager, remoteId, keySet, translatorArray, isLocal);
  20063. }
  20064. };
  20065. IRoxieServerActivityFactory *createRoxieServerIndexCountActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  20066. {
  20067. return new CRoxieServerIndexCountActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode);
  20068. }
  20069. //--------------------------------------------------------------------------------------------------------------------------
  20070. class CRoxieServerNullIndexAggregateActivity : public CRoxieServerActivity
  20071. {
  20072. IHThorIndexAggregateArg &aggregateHelper;
  20073. bool done;
  20074. public:
  20075. CRoxieServerNullIndexAggregateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  20076. : CRoxieServerActivity(_factory, _probeManager),
  20077. aggregateHelper((IHThorIndexAggregateArg &)basehelper)
  20078. {
  20079. done = false;
  20080. }
  20081. virtual bool needsAllocator() const { return true; }
  20082. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20083. {
  20084. done = false;
  20085. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  20086. }
  20087. virtual const void *nextInGroup()
  20088. {
  20089. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  20090. if (done) return NULL;
  20091. done = true;
  20092. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  20093. size32_t thisSize = aggregateHelper.clearAggregate(rowBuilder);
  20094. return rowBuilder.finalizeRowClear(thisSize);
  20095. }
  20096. };
  20097. class CRoxieServerIndexAggregateActivity : public CRoxieServerIndexActivity
  20098. {
  20099. IHThorCompoundAggregateExtra & aggregateHelper;
  20100. bool done;
  20101. public:
  20102. CRoxieServerIndexAggregateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  20103. IKeyArray * _keySet, TranslatorArray *_translators, bool _isLocal)
  20104. : CRoxieServerIndexActivity(_factory, _probeManager, _remoteId, _keySet, _translators, false, _isLocal, false),
  20105. aggregateHelper((IHThorIndexAggregateArg &)basehelper),
  20106. done(false)
  20107. {
  20108. }
  20109. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20110. {
  20111. done = false;
  20112. CRoxieServerIndexActivity::start(parentExtractSize, parentExtract, paused);
  20113. if (!paused)
  20114. processAllKeys();
  20115. }
  20116. virtual bool needsAllocator() const { return true; }
  20117. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
  20118. {
  20119. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  20120. while (tlk->lookup(true))
  20121. {
  20122. if (!rowBuilder.exists())
  20123. {
  20124. rowBuilder.ensureRow();
  20125. aggregateHelper.clearAggregate(rowBuilder);
  20126. }
  20127. try
  20128. {
  20129. aggregateHelper.processRow(rowBuilder, tlk->queryKeyBuffer(callback.getFPosRef()));
  20130. callback.finishedRow();
  20131. }
  20132. catch (IException *E)
  20133. {
  20134. throw makeWrappedException(E);
  20135. }
  20136. accepted++;
  20137. }
  20138. if (aggregateHelper.processedAnyRows())
  20139. {
  20140. size32_t size = meta.getRecordSize(rowBuilder.getSelf());
  20141. const void * recBuffer = rowBuilder.finalizeRowClear(size);
  20142. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), meta.isVariableSize());
  20143. result->append(recBuffer);
  20144. remote.injectResult(result.getClear());
  20145. }
  20146. return false;
  20147. }
  20148. virtual void onLimitExceeded(bool isKeyed)
  20149. {
  20150. if (traceLevel > 4)
  20151. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  20152. throwUnexpected();
  20153. }
  20154. virtual const void *createLimitFailRow(bool isKeyed)
  20155. {
  20156. throwUnexpected();
  20157. }
  20158. const void * gatherMerged()
  20159. {
  20160. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  20161. const void * firstRow = remote.nextInGroup();
  20162. size32_t finalSize = 0;
  20163. if (!firstRow)
  20164. {
  20165. rowBuilder.ensureRow();
  20166. finalSize = aggregateHelper.clearAggregate(rowBuilder);
  20167. }
  20168. else
  20169. {
  20170. // NOTE need to clone this because going to modify below, could special case 1 row only
  20171. finalSize = cloneRow(rowBuilder, firstRow, meta);
  20172. ReleaseRoxieRow(firstRow);
  20173. }
  20174. loop
  20175. {
  20176. const void * next = remote.nextInGroup();
  20177. if (!next)
  20178. break;
  20179. finalSize = aggregateHelper.mergeAggregate(rowBuilder, next);
  20180. ReleaseRoxieRow(next);
  20181. }
  20182. return rowBuilder.finalizeRowClear(finalSize);
  20183. }
  20184. virtual const void *nextInGroup()
  20185. {
  20186. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  20187. if (done) return NULL;
  20188. const void * ret = gatherMerged();
  20189. done = true;
  20190. return ret;
  20191. }
  20192. };
  20193. class CRoxieServerIndexAggregateActivityFactory : public CRoxieServerBaseIndexActivityFactory
  20194. {
  20195. public:
  20196. CRoxieServerIndexAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  20197. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode)
  20198. {
  20199. }
  20200. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  20201. {
  20202. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  20203. return new CRoxieServerNullIndexAggregateActivity(this, _probeManager);
  20204. // else if (isSimple)
  20205. // return new CRoxieServerSimpleIndexAggregateActivity(this, keySet->queryKeyPart(0)->queryPart(0));
  20206. else
  20207. return new CRoxieServerIndexAggregateActivity(this, _probeManager, remoteId, keySet, translatorArray, isLocal);
  20208. }
  20209. };
  20210. IRoxieServerActivityFactory *createRoxieServerIndexAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  20211. {
  20212. return new CRoxieServerIndexAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode);
  20213. }
  20214. //--------------------------------------------------------------------------------------------------------------------------
  20215. class CRoxieServerIndexGroupAggregateActivity : public CRoxieServerIndexActivity, implements IHThorGroupAggregateCallback
  20216. {
  20217. IHThorCompoundGroupAggregateExtra & aggregateHelper;
  20218. RowAggregator singleAggregator;
  20219. RowAggregator resultAggregator;
  20220. unsigned groupSegCount;
  20221. bool gathered;
  20222. bool eof;
  20223. public:
  20224. CRoxieServerIndexGroupAggregateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  20225. IKeyArray * _keySet, TranslatorArray *_translators, bool _isLocal)
  20226. : CRoxieServerIndexActivity(_factory, _probeManager, _remoteId, _keySet, _translators, false, _isLocal, false),
  20227. aggregateHelper((IHThorIndexGroupAggregateArg &)basehelper),
  20228. singleAggregator(aggregateHelper, aggregateHelper),
  20229. resultAggregator(aggregateHelper, aggregateHelper),
  20230. gathered(false), eof(true)
  20231. {
  20232. groupSegCount = 0;
  20233. }
  20234. IMPLEMENT_IINTERFACE
  20235. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20236. {
  20237. eof = false;
  20238. gathered= false;
  20239. CRoxieServerIndexActivity::start(parentExtractSize, parentExtract, paused);
  20240. groupSegCount = 0;
  20241. if (!paused)
  20242. processAllKeys();
  20243. resultAggregator.start(rowAllocator);
  20244. }
  20245. virtual bool needsAllocator() const { return true; }
  20246. virtual void reset()
  20247. {
  20248. resultAggregator.reset();
  20249. CRoxieServerIndexActivity::reset();
  20250. }
  20251. virtual void processRow(const void * next)
  20252. {
  20253. singleAggregator.addRow(next);
  20254. }
  20255. virtual void createSegmentMonitors(IKeyManager *key)
  20256. {
  20257. unsigned groupSegSize;
  20258. ThorActivityKind kind = factory->getKind();
  20259. if ((kind==TAKindexgroupcount || kind==TAKindexgroupexists))
  20260. groupSegSize = aggregateHelper.getGroupSegmentMonitorsSize();
  20261. else
  20262. groupSegSize = 0;
  20263. if (groupSegSize)
  20264. {
  20265. key->setMergeBarrier(groupSegSize);
  20266. CRoxieServerIndexActivity::createSegmentMonitors(key);
  20267. unsigned numSegs = tlk->ordinality();
  20268. for (unsigned segNo = 0; segNo < numSegs; segNo++)
  20269. {
  20270. IKeySegmentMonitor *seg = tlk->item(segNo);
  20271. if (seg->getOffset()+seg->getSize()==groupSegSize)
  20272. {
  20273. groupSegCount = segNo+1;
  20274. break;
  20275. }
  20276. }
  20277. assertex(groupSegCount);
  20278. }
  20279. else
  20280. CRoxieServerIndexActivity::createSegmentMonitors(key);
  20281. }
  20282. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
  20283. {
  20284. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), meta.isVariableSize());
  20285. singleAggregator.start(rowAllocator);
  20286. ThorActivityKind kind = factory->getKind();
  20287. while (tlk->lookup(true))
  20288. {
  20289. try
  20290. {
  20291. if (groupSegCount && !trans)
  20292. {
  20293. AggregateRowBuilder &rowBuilder = singleAggregator.addRow(tlk->queryKeyBuffer(callback.getFPosRef()));
  20294. callback.finishedRow();
  20295. if (kind==TAKindexgroupcount)
  20296. {
  20297. unsigned __int64 count = tlk->getCurrentRangeCount(groupSegCount);
  20298. aggregateHelper.processCountGrouping(rowBuilder, count-1);
  20299. }
  20300. if (!tlk->nextRange(groupSegCount))
  20301. break;
  20302. }
  20303. else
  20304. {
  20305. aggregateHelper.processRow(tlk->queryKeyBuffer(callback.getFPosRef()), this);
  20306. callback.finishedRow();
  20307. }
  20308. }
  20309. catch (IException *E)
  20310. {
  20311. throw makeWrappedException(E);
  20312. }
  20313. accepted++;
  20314. }
  20315. loop
  20316. {
  20317. Owned<AggregateRowBuilder> next = singleAggregator.nextResult();
  20318. if (!next)
  20319. break;
  20320. size32_t size = next->querySize();
  20321. result->append(next->finalizeRowClear());
  20322. }
  20323. remote.injectResult(result.getClear());
  20324. singleAggregator.reset();
  20325. return false;
  20326. }
  20327. virtual void onLimitExceeded(bool isKeyed)
  20328. {
  20329. if (traceLevel > 4)
  20330. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);DBGLOG("%d activityid = %d", __LINE__, activityId);
  20331. throwUnexpected();
  20332. }
  20333. virtual const void *createLimitFailRow(bool isKeyed)
  20334. {
  20335. throwUnexpected();
  20336. }
  20337. void gatherMerged()
  20338. {
  20339. gathered = true;
  20340. loop
  20341. {
  20342. const void * next = remote.nextInGroup();
  20343. if (!next)
  20344. break;
  20345. resultAggregator.mergeElement(next);
  20346. ReleaseRoxieRow(next);
  20347. }
  20348. }
  20349. virtual const void *nextInGroup()
  20350. {
  20351. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  20352. if (eof)
  20353. return NULL;
  20354. if (!gathered)
  20355. gatherMerged();
  20356. Owned<AggregateRowBuilder> next = resultAggregator.nextResult();
  20357. if (next)
  20358. {
  20359. processed++;
  20360. return next->finalizeRowClear();
  20361. }
  20362. eof = true;
  20363. return NULL;
  20364. }
  20365. };
  20366. class CRoxieServerIndexGroupAggregateActivityFactory : public CRoxieServerBaseIndexActivityFactory
  20367. {
  20368. public:
  20369. CRoxieServerIndexGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  20370. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode)
  20371. {
  20372. }
  20373. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  20374. {
  20375. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  20376. return new CRoxieServerNullActivity(this, _probeManager);
  20377. // else if (isSimple)
  20378. // return new CRoxieServerSimpleIndexGroupAggregateActivity(this, keySet->queryKeyPart(0)->queryPart(0));
  20379. else
  20380. return new CRoxieServerIndexGroupAggregateActivity(this, _probeManager, remoteId, keySet, translatorArray, isLocal);
  20381. }
  20382. };
  20383. IRoxieServerActivityFactory *createRoxieServerIndexGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  20384. {
  20385. return new CRoxieServerIndexGroupAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode);
  20386. }
  20387. //--------------------------------------------------------------------------------------------------------------------------
  20388. class CRoxieServerIndexNormalizeActivity : public CRoxieServerIndexReadBaseActivity
  20389. {
  20390. IHThorCompoundNormalizeExtra & readHelper;
  20391. public:
  20392. CRoxieServerIndexNormalizeActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  20393. IKeyArray * _keySet, TranslatorArray *_translators, bool _sorted, bool _isLocal)
  20394. : CRoxieServerIndexReadBaseActivity(_factory, _probeManager, _remoteId, _keySet, _translators, _sorted, _isLocal, false),
  20395. readHelper((IHThorIndexNormalizeArg &)basehelper)
  20396. {
  20397. }
  20398. virtual bool needsAllocator() const { return true; }
  20399. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20400. {
  20401. CRoxieServerIndexReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  20402. rowLimit = readHelper.getRowLimit();
  20403. keyedLimit = readHelper.getKeyedLimit();
  20404. if (!paused)
  20405. processAllKeys();
  20406. }
  20407. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
  20408. {
  20409. unsigned keyedCount = 0;
  20410. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  20411. while (tlk->lookup(true))
  20412. {
  20413. keyedCount++;
  20414. if (keyedCount > keyedLimit)
  20415. {
  20416. if (traceLevel > 4)
  20417. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  20418. onLimitExceeded(true);
  20419. break;
  20420. }
  20421. size32_t transformedSize;
  20422. if (readHelper.first(tlk->queryKeyBuffer(callback.getFPosRef())))
  20423. {
  20424. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), meta.isVariableSize());
  20425. do
  20426. {
  20427. rowBuilder.ensureRow();
  20428. try
  20429. {
  20430. transformedSize = readHelper.transform(rowBuilder);
  20431. }
  20432. catch (IException *E)
  20433. {
  20434. throw makeWrappedException(E);
  20435. }
  20436. if (transformedSize)
  20437. {
  20438. // MORE - would be a good idea to stop these asap if rowlimit exceeded
  20439. result->append(rowBuilder.finalizeRowClear(transformedSize));
  20440. accepted++;
  20441. }
  20442. else
  20443. rejected++;
  20444. } while (readHelper.next());
  20445. remote.injectResult(result.getClear());
  20446. callback.finishedRow();
  20447. }
  20448. }
  20449. return false;
  20450. }
  20451. virtual void onLimitExceeded(bool isKeyed)
  20452. {
  20453. if (traceLevel > 4)
  20454. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  20455. if (isKeyed)
  20456. {
  20457. if (indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates))
  20458. {
  20459. if (ctx->queryDebugContext())
  20460. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  20461. throw makeLimitSkipException(true);
  20462. }
  20463. else
  20464. readHelper.onKeyedLimitExceeded();
  20465. }
  20466. else
  20467. {
  20468. if (indexHelper.getFlags() & (TIRlimitskips||TIRlimitcreates))
  20469. {
  20470. if (ctx->queryDebugContext())
  20471. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  20472. throw makeLimitSkipException(false);
  20473. }
  20474. else
  20475. readHelper.onLimitExceeded();
  20476. }
  20477. }
  20478. virtual const void *createLimitFailRow(bool isKeyed)
  20479. {
  20480. UNIMPLEMENTED;
  20481. }
  20482. };
  20483. class CRoxieServerIndexNormalizeActivityFactory : public CRoxieServerBaseIndexActivityFactory
  20484. {
  20485. public:
  20486. CRoxieServerIndexNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  20487. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode)
  20488. {
  20489. }
  20490. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  20491. {
  20492. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  20493. return new CRoxieServerNullActivity(this, _probeManager);
  20494. else
  20495. return new CRoxieServerIndexNormalizeActivity(this, _probeManager, remoteId, keySet, translatorArray, sorted, isLocal);
  20496. }
  20497. };
  20498. IRoxieServerActivityFactory *createRoxieServerIndexNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  20499. {
  20500. return new CRoxieServerIndexNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode);
  20501. }
  20502. //=================================================================================
  20503. class CRoxieServerCountDiskActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler
  20504. {
  20505. unsigned __int64 answer;
  20506. public:
  20507. CRoxieServerCountDiskActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned __int64 _answer)
  20508. : CRoxieServerActivity(_factory, _probeManager),
  20509. answer(_answer)
  20510. {
  20511. }
  20512. virtual const void *nextInGroup()
  20513. {
  20514. throwUnexpected();
  20515. }
  20516. virtual void setInput(unsigned idx, IRoxieInput *_in)
  20517. {
  20518. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  20519. }
  20520. virtual __int64 evaluate()
  20521. {
  20522. return answer;
  20523. }
  20524. virtual void onLimitExceeded(bool isKeyed)
  20525. {
  20526. if (traceLevel > 4)
  20527. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  20528. throwUnexpected();
  20529. }
  20530. virtual const void *createLimitFailRow(bool isKeyed)
  20531. {
  20532. throwUnexpected();
  20533. }
  20534. };
  20535. class CRoxieServerVariableCountDiskActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler
  20536. {
  20537. public:
  20538. CRoxieServerVariableCountDiskActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  20539. : CRoxieServerActivity(_factory, _probeManager)
  20540. {
  20541. }
  20542. virtual const void *nextInGroup()
  20543. {
  20544. throwUnexpected();
  20545. }
  20546. virtual void setInput(unsigned idx, IRoxieInput *_in)
  20547. {
  20548. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  20549. }
  20550. virtual __int64 evaluate()
  20551. {
  20552. IHThorCountFileArg &helper = (IHThorCountFileArg &) basehelper;
  20553. bool isOpt = (helper.getFlags() & TDRoptional) != 0;
  20554. unsigned recsize = helper.queryRecordSize()->getFixedSize();
  20555. assertex(recsize);
  20556. OwnedRoxieString fname(helper.getFileName());
  20557. Owned<const IResolvedFile> varFileInfo = resolveLFN(fname, isOpt);
  20558. return varFileInfo->getFileSize() / recsize;
  20559. }
  20560. virtual void onLimitExceeded(bool isKeyed)
  20561. {
  20562. if (traceLevel > 4)
  20563. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  20564. throwUnexpected();
  20565. }
  20566. virtual const void *createLimitFailRow(bool isKeyed)
  20567. {
  20568. throwUnexpected();
  20569. }
  20570. };
  20571. class CRoxieServerCountDiskActivityFactory : public CRoxieServerActivityFactory
  20572. {
  20573. public:
  20574. unsigned __int64 answer;
  20575. bool variableFileName;
  20576. Owned<const IResolvedFile> datafile;
  20577. CRoxieServerCountDiskActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  20578. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  20579. {
  20580. Owned<IHThorCountFileArg> helper = (IHThorCountFileArg *) helperFactory();
  20581. variableFileName = allFilesDynamic || _queryFactory.isDynamic() || ((helper->getFlags() & (TDXvarfilename|TDXdynamicfilename)) != 0);
  20582. assertex(helper->queryRecordSize()->isFixedSize());
  20583. if (!variableFileName)
  20584. {
  20585. unsigned recsize = helper->queryRecordSize()->getFixedSize();
  20586. assertex(recsize);
  20587. OwnedRoxieString fileName(helper->getFileName());
  20588. bool isOpt = (helper->getFlags() & TDRoptional) != 0;
  20589. datafile.setown(queryFactory.queryPackage().lookupFileName(fileName, isOpt, true, true, queryFactory.queryWorkUnit()));
  20590. offset_t filesize = datafile ? datafile->getFileSize() : 0;
  20591. if (filesize % recsize != 0)
  20592. 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);
  20593. answer = filesize / recsize;
  20594. }
  20595. else
  20596. answer = 0;
  20597. }
  20598. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  20599. {
  20600. if (datafile)
  20601. addXrefFileInfo(reply, datafile);
  20602. }
  20603. virtual IRoxieServerActivity *createFunction(IHThorArg &arg, IProbeManager *_probeManager) const
  20604. {
  20605. arg.Release();
  20606. if (variableFileName)
  20607. return new CRoxieServerVariableCountDiskActivity(this, _probeManager);
  20608. else
  20609. return new CRoxieServerCountDiskActivity(this, _probeManager, answer);
  20610. }
  20611. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  20612. {
  20613. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for CountDisk activity");
  20614. }
  20615. virtual bool isFunction() const
  20616. {
  20617. return true;
  20618. }
  20619. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  20620. {
  20621. return NULL;
  20622. }
  20623. };
  20624. IRoxieServerActivityFactory *createRoxieServerDiskCountActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  20625. {
  20626. return new CRoxieServerCountDiskActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  20627. }
  20628. //=================================================================================
  20629. class CRoxieServerFetchActivity : public CRoxieServerActivity, implements IRecordPullerCallback, implements IRoxieServerErrorHandler
  20630. {
  20631. IHThorFetchBaseArg &helper;
  20632. IHThorFetchContext * fetchContext;
  20633. Linked<IFilePartMap> map;
  20634. CRemoteResultAdaptor remote;
  20635. RecordPullerThread puller;
  20636. bool needsRHS;
  20637. bool variableFileName;
  20638. bool isOpt;
  20639. Owned<const IResolvedFile> varFileInfo;
  20640. public:
  20641. CRoxieServerFetchActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IFilePartMap *_map)
  20642. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorFetchBaseArg &)basehelper), map(_map), remote(_remoteId, meta.queryOriginal(), helper, *this, true, true), puller(false)
  20643. {
  20644. fetchContext = static_cast<IHThorFetchContext *>(helper.selectInterface(TAIfetchcontext_1));
  20645. needsRHS = helper.transformNeedsRhs();
  20646. variableFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((fetchContext->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  20647. isOpt = (fetchContext->getFetchFlags() & FFdatafileoptional) != 0;
  20648. }
  20649. virtual const IResolvedFile *queryVarFileInfo() const
  20650. {
  20651. return varFileInfo;
  20652. }
  20653. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  20654. {
  20655. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  20656. remote.onCreate(this, this, _ctx, _colocalParent);
  20657. }
  20658. virtual void setInput(unsigned idx, IRoxieInput *_in)
  20659. {
  20660. if (idx)
  20661. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  20662. puller.setInput(this, _in);
  20663. }
  20664. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20665. {
  20666. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  20667. remote.onStart(parentExtractSize, parentExtract);
  20668. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  20669. if (variableFileName)
  20670. {
  20671. OwnedRoxieString fname(fetchContext->getFileName());
  20672. varFileInfo.setown(resolveLFN(fname, isOpt));
  20673. if (varFileInfo)
  20674. map.setown(varFileInfo->getFileMap());
  20675. }
  20676. puller.start(parentExtractSize, parentExtract, paused, ctx->fetchPreload(), false, ctx);
  20677. }
  20678. virtual void stop(bool aborting)
  20679. {
  20680. // Called from remote, so no need to call back to it....
  20681. puller.stop(aborting);
  20682. CRoxieServerActivity::stop(aborting);
  20683. }
  20684. virtual void reset()
  20685. {
  20686. processed = remote.processed;
  20687. remote.processed = 0;
  20688. puller.reset();
  20689. if (variableFileName)
  20690. {
  20691. varFileInfo.clear();
  20692. map.clear();
  20693. }
  20694. CRoxieServerActivity::reset();
  20695. }
  20696. virtual IRoxieInput *queryOutput(unsigned idx)
  20697. {
  20698. if (idx==(unsigned)-1)
  20699. idx = 0;
  20700. return idx ? NULL : &remote;
  20701. }
  20702. virtual void processRow(const void *row)
  20703. {
  20704. // called from puller thread
  20705. offset_t rp = fetchContext->extractPosition(row);
  20706. unsigned partNo;
  20707. if (isLocalFpos(rp))
  20708. partNo = getLocalFposPart(rp) + 1;
  20709. else
  20710. partNo = map->mapOffset(rp);
  20711. if (needsRHS)
  20712. {
  20713. Owned<IEngineRowAllocator> extractAllocator = ctx->queryCodeContext()->getRowAllocator(helper.queryExtractedSize(), activityId);
  20714. RtlDynamicRowBuilder rb(extractAllocator, true);
  20715. unsigned rhsSize = helper.extractJoinFields(rb, row);
  20716. char * block = (char *) remote.getMem(partNo, 0, sizeof(rp) + sizeof(rhsSize) + rhsSize); // MORE - superfiles
  20717. *(offset_t *) block = rp;
  20718. block += sizeof(rp);
  20719. *(unsigned *) block = rhsSize;
  20720. block += sizeof(rhsSize);
  20721. memcpy(block, rb.row(), rhsSize);
  20722. }
  20723. else
  20724. *(offset_t *) remote.getMem(partNo, 0, sizeof(rp)) = rp; // MORE - superfiles
  20725. ReleaseRoxieRow(row);
  20726. }
  20727. void processEOG()
  20728. {
  20729. #ifdef FETCH_PRESERVES_GROUPING
  20730. UNIMPLEMENTED;
  20731. #endif
  20732. // else discard is correct
  20733. }
  20734. void processGroup(const ConstPointerArray &)
  20735. {
  20736. throwUnexpected();
  20737. }
  20738. void processDone()
  20739. {
  20740. // called from puller thread
  20741. remote.flush();
  20742. remote.senddone();
  20743. }
  20744. virtual bool fireException(IException *e)
  20745. {
  20746. return remote.fireException(e);
  20747. }
  20748. virtual void onLimitExceeded(bool isKeyed)
  20749. {
  20750. if (traceLevel > 4)
  20751. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  20752. if (isKeyed)
  20753. throwUnexpected();
  20754. helper.onLimitExceeded();
  20755. }
  20756. virtual const void *createLimitFailRow(bool isKeyed)
  20757. {
  20758. UNIMPLEMENTED;
  20759. }
  20760. virtual const void *nextInGroup()
  20761. {
  20762. throwUnexpected(); // I am nobody's input
  20763. }
  20764. };
  20765. class CRoxieServerFetchActivityFactory : public CRoxieServerActivityFactory
  20766. {
  20767. RemoteActivityId remoteId;
  20768. Owned<IFilePartMap> map;
  20769. bool variableFileName;
  20770. Owned<const IResolvedFile> datafile;
  20771. public:
  20772. CRoxieServerFetchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  20773. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), remoteId(_remoteId)
  20774. {
  20775. Owned<IHThorFetchBaseArg> helper = (IHThorFetchBaseArg *) helperFactory();
  20776. IHThorFetchContext *fetchContext = static_cast<IHThorFetchContext *>(helper->selectInterface(TAIfetchcontext_1));
  20777. variableFileName = allFilesDynamic || _queryFactory.isDynamic() || ((fetchContext->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  20778. if (!variableFileName)
  20779. {
  20780. OwnedRoxieString fname(fetchContext->getFileName());
  20781. datafile.setown(_queryFactory.queryPackage().lookupFileName(fname,
  20782. (fetchContext->getFetchFlags() & FFdatafileoptional) != 0,
  20783. true, true,
  20784. _queryFactory.queryWorkUnit()));
  20785. if (datafile)
  20786. map.setown(datafile->getFileMap());
  20787. }
  20788. }
  20789. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  20790. {
  20791. return new CRoxieServerFetchActivity(this, _probeManager, remoteId, map);
  20792. }
  20793. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  20794. {
  20795. if (datafile)
  20796. addXrefFileInfo(reply, datafile);
  20797. }
  20798. };
  20799. IRoxieServerActivityFactory *createRoxieServerFetchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  20800. {
  20801. return new CRoxieServerFetchActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode);
  20802. }
  20803. // MORE - is there any point keeping this now?
  20804. class CRoxieServerDummyActivityFactory : public CRoxieServerActivityFactory // not a real activity - just used to properly link files
  20805. {
  20806. public:
  20807. Owned<const IResolvedFile> indexfile;
  20808. Owned<const IResolvedFile> datafile;
  20809. Owned<IKeyArray> keySet;
  20810. Owned<IFileIOArray> files;
  20811. Owned<IFilePartMap> map;
  20812. TranslatorArray layoutTranslators;
  20813. CRoxieServerDummyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool isLoadDataOnly)
  20814. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  20815. {
  20816. try // does not want any missing file errors to be fatal, or throw traps - just log it
  20817. {
  20818. if (_graphNode.getPropBool("att[@name='_isSpill']/@value", false) || _graphNode.getPropBool("att[@name='_isSpillGlobal']/@value", false))
  20819. return; // ignore 'spills'
  20820. bool isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  20821. bool isOpt = _graphNode.getPropBool("att[@name='_isOpt']/@value") || pretendAllOpt;
  20822. const char *fileName = queryNodeFileName(_graphNode);
  20823. const char *indexName = queryNodeIndexName(_graphNode);
  20824. if (indexName && (!fileName || !streq(indexName, fileName)))
  20825. {
  20826. indexfile.setown(queryFactory.queryPackage().lookupFileName(indexName, isOpt, true, true, queryFactory.queryWorkUnit()));
  20827. if (indexfile)
  20828. keySet.setown(indexfile->getKeyArray(NULL, &layoutTranslators, isOpt, isLocal ? queryFactory.queryChannel() : 0, false));
  20829. }
  20830. if (fileName)
  20831. {
  20832. datafile.setown(_queryFactory.queryPackage().lookupFileName(fileName, isOpt, true, true, queryFactory.queryWorkUnit()));
  20833. if (datafile)
  20834. {
  20835. if (isLocal)
  20836. files.setown(datafile->getIFileIOArray(isOpt, queryFactory.queryChannel()));
  20837. else
  20838. map.setown(datafile->getFileMap());
  20839. }
  20840. }
  20841. }
  20842. catch(IException *E)
  20843. {
  20844. StringBuffer errors;
  20845. E->errorMessage(errors);
  20846. DBGLOG("%s File error = %s", (isLoadDataOnly) ? "LOADDATAONLY" : "SUSPENDED QUERY", errors.str());
  20847. E->Release();
  20848. }
  20849. }
  20850. 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__); }
  20851. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  20852. {
  20853. if (datafile)
  20854. addXrefFileInfo(reply, datafile);
  20855. if (indexfile)
  20856. addXrefFileInfo(reply, indexfile);
  20857. }
  20858. };
  20859. IRoxieServerActivityFactory *createRoxieServerDummyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool isLoadDataOnly)
  20860. {
  20861. return new CRoxieServerDummyActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, isLoadDataOnly);
  20862. }
  20863. //=====================================================================================================
  20864. // Keyed joins...
  20865. //
  20866. // Input records are pulled by a puller thread, which checks each LHS record to determine which (if any) channels it
  20867. // may have RHS matches on, and sends the relevant fields to the relevant slaves.
  20868. // 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
  20869. // the transform and returns rows that are created.
  20870. // 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)
  20871. //
  20872. //=====================================================================================================
  20873. class CJoinGroup;
  20874. interface IJoinProcessor
  20875. {
  20876. virtual void processEOG() = 0;
  20877. virtual CJoinGroup *createJoinGroup(const void *row) = 0;
  20878. virtual void noteEndReceived(CJoinGroup *jg, unsigned candidateCount) = 0;
  20879. virtual bool fireException(IException *E) = 0;
  20880. virtual void processCompletedGroups() = 0;
  20881. };
  20882. //------------------------------------------------------------------------------------------------------
  20883. // Class CJoinGroup has a record per LHS row, plus (if preserving grouping) a 'head of group' record
  20884. // It gathers all the corresponding RHS rows, keeping track of how may slave transactions are pending in endMarkersPending
  20885. // If preserving groups, the 'head of group' record keeps track of how many LHS records in the group are still incomplete.
  20886. // CJoinGroup records are allocated out of the Roxie row memory manager by overloading operator new, so that they are included in the
  20887. // per-query limits etc (Note that the pointer array block is not though).
  20888. // Because of that, the exact size is significant - especially whether fit just under or just over a chunking threshold...
  20889. //
  20890. // There are two phases to the life of a JoinGroup - it is created by the puller thread that is also firing off slave requests
  20891. // notePending will be called once for every slave request. Puller thread calls noteEndReceived(0) once when done - this corresponds to the
  20892. // initial count when created.
  20893. // Slave replies and are noted by the consumer thread calling addRightMatch() and noteEndReceived(n).
  20894. // Once endMarkersPending reaches 0, JoinGroup is complete. Last thread to call noteEndReceived will process the rows and destroy the group.
  20895. // There is no need for a critsec because although multiple threads will access at different times, only the consumer thread will
  20896. // access any modifiable member variables while endMarkersPending != 0 (i.e. complete() is false). Once complete returns true there is a single
  20897. // remaining reference and the JoinGroup will be processed and destroyed.
  20898. //
  20899. //------------------------------------------------------------------------------------------------------
  20900. class CJoinGroup : public CInterface, implements IInterface
  20901. {
  20902. protected:
  20903. const void *left; // LHS row
  20904. PointerArrayOf<KeyedJoinHeader> rows; // matching RHS rows
  20905. atomic_t endMarkersPending; // How many slave responses still waiting for
  20906. CJoinGroup *groupStart; // Head of group, or NULL if not grouping
  20907. unsigned lastPartNo;
  20908. unsigned pos;
  20909. unsigned candidates; // Number of RHS keyed candidates - note this may not be the same as rows.ordinality()
  20910. public:
  20911. #undef new
  20912. void *operator new(size_t size, IRowManager *a, unsigned activityId)
  20913. {
  20914. return a->allocate(size, activityId);
  20915. }
  20916. #if defined(_DEBUG) && defined(_WIN32) && !defined(USING_MPATROL)
  20917. #define new new(_NORMAL_BLOCK, __FILE__, __LINE__)
  20918. #endif
  20919. void operator delete(void *ptr, IRowManager *a, unsigned activityId)
  20920. {
  20921. ReleaseRoxieRow(ptr);
  20922. }
  20923. void operator delete(void *ptr)
  20924. {
  20925. ReleaseRoxieRow(ptr);
  20926. }
  20927. public:
  20928. IMPLEMENT_IINTERFACE;
  20929. CJoinGroup(const void *_left, CJoinGroup *_groupStart)
  20930. {
  20931. #ifdef TRACE_JOINGROUPS
  20932. DBGLOG("Creating joinGroup %p, groupstart %p", this, _groupStart);
  20933. #endif
  20934. candidates = 0;
  20935. lastPartNo = 0;
  20936. pos = 0;
  20937. left = _left;
  20938. groupStart = _groupStart;
  20939. if (_groupStart)
  20940. {
  20941. atomic_inc(&_groupStart->endMarkersPending);
  20942. }
  20943. atomic_set(&endMarkersPending, 1);
  20944. }
  20945. ~CJoinGroup()
  20946. {
  20947. #ifdef TRACE_JOINGROUPS
  20948. DBGLOG("Destroying joinGroup %p", this);
  20949. #endif
  20950. if (left)
  20951. {
  20952. ReleaseRoxieRow(left);
  20953. ForEachItemIn(idx, rows)
  20954. ReleaseRoxieRow(rows.item(idx));
  20955. rows.kill();
  20956. }
  20957. }
  20958. inline bool isHeadRecord() const
  20959. {
  20960. return left==NULL;
  20961. }
  20962. inline bool complete() const
  20963. {
  20964. return atomic_read(&endMarkersPending) == 0;
  20965. }
  20966. #ifdef TRACE_JOINGROUPS
  20967. inline void notePending(unsigned lineNo)
  20968. #else
  20969. inline void notePending()
  20970. #endif
  20971. {
  20972. assert(!complete());
  20973. atomic_inc(&endMarkersPending);
  20974. #ifdef TRACE_JOINGROUPS
  20975. DBGLOG("CJoinGroup::notePending %p from %d, count became %d group count %d", this, lineNo, atomic_read(&endMarkersPending), groupStart ? atomic_read(&groupStart->endMarkersPending) : 0);
  20976. #endif
  20977. }
  20978. inline bool inGroup(CJoinGroup *leader) const
  20979. {
  20980. return groupStart==leader;
  20981. }
  20982. inline const KeyedJoinHeader *queryRow(unsigned idx) const
  20983. {
  20984. // Single threaded by now
  20985. assert(complete());
  20986. return rows.item(idx);
  20987. }
  20988. #ifdef TRACE_JOINGROUPS
  20989. bool noteEndReceived(unsigned candidateCount, unsigned lineNo)
  20990. #else
  20991. bool noteEndReceived(unsigned candidateCount)
  20992. #endif
  20993. {
  20994. assert(!complete());
  20995. if (candidateCount)
  20996. {
  20997. candidates += candidateCount;
  20998. }
  20999. #ifdef TRACE_JOINGROUPS
  21000. 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);
  21001. #endif
  21002. // NOTE - as soon as endMarkersPending and groupStart->endMarkersPending are decremented to zero this object may get released asynchronously by other threads
  21003. // There must therefore be nothing in this method after them that acceses member variables. Think of it as a delete this...
  21004. // In particular, we can't safely reference groupStart after the dec_and_test of endMarkersPending, hence copy local first
  21005. CJoinGroup *localGroupStart = groupStart;
  21006. if (atomic_dec_and_test(&endMarkersPending))
  21007. {
  21008. if (localGroupStart)
  21009. return atomic_dec_and_test(&localGroupStart->endMarkersPending);
  21010. else
  21011. return true;
  21012. }
  21013. else
  21014. return false;
  21015. }
  21016. inline const void *queryLeft() const
  21017. {
  21018. return left;
  21019. }
  21020. void addRightMatch(KeyedJoinHeader *right)
  21021. {
  21022. assert(!complete());
  21023. unsigned short partNo = right->partNo;
  21024. if (partNo != lastPartNo)
  21025. {
  21026. // MORE - should we binchop? If we did we would need to be careful to find LAST match
  21027. if (partNo > lastPartNo)
  21028. pos = rows.length();
  21029. while (pos>0)
  21030. {
  21031. if (rows.item(pos-1)->partNo <= partNo)
  21032. break;
  21033. pos--;
  21034. }
  21035. lastPartNo = partNo;
  21036. }
  21037. rows.add(right, pos);
  21038. pos++;
  21039. }
  21040. inline unsigned rowsSeen() const
  21041. {
  21042. assert(complete());
  21043. return rows.length();
  21044. }
  21045. inline unsigned candidateCount() const
  21046. {
  21047. assert(complete());
  21048. return candidates;
  21049. }
  21050. };
  21051. #ifdef TRACE_JOINGROUPS
  21052. #define notePending() notePending(__LINE__)
  21053. #define noteEndReceived(a) noteEndReceived(a, __LINE__)
  21054. #endif
  21055. class KeyedJoinRemoteAdaptor : public CRemoteResultAdaptor // MORE - not sure it should be derived from this - makes processed all wrong, for example
  21056. {
  21057. private:
  21058. SafeQueueOf<const void, true> ready;
  21059. public:
  21060. IHThorKeyedJoinArg &helper;
  21061. unsigned joinProcessed;
  21062. bool isFullKey;
  21063. bool eof;
  21064. bool isSimple;
  21065. bool allPulled;
  21066. unsigned __int64 totalCycles;
  21067. unsigned activityId;
  21068. RecordPullerThread &puller;
  21069. SafeQueueOf<const void, true> injected; // Used in isSimple mode
  21070. Owned<IEngineRowAllocator> ccdRecordAllocator;
  21071. IJoinProcessor &processor;
  21072. KeyedJoinRemoteAdaptor(const RemoteActivityId &_remoteId, IHThorKeyedJoinArg &_helper, IRoxieServerActivity &_activity, bool _isFullKey, bool _isSimple,
  21073. RecordPullerThread &_puller, IJoinProcessor &_processor)
  21074. : helper(_helper),
  21075. CRemoteResultAdaptor(_remoteId, 0, _helper, _activity, true, true),
  21076. isFullKey(_isFullKey),
  21077. isSimple(_isSimple),
  21078. puller(_puller),
  21079. processor(_processor),
  21080. activityId(_activity.queryId())
  21081. {
  21082. joinProcessed = 0;
  21083. totalCycles = 0;
  21084. allPulled = false;
  21085. eof = false;
  21086. }
  21087. virtual void onCreate(IRoxieInput *_owner, IRoxieServerErrorHandler *_errorHandler, IRoxieSlaveContext *_ctx, IHThorArg *_colocalArg)
  21088. {
  21089. CRemoteResultAdaptor::onCreate(_owner, _errorHandler, _ctx, _colocalArg);
  21090. ccdRecordAllocator.setown(ctx->queryCodeContext()->getRowAllocator(QUERYINTERFACE(helper.queryJoinFieldsRecordSize(), IOutputMetaData), activityId));
  21091. }
  21092. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21093. {
  21094. eof = false;
  21095. joinProcessed = 0;
  21096. totalCycles = 0;
  21097. allPulled = false;
  21098. assertex(ready.ordinality()==0);
  21099. CRemoteResultAdaptor::start(parentExtractSize, parentExtract, paused);
  21100. }
  21101. virtual void reset()
  21102. {
  21103. CRemoteResultAdaptor::reset();
  21104. while (ready.ordinality())
  21105. {
  21106. const void *goer = ready.dequeue();
  21107. if (goer)
  21108. ReleaseRoxieRow(goer);
  21109. }
  21110. while (injected.ordinality())
  21111. {
  21112. const void *goer = injected.dequeue();
  21113. if (goer)
  21114. ReleaseRoxieRow(goer);
  21115. }
  21116. }
  21117. inline void addResult(const void *row)
  21118. {
  21119. ready.enqueue(row);
  21120. }
  21121. virtual unsigned __int64 queryTotalCycles() const
  21122. {
  21123. return totalCycles;
  21124. }
  21125. virtual IOutputMetaData * queryOutputMeta() const
  21126. {
  21127. return owner->queryOutputMeta();
  21128. }
  21129. virtual const void *nextInGroup()
  21130. {
  21131. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  21132. loop
  21133. {
  21134. if (eof)
  21135. return NULL;
  21136. processSlaveResults();
  21137. if (ready.ordinality())
  21138. {
  21139. const void *result = ready.dequeue();
  21140. if (result)
  21141. joinProcessed++;
  21142. return result;
  21143. }
  21144. else
  21145. eof = true;
  21146. }
  21147. }
  21148. private:
  21149. void processSlaveResults()
  21150. {
  21151. while (!ready.ordinality())
  21152. {
  21153. KeyedJoinHeader *fetchedData;
  21154. if (isSimple)
  21155. {
  21156. while (!allPulled && !injected.ordinality())
  21157. {
  21158. if (!puller.pullRecords(1))
  21159. {
  21160. puller.done();
  21161. allPulled = true;
  21162. }
  21163. }
  21164. fetchedData = (KeyedJoinHeader *) injected.dequeue();
  21165. }
  21166. else
  21167. fetchedData = (KeyedJoinHeader *) CRemoteResultAdaptor::nextInGroup();
  21168. if (fetchedData)
  21169. {
  21170. CJoinGroup *thisGroup = fetchedData->thisGroup;
  21171. if (fetchedData->partNo == (unsigned short) -1)
  21172. {
  21173. #ifdef TRACE_JOINGROUPS
  21174. CTXLOG("Got end for group %p", thisGroup);
  21175. #endif
  21176. unsigned candidateCount = (unsigned) fetchedData->fpos;
  21177. ReleaseRoxieRow(fetchedData);
  21178. processor.noteEndReceived(thisGroup, candidateCount); // note - this can throw exception. So release fetchdata before calling
  21179. }
  21180. else
  21181. {
  21182. #ifdef TRACE_JOINGROUPS
  21183. CTXLOG("Reading another %d bytes for group %p data", ccdRecordSize, thisGroup);
  21184. #endif
  21185. thisGroup->addRightMatch(fetchedData);
  21186. if (isFullKey)
  21187. {
  21188. #ifdef TRACE_JOINGROUPS
  21189. CTXLOG("Calling noteEndReceived for record returned from FETCH of full keyed join");
  21190. #endif
  21191. processor.noteEndReceived(thisGroup, 0); // note - this can throw exception. So release fetchdata before calling
  21192. }
  21193. }
  21194. }
  21195. else
  21196. break;
  21197. }
  21198. }
  21199. };
  21200. class CRoxieServerFullKeyedJoinHead: public CRoxieServerActivity, implements IRecordPullerCallback, implements IRoxieServerErrorHandler
  21201. {
  21202. IHThorKeyedJoinArg &helper;
  21203. Owned<IKeyManager> tlk;
  21204. Linked<IKeyArray> keySet;
  21205. Linked<TranslatorArray> translators;
  21206. CRemoteResultAdaptor remote;
  21207. RecordPullerThread puller;
  21208. IOutputMetaData *indexReadMeta;
  21209. IJoinProcessor *joinHandler;
  21210. bool variableIndexFileName;
  21211. bool indexReadInputRecordVariable;
  21212. bool isLocal;
  21213. Owned<IEngineRowAllocator> indexReadAllocator;
  21214. Owned<const IResolvedFile> varFileInfo;
  21215. IRoxieInput *indexReadInput;
  21216. IIndexReadActivityInfo *rootIndex;
  21217. public:
  21218. CRoxieServerFullKeyedJoinHead(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IKeyArray * _keySet, TranslatorArray *_translators, IOutputMetaData *_indexReadMeta, IJoinProcessor *_joinHandler, bool _isLocal)
  21219. : CRoxieServerActivity(_factory, _probeManager),
  21220. helper((IHThorKeyedJoinArg &)basehelper),
  21221. tlk(createKeyManager(NULL, 0, this)),
  21222. translators(_translators),
  21223. keySet(_keySet),
  21224. remote(_remoteId, 0, helper, *this, true, true),
  21225. indexReadMeta(_indexReadMeta),
  21226. joinHandler(_joinHandler),
  21227. puller(false),
  21228. isLocal(_isLocal)
  21229. {
  21230. variableIndexFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getJoinFlags() & (JFvarindexfilename|JFdynamicindexfilename)) != 0);
  21231. indexReadInputRecordVariable = indexReadMeta->isVariableSize();
  21232. indexReadInput = NULL;
  21233. rootIndex = NULL;
  21234. }
  21235. virtual const IResolvedFile *queryVarFileInfo() const
  21236. {
  21237. return varFileInfo;
  21238. }
  21239. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  21240. {
  21241. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  21242. remote.onCreate(this, this, _ctx, _colocalParent);
  21243. indexReadAllocator.setown(ctx->queryCodeContext()->getRowAllocator(indexReadMeta, activityId));
  21244. }
  21245. virtual void setInput(unsigned idx, IRoxieInput *_in)
  21246. {
  21247. if (!idx)
  21248. puller.setInput(this, _in);
  21249. else if (idx==1)
  21250. indexReadInput = _in;
  21251. else
  21252. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  21253. }
  21254. virtual void serializeExtra(MemoryBuffer &out)
  21255. {
  21256. if (helper.getJoinFlags() & JFindexfromactivity)
  21257. {
  21258. assertex(rootIndex);
  21259. const RemoteActivityId& indexId = rootIndex->queryRemoteId();
  21260. indexId.serialize(out);
  21261. // could mess about reserving space for length then patching it again, to avoid copy, but probably not worth it
  21262. MemoryBuffer tmp;
  21263. rootIndex->queryActivity()->serializeCreateStartContext(tmp);
  21264. if (rootIndex->queryActivity()->queryVarFileInfo())
  21265. {
  21266. rootIndex->queryActivity()->queryVarFileInfo()->queryTimeStamp().serialize(tmp);
  21267. tmp.append(rootIndex->queryActivity()->queryVarFileInfo()->queryCheckSum());
  21268. }
  21269. unsigned ctxlen = tmp.length();
  21270. out.append(ctxlen).append(tmp);
  21271. }
  21272. }
  21273. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21274. {
  21275. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  21276. if (indexReadInput)
  21277. {
  21278. indexReadInput->start(parentExtractSize, parentExtract, true); // paused=true because we don't want to actually run the index read
  21279. rootIndex = indexReadInput->queryIndexReadActivity();
  21280. if (!rootIndex)
  21281. throw MakeStringException(ROXIE_INTERNAL_ERROR,"Index in keyed join %d could not be resolved", queryId());
  21282. }
  21283. remote.onStart(parentExtractSize, parentExtract);
  21284. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  21285. if (rootIndex)
  21286. {
  21287. varFileInfo.setown(rootIndex->getVarFileInfo());
  21288. translators.setown(rootIndex->getTranslators());
  21289. keySet.setown(rootIndex->getKeySet());
  21290. }
  21291. else if (variableIndexFileName)
  21292. {
  21293. OwnedRoxieString indexFileName(helper.getIndexFileName());
  21294. varFileInfo.setown(resolveLFN(indexFileName, (helper.getJoinFlags() & JFindexoptional) != 0));
  21295. if (varFileInfo)
  21296. {
  21297. translators.setown(new TranslatorArray);
  21298. keySet.setown(varFileInfo->getKeyArray(factory->queryActivityMeta(), translators, false, isLocal ? factory->queryQueryFactory().queryChannel() : 0, factory->queryQueryFactory().getEnableFieldTranslation())); // MORE - isLocal?
  21299. }
  21300. }
  21301. puller.start(parentExtractSize, parentExtract, paused, ctx->fullKeyedJoinPreload(), false, ctx);
  21302. }
  21303. virtual void stop(bool aborting)
  21304. {
  21305. puller.stop(aborting);
  21306. CRoxieServerActivity::stop(aborting);
  21307. }
  21308. virtual void reset()
  21309. {
  21310. CRoxieServerActivity::reset();
  21311. puller.reset();
  21312. if (varFileInfo)
  21313. {
  21314. keySet.clear();
  21315. varFileInfo.clear();
  21316. }
  21317. }
  21318. virtual IRoxieInput *queryOutput(unsigned idx)
  21319. {
  21320. if (idx==(unsigned)-1)
  21321. idx = 0;
  21322. return idx ? NULL : &remote;
  21323. }
  21324. virtual void processRow(const void *row)
  21325. {
  21326. // MORE - this code seems to be pretty much duplicated below in half-keyed....
  21327. // called from front puller thread
  21328. // buffer up an IndexRead request
  21329. if (helper.leftCanMatch(row))
  21330. {
  21331. RtlDynamicRowBuilder extractedBuilder(indexReadAllocator);
  21332. unsigned indexReadSize = helper.extractIndexReadFields(extractedBuilder, row);
  21333. OwnedConstRoxieRow extracted;
  21334. if (indexReadSize)
  21335. extracted.setown(extractedBuilder.finalizeRowClear(indexReadSize));
  21336. CJoinGroup *jg = joinHandler->createJoinGroup(row);
  21337. for (unsigned partNo = 0; partNo < keySet->length(); partNo++)
  21338. {
  21339. IKeyIndexBase *thisBase = keySet->queryKeyPart(partNo);
  21340. if (thisBase)
  21341. {
  21342. unsigned fileNo = 0;
  21343. IKeyIndex *thisKey = thisBase->queryPart(fileNo);
  21344. try
  21345. {
  21346. tlk->setKey(thisKey);
  21347. tlk->setLayoutTranslator(translators->item(fileNo));
  21348. helper.createSegmentMonitors(tlk, extracted);
  21349. if (rootIndex)
  21350. rootIndex->mergeSegmentMonitors(tlk);
  21351. tlk->finishSegmentMonitors();
  21352. tlk->reset();
  21353. loop
  21354. {
  21355. typedef const void * cvp;
  21356. if (thisKey->isTopLevelKey())
  21357. {
  21358. bool locallySorted = !thisKey->isFullySorted();
  21359. while (locallySorted || tlk->lookup(false))
  21360. {
  21361. unsigned slavePart = locallySorted ? 0 : (unsigned) tlk->queryFpos();
  21362. if (locallySorted || slavePart)
  21363. {
  21364. cvp *outputBuffer = (cvp *) remote.getMem(slavePart, fileNo, indexReadSize + sizeof(cvp) + (indexReadInputRecordVariable ? sizeof(unsigned) : 0));
  21365. *outputBuffer++ = jg;
  21366. if (indexReadInputRecordVariable)
  21367. {
  21368. *(unsigned *) outputBuffer = indexReadSize;
  21369. outputBuffer = (cvp*) (((unsigned *) outputBuffer) + 1);
  21370. }
  21371. jg->notePending();
  21372. memcpy(outputBuffer, extracted, indexReadSize);
  21373. if (locallySorted)
  21374. {
  21375. for (unsigned i = 1; i < numChannels; i++)
  21376. jg->notePending();
  21377. break;
  21378. }
  21379. }
  21380. }
  21381. }
  21382. else
  21383. {
  21384. // MORE - this code seems to be duplicated in half keyed
  21385. unsigned accepted = 0;
  21386. unsigned rejected = 0;
  21387. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), true);
  21388. jg->notePending();
  21389. unsigned candidateCount = 0;
  21390. while (tlk->lookup(true))
  21391. {
  21392. candidateCount++;
  21393. atomic_inc(&indexRecordsRead);
  21394. KLBlobProviderAdapter adapter(tlk);
  21395. offset_t recptr;
  21396. const byte *indexRow = tlk->queryKeyBuffer(recptr);
  21397. if (helper.indexReadMatch(extracted, indexRow, recptr, &adapter))
  21398. {
  21399. KeyedJoinHeader *rhs = (KeyedJoinHeader *) ctx->queryRowManager().allocate(KEYEDJOIN_RECORD_SIZE(0), activityId);
  21400. rhs->fpos = recptr;
  21401. rhs->thisGroup = jg;
  21402. rhs->partNo = partNo;
  21403. result->append(rhs);
  21404. }
  21405. else
  21406. {
  21407. rejected++;
  21408. atomic_inc(&postFiltered);
  21409. }
  21410. }
  21411. // output an end marker for the matches to this group
  21412. KeyedJoinHeader *endMarker = (KeyedJoinHeader *) ctx->queryRowManager().allocate(KEYEDJOIN_RECORD_SIZE(0), activityId);
  21413. endMarker->fpos = (offset_t) candidateCount;
  21414. endMarker->thisGroup = jg;
  21415. endMarker->partNo = (unsigned short) -1;
  21416. result->append(endMarker);
  21417. remote.injectResult(result.getClear());
  21418. if (accepted)
  21419. noteStatistic(STATS_ACCEPTED, accepted, 1);
  21420. if (rejected)
  21421. noteStatistic(STATS_REJECTED, rejected, 1);
  21422. }
  21423. if (++fileNo < thisBase->numParts())
  21424. {
  21425. thisKey = thisBase->queryPart(fileNo);
  21426. tlk->setKey(thisKey);
  21427. tlk->setLayoutTranslator(translators->item(fileNo));
  21428. tlk->reset();
  21429. }
  21430. else
  21431. break;
  21432. }
  21433. tlk->releaseSegmentMonitors();
  21434. tlk->setKey(NULL);
  21435. }
  21436. catch (...)
  21437. {
  21438. tlk->releaseSegmentMonitors();
  21439. tlk->setKey(NULL);
  21440. throw;
  21441. }
  21442. }
  21443. }
  21444. joinHandler->noteEndReceived(jg, 0);
  21445. }
  21446. else
  21447. {
  21448. joinHandler->noteEndReceived(joinHandler->createJoinGroup(row), 0);
  21449. }
  21450. }
  21451. void processGroup(const ConstPointerArray &)
  21452. {
  21453. throwUnexpected();
  21454. }
  21455. virtual void processEOG()
  21456. {
  21457. joinHandler->processEOG();
  21458. }
  21459. virtual void processDone()
  21460. {
  21461. // called from puller thread
  21462. remote.flush();
  21463. remote.senddone();
  21464. }
  21465. virtual void onLimitExceeded(bool isKeyed)
  21466. {
  21467. if (traceLevel > 4)
  21468. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  21469. if (isKeyed)
  21470. throwUnexpected();
  21471. helper.onLimitExceeded();
  21472. }
  21473. virtual const void *createLimitFailRow(bool isKeyed)
  21474. {
  21475. throwUnexpected();
  21476. }
  21477. virtual bool fireException(IException *e)
  21478. {
  21479. // called from puller thread on failure
  21480. remote.fireException(LINK(e));
  21481. return joinHandler->fireException(e);
  21482. }
  21483. virtual const void *nextInGroup()
  21484. {
  21485. throwUnexpected(); // I am nobody's input
  21486. }
  21487. };
  21488. class CRoxieServerKeyedJoinBase : public CRoxieServerActivity, implements IRecordPullerCallback, implements IRoxieServerErrorHandler, implements IJoinProcessor
  21489. {
  21490. protected:
  21491. IHThorKeyedJoinArg &helper;
  21492. KeyedJoinRemoteAdaptor remote;
  21493. RecordPullerThread puller;
  21494. OwnedConstRoxieRow defaultRight;
  21495. Owned<IEngineRowAllocator> defaultRightAllocator;
  21496. unsigned joinFlags;
  21497. unsigned atMost;
  21498. unsigned atmostsTriggered;
  21499. unsigned abortLimit;
  21500. unsigned keepLimit;
  21501. bool limitFail;
  21502. bool limitOnFail;
  21503. bool preserveGroups;
  21504. bool cloneLeft;
  21505. bool isSimple;
  21506. bool isLocal;
  21507. ThorActivityKind activityKind;
  21508. CJoinGroup *groupStart;
  21509. CriticalSection groupsCrit;
  21510. QueueOf<CJoinGroup, false> groups;
  21511. IRoxieInput *indexReadInput;
  21512. IIndexReadActivityInfo *rootIndex;
  21513. void createDefaultRight()
  21514. {
  21515. if (!defaultRight)
  21516. {
  21517. if (!defaultRightAllocator)
  21518. defaultRightAllocator.setown(ctx->queryCodeContext()->getRowAllocator(helper.queryJoinFieldsRecordSize(), activityId));
  21519. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  21520. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  21521. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  21522. }
  21523. }
  21524. public:
  21525. CRoxieServerKeyedJoinBase(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _joinFlags
  21526. , bool isFull, bool _isSimple, bool _isLocal)
  21527. : CRoxieServerActivity(_factory, _probeManager),
  21528. helper((IHThorKeyedJoinArg &)basehelper),
  21529. remote(_remoteId, helper, *this, isFull, _isSimple, puller, *this),
  21530. joinFlags(_joinFlags),
  21531. preserveGroups(meta.isGrouped()),
  21532. puller(false),
  21533. isSimple(_isSimple),
  21534. isLocal(_isLocal),
  21535. abortLimit(0),
  21536. keepLimit(0),
  21537. atMost(0),
  21538. limitFail(false),
  21539. limitOnFail(false),
  21540. cloneLeft(false)
  21541. {
  21542. groupStart = NULL;
  21543. activityKind = _factory->getKind();
  21544. indexReadInput = NULL;
  21545. rootIndex = NULL;
  21546. atmostsTriggered = 0;
  21547. // MORE - code would be easier to read if I got more values from helper rather than passing from factory
  21548. }
  21549. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  21550. {
  21551. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  21552. remote.onCreate(this, this, _ctx, _colocalParent);
  21553. }
  21554. virtual void setInput(unsigned idx, IRoxieInput *_in)
  21555. {
  21556. if (!idx)
  21557. puller.setInput(this, _in);
  21558. else if (idx==1)
  21559. indexReadInput = _in;
  21560. else
  21561. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  21562. }
  21563. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21564. {
  21565. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  21566. if (indexReadInput)
  21567. {
  21568. indexReadInput->start(parentExtractSize, parentExtract, true); // paused=true because we don't want to actually run the index read
  21569. rootIndex = indexReadInput->queryIndexReadActivity();
  21570. if (!rootIndex)
  21571. throw MakeStringException(ROXIE_INTERNAL_ERROR,"Index in keyed join %d could not be resolved", queryId());
  21572. }
  21573. remote.onStart(parentExtractSize, parentExtract);
  21574. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  21575. atmostsTriggered = 0;
  21576. atMost = helper.getJoinLimit();
  21577. if (atMost == 0) atMost = (unsigned)-1;
  21578. abortLimit = helper.getMatchAbortLimit();
  21579. if (abortLimit == 0 || atMost != (unsigned) -1) abortLimit = (unsigned)-1;
  21580. keepLimit = helper.getKeepLimit();
  21581. if (keepLimit == 0) keepLimit = (unsigned)-1;
  21582. getLimitType(joinFlags, limitFail, limitOnFail);
  21583. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  21584. if (joinFlags & JFleftouter)
  21585. createDefaultRight();
  21586. }
  21587. virtual void stop(bool aborting)
  21588. {
  21589. puller.stop(aborting);
  21590. if (indexReadInput)
  21591. indexReadInput->stop(aborting);
  21592. CRoxieServerActivity::stop(aborting);
  21593. }
  21594. virtual unsigned __int64 queryLocalCycles() const
  21595. {
  21596. __int64 localCycles = remote.totalCycles;
  21597. localCycles -= puller.queryTotalCycles(); // MORE - debatable... but probably fair.
  21598. if (localCycles < 0)
  21599. localCycles = 0;
  21600. return localCycles;
  21601. }
  21602. virtual IRoxieInput *queryInput(unsigned idx)
  21603. {
  21604. if (idx==0)
  21605. return puller.queryInput();
  21606. else if (idx==1)
  21607. return indexReadInput;
  21608. else
  21609. return NULL;
  21610. }
  21611. virtual void reset()
  21612. {
  21613. totalCycles = remote.totalCycles;
  21614. remote.totalCycles = 0;
  21615. processed = remote.joinProcessed;
  21616. remote.joinProcessed = 0;
  21617. defaultRight.clear();
  21618. if (indexReadInput)
  21619. indexReadInput->reset();
  21620. if (atmostsTriggered)
  21621. noteStatistic(STATS_ATMOST, atmostsTriggered, 1);
  21622. CRoxieServerActivity::reset();
  21623. puller.reset();
  21624. while (groups.ordinality())
  21625. {
  21626. ::Release(groups.dequeue());
  21627. }
  21628. }
  21629. virtual IRoxieInput *queryOutput(unsigned idx)
  21630. {
  21631. if (idx==(unsigned)-1)
  21632. idx = 0;
  21633. return idx ? NULL : &remote;
  21634. }
  21635. #undef new
  21636. virtual CJoinGroup *createJoinGroup(const void *row)
  21637. {
  21638. // NOTE - we need to protect access to queue, since it's also modified by consumer thread. Groupstart is only modified by puller thread.
  21639. CriticalBlock c(groupsCrit);
  21640. if (preserveGroups && !groupStart)
  21641. {
  21642. groupStart = new (&ctx->queryRowManager(), activityId) CJoinGroup(NULL, NULL);
  21643. groups.enqueue(groupStart);
  21644. }
  21645. CJoinGroup *jg = new (&ctx->queryRowManager(), activityId) CJoinGroup(row, groupStart);
  21646. groups.enqueue(jg);
  21647. return jg;
  21648. }
  21649. #if defined(_DEBUG) && defined(_WIN32) && !defined(USING_MPATROL)
  21650. #define new new(_NORMAL_BLOCK, __FILE__, __LINE__)
  21651. #endif
  21652. void endGroup()
  21653. {
  21654. CriticalBlock c(groupsCrit);
  21655. if (groupStart)
  21656. noteEndReceived(groupStart, 0);
  21657. groupStart = NULL;
  21658. }
  21659. virtual void noteEndReceived(CJoinGroup *jg, unsigned candidateCount)
  21660. {
  21661. if (jg->noteEndReceived(candidateCount))
  21662. processCompletedGroups();
  21663. }
  21664. void processCompletedGroups()
  21665. {
  21666. loop
  21667. {
  21668. CriticalBlock c(groupsCrit);
  21669. if (!groups.head()->complete())
  21670. break;
  21671. Owned<CJoinGroup> head = groups.dequeue();
  21672. if (preserveGroups)
  21673. {
  21674. assert(head->isHeadRecord());
  21675. assert(groups.head()->inGroup(head));
  21676. unsigned joinGroupSize = 0;
  21677. while (groups.ordinality() && groups.head()->inGroup(head))
  21678. {
  21679. Owned<CJoinGroup> finger = groups.dequeue();
  21680. joinGroupSize += doJoinGroup(finger);
  21681. }
  21682. if (joinGroupSize)
  21683. remote.addResult(NULL);
  21684. }
  21685. else
  21686. doJoinGroup(head);
  21687. if (!groups.ordinality())
  21688. break;
  21689. }
  21690. }
  21691. void failLimit(const void * left)
  21692. {
  21693. helper.onMatchAbortLimitExceeded();
  21694. CommonXmlWriter xmlwrite(0);
  21695. if (input && input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  21696. {
  21697. input->queryOutputMeta()->toXML((byte *) left, xmlwrite);
  21698. }
  21699. throw MakeStringException(ROXIE_JOIN_ERROR, "More than %d match candidates in keyed join %d for row %s", abortLimit, queryId(), xmlwrite.str());
  21700. }
  21701. virtual bool needsAllocator() const { return true; }
  21702. unsigned doTransform(const void *left, const void *right, offset_t fpos_or_count, IException *except, const void **group)
  21703. {
  21704. if (cloneLeft && !except)
  21705. {
  21706. LinkRoxieRow(left);
  21707. remote.addResult((void *) left);
  21708. return 1;
  21709. }
  21710. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  21711. unsigned outSize;
  21712. try
  21713. {
  21714. outSize = except ? helper.onFailTransform(rowBuilder, left, right, fpos_or_count, except) :
  21715. (activityKind == TAKkeyeddenormalizegroup) ? helper.transform(rowBuilder, left, right, (unsigned) fpos_or_count, group) :
  21716. helper.transform(rowBuilder, left, right, fpos_or_count);
  21717. }
  21718. catch (IException *E)
  21719. {
  21720. throw makeWrappedException(E);
  21721. }
  21722. if (outSize)
  21723. {
  21724. const void *shrunk = rowBuilder.finalizeRowClear(outSize);
  21725. remote.addResult(shrunk);
  21726. return 1;
  21727. }
  21728. else
  21729. return 0;
  21730. }
  21731. unsigned doJoinGroup(CJoinGroup *jg)
  21732. {
  21733. unsigned matched = jg->rowsSeen();
  21734. unsigned added = 0;
  21735. const void *left = jg->queryLeft();
  21736. if (jg->candidateCount() > abortLimit)
  21737. {
  21738. if (limitFail)
  21739. failLimit(left);
  21740. if (ctx->queryDebugContext())
  21741. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  21742. if (limitOnFail)
  21743. {
  21744. Owned<IException> except;
  21745. try
  21746. {
  21747. failLimit(left);
  21748. }
  21749. catch(IException * e)
  21750. {
  21751. except.setown(e);
  21752. }
  21753. added = doTransform(left, defaultRight, 0, except, NULL);
  21754. }
  21755. }
  21756. else if (!matched || jg->candidateCount() > atMost)
  21757. {
  21758. if (jg->candidateCount() > atMost)
  21759. atmostsTriggered++;
  21760. switch (joinFlags & JFtypemask)
  21761. {
  21762. case JFleftouter:
  21763. case JFleftonly:
  21764. switch (activityKind)
  21765. {
  21766. case TAKkeyedjoin:
  21767. case TAKkeyeddenormalizegroup:
  21768. added = doTransform(left, defaultRight, 0, NULL, NULL);
  21769. break;
  21770. case TAKkeyeddenormalize:
  21771. LinkRoxieRow(left);
  21772. remote.addResult((void *) left);
  21773. added++;
  21774. break;
  21775. }
  21776. break;
  21777. }
  21778. }
  21779. else if (!(joinFlags & JFexclude))
  21780. {
  21781. unsigned idx = 0;
  21782. switch (activityKind)
  21783. {
  21784. case TAKkeyedjoin:
  21785. while (idx < matched)
  21786. {
  21787. const KeyedJoinHeader *rhs = jg->queryRow(idx);
  21788. added += doTransform(left, &rhs->rhsdata, rhs->fpos, NULL, NULL);
  21789. if (added==keepLimit)
  21790. break;
  21791. idx++;
  21792. }
  21793. break;
  21794. case TAKkeyeddenormalize:
  21795. {
  21796. OwnedConstRoxieRow newLeft;
  21797. newLeft.set(left);
  21798. unsigned rowSize = 0;
  21799. unsigned rightAdded = 0;
  21800. while (idx < matched)
  21801. {
  21802. const KeyedJoinHeader *rhs = jg->queryRow(idx);
  21803. try
  21804. {
  21805. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  21806. size32_t transformedSize = helper.transform(rowBuilder, newLeft, &rhs->rhsdata, rhs->fpos, idx+1);
  21807. if (transformedSize)
  21808. {
  21809. rowSize = transformedSize;
  21810. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  21811. rightAdded++;
  21812. if (rightAdded==keepLimit)
  21813. break;
  21814. }
  21815. idx++;
  21816. }
  21817. catch (IException *E)
  21818. {
  21819. throw makeWrappedException(E);
  21820. }
  21821. }
  21822. if (rowSize)
  21823. {
  21824. remote.addResult(newLeft.getClear());
  21825. added++;
  21826. }
  21827. }
  21828. break;
  21829. case TAKkeyeddenormalizegroup:
  21830. {
  21831. ConstPointerArray extractedRows;
  21832. while (idx < matched && idx < keepLimit)
  21833. {
  21834. const KeyedJoinHeader *rhs = jg->queryRow(idx);
  21835. extractedRows.append((void *) &rhs->rhsdata);
  21836. idx++;
  21837. }
  21838. added += doTransform(left, extractedRows.item(0), extractedRows.ordinality(), NULL, (const void * *)extractedRows.getArray());
  21839. }
  21840. break;
  21841. }
  21842. }
  21843. return added;
  21844. }
  21845. virtual void processDone()
  21846. {
  21847. // called from puller thread
  21848. remote.flush();
  21849. remote.senddone();
  21850. }
  21851. virtual void onLimitExceeded(bool isKeyed)
  21852. {
  21853. if (traceLevel > 4)
  21854. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  21855. if (isKeyed)
  21856. throwUnexpected();
  21857. helper.onLimitExceeded();
  21858. }
  21859. virtual const void *createLimitFailRow(bool isKeyed)
  21860. {
  21861. throwUnexpected();
  21862. }
  21863. virtual bool fireException(IException *e)
  21864. {
  21865. // called from puller thread on failure
  21866. return remote.fireException(e);
  21867. }
  21868. virtual const void *nextInGroup()
  21869. {
  21870. throwUnexpected(); // I am nobody's input
  21871. }
  21872. };
  21873. #ifdef _MSC_VER
  21874. #pragma warning ( push )
  21875. #pragma warning ( disable: 4355 )
  21876. #endif
  21877. class CRoxieServerKeyedJoinActivity : public CRoxieServerKeyedJoinBase
  21878. {
  21879. CRoxieServerFullKeyedJoinHead head;
  21880. Owned<IEngineRowAllocator> fetchInputAllocator;
  21881. Linked<IFilePartMap> map;
  21882. bool variableFetchFileName;
  21883. Owned<const IResolvedFile> varFetchFileInfo;
  21884. CachedOutputMetaData fetchInputFields;
  21885. public:
  21886. CRoxieServerKeyedJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_headId, IKeyArray * _key, TranslatorArray *_translators, IOutputMetaData *_indexReadMeta,
  21887. const RemoteActivityId &_tailId, IFilePartMap *_map, unsigned _joinFlags, bool _isLocal)
  21888. : CRoxieServerKeyedJoinBase(_factory, _probeManager, _tailId, _joinFlags, true, false, _isLocal),
  21889. head(_factory, _probeManager, _headId, _key, _translators, _indexReadMeta, this, _isLocal),
  21890. map(_map)
  21891. {
  21892. CRoxieServerKeyedJoinBase::setInput(0, head.queryOutput(0));
  21893. variableFetchFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  21894. }
  21895. virtual const IResolvedFile *queryVarFileInfo() const
  21896. {
  21897. return varFetchFileInfo;
  21898. }
  21899. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  21900. {
  21901. CRoxieServerKeyedJoinBase::onCreate(_ctx, _colocalParent);
  21902. head.onCreate(_ctx, _colocalParent);
  21903. fetchInputFields.set(helper.queryFetchInputRecordSize());
  21904. fetchInputAllocator.setown(ctx->queryCodeContext()->getRowAllocator(helper.queryFetchInputRecordSize(), activityId));
  21905. }
  21906. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21907. {
  21908. CRoxieServerKeyedJoinBase::start(parentExtractSize, parentExtract, paused);
  21909. if (variableFetchFileName)
  21910. {
  21911. bool isFetchOpt = (helper.getFetchFlags() & FFdatafileoptional) != 0;
  21912. OwnedRoxieString fname(helper.getFileName());
  21913. varFetchFileInfo.setown(resolveLFN(fname, isFetchOpt));
  21914. if (varFetchFileInfo)
  21915. map.setown(varFetchFileInfo->getFileMap());
  21916. }
  21917. puller.start(parentExtractSize, parentExtract, paused, ctx->keyedJoinPreload(), false, ctx);
  21918. }
  21919. virtual void setInput(unsigned idx, IRoxieInput *in)
  21920. {
  21921. head.setInput(idx, in);
  21922. }
  21923. virtual void processRow(const void *_rhs)
  21924. {
  21925. // called from puller thread
  21926. KeyedJoinHeader *rhs = (KeyedJoinHeader *) _rhs;
  21927. CJoinGroup *jg = rhs->thisGroup;
  21928. if (rhs->partNo != (unsigned short) -1)
  21929. {
  21930. unsigned partNo = map->mapOffset(rhs->fpos);
  21931. RtlDynamicRowBuilder fetchBuilder(fetchInputAllocator, true);
  21932. size32_t fisize = helper.extractFetchFields(fetchBuilder, jg->queryLeft());
  21933. if (fetchInputFields.isVariableSize())
  21934. {
  21935. KeyedJoinHeader *outRow = (KeyedJoinHeader *) remote.getMem(partNo, 0, KEYEDJOIN_RECORD_SIZE(fisize + sizeof(fisize)));
  21936. memcpy(outRow, rhs, KEYEDJOIN_RECORD_SIZE(0)); // MORE - copy constructor might be more appropriate....
  21937. ReleaseRoxieRow(rhs);
  21938. jg->notePending();
  21939. memcpy(&outRow->rhsdata, &fisize, sizeof(fisize));
  21940. memcpy((&outRow->rhsdata)+sizeof(fisize), fetchBuilder.row(), fisize);
  21941. }
  21942. else
  21943. {
  21944. KeyedJoinHeader *outRow = (KeyedJoinHeader *) remote.getMem(partNo, 0, KEYEDJOIN_RECORD_SIZE(fisize));
  21945. memcpy(outRow, rhs, KEYEDJOIN_RECORD_SIZE(0)); // MORE - copy constructor might be more appropriate....
  21946. ReleaseRoxieRow(rhs);
  21947. jg->notePending();
  21948. memcpy(&outRow->rhsdata, fetchBuilder.row(), fisize);
  21949. }
  21950. }
  21951. else
  21952. {
  21953. unsigned candidateCount = (unsigned) rhs->fpos;
  21954. // CTXLOG("Full keyed join - all results back from index");
  21955. ReleaseRoxieRow(rhs);
  21956. noteEndReceived(jg, candidateCount); // may throw exception - so release row before calling
  21957. }
  21958. }
  21959. virtual void processEOG()
  21960. {
  21961. // called from front puller thread
  21962. if (preserveGroups)
  21963. endGroup();
  21964. }
  21965. void processGroup(const ConstPointerArray &)
  21966. {
  21967. throwUnexpected();
  21968. }
  21969. };
  21970. #ifdef _MSC_VER
  21971. #pragma warning ( pop )
  21972. #endif
  21973. class CRoxieServerHalfKeyedJoinActivity : public CRoxieServerKeyedJoinBase
  21974. {
  21975. IOutputMetaData *indexReadMeta;
  21976. Owned<IEngineRowAllocator> indexReadAllocator;
  21977. Owned<IKeyManager> tlk;
  21978. bool variableIndexFileName;
  21979. bool indexReadInputRecordVariable;
  21980. Owned<const IResolvedFile> varFileInfo;
  21981. Linked<TranslatorArray> translators;
  21982. Linked<IKeyArray> keySet;
  21983. Owned<IOutputMetaData> joinPrefixedMeta;
  21984. Owned<IEngineRowAllocator> joinFieldsAllocator;
  21985. public:
  21986. CRoxieServerHalfKeyedJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IKeyArray * _keySet, TranslatorArray *_translators,
  21987. IOutputMetaData *_indexReadMeta, unsigned _joinFlags, bool _isSimple, bool _isLocal)
  21988. : CRoxieServerKeyedJoinBase(_factory, _probeManager, _remoteId, _joinFlags, false, _isSimple, _isLocal),
  21989. indexReadMeta(_indexReadMeta),
  21990. tlk(createKeyManager(NULL, 0, this)),
  21991. keySet(_keySet),
  21992. translators(_translators)
  21993. {
  21994. variableIndexFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getJoinFlags() & (JFvarindexfilename|JFdynamicindexfilename)) != 0);
  21995. indexReadInputRecordVariable = indexReadMeta->isVariableSize();
  21996. }
  21997. virtual void serializeExtra(MemoryBuffer &out)
  21998. {
  21999. if (helper.getJoinFlags() & JFindexfromactivity)
  22000. {
  22001. assertex(rootIndex);
  22002. const RemoteActivityId& indexId = rootIndex->queryRemoteId();
  22003. indexId.serialize(out);
  22004. // could mess about reserving space for length then patching it again, to avoid copy, but probably not worth it
  22005. MemoryBuffer tmp;
  22006. rootIndex->queryActivity()->serializeCreateStartContext(tmp);
  22007. if (rootIndex->queryActivity()->queryVarFileInfo())
  22008. {
  22009. rootIndex->queryActivity()->queryVarFileInfo()->queryTimeStamp().serialize(tmp);
  22010. tmp.append(rootIndex->queryActivity()->queryVarFileInfo()->queryCheckSum());
  22011. }
  22012. unsigned ctxlen = tmp.length();
  22013. out.append(ctxlen).append(tmp);
  22014. }
  22015. }
  22016. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  22017. {
  22018. CRoxieServerKeyedJoinBase::onCreate(_ctx, _colocalParent);
  22019. indexReadAllocator.setown(ctx->queryCodeContext()->getRowAllocator(indexReadMeta, activityId));
  22020. IOutputMetaData *joinFieldsMeta = helper.queryJoinFieldsRecordSize();
  22021. joinPrefixedMeta.setown(new CPrefixedOutputMeta(KEYEDJOIN_RECORD_SIZE(0), joinFieldsMeta)); // MORE - not sure if we really need this
  22022. joinFieldsAllocator.setown(ctx->queryCodeContext()->getRowAllocator(joinPrefixedMeta, activityId));
  22023. }
  22024. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  22025. {
  22026. CRoxieServerKeyedJoinBase::start(parentExtractSize, parentExtract, paused);
  22027. if (rootIndex)
  22028. {
  22029. varFileInfo.setown(rootIndex->getVarFileInfo());
  22030. translators.setown(rootIndex->getTranslators());
  22031. keySet.setown(rootIndex->getKeySet());
  22032. }
  22033. else if (variableIndexFileName)
  22034. {
  22035. OwnedRoxieString indexFileName(helper.getIndexFileName());
  22036. varFileInfo.setown(resolveLFN(indexFileName, (helper.getJoinFlags() & JFindexoptional) != 0));
  22037. if (varFileInfo)
  22038. {
  22039. translators.setown(new TranslatorArray);
  22040. keySet.setown(varFileInfo->getKeyArray(factory->queryActivityMeta(), translators, false, isLocal ? factory->queryQueryFactory().queryChannel() : 0, factory->queryQueryFactory().getEnableFieldTranslation()));
  22041. }
  22042. }
  22043. puller.start(parentExtractSize, parentExtract, paused, ctx->keyedJoinPreload(), isSimple, ctx);
  22044. }
  22045. virtual const IResolvedFile *queryVarFileInfo() const
  22046. {
  22047. return varFileInfo;
  22048. }
  22049. virtual void reset()
  22050. {
  22051. CRoxieServerKeyedJoinBase::reset();
  22052. if (varFileInfo)
  22053. {
  22054. keySet.clear();
  22055. varFileInfo.clear();
  22056. }
  22057. }
  22058. virtual void processRow(const void *row)
  22059. {
  22060. // called from front puller thread
  22061. // buffer up an IndexRead request
  22062. if (helper.leftCanMatch(row) && keySet)
  22063. {
  22064. RtlDynamicRowBuilder extractBuilder(indexReadAllocator);
  22065. unsigned indexReadRecordSize = helper.extractIndexReadFields(extractBuilder, row);
  22066. OwnedConstRoxieRow extracted;
  22067. if (indexReadRecordSize)
  22068. extracted.setown(extractBuilder.finalizeRowClear(indexReadRecordSize));
  22069. CJoinGroup *jg = createJoinGroup(row);
  22070. for (unsigned partNo = 0; partNo < keySet->length(); partNo++)
  22071. {
  22072. IKeyIndexBase *thisBase = keySet->queryKeyPart(partNo);
  22073. if (thisBase)
  22074. {
  22075. unsigned fileNo = 0;
  22076. IKeyIndex *thisKey = thisBase->queryPart(fileNo);
  22077. tlk->setKey(thisKey);
  22078. tlk->setLayoutTranslator(translators->item(fileNo));
  22079. helper.createSegmentMonitors(tlk, extracted);
  22080. if (rootIndex)
  22081. rootIndex->mergeSegmentMonitors(tlk);
  22082. tlk->finishSegmentMonitors();
  22083. try
  22084. {
  22085. tlk->reset();
  22086. loop
  22087. {
  22088. typedef const void * cvp;
  22089. if (thisKey && thisKey->isTopLevelKey())
  22090. {
  22091. bool locallySorted = (!thisKey->isFullySorted());
  22092. while (locallySorted || tlk->lookup(false))
  22093. {
  22094. unsigned slavePart = locallySorted ? 0 : (unsigned) tlk->queryFpos();
  22095. if (locallySorted || slavePart)
  22096. {
  22097. cvp *outputBuffer = (cvp *) remote.getMem(slavePart, fileNo, indexReadRecordSize + sizeof(cvp) + (indexReadInputRecordVariable ? sizeof(unsigned) : 0));
  22098. *outputBuffer++ = jg;
  22099. if (indexReadInputRecordVariable)
  22100. {
  22101. *(unsigned *) outputBuffer = indexReadRecordSize;
  22102. outputBuffer = (cvp *) (((unsigned *) outputBuffer) + 1);
  22103. }
  22104. jg->notePending();
  22105. memcpy(outputBuffer, extracted, indexReadRecordSize);
  22106. if (locallySorted)
  22107. {
  22108. for (unsigned i = 1; i < numChannels; i++)
  22109. jg->notePending();
  22110. break;
  22111. }
  22112. }
  22113. }
  22114. }
  22115. else
  22116. {
  22117. unsigned accepted = 0;
  22118. unsigned rejected = 0;
  22119. Owned<CRowArrayMessageResult> result;
  22120. if (!isSimple)
  22121. result.setown(new CRowArrayMessageResult(ctx->queryRowManager(), true));
  22122. // MORE - This code seems to be duplicated in keyedJoinHead
  22123. jg->notePending();
  22124. unsigned candidateCount = 0;
  22125. while (tlk->lookup(true))
  22126. {
  22127. candidateCount++;
  22128. atomic_inc(&indexRecordsRead);
  22129. KLBlobProviderAdapter adapter(tlk);
  22130. offset_t recptr;
  22131. const byte *indexRow = tlk->queryKeyBuffer(recptr);
  22132. if (helper.indexReadMatch(extracted, indexRow, recptr, &adapter))
  22133. {
  22134. RtlDynamicRowBuilder rb(joinFieldsAllocator, true);
  22135. CPrefixedRowBuilder pb(KEYEDJOIN_RECORD_SIZE(0), rb);
  22136. accepted++;
  22137. KLBlobProviderAdapter adapter(tlk);
  22138. size32_t joinFieldsSize = helper.extractJoinFields(pb, indexRow, recptr, &adapter);
  22139. KeyedJoinHeader *rec = (KeyedJoinHeader *) rb.getUnfinalizedClear(); // lack of finalize ok as unserialized data here.
  22140. rec->fpos = recptr;
  22141. rec->thisGroup = jg;
  22142. rec->partNo = partNo;
  22143. if (isSimple)
  22144. remote.injected.enqueue(rec);
  22145. else
  22146. result->append(rec);
  22147. }
  22148. else
  22149. {
  22150. rejected++;
  22151. atomic_inc(&postFiltered);
  22152. }
  22153. }
  22154. // output an end marker for the matches to this group
  22155. KeyedJoinHeader *rec = (KeyedJoinHeader *) ctx->queryRowManager().allocate(KEYEDJOIN_RECORD_SIZE(0), activityId);
  22156. rec->fpos = (offset_t) candidateCount;
  22157. rec->thisGroup = jg;
  22158. rec->partNo = (unsigned short) -1;
  22159. if (isSimple)
  22160. remote.injected.enqueue(rec);
  22161. else
  22162. {
  22163. result->append(rec);
  22164. remote.injectResult(result.getClear());
  22165. }
  22166. if (accepted)
  22167. noteStatistic(STATS_ACCEPTED, accepted, 1);
  22168. if (rejected)
  22169. noteStatistic(STATS_REJECTED, rejected, 1);
  22170. }
  22171. if (++fileNo < thisBase->numParts())
  22172. {
  22173. thisKey = thisBase->queryPart(fileNo);
  22174. tlk->setKey(thisKey);
  22175. tlk->setLayoutTranslator(translators->item(fileNo));
  22176. tlk->reset();
  22177. }
  22178. else
  22179. break;
  22180. }
  22181. tlk->releaseSegmentMonitors();
  22182. tlk->setKey(NULL);
  22183. }
  22184. catch (...)
  22185. {
  22186. tlk->releaseSegmentMonitors();
  22187. tlk->setKey(NULL);
  22188. throw;
  22189. }
  22190. }
  22191. }
  22192. noteEndReceived(jg, 0);
  22193. }
  22194. else
  22195. {
  22196. noteEndReceived(createJoinGroup(row), 0);
  22197. }
  22198. }
  22199. virtual void processEOG()
  22200. {
  22201. // called from front puller thread
  22202. if (preserveGroups)
  22203. endGroup();
  22204. }
  22205. void processGroup(const ConstPointerArray &)
  22206. {
  22207. throwUnexpected();
  22208. }
  22209. };
  22210. class CRoxieServerKeyedJoinActivityFactory : public CRoxieServerMultiInputFactory
  22211. {
  22212. Owned<const IResolvedFile> indexfile;
  22213. Owned<const IResolvedFile> datafile;
  22214. Owned<IKeyArray> keySet;
  22215. Owned<TranslatorArray> translatorArray;
  22216. Owned<IDefRecordMeta> activityMeta;
  22217. RemoteActivityId headId;
  22218. RemoteActivityId tailId;
  22219. IOutputMetaData *indexReadMeta;
  22220. Owned<IFilePartMap> map;
  22221. Owned<IFileIOArray> files;
  22222. unsigned joinFlags;
  22223. bool isHalfKeyed;
  22224. bool isLocal;
  22225. bool enableFieldTranslation;
  22226. bool variableFetchFileName;
  22227. bool variableIndexFileName;
  22228. bool isSimple;
  22229. public:
  22230. CRoxieServerKeyedJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_headId, const RemoteActivityId &_tailId, IPropertyTree &_graphNode)
  22231. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), headId(_headId), tailId(_tailId)
  22232. {
  22233. Owned<IHThorKeyedJoinArg> helper = (IHThorKeyedJoinArg *) helperFactory();
  22234. isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  22235. isSimple = isLocal;
  22236. rtlDataAttr indexLayoutMeta;
  22237. size32_t indexLayoutSize;
  22238. if(!helper->getIndexLayout(indexLayoutSize, indexLayoutMeta.refdata()))
  22239. assertex(indexLayoutSize== 0);
  22240. MemoryBuffer m;
  22241. m.setBuffer(indexLayoutSize, indexLayoutMeta.getdata());
  22242. activityMeta.setown(deserializeRecordMeta(m, true));
  22243. enableFieldTranslation = queryFactory.getEnableFieldTranslation();
  22244. translatorArray.setown(new TranslatorArray);
  22245. joinFlags = helper->getJoinFlags();
  22246. variableIndexFileName = allFilesDynamic || _queryFactory.isDynamic() || ((joinFlags & (JFvarindexfilename|JFdynamicindexfilename)) != 0);
  22247. variableFetchFileName = allFilesDynamic || _queryFactory.isDynamic() || ((helper->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  22248. if (!variableIndexFileName)
  22249. {
  22250. bool isOpt = (joinFlags & JFindexoptional) != 0;
  22251. OwnedRoxieString indexFileName(helper->getIndexFileName());
  22252. indexfile.setown(queryFactory.queryPackage().lookupFileName(indexFileName, isOpt, true, true, queryFactory.queryWorkUnit()));
  22253. if (indexfile)
  22254. keySet.setown(indexfile->getKeyArray(activityMeta, translatorArray, isOpt, isLocal ? queryFactory.queryChannel() : 0, enableFieldTranslation));
  22255. }
  22256. if (keySet && keySet->length()==1 && !isSimple)
  22257. {
  22258. IKeyIndexBase *thisBase = keySet->queryKeyPart(0);
  22259. if (thisBase->numParts()==1 && !thisBase->queryPart(0)->isTopLevelKey() && !_queryFactory.getDebugValueBool("disableLocalOptimizations", false))
  22260. isSimple = true;
  22261. // MORE - if it's a variable filename then it MAY be simple, we don't know. Tough.
  22262. }
  22263. if (!simpleLocalKeyedJoins)
  22264. isSimple = false;
  22265. isHalfKeyed = !helper->diskAccessRequired();
  22266. indexReadMeta = QUERYINTERFACE(helper->queryIndexReadInputRecordSize(), IOutputMetaData);
  22267. if (!isHalfKeyed && !variableFetchFileName)
  22268. {
  22269. bool isFetchOpt = (helper->getFetchFlags() & FFdatafileoptional) != 0;
  22270. datafile.setown(_queryFactory.queryPackage().lookupFileName(queryNodeFileName(_graphNode), isFetchOpt, true, true, _queryFactory.queryWorkUnit()));
  22271. if (datafile)
  22272. {
  22273. if (isLocal)
  22274. files.setown(datafile->getIFileIOArray(isFetchOpt, queryFactory.queryChannel()));
  22275. else
  22276. map.setown(datafile->getFileMap());
  22277. }
  22278. }
  22279. }
  22280. virtual bool getEnableFieldTranslation() const
  22281. {
  22282. return enableFieldTranslation;
  22283. }
  22284. virtual IDefRecordMeta *queryActivityMeta() const
  22285. {
  22286. return activityMeta;
  22287. }
  22288. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  22289. {
  22290. if (isHalfKeyed)
  22291. return new CRoxieServerHalfKeyedJoinActivity(this, _probeManager,
  22292. headId, keySet, translatorArray, indexReadMeta, joinFlags, isSimple, isLocal);
  22293. else
  22294. return new CRoxieServerKeyedJoinActivity(this, _probeManager,
  22295. headId, keySet, translatorArray, indexReadMeta,
  22296. tailId, map, joinFlags, isLocal);
  22297. }
  22298. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  22299. {
  22300. if (datafile)
  22301. addXrefFileInfo(reply, datafile);
  22302. if (indexfile)
  22303. addXrefFileInfo(reply, indexfile);
  22304. }
  22305. };
  22306. IRoxieServerActivityFactory *createRoxieServerKeyedJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, const RemoteActivityId &_remoteId2, IPropertyTree &_graphNode)
  22307. {
  22308. return new CRoxieServerKeyedJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _remoteId2, _graphNode);
  22309. }
  22310. //=================================================================================
  22311. class CRoxieServerSoapActivityBase : public CRoxieServerActivity, implements ISoapCallRowProvider, implements IRoxieAbortMonitor
  22312. {
  22313. protected:
  22314. Owned<ISoapCallHelper> soaphelper;
  22315. IHThorSoapActionArg & helper;
  22316. StringBuffer authToken;
  22317. bool eof;
  22318. CriticalSection crit;
  22319. ClientCertificate *pClientCert;
  22320. public:
  22321. IMPLEMENT_IINTERFACE;
  22322. CRoxieServerSoapActivityBase(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  22323. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorSoapActionArg &)basehelper)
  22324. {
  22325. eof = false;
  22326. if (clientCert.certificate.length() > 0 && clientCert.privateKey.length() > 0 && clientCert.passphrase.length() > 0)
  22327. pClientCert = &clientCert;
  22328. else
  22329. pClientCert = NULL;
  22330. }
  22331. // ISoapCallRowProvider
  22332. virtual IHThorSoapActionArg * queryActionHelper() { return &helper; };
  22333. virtual IHThorSoapCallArg * queryCallHelper() { return NULL; };
  22334. virtual const void * getNextRow() { return NULL; };
  22335. virtual void releaseRow(const void * r) { ReleaseRoxieRow(r); };
  22336. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  22337. {
  22338. eof = false;
  22339. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  22340. authToken.append(ctx->queryAuthToken());
  22341. }
  22342. virtual void reset()
  22343. {
  22344. // MORE - Shouldn't we make sure thread is stopped etc???
  22345. soaphelper.clear();
  22346. CRoxieServerActivity::reset();
  22347. }
  22348. // IRoxieAbortMonitor
  22349. virtual void checkForAbort() { checkAbort(); }
  22350. };
  22351. //---------------------------------------------------------------------------
  22352. class CRoxieServerSoapRowCallActivity : public CRoxieServerSoapActivityBase
  22353. {
  22354. IHThorSoapCallArg & callHelper;
  22355. public:
  22356. CRoxieServerSoapRowCallActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  22357. : CRoxieServerSoapActivityBase(_factory, _probeManager), callHelper((IHThorSoapCallArg &)basehelper)
  22358. {
  22359. }
  22360. virtual IHThorSoapCallArg * queryCallHelper()
  22361. {
  22362. return &callHelper;
  22363. }
  22364. virtual bool needsAllocator() const { return true; }
  22365. virtual const void *nextInGroup()
  22366. {
  22367. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  22368. if(eof) return NULL;
  22369. if (soaphelper == NULL)
  22370. {
  22371. if (factory->getKind()==TAKhttp_rowdataset)
  22372. soaphelper.setown(createHttpCallHelper(this, rowAllocator, authToken.str(), SCrow, pClientCert, *ctx, this));
  22373. else
  22374. soaphelper.setown(createSoapCallHelper(this, rowAllocator, authToken.str(), SCrow, pClientCert, *ctx, this));
  22375. soaphelper->start();
  22376. }
  22377. OwnedConstRoxieRow ret = soaphelper->getRow();
  22378. if (!ret)
  22379. {
  22380. eof = true;
  22381. return NULL;
  22382. }
  22383. ++processed;
  22384. return ret.getClear();
  22385. }
  22386. };
  22387. class CRoxieServerSoapRowCallActivityFactory : public CRoxieServerActivityFactory
  22388. {
  22389. public:
  22390. CRoxieServerSoapRowCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  22391. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  22392. {
  22393. }
  22394. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  22395. {
  22396. return new CRoxieServerSoapRowCallActivity(this, _probeManager);
  22397. }
  22398. };
  22399. IRoxieServerActivityFactory *createRoxieServerSoapRowCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  22400. {
  22401. return new CRoxieServerSoapRowCallActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  22402. }
  22403. //---------------------------------------------------------------------------
  22404. class CRoxieServerSoapRowActionActivity : public CRoxieServerSoapActivityBase
  22405. {
  22406. public:
  22407. CRoxieServerSoapRowActionActivity (const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  22408. : CRoxieServerSoapActivityBase(_factory, _probeManager)
  22409. {}
  22410. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  22411. {
  22412. //MORE: parentExtract not passed to start - although shouldn't be a problem.
  22413. soaphelper.setown(createSoapCallHelper(this, NULL, ctx->queryAuthToken(), SCrow, pClientCert, *ctx, this));
  22414. soaphelper->start();
  22415. soaphelper->waitUntilDone();
  22416. IException *e = soaphelper->getError();
  22417. soaphelper.clear();
  22418. if (e)
  22419. throw e;
  22420. }
  22421. virtual IRoxieInput *queryOutput(unsigned idx)
  22422. {
  22423. return NULL;
  22424. }
  22425. virtual const void *nextInGroup()
  22426. {
  22427. throwUnexpected(); // I am nobody's input
  22428. }
  22429. };
  22430. class CRoxieServerSoapRowActionActivityFactory : public CRoxieServerActivityFactory
  22431. {
  22432. bool isRoot;
  22433. public:
  22434. CRoxieServerSoapRowActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  22435. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  22436. {
  22437. }
  22438. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  22439. {
  22440. return new CRoxieServerSoapRowActionActivity(this, _probeManager);
  22441. }
  22442. virtual bool isSink() const
  22443. {
  22444. return isRoot;
  22445. }
  22446. };
  22447. IRoxieServerActivityFactory *createRoxieServerSoapRowActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  22448. {
  22449. return new CRoxieServerSoapRowActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  22450. }
  22451. //---------------------------------------------------------------------------
  22452. class CRoxieServerSoapDatasetCallActivity : public CRoxieServerSoapActivityBase
  22453. {
  22454. IHThorSoapCallArg & callHelper;
  22455. public:
  22456. CRoxieServerSoapDatasetCallActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  22457. : CRoxieServerSoapActivityBase(_factory, _probeManager), callHelper((IHThorSoapCallArg &)basehelper)
  22458. {
  22459. }
  22460. virtual IHThorSoapCallArg * queryCallHelper()
  22461. {
  22462. return &callHelper;
  22463. }
  22464. virtual const void *getNextRow()
  22465. {
  22466. CriticalBlock b(crit);
  22467. const void *nextrec = input->nextInGroup();
  22468. if (!nextrec)
  22469. {
  22470. nextrec = input->nextInGroup();
  22471. }
  22472. return nextrec;
  22473. }
  22474. virtual bool needsAllocator() const { return true; }
  22475. virtual const void *nextInGroup()
  22476. {
  22477. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  22478. if(eof) return NULL;
  22479. if (soaphelper == NULL)
  22480. {
  22481. soaphelper.setown(createSoapCallHelper(this, rowAllocator, authToken.str(), SCdataset, pClientCert, *ctx, this));
  22482. soaphelper->start();
  22483. }
  22484. OwnedConstRoxieRow ret = soaphelper->getRow();
  22485. if (!ret)
  22486. {
  22487. eof = true;
  22488. return NULL;
  22489. }
  22490. ++processed;
  22491. return ret.getClear();
  22492. }
  22493. };
  22494. class CRoxieServerSoapDatasetCallActivityFactory : public CRoxieServerActivityFactory
  22495. {
  22496. public:
  22497. CRoxieServerSoapDatasetCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  22498. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  22499. {
  22500. }
  22501. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  22502. {
  22503. return new CRoxieServerSoapDatasetCallActivity(this, _probeManager);
  22504. }
  22505. };
  22506. IRoxieServerActivityFactory *createRoxieServerSoapDatasetCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  22507. {
  22508. return new CRoxieServerSoapDatasetCallActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  22509. }
  22510. //---------------------------------------------------------------------------
  22511. class CRoxieServerSoapDatasetActionActivity : public CRoxieServerSoapActivityBase
  22512. {
  22513. public:
  22514. CRoxieServerSoapDatasetActionActivity (const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  22515. : CRoxieServerSoapActivityBase(_factory, _probeManager)
  22516. {}
  22517. virtual const void *getNextRow()
  22518. {
  22519. CriticalBlock b(crit);
  22520. const void *nextrec = input->nextInGroup();
  22521. if (!nextrec)
  22522. {
  22523. nextrec = input->nextInGroup();
  22524. }
  22525. if (nextrec)
  22526. processed++;
  22527. return nextrec;
  22528. }
  22529. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  22530. {
  22531. try
  22532. {
  22533. start(parentExtractSize, parentExtract, false);
  22534. soaphelper.setown(createSoapCallHelper(this, NULL, ctx->queryAuthToken(), SCdataset, pClientCert, *ctx, this));
  22535. soaphelper->start();
  22536. soaphelper->waitUntilDone();
  22537. IException *e = soaphelper->getError();
  22538. soaphelper.clear();
  22539. if (e)
  22540. throw e;
  22541. stop(false);
  22542. }
  22543. catch (IException *E)
  22544. {
  22545. ctx->notifyAbort(E);
  22546. stop(true);
  22547. throw;
  22548. }
  22549. catch(...)
  22550. {
  22551. Owned<IException> E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught at %s:%d", __FILE__, __LINE__);
  22552. ctx->notifyAbort(E);
  22553. stop(true);
  22554. throw;
  22555. }
  22556. }
  22557. virtual IRoxieInput *queryOutput(unsigned idx)
  22558. {
  22559. return NULL;
  22560. }
  22561. virtual const void *nextInGroup()
  22562. {
  22563. throwUnexpected(); // I am nobody's input
  22564. }
  22565. };
  22566. class CRoxieServerSoapDatasetActionActivityFactory : public CRoxieServerActivityFactory
  22567. {
  22568. bool isRoot;
  22569. public:
  22570. CRoxieServerSoapDatasetActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  22571. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  22572. {
  22573. }
  22574. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  22575. {
  22576. return new CRoxieServerSoapDatasetActionActivity(this, _probeManager);
  22577. }
  22578. virtual bool isSink() const
  22579. {
  22580. return isRoot;
  22581. }
  22582. };
  22583. IRoxieServerActivityFactory *createRoxieServerSoapDatasetActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  22584. {
  22585. return new CRoxieServerSoapDatasetActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  22586. }
  22587. //=====================================================================================================
  22588. class CGraphResults : public CInterface, implements IRoxieGraphResults
  22589. {
  22590. IArrayOf<IGraphResult> results;
  22591. CriticalSection cs;
  22592. IGraphResult & select(unsigned idx)
  22593. {
  22594. CriticalBlock procedure(cs);
  22595. if (idx >= results.ordinality())
  22596. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Error reading graph result %d before it is calculated", idx);
  22597. return results.item(idx);
  22598. }
  22599. public:
  22600. IMPLEMENT_IINTERFACE
  22601. void clear()
  22602. {
  22603. CriticalBlock procedure(cs);
  22604. results.kill();
  22605. }
  22606. IRoxieInput * createIterator(unsigned id)
  22607. {
  22608. return select(id).createIterator();
  22609. }
  22610. virtual void getLinkedResult(unsigned & count, byte * * & ret, unsigned id)
  22611. {
  22612. select(id).getLinkedResult(count, ret);
  22613. }
  22614. virtual void getDictionaryResult(unsigned & count, byte * * & ret, unsigned id)
  22615. {
  22616. select(id).getLinkedResult(count, ret);
  22617. }
  22618. virtual const void * getLinkedRowResult(unsigned id)
  22619. {
  22620. return select(id).getLinkedRowResult();
  22621. }
  22622. void setResult(unsigned id, IGraphResult * result)
  22623. {
  22624. CriticalBlock procedure(cs);
  22625. if (results.ordinality() <= id)
  22626. {
  22627. while (results.ordinality() < id)
  22628. results.append(*new CGraphResult);
  22629. results.append(*LINK(result));
  22630. }
  22631. else
  22632. results.replace(*LINK(result), id);
  22633. }
  22634. void appendResult(IGraphResult * result)
  22635. {
  22636. CriticalBlock procedure(cs);
  22637. results.append(*LINK(result));
  22638. }
  22639. };
  22640. //===================================================================================================================
  22641. class CPseudoArg : public CInterface, implements IHThorArg
  22642. {
  22643. public:
  22644. IMPLEMENT_IINTERFACE
  22645. virtual IOutputMetaData * queryOutputMeta() { return NULL; }
  22646. };
  22647. class CPseudoActivity : public CRoxieServerActivity
  22648. {
  22649. public:
  22650. CPseudoActivity(IHThorArg & _helper) : CRoxieServerActivity(_helper) {}
  22651. virtual const void *nextInGroup()
  22652. {
  22653. throwUnexpected(); // I am nobody's input
  22654. }
  22655. };
  22656. class CActivityGraph : public CInterface, implements IActivityGraph, implements IThorChildGraph, implements ILocalGraphEx, implements IRoxieServerChildGraph
  22657. {
  22658. protected:
  22659. IArrayOf<IRoxieServerActivity> activities;
  22660. IArrayOf<IRoxieInput> probes;
  22661. IRoxieServerActivityCopyArray sinks;
  22662. StringAttr graphName;
  22663. Owned<CGraphResults> results;
  22664. CGraphResults graphLoopResults;
  22665. ActivityArray & graphDefinition;
  22666. CriticalSection evaluateCrit;
  22667. IProbeManager *probeManager;
  22668. unsigned id;
  22669. unsigned loopCounter;
  22670. class ActivityGraphSlaveContext : public IndirectSlaveContext
  22671. {
  22672. SpinLock abortLock;
  22673. bool aborted;
  22674. Owned<IException> exception;
  22675. public:
  22676. ActivityGraphSlaveContext(const IRoxieContextLogger &_logctx) : logctx(_logctx), loopCounter(0), codeContext(NULL)
  22677. {
  22678. aborted = false;
  22679. }
  22680. // Note - we must track exceptions at the child level in case there is a CATCH in parent
  22681. virtual void notifyAbort(IException *E)
  22682. {
  22683. SpinBlock b(abortLock);
  22684. if (!aborted && QUERYINTERFACE(E, InterruptedSemaphoreException) == NULL)
  22685. {
  22686. aborted = true;
  22687. exception.set(E);
  22688. }
  22689. }
  22690. virtual void checkAbort()
  22691. {
  22692. if (aborted) // NOTE - don't bother getting lock before reading this (for speed) - a false read is very unlikely and not a problem
  22693. {
  22694. SpinBlock b(abortLock);
  22695. if (!exception)
  22696. exception.setown(MakeStringException(ROXIE_INTERNAL_ERROR, "Query was aborted"));
  22697. throw exception.getLink();
  22698. }
  22699. IndirectSlaveContext::checkAbort();
  22700. }
  22701. virtual ICodeContext *queryCodeContext()
  22702. {
  22703. return codeContext;
  22704. }
  22705. void setCodeContext(ICodeContext * _codeContext)
  22706. {
  22707. codeContext = _codeContext;
  22708. }
  22709. void setLoopCounter(unsigned _loopCounter)
  22710. {
  22711. loopCounter = _loopCounter;
  22712. }
  22713. virtual void noteChildGraph(unsigned id, IActivityGraph *childGraph)
  22714. {
  22715. childGraphs.setValue(id, childGraph);
  22716. }
  22717. virtual IActivityGraph * queryChildGraph(unsigned id)
  22718. {
  22719. if (queryTraceLevel() > 10)
  22720. CTXLOG("resolveChildGraph %d", id);
  22721. IActivityGraph *childGraph = childGraphs.getValue(id);
  22722. assertex(childGraph);
  22723. return childGraph;
  22724. }
  22725. // 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
  22726. virtual StringBuffer &getLogPrefix(StringBuffer &ret) const
  22727. {
  22728. logctx.getLogPrefix(ret);
  22729. if (loopCounter)
  22730. ret.appendf("{%u}", loopCounter);
  22731. return ret;
  22732. }
  22733. protected:
  22734. const IRoxieContextLogger &logctx;
  22735. unsigned loopCounter;
  22736. ICodeContext * codeContext;
  22737. MapXToMyClass<unsigned, unsigned, IActivityGraph> childGraphs;
  22738. } graphSlaveContext;
  22739. class ActivityGraphCodeContext : public IndirectCodeContext
  22740. {
  22741. public:
  22742. virtual IEclGraphResults * resolveLocalQuery(__int64 activityId)
  22743. {
  22744. if ((unsigned) activityId == container->queryId())
  22745. return container;
  22746. IActivityGraph * match = slaveContext->queryChildGraph((unsigned) activityId);
  22747. if (match)
  22748. return match->queryLocalGraph();
  22749. return IndirectCodeContext::resolveLocalQuery(activityId);
  22750. }
  22751. virtual IThorChildGraph * resolveChildQuery(__int64 activityId, IHThorArg * colocal)
  22752. {
  22753. IActivityGraph * match = slaveContext->queryChildGraph((unsigned) activityId);
  22754. return LINK(match->queryChildGraph());
  22755. }
  22756. virtual unsigned getGraphLoopCounter() const
  22757. {
  22758. return container->queryLoopCounter(); // only called if value is valid
  22759. }
  22760. void setContainer(IRoxieSlaveContext * _slaveContext, CActivityGraph * _container)
  22761. {
  22762. slaveContext = _slaveContext;
  22763. container = _container;
  22764. }
  22765. protected:
  22766. IRoxieSlaveContext * slaveContext;
  22767. CActivityGraph * container;
  22768. } graphCodeContext;
  22769. public:
  22770. IMPLEMENT_IINTERFACE;
  22771. CActivityGraph(const char *_graphName, unsigned _id, ActivityArray &x, IProbeManager *_probeManager, const IRoxieContextLogger &_logctx)
  22772. : probeManager(_probeManager), graphDefinition(x), graphName(_graphName), graphSlaveContext(_logctx)
  22773. {
  22774. id = x.getLibraryGraphId();
  22775. if (!id)
  22776. id = _id;
  22777. loopCounter = 0;
  22778. graphSlaveContext.setCodeContext(&graphCodeContext);
  22779. graphCodeContext.setContainer(&graphSlaveContext, this);
  22780. }
  22781. ~CActivityGraph()
  22782. {
  22783. if (probeManager)
  22784. probeManager->deleteGraph((IArrayOf<IActivityBase>*)&activities, (IArrayOf<IInputBase>*)&probes);
  22785. }
  22786. virtual const char *queryName() const
  22787. {
  22788. return graphName.get();
  22789. }
  22790. void createGraph()
  22791. {
  22792. ForEachItemIn(idx, graphDefinition)
  22793. {
  22794. IRoxieServerActivityFactory &donor = graphDefinition.serverItem(idx);
  22795. IRoxieServerActivity &activity = *donor.createActivity(probeManager);
  22796. activities.append(activity);
  22797. if (donor.isSink())
  22798. {
  22799. sinks.append(activity);
  22800. if (probeManager)
  22801. probeManager->noteSink(&activity);
  22802. }
  22803. }
  22804. ForEachItemIn(idx1, graphDefinition)
  22805. {
  22806. IRoxieServerActivityFactory &donor = graphDefinition.serverItem(idx1);
  22807. IRoxieServerActivity &activity = activities.item(idx1);
  22808. unsigned inputidx = 0;
  22809. loop
  22810. {
  22811. unsigned outputidx;
  22812. unsigned source = donor.getInput(inputidx, outputidx);
  22813. if (source==(unsigned) -1)
  22814. break;
  22815. connectInput(idx1, inputidx, source, outputidx, 0);
  22816. inputidx++;
  22817. }
  22818. IntArray &dependencies = donor.queryDependencies();
  22819. IntArray &dependencyIndexes = donor.queryDependencyIndexes();
  22820. IntArray &dependencyControlIds = donor.queryDependencyControlIds();
  22821. StringArray &dependencyEdgeIds = donor.queryDependencyEdgeIds();
  22822. ForEachItemIn(idx2, dependencies)
  22823. {
  22824. IRoxieServerActivity &dependencySourceActivity = activities.item(dependencies.item(idx2));
  22825. unsigned dependencySourceIndex = dependencyIndexes.item(idx2);
  22826. unsigned dependencyControlId = dependencyControlIds.item(idx2);
  22827. activity.addDependency(dependencySourceActivity, dependencySourceIndex, dependencyControlId);
  22828. if (probeManager)
  22829. probeManager->noteDependency( &dependencySourceActivity, dependencySourceIndex, dependencyControlId, dependencyEdgeIds.item(idx2), &activity);
  22830. }
  22831. }
  22832. }
  22833. void connectInput(unsigned target, unsigned targetIdx, unsigned source, unsigned sourceIdx, unsigned iteration)
  22834. {
  22835. IRoxieServerActivity &targetActivity = activities.item(target);
  22836. IRoxieServerActivity &sourceActivity = activities.item(source);
  22837. IRoxieInput * output = sourceActivity.queryOutput(sourceIdx);
  22838. if (probeManager)
  22839. {
  22840. IInputBase * inputBase = probeManager->createProbe(static_cast<IInputBase*>(output), &sourceActivity, &targetActivity, sourceIdx, targetIdx, iteration);
  22841. output = static_cast<IRoxieInput*>(inputBase);
  22842. probes.append(*LINK(output));
  22843. }
  22844. targetActivity.setInput(targetIdx, output);
  22845. }
  22846. virtual void onCreate(IRoxieSlaveContext *ctx, IHThorArg *_colocalParent)
  22847. {
  22848. graphSlaveContext.set(ctx);
  22849. if (graphDefinition.isMultiInstance())
  22850. {
  22851. graphCodeContext.set(ctx->queryCodeContext());
  22852. ctx = &graphSlaveContext;
  22853. }
  22854. ForEachItemIn(idx, activities)
  22855. {
  22856. IRoxieServerActivity *activity = &activities.item(idx);
  22857. if (activity)
  22858. activity->onCreate(ctx, _colocalParent);
  22859. }
  22860. }
  22861. virtual void abort()
  22862. {
  22863. ForEachItemIn(idx, sinks)
  22864. {
  22865. IRoxieServerActivity &sink = sinks.item(idx);
  22866. sink.stop(true);
  22867. }
  22868. }
  22869. virtual void reset()
  22870. {
  22871. ForEachItemIn(idx, sinks)
  22872. {
  22873. IRoxieServerActivity &sink = sinks.item(idx);
  22874. sink.reset();
  22875. }
  22876. }
  22877. Linked<IException> exception;
  22878. CriticalSection eCrit;
  22879. virtual void noteException(IException *E)
  22880. {
  22881. CriticalBlock b(eCrit);
  22882. if (!exception)
  22883. {
  22884. if (graphSlaveContext.queryDebugContext())
  22885. {
  22886. graphSlaveContext.queryDebugContext()->checkBreakpoint(DebugStateException, NULL, exception);
  22887. }
  22888. exception.set(E);
  22889. }
  22890. }
  22891. virtual void checkAbort()
  22892. {
  22893. CriticalBlock b(eCrit);
  22894. if (exception)
  22895. throw exception.getLink();
  22896. }
  22897. virtual void execute()
  22898. {
  22899. results.setown(new CGraphResults);
  22900. doExecute(0, NULL);
  22901. }
  22902. //New child query code...
  22903. virtual IThorChildGraph * queryChildGraph()
  22904. {
  22905. return this;
  22906. }
  22907. virtual IEclGraphResults * queryLocalGraph()
  22908. {
  22909. return this;
  22910. }
  22911. virtual IRoxieServerChildGraph * queryLoopGraph()
  22912. {
  22913. return this;
  22914. }
  22915. inline unsigned queryId() const
  22916. {
  22917. return id;
  22918. }
  22919. inline unsigned queryLoopCounter() const
  22920. {
  22921. return loopCounter;
  22922. }
  22923. void doExecute(unsigned parentExtractSize, const byte * parentExtract)
  22924. {
  22925. if (sinks.ordinality()==1)
  22926. sinks.item(0).execute(parentExtractSize, parentExtract);
  22927. #ifdef PARALLEL_EXECUTE
  22928. else if (!probeManager && !graphDefinition.isSequential())
  22929. {
  22930. class casyncfor: public CAsyncFor
  22931. {
  22932. public:
  22933. IActivityGraph &parent;
  22934. unsigned parentExtractSize;
  22935. const byte * parentExtract;
  22936. casyncfor(IRoxieServerActivityCopyArray &_sinks, IActivityGraph &_parent, unsigned _parentExtractSize, const byte * _parentExtract) :
  22937. sinks(_sinks), parent(_parent), parentExtractSize(_parentExtractSize), parentExtract(_parentExtract) { }
  22938. void Do(unsigned i)
  22939. {
  22940. try
  22941. {
  22942. sinks.item(i).execute(parentExtractSize, parentExtract);
  22943. }
  22944. catch (IException *E)
  22945. {
  22946. parent.noteException(E);
  22947. throw;
  22948. }
  22949. }
  22950. private:
  22951. IRoxieServerActivityCopyArray &sinks;
  22952. } afor(sinks, *this, parentExtractSize, parentExtract);
  22953. afor.For(sinks.ordinality(), sinks.ordinality());
  22954. }
  22955. #endif
  22956. else
  22957. {
  22958. ForEachItemIn(idx, sinks)
  22959. {
  22960. IRoxieServerActivity &sink = sinks.item(idx);
  22961. sink.execute(parentExtractSize, parentExtract);
  22962. }
  22963. }
  22964. }
  22965. virtual IEclGraphResults *evaluate(unsigned parentExtractSize, const byte * parentExtract)
  22966. {
  22967. CriticalBlock block(evaluateCrit);
  22968. results.setown(new CGraphResults);
  22969. try
  22970. {
  22971. doExecute(parentExtractSize, parentExtract);
  22972. }
  22973. catch (...)
  22974. {
  22975. DBGLOG("Exception thrown in child query - cleaning up");
  22976. reset();
  22977. throw;
  22978. }
  22979. reset();
  22980. return results.getClear();
  22981. }
  22982. //interface IRoxieServerChildGraph
  22983. virtual void beforeExecute()
  22984. {
  22985. results.setown(new CGraphResults);
  22986. }
  22987. virtual IRoxieInput * startOutput(unsigned id, unsigned parentExtractSize, const byte *parentExtract, bool paused)
  22988. {
  22989. IRoxieInput * ret = selectOutput(id);
  22990. ret->start(parentExtractSize, parentExtract, paused);
  22991. return ret;
  22992. }
  22993. virtual IRoxieInput * selectOutput(unsigned id)
  22994. {
  22995. ForEachItemIn(i, sinks)
  22996. {
  22997. IRoxieInput * ret = sinks.item(i).querySelectOutput(id);
  22998. if (ret)
  22999. return ret;
  23000. }
  23001. throwUnexpected();
  23002. return NULL;
  23003. }
  23004. virtual void setInputResult(unsigned id, IGraphResult * result)
  23005. {
  23006. results->setResult(id, result);
  23007. }
  23008. virtual bool querySetInputResult(unsigned id, IRoxieInput * input)
  23009. {
  23010. ForEachItemIn(i, activities)
  23011. {
  23012. if (activities.item(i).querySetStreamInput(id, input))
  23013. return true;
  23014. }
  23015. return false;
  23016. }
  23017. virtual void stopUnusedOutputs()
  23018. {
  23019. //Hmm not sure how to do this...
  23020. }
  23021. virtual void afterExecute()
  23022. {
  23023. ForEachItemIn(i, sinks)
  23024. {
  23025. sinks.item(i).stop(false);
  23026. }
  23027. if (graphSlaveContext.queryDebugContext())
  23028. {
  23029. graphSlaveContext.queryDebugContext()->checkBreakpoint(DebugStateGraphFinished, NULL, NULL);
  23030. }
  23031. reset();
  23032. }
  23033. virtual IRoxieGraphResults * execute(size32_t parentExtractSize, const byte *parentExtract)
  23034. {
  23035. doExecute(parentExtractSize, parentExtract);
  23036. return LINK(results);
  23037. }
  23038. virtual void getLinkedResult(unsigned & count, byte * * & ret, unsigned id)
  23039. {
  23040. results->getLinkedResult(count, ret, id);
  23041. }
  23042. virtual void getDictionaryResult(unsigned & count, byte * * & ret, unsigned id)
  23043. {
  23044. results->getLinkedResult(count, ret, id);
  23045. }
  23046. virtual const void * getLinkedRowResult(unsigned id)
  23047. {
  23048. return results->getLinkedRowResult(id);
  23049. }
  23050. virtual void setResult(unsigned id, IGraphResult * result)
  23051. {
  23052. results->setResult(id, result);
  23053. }
  23054. virtual IRoxieInput * createResultIterator(unsigned id)
  23055. {
  23056. return results->createIterator(id);
  23057. }
  23058. virtual void setGraphLoopResult(IGraphResult * result)
  23059. {
  23060. graphLoopResults.appendResult(result);
  23061. }
  23062. virtual IRoxieInput * createGraphLoopResultIterator(unsigned id)
  23063. {
  23064. try
  23065. {
  23066. return graphLoopResults.createIterator(id);
  23067. }
  23068. catch (IException * e)
  23069. {
  23070. e->Release();
  23071. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Error reading graph result %d before it is calculated", id);
  23072. }
  23073. }
  23074. virtual void clearGraphLoopResults()
  23075. {
  23076. graphLoopResults.clear();
  23077. }
  23078. virtual void executeGraphLoop(size32_t parentExtractSize, const byte *parentExtract)
  23079. {
  23080. doExecute(parentExtractSize, parentExtract);
  23081. }
  23082. virtual void setGraphLoopResult(unsigned id, IGraphResult * result)
  23083. {
  23084. graphLoopResults.setResult(id, result);
  23085. }
  23086. virtual IRoxieInput * getGraphLoopResult(unsigned id)
  23087. {
  23088. return graphLoopResults.createIterator(id);
  23089. }
  23090. virtual void getProbeResponse(IPropertyTree *query)
  23091. {
  23092. if (probeManager)
  23093. probeManager->getProbeResponse(query);
  23094. }
  23095. virtual IRoxieServerChildGraph * createGraphLoopInstance(unsigned loopCounter, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &logctx)
  23096. {
  23097. throwUnexpected();
  23098. }
  23099. virtual CGraphIterationInfo *selectGraphLoopOutput()
  23100. {
  23101. return NULL;
  23102. }
  23103. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor)
  23104. {
  23105. throwUnexpected();
  23106. }
  23107. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor)
  23108. {
  23109. throwUnexpected();
  23110. }
  23111. };
  23112. class CIterationActivityGraph : public CActivityGraph
  23113. {
  23114. IHThorArg * colocalParent;
  23115. unsigned fixedParentExtractSize;
  23116. const byte * fixedParentExtract;
  23117. unsigned graphOutputActivityIndex;
  23118. public:
  23119. CIterationActivityGraph(const char *_graphName, unsigned _id, ActivityArray &x, IProbeManager *_probeManager,
  23120. unsigned _loopCounter, IRoxieSlaveContext *ctx, IHThorArg * _colocalParent, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &_logctx)
  23121. : CActivityGraph(_graphName, _id, x, _probeManager, _logctx)
  23122. {
  23123. graphOutputActivityIndex = 0;
  23124. loopCounter = _loopCounter;
  23125. colocalParent = _colocalParent;
  23126. graphSlaveContext.set(ctx);
  23127. graphSlaveContext.setLoopCounter(loopCounter);
  23128. graphCodeContext.set(ctx->queryCodeContext());
  23129. fixedParentExtractSize = parentExtractSize;
  23130. fixedParentExtract = parentExtract;
  23131. }
  23132. void createIterationGraph()
  23133. {
  23134. Owned<IRoxieServerActivity> pseudoActivity = new CPseudoActivity(*new CPseudoArg);
  23135. ForEachItemIn(idx1, graphDefinition)
  23136. activities.append(*LINK(pseudoActivity));
  23137. graphOutputActivityIndex = queryGraphOutputIndex();
  23138. recursiveCreateGraph(graphOutputActivityIndex);
  23139. }
  23140. unsigned queryGraphOutputIndex() const
  23141. {
  23142. ForEachItemIn(i, graphDefinition)
  23143. if (graphDefinition.serverItem(i).getKind() == TAKgraphloopresultwrite)
  23144. return i;
  23145. throwUnexpected();
  23146. }
  23147. void recursiveCreateGraph(unsigned whichActivity)
  23148. {
  23149. //Check to see if already created
  23150. IRoxieServerActivity & prevActivity = activities.item(whichActivity);
  23151. if (prevActivity.queryId() != 0)
  23152. {
  23153. prevActivity.noteOutputUsed(); //We need to patch up the number of outputs for splitters.
  23154. return;
  23155. }
  23156. IRoxieServerActivityFactory &donor = graphDefinition.serverItem(whichActivity);
  23157. IRoxieServerActivity * activity = NULL;
  23158. if (donor.isGraphInvariant())
  23159. {
  23160. ThorActivityKind kind = donor.getKind();
  23161. switch (kind)
  23162. {
  23163. case TAKif:
  23164. case TAKchildif:
  23165. case TAKcase:
  23166. case TAKchildcase: // MORE RKC->GH - what about FILTER with a graph-invariant condition and other latestart activities?
  23167. {
  23168. Owned<IHThorArg> helper = &donor.getHelper();
  23169. helper->onCreate(&graphCodeContext, colocalParent, NULL);
  23170. helper->onStart(fixedParentExtract, NULL);
  23171. unsigned branch;
  23172. switch (kind)
  23173. {
  23174. case TAKif: case TAKchildif:
  23175. branch = static_cast<IHThorIfArg *>(helper.get())->getCondition() ? 0 : 1;
  23176. break;
  23177. case TAKcase: case TAKchildcase:
  23178. branch = static_cast<IHThorCaseArg *>(helper.get())->getBranch();
  23179. if (branch >= donor.numInputs())
  23180. branch = donor.numInputs() - 1;
  23181. break;
  23182. default:
  23183. throwUnexpected();
  23184. }
  23185. helper.clear();
  23186. unsigned outputidx;
  23187. unsigned source = donor.getInput(branch, outputidx);
  23188. if (source ==(unsigned) -1)
  23189. activity = createRoxieServerNullActivity(&donor, probeManager);
  23190. else
  23191. activity = createRoxieServerPassThroughActivity(&donor, probeManager);
  23192. activities.replace(*activity, whichActivity);
  23193. activity->onCreate(&graphSlaveContext, colocalParent);
  23194. if (source ==(unsigned) -1)
  23195. return;
  23196. recursiveCreateGraph(source);
  23197. connectInput(whichActivity, 0, source, outputidx, loopCounter);
  23198. break;
  23199. }
  23200. }
  23201. }
  23202. if (!activity)
  23203. {
  23204. activity = donor.createActivity(probeManager);
  23205. activities.replace(*activity, whichActivity);
  23206. activity->onCreate(&graphSlaveContext, colocalParent);
  23207. activity->resetOutputsUsed();
  23208. unsigned inputidx = 0;
  23209. loop
  23210. {
  23211. unsigned outputidx;
  23212. unsigned source = donor.getInput(inputidx, outputidx);
  23213. if (source==(unsigned) -1)
  23214. break;
  23215. recursiveCreateGraph(source);
  23216. connectInput(whichActivity, inputidx, source, outputidx, loopCounter);
  23217. inputidx++;
  23218. }
  23219. }
  23220. IntArray &dependencies = donor.queryDependencies();
  23221. IntArray &dependencyIndexes = donor.queryDependencyIndexes();
  23222. IntArray &dependencyControlIds = donor.queryDependencyControlIds();
  23223. ForEachItemIn(idx2, dependencies)
  23224. {
  23225. unsigned input = dependencies.item(idx2);
  23226. recursiveCreateGraph(input);
  23227. activity->addDependency(activities.item(input),dependencyIndexes.item(idx2),dependencyControlIds.item(idx2));
  23228. }
  23229. }
  23230. virtual CGraphIterationInfo *selectGraphLoopOutput()
  23231. {
  23232. IRoxieServerActivity &sourceActivity = activities.item(graphOutputActivityIndex);
  23233. return new CGraphIterationInfo(&sourceActivity, sourceActivity.queryOutput(0), 0, loopCounter);
  23234. }
  23235. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor)
  23236. {
  23237. ForEachItemIn(i, activities)
  23238. activities.item(i).gatherIterationUsage(processor, fixedParentExtractSize, fixedParentExtract);
  23239. }
  23240. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor)
  23241. {
  23242. ForEachItemIn(i, activities)
  23243. activities.item(i).associateIterationOutputs(processor, fixedParentExtractSize, fixedParentExtract, probeManager, probes);
  23244. }
  23245. };
  23246. class CDelayedActivityGraph : public CInterface, implements IActivityGraph
  23247. {
  23248. StringAttr graphName;
  23249. ActivityArray & graphDefinition;
  23250. IProbeManager *probeManager;
  23251. unsigned id;
  23252. IRoxieSlaveContext * ctx;
  23253. IHThorArg * colocalParent;
  23254. public:
  23255. IMPLEMENT_IINTERFACE;
  23256. CDelayedActivityGraph(const char *_graphName, unsigned _id, ActivityArray &x, IProbeManager *_probeManager)
  23257. : probeManager(_probeManager), graphDefinition(x)
  23258. {
  23259. graphName.set(_graphName);
  23260. id = _id;
  23261. ctx = NULL;
  23262. colocalParent = NULL;
  23263. }
  23264. virtual const char *queryName() const { return graphName.get(); }
  23265. virtual void abort() { throwUnexpected(); }
  23266. virtual void reset() { }
  23267. virtual void execute() { throwUnexpected(); }
  23268. virtual void getProbeResponse(IPropertyTree *query) { throwUnexpected(); }
  23269. virtual void noteException(IException *E) { throwUnexpected(); }
  23270. virtual void checkAbort() { throwUnexpected(); }
  23271. virtual IThorChildGraph * queryChildGraph() { throwUnexpected(); }
  23272. virtual IEclGraphResults * queryLocalGraph() { throwUnexpected(); }
  23273. virtual IRoxieServerChildGraph * queryLoopGraph() { throwUnexpected(); }
  23274. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  23275. {
  23276. ctx = _ctx;
  23277. colocalParent = _colocalParent;
  23278. }
  23279. virtual IRoxieServerChildGraph * createGraphLoopInstance(unsigned loopCounter, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &logctx)
  23280. {
  23281. Owned<CIterationActivityGraph> ret = new CIterationActivityGraph(graphName, id, graphDefinition, probeManager, loopCounter, ctx, colocalParent, parentExtractSize, parentExtract, logctx);
  23282. ret->createIterationGraph();
  23283. return ret.getClear();
  23284. }
  23285. };
  23286. IActivityGraph *createActivityGraph(const char *_graphName, unsigned id, ActivityArray &childFactories, IRoxieServerActivity *parentActivity, IProbeManager *_probeManager, const IRoxieContextLogger &_logctx)
  23287. {
  23288. if (childFactories.isDelayed())
  23289. {
  23290. return new CDelayedActivityGraph(_graphName, id, childFactories, _probeManager);
  23291. }
  23292. else
  23293. {
  23294. Owned<IProbeManager> childProbe;
  23295. if (_probeManager)
  23296. childProbe.setown(_probeManager->startChildGraph(id, parentActivity));
  23297. Owned<CActivityGraph> ret = new CActivityGraph(_graphName, id, childFactories, childProbe, _logctx);
  23298. ret->createGraph();
  23299. if (_probeManager)
  23300. _probeManager->endChildGraph(childProbe, parentActivity);
  23301. return ret.getClear();
  23302. }
  23303. }
  23304. //================================================================================================================
  23305. #ifdef _USE_CPPUNIT
  23306. #include "unittests.hpp"
  23307. // 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...
  23308. #if _MSC_VER==1200
  23309. #undef protected
  23310. #endif
  23311. static const char *sortAlgorithm;
  23312. class TestMetaData : public CInterface, implements IOutputMetaData
  23313. {
  23314. public:
  23315. IMPLEMENT_IINTERFACE;
  23316. virtual size32_t getRecordSize(const void *) { return 10; }
  23317. virtual size32_t getMinRecordSize() const { return 10; }
  23318. virtual size32_t getFixedSize() const { return 10; }
  23319. virtual void toXML(const byte * self, IXmlWriter & out) {}
  23320. virtual unsigned getVersion() const { return OUTPUTMETADATA_VERSION; }
  23321. virtual unsigned getMetaFlags() { return 0; }
  23322. virtual void destruct(byte * self) {}
  23323. virtual IOutputRowSerializer * createDiskSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  23324. virtual IOutputRowDeserializer * createDiskDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  23325. virtual ISourceRowPrefetcher * createDiskPrefetcher(ICodeContext * ctx, unsigned activityId) { return NULL; }
  23326. virtual IOutputMetaData * querySerializedDiskMeta() { return NULL; }
  23327. virtual IOutputRowSerializer * createInternalSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  23328. virtual IOutputRowDeserializer * createInternalDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  23329. virtual void walkIndirectMembers(const byte * self, IIndirectMemberVisitor & visitor) {}
  23330. virtual IOutputMetaData * queryChildMeta(unsigned i) { return NULL; }
  23331. } testMeta;
  23332. class TestInput : public CInterface, implements IRoxieInput
  23333. {
  23334. char const * const *input;
  23335. IRoxieSlaveContext *ctx;
  23336. unsigned endSeen;
  23337. bool eof;
  23338. unsigned count;
  23339. unsigned __int64 totalCycles;
  23340. size32_t recordSize;
  23341. unsigned activityId;
  23342. public:
  23343. enum { STATEreset, STATEstarted, STATEstopped } state;
  23344. bool allRead;
  23345. IMPLEMENT_IINTERFACE;
  23346. TestInput(IRoxieSlaveContext *_ctx, char const * const *_input)
  23347. {
  23348. ctx = _ctx;
  23349. input = _input;
  23350. count = 0;
  23351. eof = false;
  23352. allRead = false;
  23353. endSeen = 0;
  23354. recordSize = testMeta.getFixedSize();
  23355. state = STATEreset;
  23356. totalCycles = 0;
  23357. activityId = 1;
  23358. }
  23359. virtual IOutputMetaData * queryOutputMeta() const { return &testMeta; }
  23360. virtual void prestart(unsigned parentExtractSize, const byte *parentExtract)
  23361. {
  23362. ASSERT(state == STATEreset);
  23363. }
  23364. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  23365. {
  23366. ASSERT(state == STATEreset);
  23367. state = STATEstarted;
  23368. }
  23369. virtual IRoxieServerActivity *queryActivity()
  23370. {
  23371. throwUnexpected();
  23372. }
  23373. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  23374. {
  23375. throwUnexpected();
  23376. }
  23377. virtual void stop(bool aborting)
  23378. {
  23379. state = STATEstopped;
  23380. }
  23381. virtual void reset()
  23382. {
  23383. ASSERT(state == STATEstopped);
  23384. eof = false; count = 0; endSeen = 0; allRead = false; state = STATEreset; totalCycles = 0;
  23385. }
  23386. virtual void resetEOF()
  23387. {
  23388. throwUnexpected();
  23389. }
  23390. virtual void checkAbort() {}
  23391. virtual unsigned queryId() const { return activityId; };
  23392. virtual const void *nextInGroup()
  23393. {
  23394. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  23395. ASSERT(state == STATEstarted);
  23396. ASSERT(allRead || !eof);
  23397. if (eof)
  23398. return NULL;
  23399. const char *nextSource = input[count++];
  23400. if (nextSource)
  23401. {
  23402. endSeen = 0;
  23403. void *ret = ctx->queryRowManager().ALLOCATE(recordSize);
  23404. memset(ret, 0, recordSize);
  23405. strncpy((char *) ret, nextSource, recordSize);
  23406. return ret;
  23407. }
  23408. else
  23409. {
  23410. endSeen++;
  23411. if (endSeen==2)
  23412. eof = true;
  23413. return NULL;
  23414. }
  23415. }
  23416. virtual bool nextGroup(ConstPointerArray & group)
  23417. {
  23418. const void * next;
  23419. while ((next = nextInGroup()) != NULL)
  23420. group.append(next);
  23421. if (group.ordinality())
  23422. return true;
  23423. return false;
  23424. }
  23425. virtual unsigned __int64 queryTotalCycles() const { return totalCycles; }
  23426. virtual unsigned __int64 queryLocalCycles() const { return totalCycles; }
  23427. virtual IRoxieInput *queryInput(unsigned idx) const
  23428. {
  23429. return NULL;
  23430. }
  23431. };
  23432. struct SortActivityTest : public ccdserver_hqlhelper::CThorSortArg {
  23433. public:
  23434. struct CompareClass : public ICompare {
  23435. virtual int docompare(const void * _left, const void * _right) const {
  23436. return memcmp(_left, _right, 5);
  23437. }
  23438. } compare;
  23439. virtual ICompare * queryCompare() { return &compare; }
  23440. virtual IOutputMetaData * queryOutputMeta()
  23441. {
  23442. return &testMeta;
  23443. }
  23444. virtual unsigned getAlgorithmFlags() { return TAFunstable; }
  23445. virtual const char * getAlgorithm() { return sortAlgorithm; }
  23446. };
  23447. extern "C" IHThorArg * sortActivityTestFactory() { return new SortActivityTest; }
  23448. struct MergeActivityTest : public ccdserver_hqlhelper::CThorMergeArg {
  23449. static bool isDedup;
  23450. public:
  23451. struct CompareClass : public ICompare {
  23452. virtual int docompare(const void * _left, const void * _right) const {
  23453. return memcmp(_left, _right, 5);
  23454. }
  23455. } compare;
  23456. virtual ICompare * queryCompare() { return &compare; }
  23457. virtual IOutputMetaData * queryOutputMeta()
  23458. {
  23459. return &testMeta;
  23460. }
  23461. virtual bool dedup() { return isDedup; }
  23462. };
  23463. bool MergeActivityTest::isDedup = false;
  23464. extern "C" IHThorArg * mergeActivityTestFactory() { return new MergeActivityTest; }
  23465. class CcdServerTest : public CppUnit::TestFixture
  23466. {
  23467. CPPUNIT_TEST_SUITE(CcdServerTest);
  23468. CPPUNIT_TEST(testSetup);
  23469. CPPUNIT_TEST(testHeapSort);
  23470. CPPUNIT_TEST(testInsertionSort);
  23471. CPPUNIT_TEST(testQuickSort);
  23472. CPPUNIT_TEST(testMerge);
  23473. CPPUNIT_TEST(testMergeDedup);
  23474. CPPUNIT_TEST(testMiscellaneous);
  23475. CPPUNIT_TEST(testCleanup);
  23476. CPPUNIT_TEST_SUITE_END();
  23477. protected:
  23478. SlaveContextLogger logctx;
  23479. Owned<const IQueryDll> queryDll;
  23480. Owned<IRoxiePackage> package;
  23481. Owned<IRoxieSlaveContext> ctx;
  23482. Owned<IQueryFactory> queryFactory;
  23483. void testSetup()
  23484. {
  23485. roxiemem::setTotalMemoryLimit(false, 100 * 1024 * 1024, 0, NULL);
  23486. }
  23487. void testCleanup()
  23488. {
  23489. roxiemem::releaseRoxieHeap();
  23490. }
  23491. void init()
  23492. {
  23493. package.setown(createRoxiePackage(NULL, NULL));
  23494. ctx.setown(createSlaveContext(NULL, logctx, 0, 50*1024*1024, NULL));
  23495. queryDll.setown(createExeQueryDll("roxie"));
  23496. queryFactory.setown(createServerQueryFactory("test", queryDll.getLink(), *package, NULL, false));
  23497. timer->reset();
  23498. }
  23499. void testActivity(IRoxieServerActivity *activity, char const * const *input, char const * const *output)
  23500. {
  23501. testActivity(activity, input, NULL, output);
  23502. }
  23503. void testActivity(IRoxieServerActivity *activity, char const * const *input, char const * const *input2, char const * const *output)
  23504. {
  23505. TestInput in(ctx, input);
  23506. TestInput in2(ctx, input2);
  23507. IRoxieInput *out = activity->queryOutput(0);
  23508. IOutputMetaData *meta = out->queryOutputMeta();
  23509. activity->setInput(0, &in);
  23510. if (input2)
  23511. activity->setInput(1, &in2);
  23512. void *buf = alloca(meta->getFixedSize());
  23513. for (unsigned iteration = 0; iteration < 8; iteration++)
  23514. {
  23515. // 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)
  23516. // This should be true whether we read all, some, or none of the data.
  23517. // Should not matter if an activity is not started
  23518. if (iteration % 4 == 0)
  23519. activity->onCreate(ctx, NULL);
  23520. unsigned count = 0;
  23521. if (iteration % 4 != 3)
  23522. {
  23523. activity->start(0, NULL, false);
  23524. ASSERT(in.state == TestInput::STATEstarted);
  23525. ASSERT(!input2 || in2.state == TestInput::STATEstarted);
  23526. loop
  23527. {
  23528. const void *next = out->nextInGroup();
  23529. if (!next)
  23530. {
  23531. ASSERT(output[count++] == NULL);
  23532. next = out->nextInGroup();
  23533. if (!next)
  23534. {
  23535. ASSERT(output[count++] == NULL);
  23536. break;
  23537. }
  23538. }
  23539. ASSERT(output[count] != NULL);
  23540. unsigned outsize = meta->getRecordSize(next);
  23541. memset(buf, 0, outsize);
  23542. strncpy((char *) buf, output[count++], outsize);
  23543. ASSERT(memcmp(next, buf, outsize) == 0);
  23544. ReleaseRoxieRow(next);
  23545. if (iteration % 4 == 2)
  23546. break;
  23547. }
  23548. if (iteration % 4 != 2)
  23549. {
  23550. // Check that reading after end is harmless
  23551. in.allRead = true;
  23552. const void *next = out->nextInGroup();
  23553. ASSERT(next == NULL);
  23554. }
  23555. }
  23556. activity->stop(false);
  23557. ASSERT(in.state == TestInput::STATEstopped);
  23558. ASSERT(!input2 || in2.state == TestInput::STATEstopped);
  23559. activity->reset();
  23560. ASSERT(in.state == TestInput::STATEreset);
  23561. ASSERT(!input2 || in2.state == TestInput::STATEreset);
  23562. ctx->queryRowManager().reportLeaks();
  23563. ASSERT(ctx->queryRowManager().numPagesAfterCleanup(true) == 0);
  23564. }
  23565. }
  23566. static int compareFunc(const void *l, const void *r)
  23567. {
  23568. return strcmp(*(char **) l, *(char **) r);
  23569. }
  23570. void testSort(unsigned type)
  23571. {
  23572. init();
  23573. sortAlgorithm = NULL;
  23574. if (type==2)
  23575. sortAlgorithm = "heapSort";
  23576. else if (type == 1)
  23577. sortAlgorithm = "insertionSort";
  23578. else
  23579. sortAlgorithm = "quickSort";
  23580. DBGLOG("Testing %s activity", sortAlgorithm);
  23581. Owned <IRoxieServerActivityFactory> factory = createRoxieServerSortActivityFactory(1, 1, *queryFactory, sortActivityTestFactory, TAKsort);
  23582. Owned <IRoxieServerActivity> activity = factory->createActivity(NULL);
  23583. const char * test[] = { NULL, NULL };
  23584. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  23585. const char * test54321[] = { "5", "4", "3", "2", "1", NULL, NULL };
  23586. const char * test11111[] = { "1", "1", "1", "1", "1", NULL, NULL };
  23587. const char * test11111_12345[] = { "1", "1", "1", "1", "1", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  23588. const char * test11111_54321[] = { "1", "1", "1", "1", "1", NULL, "5", "4", "3", "2", "1", NULL, NULL };
  23589. const char * test54321_54321[] = { "5", "4", "3", "2", "1", NULL, "5", "4", "3", "2", "1", NULL, NULL };
  23590. const char * test12345_12345[] = { "1", "2", "3", "4", "5", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  23591. testActivity(activity, test, test);
  23592. testActivity(activity, test12345, test12345);
  23593. testActivity(activity, test54321, test12345);
  23594. testActivity(activity, test11111, test11111);
  23595. testActivity(activity, test11111_12345, test11111_12345);
  23596. testActivity(activity, test11111_54321, test11111_12345);
  23597. testActivity(activity, test54321_54321, test12345_12345);
  23598. // A few larger tests
  23599. char *input[2002];
  23600. char *output[2002];
  23601. input[2000] = input[2001] = output[2000] = output[2001] = NULL;
  23602. unsigned i;
  23603. // identical
  23604. for (i=0; i<2000; i++)
  23605. {
  23606. input[i] = new char[11];
  23607. output[i] = new char[11];
  23608. sprintf(input[i], "1");
  23609. sprintf(output[i], "1");
  23610. }
  23611. testActivity(activity, input, output);
  23612. // Ascending
  23613. for (i=0; i<2000; i++)
  23614. {
  23615. sprintf(input[i], "%04d", i);
  23616. sprintf(output[i], "%04d", i);
  23617. }
  23618. testActivity(activity, input, output);
  23619. // Almost sorted
  23620. for (i=0; i<20; i++)
  23621. {
  23622. unsigned h = i*100;
  23623. sprintf(input[h], "%04d", 1900-h);
  23624. }
  23625. testActivity(activity, input, output);
  23626. // Descending
  23627. for (i=0; i<2000; i++)
  23628. {
  23629. sprintf(input[i], "%04d", 1999-i);
  23630. sprintf(output[i], "%04d", i);
  23631. }
  23632. testActivity(activity, input, output);
  23633. // Random
  23634. for (i=0; i<2000; i++)
  23635. {
  23636. unsigned r = rand() % 1500;
  23637. sprintf(input[i], "%04d", r);
  23638. sprintf(output[i], "%04d", r);
  23639. }
  23640. qsort(output, 2000, sizeof(output[0]), compareFunc);
  23641. testActivity(activity, input, output);
  23642. #if 0
  23643. // Random
  23644. #define BIGSORTSIZE 1000000
  23645. char **linput = new char*[BIGSORTSIZE +2];
  23646. char **loutput = new char *[BIGSORTSIZE+2];
  23647. linput[BIGSORTSIZE] = linput[BIGSORTSIZE+1] = loutput[BIGSORTSIZE] = loutput[BIGSORTSIZE+1] = NULL;
  23648. for (i=0; i<BIGSORTSIZE; i++)
  23649. {
  23650. unsigned r = rand() % 15000;
  23651. linput[i] = loutput[i] = new char[11];
  23652. sprintf(linput[i], "%04d", r);
  23653. }
  23654. qsort(loutput, BIGSORTSIZE, 4, compareFunc);
  23655. testActivity(activity, linput, loutput);
  23656. for (i=0; i<BIGSORTSIZE; i++)
  23657. {
  23658. delete [] linput[i];
  23659. }
  23660. delete [] linput;
  23661. delete [] loutput;
  23662. #endif
  23663. unsigned __int64 us = cycle_to_nanosec(factory->queryLocalCycles()/1000);
  23664. DBGLOG("Simple %s sorts: activity time %u.%u ms", type==2?"Heap" : (type==1 ? "Insertion" : "Quick"), (int)(us/1000), (int)(us%1000));
  23665. factory->resetNodeProgressInfo();
  23666. if (type)
  23667. {
  23668. // Other than quicksort, it's supposed to be stable. Let's check that it is
  23669. // All sort identical
  23670. for (i=0; i<2000; i++)
  23671. {
  23672. sprintf(input[i], "1 %d", i);
  23673. sprintf(output[i], "1 %d", i);
  23674. }
  23675. testActivity(activity, input, output);
  23676. // Already sorted
  23677. for (i=0; i<2000; i++)
  23678. {
  23679. sprintf(input[i], "%04d %d", i / 10, i);
  23680. sprintf(output[i], "%04d %d", i / 10, i);
  23681. }
  23682. testActivity(activity, input, output);
  23683. // Reverse order
  23684. for (i=0; i<2000; i++)
  23685. {
  23686. sprintf(input[i], "%04d %d", 199 - (i / 10), i%10);
  23687. sprintf(output[i], "%04d %d", i / 10, i%10);
  23688. }
  23689. testActivity(activity, input, output);
  23690. }
  23691. for (i=0; i<2000; i++)
  23692. {
  23693. delete [] input[i];
  23694. delete [] output[i];
  23695. }
  23696. DBGLOG("Finished testing %s sort", type==2?"Heap" : (type==1 ? "Insertion" : "Quick"));
  23697. }
  23698. void testQuickSort()
  23699. {
  23700. testSort(0);
  23701. }
  23702. void testInsertionSort()
  23703. {
  23704. testSort(1);
  23705. }
  23706. void testHeapSort()
  23707. {
  23708. testSort(2);
  23709. }
  23710. void testMerge()
  23711. {
  23712. DBGLOG("testMerge");
  23713. init();
  23714. Owned <IRoxieServerActivityFactory> factory = createRoxieServerMergeActivityFactory(1, 1, *queryFactory, mergeActivityTestFactory, TAKmerge);
  23715. factory->setInput(0,0,0);
  23716. factory->setInput(1,0,0);
  23717. Owned <IRoxieServerActivity> activity = factory->createActivity(NULL);
  23718. const char * test[] = { NULL, NULL };
  23719. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  23720. const char * test1122334455[] = { "1", "1", "2", "2", "3", "3", "4", "4", "5", "5", NULL, NULL };
  23721. const char * test11111[] = { "1", "1", "1", "1", "1", NULL, NULL };
  23722. const char * test1111111111[] = { "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", NULL, NULL };
  23723. const char * test11111_12345[] = { "1", "1", "1", "1", "1", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  23724. const char * test1111112345[] = { "1", "1", "1", "1", "1", "1", "2", "3", "4", "5", NULL, NULL };
  23725. 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 };
  23726. testActivity(activity, test, test, test);
  23727. testActivity(activity, test12345, test, test12345);
  23728. testActivity(activity, test, test12345, test12345);
  23729. testActivity(activity, test12345, test12345, test1122334455);
  23730. testActivity(activity, test11111, test, test11111);
  23731. testActivity(activity, test, test11111, test11111);
  23732. testActivity(activity, test11111, test11111, test1111111111);
  23733. testActivity(activity, test11111_12345, test, test1111112345);
  23734. testActivity(activity, test11111_12345, test11111_12345, test11111111111122334455);
  23735. // Should really test WHICH side gets kept...
  23736. // Should test with more than 2 inputs...
  23737. DBGLOG("testMerge done");
  23738. }
  23739. void testMergeDedup()
  23740. {
  23741. DBGLOG("testMergeDedup");
  23742. init();
  23743. MergeActivityTest::isDedup = true;
  23744. Owned <IRoxieServerActivityFactory> factory = createRoxieServerMergeActivityFactory(1, 1, *queryFactory, mergeActivityTestFactory, TAKmerge);
  23745. factory->setInput(0,0,0);
  23746. factory->setInput(1,0,0);
  23747. Owned <IRoxieServerActivity> activity = factory->createActivity(NULL);
  23748. const char * test[] = { NULL, NULL };
  23749. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  23750. const char * test11111[] = { "1", "1", "1", "1", "1", NULL, NULL };
  23751. const char * test11111_12345[] = { "1", "1", "1", "1", "1", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  23752. const char * test1111112345[] = { "1", "1", "1", "1", "1", "1", "2", "3", "4", "5", NULL, NULL };
  23753. testActivity(activity, test11111, test, test11111); // No dedup within a stream
  23754. testActivity(activity, test11111, test11111, test11111); // No dedup within a stream
  23755. testActivity(activity, test, test11111, test11111);
  23756. testActivity(activity, test, test, test);
  23757. testActivity(activity, test12345, test, test12345);
  23758. testActivity(activity, test, test12345, test12345);
  23759. testActivity(activity, test12345, test12345, test12345);
  23760. testActivity(activity, test11111_12345, test, test1111112345);
  23761. testActivity(activity, test11111_12345, test11111_12345, test1111112345);
  23762. // Should really test WHICH side gets kept...
  23763. // Should test with more than 2 inputs...
  23764. DBGLOG("testMergeDedup done");
  23765. }
  23766. void testMiscellaneous()
  23767. {
  23768. DBGLOG("sizeof(CriticalSection)=%u", (unsigned) sizeof(CriticalSection));
  23769. DBGLOG("sizeof(SpinLock)=%u", (unsigned) sizeof(SpinLock));
  23770. DBGLOG("sizeof(CJoinGroup)=%u", (unsigned) sizeof(CJoinGroup));
  23771. ASSERT(sizeof(CJoinGroup) <= 120);
  23772. }
  23773. };
  23774. CPPUNIT_TEST_SUITE_REGISTRATION( CcdServerTest );
  23775. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( CcdServerTest, "CcdServerTest" );
  23776. #endif