ccdserver.cpp 992 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385
  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 "thorsort.hpp"
  27. #include "thorstats.hpp"
  28. #include "jlzw.hpp"
  29. #include "javahash.hpp"
  30. #include "javahash.tpp"
  31. #include "thorstep.ipp"
  32. #include "thorpipe.hpp"
  33. #include "thorfile.hpp"
  34. #include "eclhelper.hpp"
  35. #include "eclrtl_imp.hpp"
  36. #include "rtlfield.hpp"
  37. #include "rtlds_imp.hpp"
  38. #include "rtlread_imp.hpp"
  39. #include <algorithm>
  40. #include "dafdesc.hpp"
  41. #include "dautils.hpp"
  42. #include "ftbase.ipp"
  43. namespace ccdserver_hqlhelper
  44. {
  45. #include "eclhelper_base.hpp"
  46. }
  47. #include "ccd.hpp"
  48. #include "ccdserver.hpp"
  49. #include "ccdcontext.hpp"
  50. #include "ccdactivities.hpp"
  51. #include "ccdquery.hpp"
  52. #include "ccdstate.hpp"
  53. #include "ccdqueue.ipp"
  54. #include "ccdsnmp.hpp"
  55. #include "ccddali.hpp"
  56. #include "jsmartsock.hpp"
  57. #include "dllserver.hpp"
  58. #include "workflow.hpp"
  59. #include "roxiemem.hpp"
  60. #include "roxierowbuff.hpp"
  61. #include "roxiehelper.hpp"
  62. #include "roxielmj.hpp"
  63. #include "roxierow.hpp"
  64. #include "thorplugin.hpp"
  65. #include "keybuild.hpp"
  66. #include "thorstrand.hpp"
  67. #define MAX_HTTP_HEADERSIZE 8000
  68. #define MIN_PAYLOAD_SIZE 800
  69. #pragma warning(disable : 4355)
  70. #define DEFAULT_PARALLEL_LOOP_THREADS 1
  71. #define PROBE
  72. #ifdef _DEBUG
  73. //#define FAKE_EXCEPTIONS
  74. //#define TRACE_JOINGROUPS
  75. //#define TRACE_SPLIT
  76. //#define _CHECK_HEAPSORT
  77. //#undef PARALLEL_EXECUTE
  78. //#define TRACE_SEEK_REQUESTS
  79. #endif
  80. using roxiemem::OwnedRoxieRow;
  81. using roxiemem::OwnedRoxieString;
  82. using roxiemem::OwnedConstRoxieRow;
  83. using roxiemem::IRowManager;
  84. using roxiemem::ReleaseRoxieRows;
  85. // 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...
  86. #if _MSC_VER==1200
  87. #define protected public
  88. #endif
  89. #define TRACE_STARTSTOP // This determines if it is available - it is enabled/disabled by a configuration option
  90. #define TRACE_STRANDS
  91. #define MAX_SENSIBLE_STRANDS 1024 // Architecture dependent...
  92. static const SmartStepExtra dummySmartStepExtra(SSEFreadAhead, NULL);
  93. //=================================================================================
  94. class RestartableThread : public CInterface
  95. {
  96. class MyThread : public Thread
  97. {
  98. Linked<RestartableThread> owner;
  99. public:
  100. MyThread(RestartableThread *_owner, const char *name) : Thread(name), owner(_owner)
  101. {
  102. }
  103. virtual int run()
  104. {
  105. owner->started.signal();
  106. return owner->run();
  107. }
  108. };
  109. friend class MyThread;
  110. Semaphore started;
  111. Owned<MyThread> thread;
  112. CriticalSection crit;
  113. StringAttr name;
  114. public:
  115. RestartableThread(const char *_name) : name(_name)
  116. {
  117. }
  118. virtual void start(const char *namePrefix)
  119. {
  120. StringBuffer s(namePrefix);
  121. s.append(name);
  122. {
  123. CriticalBlock b(crit);
  124. assertex(!thread);
  125. thread.setown(new MyThread(this, s));
  126. thread->start();
  127. }
  128. started.wait();
  129. }
  130. virtual void join()
  131. {
  132. {
  133. Owned<Thread> tthread;
  134. {
  135. CriticalBlock b(crit);
  136. tthread.setown(thread.getClear());
  137. }
  138. if (tthread)
  139. tthread->join();
  140. }
  141. }
  142. virtual int run() = 0;
  143. };
  144. //================================================================================
  145. //The following don't link their arguments because that creates a circular reference
  146. //But I wish there was a better way
  147. class IndirectSlaveContext : implements IRoxieSlaveContext, public CInterface
  148. {
  149. public:
  150. IndirectSlaveContext(IRoxieSlaveContext * _ctx) : ctx(_ctx) {}
  151. IMPLEMENT_IINTERFACE
  152. // void set(IRoxieSlaveContext * _ctx) { ctx = _ctx; }
  153. virtual ICodeContext *queryCodeContext()
  154. {
  155. return ctx->queryCodeContext();
  156. }
  157. virtual void checkAbort()
  158. {
  159. ctx->checkAbort();
  160. }
  161. virtual void notifyAbort(IException *E)
  162. {
  163. ctx->notifyAbort(E);
  164. }
  165. virtual IActivityGraph * queryChildGraph(unsigned id)
  166. {
  167. return ctx->queryChildGraph(id);
  168. }
  169. virtual void noteChildGraph(unsigned id, IActivityGraph *childGraph)
  170. {
  171. ctx->noteChildGraph(id, childGraph) ;
  172. }
  173. virtual IRowManager &queryRowManager()
  174. {
  175. return ctx->queryRowManager();
  176. }
  177. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value) const
  178. {
  179. ctx->noteStatistic(kind, value);
  180. }
  181. virtual void mergeStats(const CRuntimeStatisticCollection &from) const
  182. {
  183. ctx->mergeStats(from);
  184. }
  185. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  186. {
  187. ctx->gatherStats(merged);
  188. }
  189. virtual void CTXLOGva(const char *format, va_list args) const __attribute__((format(printf,2,0)))
  190. {
  191. ctx->CTXLOGva(format, args);
  192. }
  193. virtual void CTXLOGa(TracingCategory category, const char *prefix, const char *text) const
  194. {
  195. ctx->CTXLOGa(category, prefix, text);
  196. }
  197. virtual void logOperatorExceptionVA(IException *E, const char *file, unsigned line, const char *format, va_list args) const __attribute__((format(printf,5,0)))
  198. {
  199. ctx->logOperatorExceptionVA(E, file, line, format, args);
  200. }
  201. virtual void CTXLOGaeva(IException *E, const char *file, unsigned line, const char *prefix, const char *format, va_list args) const __attribute__((format(printf,6,0)))
  202. {
  203. ctx->CTXLOGaeva(E, file, line, prefix, format, args);
  204. }
  205. virtual void CTXLOGl(LogItem *log) const
  206. {
  207. ctx->CTXLOGl(log);
  208. }
  209. virtual StringBuffer &getLogPrefix(StringBuffer &ret) const
  210. {
  211. return ctx->getLogPrefix(ret);
  212. }
  213. virtual unsigned queryTraceLevel() const
  214. {
  215. return ctx->queryTraceLevel();
  216. }
  217. virtual bool isIntercepted() const
  218. {
  219. return ctx->isIntercepted();
  220. }
  221. virtual bool isBlind() const
  222. {
  223. return ctx->isBlind();
  224. }
  225. virtual const QueryOptions &queryOptions() const
  226. {
  227. return ctx->queryOptions();
  228. }
  229. virtual void addSlavesReplyLen(unsigned len)
  230. {
  231. ctx->addSlavesReplyLen(len);
  232. }
  233. virtual const char *queryAuthToken()
  234. {
  235. return ctx->queryAuthToken();
  236. }
  237. virtual const IResolvedFile *resolveLFN(const char *filename, bool isOpt)
  238. {
  239. return ctx->resolveLFN(filename, isOpt);
  240. }
  241. virtual IRoxieWriteHandler *createLFN(const char *filename, bool overwrite, bool extend, const StringArray &clusters)
  242. {
  243. return ctx->createLFN(filename, overwrite, extend, clusters);
  244. }
  245. virtual void onFileCallback(const RoxiePacketHeader &header, const char *lfn, bool isOpt, bool isLocal)
  246. {
  247. ctx->onFileCallback(header, lfn, isOpt, isLocal);
  248. }
  249. virtual IActivityGraph *getLibraryGraph(const LibraryCallFactoryExtra &extra, IRoxieServerActivity *parentActivity)
  250. {
  251. return ctx->getLibraryGraph(extra, parentActivity);
  252. }
  253. virtual void noteProcessed(unsigned subgraphId, unsigned activityId, unsigned _idx, unsigned _processed, unsigned _strands) const
  254. {
  255. ctx->noteProcessed(subgraphId, activityId, _idx, _processed, _strands);
  256. }
  257. virtual void mergeActivityStats(const CRuntimeStatisticCollection &fromStats, unsigned subgraphId, unsigned activityId) const
  258. {
  259. ctx->mergeActivityStats(fromStats, subgraphId, activityId);
  260. }
  261. virtual IProbeManager *queryProbeManager() const
  262. {
  263. return ctx->queryProbeManager();
  264. }
  265. virtual IDebuggableContext *queryDebugContext() const
  266. {
  267. return ctx->queryDebugContext();
  268. }
  269. virtual void printResults(IXmlWriter *output, const char *name, unsigned sequence)
  270. {
  271. ctx->printResults(output, name, sequence);
  272. }
  273. virtual void setWUState(WUState state)
  274. {
  275. ctx->setWUState(state);
  276. }
  277. virtual bool checkWuAborted()
  278. {
  279. return ctx->checkWuAborted();
  280. }
  281. virtual IWorkUnit *updateWorkUnit() const
  282. {
  283. return ctx->updateWorkUnit();
  284. }
  285. virtual IConstWorkUnit *queryWorkUnit() const
  286. {
  287. return ctx->queryWorkUnit();
  288. }
  289. virtual IRoxieServerContext *queryServerContext()
  290. {
  291. return ctx->queryServerContext();
  292. }
  293. virtual IWorkUnitRowReader *getWorkunitRowReader(const char *wuid, const char * name, unsigned sequence, IXmlToRowTransformer * xmlTransformer, IEngineRowAllocator *rowAllocator, bool isGrouped)
  294. {
  295. return ctx->getWorkunitRowReader(wuid, name, sequence, xmlTransformer, rowAllocator, isGrouped);
  296. }
  297. virtual IEngineRowAllocator *getRowAllocatorEx(IOutputMetaData * meta, unsigned activityId, roxiemem::RoxieHeapFlags flags) const
  298. {
  299. return ctx->getRowAllocatorEx(meta, activityId, flags);
  300. }
  301. protected:
  302. IRoxieSlaveContext * ctx;
  303. };
  304. //=================================================================================
  305. #define RESULT_FLUSH_THRESHOLD 10000u
  306. #ifdef _DEBUG
  307. #define SOAP_SPLIT_THRESHOLD 100u
  308. #define SOAP_SPLIT_RESERVE 200u
  309. #else
  310. #define SOAP_SPLIT_THRESHOLD 64000u
  311. #define SOAP_SPLIT_RESERVE 65535u
  312. #endif
  313. //=================================================================================
  314. // General activity statistics
  315. static const StatisticsMapping actStatistics(StWhenFirstRow, StTimeElapsed, StTimeLocalExecute, StTimeTotalExecute, StSizeMaxRowSize,
  316. StNumRowsProcessed, StNumSlaves, StNumStarted, StNumStopped, StNumStrands,
  317. StNumScansPerRow, StNumAllocations, StNumAllocationScans,
  318. StTimeFirstExecute, StCycleLocalExecuteCycles, StCycleTotalExecuteCycles, StKindNone);
  319. static const StatisticsMapping joinStatistics(&actStatistics, StNumAtmostTriggered, StKindNone);
  320. static const StatisticsMapping keyedJoinStatistics(&joinStatistics, StNumServerCacheHits, StNumIndexSeeks, StNumIndexScans, StNumIndexWildSeeks,
  321. StNumIndexSkips, StNumIndexNullSkips, StNumIndexMerges, StNumIndexMergeCompares,
  322. StNumPreFiltered, StNumPostFiltered, StNumIndexAccepted, StNumIndexRejected,
  323. StNumIndexRowsRead, StNumDiskRowsRead, StNumDiskSeeks, StNumDiskAccepted,
  324. StNumBlobCacheHits, StNumLeafCacheHits, StNumNodeCacheHits,
  325. StNumBlobCacheAdds, StNumLeafCacheAdds, StNumNodeCacheAdds,
  326. StNumDiskRejected, StKindNone);
  327. static const StatisticsMapping indexStatistics(&actStatistics, StNumServerCacheHits, StNumIndexSeeks, StNumIndexScans, StNumIndexWildSeeks,
  328. StNumIndexSkips, StNumIndexNullSkips, StNumIndexMerges, StNumIndexMergeCompares,
  329. StNumPreFiltered, StNumPostFiltered, StNumIndexAccepted, StNumIndexRejected,
  330. StNumBlobCacheHits, StNumLeafCacheHits, StNumNodeCacheHits,
  331. StNumBlobCacheAdds, StNumLeafCacheAdds, StNumNodeCacheAdds,
  332. StNumIndexRowsRead, StKindNone);
  333. static const StatisticsMapping diskStatistics(&actStatistics, StNumServerCacheHits, StNumDiskRowsRead, StNumDiskSeeks, StNumDiskAccepted,
  334. StNumDiskRejected, StKindNone);
  335. static const StatisticsMapping soapStatistics(&actStatistics, StTimeSoapcall, StKindNone);
  336. static const StatisticsMapping groupStatistics(&actStatistics, StNumGroups, StNumGroupMax, StKindNone);
  337. static const StatisticsMapping sortStatistics(&actStatistics, StTimeSortElapsed, StKindNone);
  338. //=================================================================================
  339. const static unsigned minus1U = (0U-1U);
  340. class CRoxieServerActivityFactoryBase : public CActivityFactory, implements IRoxieServerActivityFactory
  341. {
  342. protected:
  343. IntArray dependencies; // things I am dependent on
  344. IntArray dependencyIndexes; // things I am dependent on
  345. IntArray dependencyControlIds; // things I am dependent on
  346. StringArray dependencyEdgeIds; // How to describe them to the debugger
  347. unsigned dependentCount; // things dependent on me
  348. unsigned optParallel = 0; // -1=enable,0=not specified,1=single-threaded,n=<num threads>
  349. bool optStableInput = true; // is the input forced to ordered?
  350. bool optUnstableInput = false; // is the input forced to unordered?
  351. bool optUnordered = false; // is the output specified as unordered?
  352. unsigned heapFlags;
  353. mutable __int64 processed;
  354. mutable __int64 started;
  355. public:
  356. IMPLEMENT_IINTERFACE;
  357. CRoxieServerActivityFactoryBase(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  358. : CActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  359. {
  360. processed = 0;
  361. started = 0;
  362. dependentCount = 0;
  363. optParallel = _graphNode.getPropInt("att[@name='parallel']/@value", 0);
  364. optUnordered = !_graphNode.getPropBool("att[@name='ordered']/@value", true);
  365. heapFlags = _graphNode.getPropInt("hint[@name='heapflags']/@value", _queryFactory.queryOptions().heapFlags);
  366. }
  367. ~CRoxieServerActivityFactoryBase()
  368. {
  369. }
  370. StringBuffer &toString(StringBuffer &ret) const
  371. {
  372. return ret.appendf("%p", this);
  373. }
  374. virtual void addDependency(unsigned _source, ThorActivityKind _kind, unsigned _sourceIdx, int controlId, const char *edgeId)
  375. {
  376. dependencies.append(_source);
  377. dependencyIndexes.append(_sourceIdx);
  378. dependencyControlIds.append(controlId);
  379. dependencyEdgeIds.append(edgeId);
  380. }
  381. virtual bool isInputOrdered(bool consumerOrdered, unsigned idx) const
  382. {
  383. if (optStableInput)
  384. return true;
  385. if (optUnstableInput)
  386. return false;
  387. if (optUnordered)
  388. return false;
  389. return consumerOrdered;
  390. }
  391. virtual void noteDependent(unsigned target)
  392. {
  393. dependentCount++;
  394. }
  395. virtual IntArray &queryDependencies() { return dependencies; }
  396. virtual IntArray &queryDependencyIndexes() { return dependencyIndexes; }
  397. virtual IntArray &queryDependencyControlIds() { return dependencyControlIds; }
  398. virtual StringArray &queryDependencyEdgeIds() { return dependencyEdgeIds; }
  399. virtual unsigned queryId() const { return id; }
  400. virtual unsigned querySubgraphId() const { return subgraphId; }
  401. virtual ThorActivityKind getKind() const { return kind; }
  402. virtual IOutputMetaData * queryOutputMeta() const
  403. {
  404. return meta;
  405. }
  406. virtual bool isSink() const
  407. {
  408. return false;
  409. }
  410. virtual bool isFunction() const
  411. {
  412. return false;
  413. }
  414. virtual bool isGraphInvariant() const
  415. {
  416. return false;
  417. }
  418. virtual IHThorArg &getHelper() const
  419. {
  420. return *helperFactory();
  421. }
  422. virtual IRoxieServerActivity *createFunction(IHThorArg &arg, IProbeManager *_probeManager) const
  423. {
  424. arg.Release();
  425. throwUnexpected();
  426. }
  427. virtual void mergeStats(const CRuntimeStatisticCollection &from) const
  428. {
  429. CActivityFactory::mergeStats(from);
  430. }
  431. virtual void noteProcessed(unsigned _idx, unsigned _processed) const
  432. {
  433. dbgassertex(!_idx);
  434. if (_processed)
  435. {
  436. CriticalBlock b(statsCrit);
  437. processed += _processed;
  438. }
  439. }
  440. virtual void noteStarted() const
  441. {
  442. CriticalBlock b(statsCrit);
  443. started ++;
  444. }
  445. virtual void noteStarted(unsigned idx) const
  446. {
  447. throwUnexpected(); // should be implemented/required by multiOutput cases only
  448. }
  449. virtual void getEdgeProgressInfo(unsigned output, IPropertyTree &edge) const
  450. {
  451. CriticalBlock b(statsCrit);
  452. if (output == 0)
  453. {
  454. putStatsValue(&edge, "count", "sum", processed);
  455. if (started)
  456. putStatsValue(&edge, "started", "sum", started);
  457. }
  458. else
  459. ERRLOG("unexpected call to getEdgeProcessInfo for output %d in activity %d", output, queryId());
  460. }
  461. virtual void getNodeProgressInfo(IPropertyTree &node) const
  462. {
  463. CActivityFactory::getNodeProgressInfo(node);
  464. CriticalBlock b(statsCrit);
  465. if (started)
  466. putStatsValue(&node, "_roxieStarted", "sum", started);
  467. }
  468. virtual void resetNodeProgressInfo()
  469. {
  470. CActivityFactory::resetNodeProgressInfo();
  471. CriticalBlock b(statsCrit);
  472. processed = 0;
  473. started = 0;
  474. }
  475. virtual void getActivityMetrics(StringBuffer &reply) const
  476. {
  477. CActivityFactory::getActivityMetrics(reply);
  478. CriticalBlock b(statsCrit);
  479. putStatsValue(reply, "_roxieStarted", "sum", started);
  480. putStatsValue(reply, "totalTime", "sum", (unsigned) (mystats.getSerialStatisticValue(StTimeTotalExecute)/1000));
  481. putStatsValue(reply, "localTime", "sum", (unsigned) (mystats.getSerialStatisticValue(StTimeLocalExecute)/1000));
  482. }
  483. virtual unsigned __int64 queryLocalTimeNs() const
  484. {
  485. return mystats.getSerialStatisticValue(StTimeLocalExecute);
  486. }
  487. virtual IQueryFactory &queryQueryFactory() const
  488. {
  489. return CActivityFactory::queryQueryFactory();
  490. }
  491. virtual ActivityArray *queryChildQuery(unsigned idx, unsigned &id)
  492. {
  493. return CActivityFactory::queryChildQuery(idx, id);
  494. }
  495. virtual void addChildQuery(unsigned id, ActivityArray *childQuery)
  496. {
  497. CActivityFactory::addChildQuery(id, childQuery);
  498. }
  499. virtual void onCreateChildQueries(IRoxieSlaveContext *ctx, IHThorArg *colocalArg, IArrayOf<IActivityGraph> &childGraphs, IRoxieServerActivity *parentActivity, IProbeManager *_probeManager, const IRoxieContextLogger &_logctx, unsigned numParallel) const
  500. {
  501. ForEachItemIn(idx, childQueries)
  502. {
  503. childGraphs.append(*createActivityGraph(ctx, NULL, childQueryIndexes.item(idx), childQueries.item(idx), parentActivity, _probeManager, _logctx, numParallel));
  504. ctx->noteChildGraph(childQueryIndexes.item(idx), &childGraphs.item(idx));
  505. childGraphs.item(idx).onCreate(colocalArg);
  506. }
  507. }
  508. IActivityGraph * createChildGraph(IRoxieSlaveContext * ctx, IHThorArg *colocalArg, unsigned childId, IRoxieServerActivity *parentActivity, IProbeManager * _probeManager, const IRoxieContextLogger &_logctx) const
  509. {
  510. unsigned match = childQueryIndexes.find(childId);
  511. assertex(match != NotFound);
  512. Owned<IActivityGraph> graph = createActivityGraph(ctx, NULL, childQueryIndexes.item(match), childQueries.item(match), parentActivity, _probeManager, _logctx, 1);
  513. graph->onCreate(colocalArg);
  514. return graph.getClear();
  515. }
  516. virtual IRoxieServerSideCache *queryServerSideCache() const
  517. {
  518. return NULL; // Activities that wish to support server-side caching will need to do better....
  519. }
  520. virtual bool getEnableFieldTranslation() const
  521. {
  522. throwUnexpected(); // only implemented by index-related subclasses
  523. }
  524. virtual IDefRecordMeta *queryActivityMeta() const
  525. {
  526. throwUnexpected(); // only implemented by index-related subclasses
  527. }
  528. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  529. {
  530. // Most activities have nothing to say...
  531. }
  532. virtual const StatisticsMapping &queryStatsMapping() const
  533. {
  534. return actStatistics; // Overridden by anyone that needs more
  535. }
  536. virtual roxiemem::RoxieHeapFlags getHeapFlags() const
  537. {
  538. return (roxiemem::RoxieHeapFlags)heapFlags;
  539. }
  540. };
  541. class CRoxieServerMultiInputInfo
  542. {
  543. private:
  544. UnsignedArray inputs;
  545. UnsignedArray inputIndexes;
  546. public:
  547. void set(unsigned idx, unsigned source, unsigned sourceidx)
  548. {
  549. if (idx==inputs.length())
  550. {
  551. inputs.append(source);
  552. inputIndexes.append(sourceidx);
  553. }
  554. else
  555. {
  556. while (!inputs.isItem(idx))
  557. {
  558. inputs.append(0);
  559. inputIndexes.append(0);
  560. }
  561. inputs.replace(source, idx);
  562. inputIndexes.replace(sourceidx, idx);
  563. }
  564. }
  565. unsigned get(unsigned idx, unsigned &sourceidx) const
  566. {
  567. if (inputs.isItem(idx))
  568. {
  569. sourceidx = inputIndexes.item(idx);
  570. return inputs.item(idx);
  571. }
  572. else
  573. return (unsigned) -1;
  574. }
  575. inline unsigned ordinality() const { return inputs.ordinality(); }
  576. };
  577. class CRoxieServerMultiInputFactory : public CRoxieServerActivityFactoryBase
  578. {
  579. private:
  580. CRoxieServerMultiInputInfo inputs;
  581. public:
  582. CRoxieServerMultiInputFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  583. : CRoxieServerActivityFactoryBase(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  584. {
  585. }
  586. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  587. {
  588. inputs.set(idx, source, sourceidx);
  589. }
  590. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  591. {
  592. return inputs.get(idx, sourceidx);
  593. }
  594. virtual unsigned numInputs() const { return inputs.ordinality(); }
  595. };
  596. class DECL_EXCEPTION CWrappedException : implements IException, public CInterface
  597. {
  598. Owned<IException> wrapped;
  599. ThorActivityKind kind;
  600. unsigned queryId;
  601. public:
  602. IMPLEMENT_IINTERFACE;
  603. CWrappedException(IException *_wrapped, ThorActivityKind _kind, unsigned _queryId)
  604. : wrapped(_wrapped), kind(_kind), queryId(_queryId)
  605. {
  606. }
  607. virtual int errorCode() const { return wrapped->errorCode(); }
  608. virtual StringBuffer & errorMessage(StringBuffer &msg) const { return wrapped->errorMessage(msg).appendf(" (in %s %d)", getActivityText(kind), queryId); }
  609. virtual MessageAudience errorAudience() const { return wrapped->errorAudience(); }
  610. };
  611. class CRoxieServerActivityFactory : public CRoxieServerActivityFactoryBase
  612. {
  613. protected:
  614. unsigned input;
  615. unsigned inputidx;
  616. public:
  617. CRoxieServerActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  618. : CRoxieServerActivityFactoryBase(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  619. {
  620. input = (unsigned) -1;
  621. inputidx = 0;
  622. }
  623. inline void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  624. {
  625. if (idx != 0)
  626. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: id = %d : setInput() parameter out of bounds idx = %d at %s(%d)", id, idx, sanitizeSourceFile(__FILE__), __LINE__);
  627. if (input != -1)
  628. 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, sanitizeSourceFile(__FILE__), __LINE__);
  629. input = source;
  630. inputidx = sourceidx;
  631. }
  632. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  633. {
  634. if (!idx)
  635. {
  636. sourceidx = inputidx;
  637. return input;
  638. }
  639. return (unsigned) -1;
  640. }
  641. virtual unsigned numInputs() const { return (input == (unsigned)-1) ? 0 : 1; }
  642. };
  643. class CRoxieServerMultiOutputFactory : public CRoxieServerActivityFactory
  644. {
  645. protected:
  646. unsigned numOutputs;
  647. unsigned __int64 *processedArray;
  648. bool *startedArray;
  649. CRoxieServerMultiOutputFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  650. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  651. {
  652. numOutputs = 0;
  653. processedArray = NULL;
  654. startedArray = NULL;
  655. }
  656. ~CRoxieServerMultiOutputFactory()
  657. {
  658. delete [] processedArray;
  659. delete [] startedArray;
  660. }
  661. void setNumOutputs(unsigned num)
  662. {
  663. numOutputs = num;
  664. if (!num)
  665. num = 1; // Even sink activities like to track how many records they process
  666. processedArray = new unsigned __int64[num];
  667. startedArray = new bool[num];
  668. for (unsigned i = 0; i < num; i++)
  669. {
  670. processedArray[i] = 0;
  671. startedArray[i] = 0;
  672. }
  673. }
  674. virtual void getEdgeProgressInfo(unsigned idx, IPropertyTree &edge) const
  675. {
  676. assertex(numOutputs ? idx < numOutputs : idx==0);
  677. CriticalBlock b(statsCrit);
  678. putStatsValue(&edge, "count", "sum", processedArray[idx]);
  679. putStatsValue(&edge, "started", "sum", startedArray[idx]);
  680. }
  681. virtual void resetNodeProgressInfo()
  682. {
  683. CRoxieServerActivityFactory::resetNodeProgressInfo();
  684. CriticalBlock b(statsCrit);
  685. for (unsigned i = 0; i < numOutputs; i++)
  686. {
  687. processedArray[i] = 0;
  688. startedArray[i] = 0;
  689. }
  690. }
  691. virtual void noteProcessed(unsigned idx, unsigned _processed) const
  692. {
  693. assertex(numOutputs ? idx < numOutputs : idx==0);
  694. CriticalBlock b(statsCrit);
  695. processedArray[idx] += _processed;
  696. }
  697. virtual void noteStarted(unsigned idx) const
  698. {
  699. assertex(numOutputs ? idx < numOutputs : idx==0);
  700. CriticalBlock b(statsCrit);
  701. startedArray[idx] = true;
  702. }
  703. };
  704. class CRoxieServerInternalSinkFactory : public CRoxieServerActivityFactory
  705. {
  706. protected:
  707. bool isInternal;
  708. bool isRoot;
  709. unsigned usageCount;
  710. public:
  711. CRoxieServerInternalSinkFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  712. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  713. {
  714. usageCount = _usageCount;
  715. isRoot = _isRoot;
  716. isInternal = false; // filled in by derived class constructor
  717. }
  718. virtual bool isSink() const
  719. {
  720. //only a sink if a root activity
  721. 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?
  722. }
  723. virtual void getEdgeProgressInfo(unsigned idx, IPropertyTree &edge) const
  724. {
  725. // 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
  726. // Just leave it blank is safest.
  727. }
  728. };
  729. typedef enum { STATEreset, STATEstarted, STATEstopped, STATEstarting } activityState;
  730. const char *queryStateText(activityState state)
  731. {
  732. switch (state)
  733. {
  734. case STATEreset: return "reset";
  735. case STATEstarted: return "started";
  736. case STATEstopped: return "stopped";
  737. case STATEstarting: return "starting";
  738. default: return "unknown";
  739. }
  740. }
  741. typedef ICopyArrayOf<IRoxieServerActivity> IRoxieServerActivityCopyArray;
  742. class CParallelActivityExecutor : public CAsyncFor
  743. {
  744. public:
  745. unsigned parentExtractSize;
  746. const byte * parentExtract;
  747. CParallelActivityExecutor(IRoxieServerActivityCopyArray & _activities, unsigned _parentExtractSize, const byte * _parentExtract) :
  748. activities(_activities), parentExtractSize(_parentExtractSize), parentExtract(_parentExtract) { }
  749. void Do(unsigned i)
  750. {
  751. activities.item(i).execute(parentExtractSize, parentExtract);
  752. }
  753. private:
  754. IRoxieServerActivityCopyArray & activities;
  755. };
  756. extern IEngineRowStream * ensureSingleStream(IRoxieSlaveContext *ctx, PointerArrayOf<IEngineRowStream> & instreams, Owned<IStrandJunction> &junction)
  757. {
  758. if (instreams.length() != 1)
  759. {
  760. assertex(instreams.length());
  761. if (!junction)
  762. junction.setown(createStrandJunction(ctx->queryRowManager(), instreams.length(), 1, ctx->queryOptions().strandBlockSize, false));
  763. ForEachItemIn(stream, instreams)
  764. {
  765. junction->setInput(stream, instreams.item(stream));
  766. }
  767. return junction->queryOutput(0);
  768. }
  769. else
  770. return instreams.item(0);
  771. }
  772. extern IEngineRowStream *connectSingleStream(IRoxieSlaveContext *ctx, IFinalRoxieInput *input, unsigned idx, Owned<IStrandJunction> &junction, bool consumerOrdered)
  773. {
  774. if (input)
  775. {
  776. PointerArrayOf<IEngineRowStream> instreams;
  777. junction.setown(input->getOutputStreams(ctx, idx, instreams, NULL, consumerOrdered, nullptr));
  778. return ensureSingleStream(ctx, instreams, junction);
  779. }
  780. else
  781. return NULL;
  782. }
  783. extern IEngineRowStream *connectSingleStream(IRoxieSlaveContext *ctx, IFinalRoxieInput *input, unsigned idx, bool consumerOrdered)
  784. {
  785. Owned<IStrandJunction> junction;
  786. IEngineRowStream * result = connectSingleStream(ctx, input, idx, junction, consumerOrdered);
  787. assertex(!junction);
  788. return result;
  789. }
  790. class CRoxieServerActivity : implements CInterfaceOf<IRoxieServerActivity>, implements IFinalRoxieInput, implements IEngineRowStream, implements IRoxieContextLogger
  791. {
  792. friend class StrandProcessor;
  793. protected:
  794. IFinalRoxieInput *input;
  795. unsigned sourceIdx;
  796. IEngineRowStream *inputStream;
  797. Owned<IStrandJunction> junction;
  798. IHThorArg &basehelper;
  799. IRoxieSlaveContext *ctx;
  800. class InterceptRegisterTimer : public IndirectCodeContext
  801. {
  802. public:
  803. InterceptRegisterTimer(CRoxieServerActivity &_activity) : activity(_activity) {}
  804. virtual ISectionTimer *registerTimer(unsigned activityId, const char * name)
  805. {
  806. if (activityId == activity.queryId())
  807. return activity.registerTimer(activityId, name);
  808. else
  809. return ctx->registerTimer(activityId, name);
  810. }
  811. private:
  812. CRoxieServerActivity &activity;
  813. } interceptedCtx;
  814. const IRoxieServerActivityFactory *factory;
  815. IRoxieServerActivityCopyArray dependencies;
  816. IntArray dependencyIndexes;
  817. IntArray dependencyControlIds;
  818. IArrayOf<IActivityGraph> childGraphs;
  819. CachedOutputMetaData meta;
  820. IHThorArg *colocalParent;
  821. IEngineRowAllocator *rowAllocator;
  822. CriticalSection statecrit;
  823. CriticalSection statscrit;
  824. mutable CRuntimeStatisticCollection stats;
  825. MapStringToMyClass<ThorSectionTimer> functionTimers;
  826. unsigned processed;
  827. ActivityTimeAccumulator totalCycles;
  828. unsigned activityId;
  829. activityState state;
  830. bool createPending;
  831. bool debugging;
  832. bool timeActivities;
  833. bool aborted;
  834. bool connected = false;
  835. IProbeManager *probeManager = NULL;
  836. public:
  837. IMPLEMENT_IINTERFACE_USING(CInterfaceOf<IRoxieServerActivity>)
  838. CRoxieServerActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  839. : ctx(_ctx),
  840. interceptedCtx(*this),
  841. factory(_factory),
  842. basehelper(_factory->getHelper()),
  843. activityId(_factory->queryId()),
  844. stats(_factory->queryStatsMapping()),
  845. probeManager(_probeManager)
  846. {
  847. input = NULL;
  848. sourceIdx = 0;
  849. inputStream = NULL;
  850. meta.set(basehelper.queryOutputMeta());
  851. processed = 0;
  852. state=STATEreset;
  853. rowAllocator = NULL;
  854. debugging = _probeManager != NULL; // Don't want to collect timing stats from debug sessions
  855. colocalParent = NULL;
  856. createPending = true;
  857. timeActivities = defaultTimeActivities;
  858. aborted = false;
  859. }
  860. CRoxieServerActivity(IRoxieSlaveContext *_ctx, IHThorArg & _helper)
  861. : ctx(_ctx),
  862. interceptedCtx(*this),
  863. factory(NULL), basehelper(_helper), stats(allStatistics)
  864. {
  865. activityId = 0;
  866. input = NULL;
  867. sourceIdx = 0;
  868. inputStream = NULL;
  869. ctx = NULL;
  870. meta.set(basehelper.queryOutputMeta());
  871. processed = 0;
  872. state=STATEreset;
  873. rowAllocator = NULL;
  874. debugging = false;
  875. colocalParent = NULL;
  876. createPending = true;
  877. timeActivities = defaultTimeActivities;
  878. aborted = false;
  879. }
  880. ~CRoxieServerActivity()
  881. {
  882. basehelper.Release();
  883. ::Release(rowAllocator);
  884. }
  885. virtual void beforeDispose() override
  886. {
  887. if (traceStartStop)
  888. {
  889. // There was an old comment here stating // Note- CTXLOG may not be safe
  890. // There were problems in the destruction order of graphs that might mean an IndirectSlaveContext
  891. // was released while activities still referenced it.
  892. // However these should now all be fixed
  893. DBGLOG("%p destroy %d state=%s", this, activityId, queryStateText(state));
  894. if (watchActivityId && watchActivityId==activityId)
  895. {
  896. DBGLOG("WATCH: %p destroy %d state=%s", this, activityId, queryStateText(state));
  897. }
  898. }
  899. if (state!=STATEreset)
  900. {
  901. DBGLOG("STATE: Activity %d destroyed but not reset", activityId);
  902. state = STATEreset; // bit pointless but there you go...
  903. }
  904. }
  905. virtual void updateFactoryStatistics() override
  906. {
  907. CRuntimeStatisticCollection mergedStats(stats.queryMapping());
  908. gatherStats(mergedStats);
  909. if (factory && !debugging)
  910. {
  911. if (processed)
  912. factory->noteProcessed(0, processed);
  913. factory->mergeStats(mergedStats);
  914. }
  915. if (ctx && factory)
  916. {
  917. if (processed)
  918. ctx->noteProcessed(factory->querySubgraphId(), activityId, 0, processed, 0);
  919. ctx->mergeActivityStats(mergedStats, factory->querySubgraphId(), activityId);
  920. }
  921. }
  922. virtual const IRoxieContextLogger &queryLogCtx()const
  923. {
  924. return *this;
  925. }
  926. inline const StatisticsMapping & queryStatsMapping() const
  927. {
  928. return factory ? factory->queryStatsMapping() : actStatistics;
  929. }
  930. virtual void mergeStats(MemoryBuffer &buf)
  931. {
  932. stats.deserializeMerge(buf);
  933. }
  934. virtual ISectionTimer *registerTimer(unsigned _activityId, const char * name)
  935. {
  936. CriticalBlock b(statscrit); // reuse statscrit to protect functionTimers - it will not be held concurrently
  937. ISectionTimer *timer = functionTimers.getValue(name);
  938. if (!timer)
  939. {
  940. timer = ThorSectionTimer::createTimer(stats, name);
  941. functionTimers.setValue(name, timer);
  942. timer->Release(); // Value returned is not linked
  943. }
  944. return timer;
  945. }
  946. void mergeStrandStats(unsigned strandProcessed, const ActivityTimeAccumulator & strandCycles)
  947. {
  948. CriticalBlock cb(statscrit);
  949. processed += strandProcessed;
  950. totalCycles.merge(strandCycles);
  951. }
  952. inline void ensureRowAllocator()
  953. {
  954. if (!rowAllocator)
  955. rowAllocator = createRowAllocator(meta.queryOriginal());
  956. }
  957. virtual IEngineRowAllocator * createRowAllocator(IOutputMetaData * metadata)
  958. {
  959. return ctx->getRowAllocatorEx(metadata, activityId, factory->getHeapFlags());
  960. }
  961. virtual IEngineRowAllocator * createRowAllocatorEx(IOutputMetaData * metadata, roxiemem::RoxieHeapFlags extraFlags)
  962. {
  963. return ctx->getRowAllocatorEx(metadata, activityId, (roxiemem::RoxieHeapFlags)(factory->getHeapFlags()|extraFlags));
  964. }
  965. inline ICodeContext *queryCodeContext()
  966. {
  967. return ctx->queryCodeContext();
  968. }
  969. // MORE - most of this is copied from ccd.hpp - can't we refactor?
  970. virtual void CTXLOGa(TracingCategory category, const char *prefix, const char *text) const
  971. {
  972. if (ctx)
  973. ctx->CTXLOGa(category, prefix, text);
  974. else
  975. DBGLOG("[%s] %s", prefix, text);
  976. }
  977. virtual void CTXLOGaeva(IException *E, const char *file, unsigned line, const char *prefix, const char *format, va_list args) const __attribute__((format(printf,6,0)))
  978. {
  979. if (ctx)
  980. ctx->CTXLOGaeva(E, file, line, prefix, format, args);
  981. else
  982. {
  983. StringBuffer ss;
  984. ss.appendf("[%s] ERROR", prefix);
  985. if (E)
  986. ss.append(": ").append(E->errorCode());
  987. if (file)
  988. ss.appendf(": %s(%d) ", file, line);
  989. if (E)
  990. E->errorMessage(ss.append(": "));
  991. if (format)
  992. {
  993. ss.append(": ").valist_appendf(format, args);
  994. }
  995. LOG(MCoperatorProgress, unknownJob, "%s", ss.str());
  996. }
  997. }
  998. virtual void CTXLOGl(LogItem *log) const
  999. {
  1000. if (ctx)
  1001. ctx->CTXLOGl(log);
  1002. else
  1003. {
  1004. assert(ctx);
  1005. log->Release(); // Should never happen
  1006. }
  1007. }
  1008. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value) const
  1009. {
  1010. stats.addStatistic(kind, value);
  1011. }
  1012. virtual void mergeStats(const CRuntimeStatisticCollection &from) const
  1013. {
  1014. stats.merge(from);
  1015. }
  1016. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  1017. {
  1018. merged.merge(stats);
  1019. if (rowAllocator)
  1020. rowAllocator->gatherStats(merged);
  1021. totalCycles.addStatistics(merged);
  1022. merged.mergeStatistic(StCycleLocalExecuteCycles, queryLocalCycles());
  1023. }
  1024. virtual StringBuffer &getLogPrefix(StringBuffer &ret) const
  1025. {
  1026. if (ctx)
  1027. ctx->getLogPrefix(ret);
  1028. return ret.append('@').append(activityId);
  1029. }
  1030. virtual bool isIntercepted() const
  1031. {
  1032. return ctx ? ctx->isIntercepted() : false;
  1033. }
  1034. virtual bool isBlind() const
  1035. {
  1036. return ctx ? ctx->isBlind() : blindLogging;
  1037. }
  1038. virtual unsigned queryTraceLevel() const
  1039. {
  1040. if (ctx)
  1041. return ctx->queryTraceLevel();
  1042. else
  1043. return traceLevel;
  1044. }
  1045. virtual bool isPassThrough()
  1046. {
  1047. return false;
  1048. }
  1049. virtual const IResolvedFile *resolveLFN(const char *filename, bool isOpt)
  1050. {
  1051. return ctx->resolveLFN(filename, isOpt);
  1052. }
  1053. virtual const IResolvedFile *queryVarFileInfo() const
  1054. {
  1055. throwUnexpected(); // should be implemented in more derived class by anyone that has a remote adaptor
  1056. return NULL;
  1057. }
  1058. virtual void serializeSkipInfo(MemoryBuffer &out, unsigned seekLen, const void *rawSeek, unsigned numFields, const void * seek, const SmartStepExtra &stepExtra) const
  1059. {
  1060. throwUnexpected(); // should be implemented in more derived class wherever needed
  1061. }
  1062. virtual IRoxieSlaveContext *queryContext()
  1063. {
  1064. return ctx;
  1065. }
  1066. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { assertex(whichInput==0); return this; }
  1067. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { assertex(idx==0); return junction; }
  1068. virtual IRoxieServerActivity *queryActivity() { return this; }
  1069. virtual IIndexReadActivityInfo *queryIndexReadActivity() { return NULL; }
  1070. virtual bool needsAllocator() const { return false; }
  1071. void _onCreate(IHThorArg *_colocalParent, unsigned _numParallel)
  1072. {
  1073. colocalParent = _colocalParent;
  1074. createPending = true;
  1075. if (needsAllocator())
  1076. ensureRowAllocator();
  1077. processed = 0;
  1078. if (factory)
  1079. factory->onCreateChildQueries(ctx, &basehelper, childGraphs, this, probeManager, *this, _numParallel);
  1080. if (ctx)
  1081. timeActivities = ctx->queryOptions().timeActivities;
  1082. }
  1083. virtual void onCreate(IHThorArg *_colocalParent)
  1084. {
  1085. _onCreate(_colocalParent, 1);
  1086. }
  1087. virtual void serializeCreateStartContext(MemoryBuffer &out)
  1088. {
  1089. //This should only be called after onStart has been called on the helper
  1090. assertex(!createPending);
  1091. assertex(state==STATEstarted);
  1092. unsigned startlen = out.length();
  1093. basehelper.serializeCreateContext(out);
  1094. basehelper.serializeStartContext(out);
  1095. if (queryTraceLevel() > 10)
  1096. CTXLOG("serializeCreateStartContext for %d added %d bytes", activityId, out.length()-startlen);
  1097. }
  1098. virtual void serializeExtra(MemoryBuffer &out) {}
  1099. inline void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  1100. {
  1101. CriticalBlock cb(statecrit);
  1102. if (state != STATEreset && state != STATEstarting)
  1103. {
  1104. CTXLOG("STATE: Expected state to be reset, but was %s, in activity %d", queryStateText(state), activityId);
  1105. }
  1106. state=STATEstarted;
  1107. #ifdef TRACE_STARTSTOP
  1108. if (traceStartStop)
  1109. {
  1110. CTXLOG("start %p %d", this, activityId);
  1111. if (watchActivityId && watchActivityId==activityId)
  1112. {
  1113. CTXLOG("WATCH: start %p %d", this, activityId);
  1114. }
  1115. }
  1116. #endif
  1117. executeDependencies(parentExtractSize, parentExtract, 0);
  1118. if (input)
  1119. input->start(parentExtractSize, parentExtract, paused);
  1120. ensureCreated();
  1121. basehelper.onStart(parentExtract, NULL);
  1122. if (factory)
  1123. factory->noteStarted();
  1124. startJunction(junction);
  1125. }
  1126. void executeDependencies(unsigned parentExtractSize, const byte *parentExtract, unsigned controlId)
  1127. {
  1128. //MORE: Create a filtered list and then use asyncfor
  1129. ForEachItemIn(idx, dependencies)
  1130. {
  1131. if (dependencyControlIds.item(idx) == controlId)
  1132. dependencies.item(idx).execute(parentExtractSize, parentExtract);
  1133. }
  1134. }
  1135. void stopDependencies(unsigned parentExtractSize, const byte *parentExtract, unsigned controlId)
  1136. {
  1137. ForEachItemIn(idx, dependencies)
  1138. {
  1139. if (dependencyControlIds.item(idx) == controlId)
  1140. dependencies.item(idx).stop();
  1141. }
  1142. }
  1143. virtual unsigned __int64 queryTotalCycles() const
  1144. {
  1145. return totalCycles.totalCycles;
  1146. }
  1147. virtual unsigned __int64 queryLocalCycles() const
  1148. {
  1149. __int64 ret = totalCycles.totalCycles;
  1150. if (input) ret -= input->queryTotalCycles();
  1151. if (ret < 0)
  1152. ret = 0;
  1153. return ret;
  1154. }
  1155. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  1156. {
  1157. if (idx==0)
  1158. return input;
  1159. else
  1160. return NULL;
  1161. }
  1162. inline void ensureCreated()
  1163. {
  1164. if (createPending)
  1165. {
  1166. createPending = false;
  1167. interceptedCtx.set(ctx->queryCodeContext());
  1168. basehelper.onCreate(&interceptedCtx, colocalParent, NULL);
  1169. }
  1170. }
  1171. virtual void stop()
  1172. {
  1173. // NOTE - don't be tempted to skip the stop for activities that are reset - splitters need to see the stops
  1174. if (state != STATEstopped)
  1175. {
  1176. CriticalBlock cb(statecrit);
  1177. if (state != STATEstopped)
  1178. {
  1179. #ifdef TRACE_STARTSTOP
  1180. if (traceStartStop)
  1181. {
  1182. CTXLOG("stop %p %d (state currently %s)", this, activityId, queryStateText(state));
  1183. if (watchActivityId && watchActivityId==activityId)
  1184. {
  1185. CTXLOG("WATCH: stop %p %d", this, activityId);
  1186. }
  1187. }
  1188. #endif
  1189. state=STATEstopped;
  1190. // NOTE - this is needed to ensure that dependencies which were not used are properly stopped
  1191. ForEachItemIn(idx, dependencies)
  1192. {
  1193. if (dependencyControlIds.item(idx) == 0)
  1194. dependencies.item(idx).stopSink(dependencyIndexes.item(idx));
  1195. }
  1196. if (inputStream)
  1197. inputStream->stop();
  1198. }
  1199. }
  1200. }
  1201. virtual void abort()
  1202. {
  1203. aborted = true;
  1204. // MORE - should abort dependencies here?
  1205. stop();
  1206. }
  1207. inline void reset()
  1208. {
  1209. if (state != STATEreset)
  1210. {
  1211. CriticalBlock cb(statecrit);
  1212. if (state != STATEreset)
  1213. {
  1214. if (state==STATEstarted || state==STATEstarting)
  1215. {
  1216. if (ctx->queryOptions().failOnLeaks)
  1217. throw makeStringExceptionV(ROXIE_INTERNAL_ERROR, "STATE: activity %d reset without stop", activityId);
  1218. if (traceStartStop || traceLevel > 2)
  1219. CTXLOG("STATE: activity %d reset without stop", activityId);
  1220. stop();
  1221. }
  1222. state = STATEreset;
  1223. #ifdef TRACE_STARTSTOP
  1224. if (traceStartStop)
  1225. {
  1226. CTXLOG("reset %p %d", this, activityId);
  1227. if (watchActivityId && watchActivityId==activityId)
  1228. {
  1229. CTXLOG("WATCH: reset %p %d", this, activityId);
  1230. }
  1231. }
  1232. #endif
  1233. resetJunction(junction);
  1234. ForEachItemIn(idx, dependencies)
  1235. dependencies.item(idx).reset();
  1236. if (input)
  1237. input->reset();
  1238. }
  1239. }
  1240. aborted = false;
  1241. }
  1242. virtual void addDependency(IRoxieServerActivity &source, unsigned sourceIdx, int controlId)
  1243. {
  1244. dependencies.append(source);
  1245. dependencyIndexes.append(sourceIdx);
  1246. dependencyControlIds.append(controlId);
  1247. }
  1248. virtual void resetEOF()
  1249. {
  1250. //would make more sense if the default implementation (and eof member) were in the base class
  1251. }
  1252. // Sink activities should override this....
  1253. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  1254. {
  1255. throw MakeStringException(ROXIE_SINK, "Internal error: execute() requires a sink");
  1256. }
  1257. virtual void executeChild(size32_t & retSize, void * & ret, unsigned parentExtractSize, const byte * parentExtract)
  1258. {
  1259. throw MakeStringException(ROXIE_SINK, "Internal error: executeChild() requires a suitable sink");
  1260. }
  1261. virtual void stopSink(unsigned idx)
  1262. {
  1263. throw MakeStringException(ROXIE_SINK, "Internal error: stopSink() requires a suitable sink");
  1264. }
  1265. virtual void connectInputStreams(bool consumerOrdered)
  1266. {
  1267. if (input && !inputStream)
  1268. inputStream = connectSingleStream(ctx, input, sourceIdx, junction, isInputOrdered(consumerOrdered, 0));
  1269. if (!connected)
  1270. {
  1271. connectDependencies();
  1272. connected = true;
  1273. }
  1274. }
  1275. void connectDependencies()
  1276. {
  1277. ForEachItemIn(i, dependencies)
  1278. dependencies.item(i).connectInputStreams(true);
  1279. }
  1280. virtual __int64 evaluate()
  1281. {
  1282. throw MakeStringException(ROXIE_SINK, "Internal error: evaluate() requires a function");
  1283. }
  1284. virtual IFinalRoxieInput * querySelectOutput(unsigned id)
  1285. {
  1286. return NULL;
  1287. }
  1288. virtual bool querySetStreamInput(unsigned id, unsigned _sourceIdx, IFinalRoxieInput * _input)
  1289. {
  1290. return false;
  1291. }
  1292. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  1293. {
  1294. assertex(!idx);
  1295. input = _in;
  1296. sourceIdx = _sourceIdx;
  1297. inputStream = NULL;
  1298. }
  1299. bool isInputOrdered(bool consumerOrdered, unsigned idx) const
  1300. {
  1301. if (!factory)
  1302. return true;
  1303. //Grouping implies the stream processing must be ordered - I think this always applies
  1304. IFinalRoxieInput * curInput = queryInput(idx);
  1305. if (curInput && curInput->queryOutputMeta()->isGrouped())
  1306. return true;
  1307. return factory->isInputOrdered(consumerOrdered, idx);
  1308. }
  1309. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  1310. {
  1311. assertex(!idx);
  1312. // By default, activities are assumed NOT to support streams
  1313. bool inputOrdered = isInputOrdered(consumerOrdered, 0);
  1314. connectInputStreams(inputOrdered);
  1315. // Return a single stream
  1316. streams.append(this);
  1317. return NULL;
  1318. }
  1319. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  1320. {
  1321. if (idx == (unsigned) -1)
  1322. idx = 0;
  1323. return idx ? NULL : this;
  1324. }
  1325. virtual IOutputMetaData *queryOutputMeta() const
  1326. {
  1327. return meta.queryOriginal();
  1328. }
  1329. virtual unsigned queryId() const
  1330. {
  1331. return activityId;
  1332. }
  1333. virtual unsigned querySubgraphId() const
  1334. {
  1335. return factory->querySubgraphId();
  1336. }
  1337. virtual void checkAbort()
  1338. {
  1339. ctx->checkAbort();
  1340. }
  1341. IException *makeWrappedException(IException *e)
  1342. {
  1343. StringBuffer msg;
  1344. ThorActivityKind activityKind = factory ? factory->getKind() : TAKnone;
  1345. CTXLOG("makeWrappedException - %s (in %s %d)", e->errorMessage(msg).str(), getActivityText(activityKind), activityId);
  1346. if (QUERYINTERFACE(e, CWrappedException) || QUERYINTERFACE(e, IUserException))
  1347. return e;
  1348. else
  1349. return new CWrappedException(e, activityKind, activityId);
  1350. }
  1351. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract)
  1352. {
  1353. }
  1354. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract, IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes)
  1355. {
  1356. }
  1357. virtual void resetOutputsUsed()
  1358. {
  1359. }
  1360. virtual void noteOutputUsed()
  1361. {
  1362. }
  1363. virtual IRoxieServerSideCache *queryServerSideCache() const
  1364. {
  1365. return factory->queryServerSideCache();
  1366. }
  1367. virtual const IRoxieServerActivityFactory *queryFactory() const
  1368. {
  1369. return factory;
  1370. }
  1371. inline ThorActivityKind getKind() const
  1372. {
  1373. return factory->getKind();
  1374. }
  1375. inline bool isSink() const
  1376. {
  1377. return (factory != NULL) && factory->isSink();
  1378. }
  1379. };
  1380. //=====================================================================================================
  1381. class CRoxieServerLateStartActivity : public CRoxieServerActivity
  1382. {
  1383. protected:
  1384. bool prefiltered;
  1385. bool eof;
  1386. void lateStart(unsigned parentExtractSize, const byte *parentExtract, bool any)
  1387. {
  1388. prefiltered = !any;
  1389. eof = prefiltered;
  1390. if (!prefiltered)
  1391. {
  1392. input->start(parentExtractSize, parentExtract, false);
  1393. startJunction(junction);
  1394. }
  1395. else
  1396. {
  1397. if (traceStartStop)
  1398. CTXLOG("lateStart activity stopping input early as prefiltered");
  1399. inputStream->stop();
  1400. }
  1401. }
  1402. public:
  1403. CRoxieServerLateStartActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  1404. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  1405. {
  1406. prefiltered = false;
  1407. eof = false;
  1408. }
  1409. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  1410. {
  1411. IFinalRoxieInput *saveInput = input;
  1412. Owned<IStrandJunction> saveJunction = junction.getClear();
  1413. input = NULL; // Make sure parent does not start the chain yet
  1414. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  1415. input = saveInput;
  1416. junction.setown(saveJunction.getClear());
  1417. }
  1418. virtual void stop()
  1419. {
  1420. if (!prefiltered)
  1421. {
  1422. inputStream->stop();
  1423. }
  1424. else if (traceStartStop)
  1425. CTXLOG("lateStart activity NOT stopping input late as prefiltered");
  1426. IEngineRowStream *save = inputStream;
  1427. inputStream = NULL; // We already stopped inputStream - prevent parent from doing so again
  1428. CRoxieServerActivity::stop();
  1429. inputStream = save;
  1430. }
  1431. virtual void reset()
  1432. {
  1433. CRoxieServerActivity::reset();
  1434. prefiltered = false;
  1435. }
  1436. };
  1437. //=================================================================================
  1438. class StrandOptions
  1439. {
  1440. // Typically set from hints, common to many stranded activities
  1441. public:
  1442. explicit StrandOptions(IPropertyTree &_graphNode)
  1443. {
  1444. //PARALLEL(1) can be used to explicitly disable parallel processing.
  1445. numStrands = _graphNode.getPropInt("att[@name='parallel']/@value", 0);
  1446. if ((numStrands == minus1U) || (numStrands > MAX_SENSIBLE_STRANDS))
  1447. numStrands = getAffinityCpus();
  1448. blockSize = _graphNode.getPropInt("hint[@name='strandblocksize']/@value", 0);
  1449. }
  1450. StrandOptions(const StrandOptions &from, IRoxieSlaveContext *ctx)
  1451. {
  1452. numStrands = from.numStrands;
  1453. blockSize = from.blockSize;
  1454. if (!blockSize)
  1455. blockSize = ctx->queryOptions().strandBlockSize;
  1456. if (numStrands == 0)
  1457. numStrands = ctx->queryOptions().forceNumStrands;
  1458. }
  1459. public:
  1460. unsigned numStrands = 0; // if 1 it forces single-stranded operations. (Useful for testing.)
  1461. unsigned blockSize = 0;
  1462. };
  1463. class StrandProcessor : public CInterfaceOf<IEngineRowStream>
  1464. {
  1465. protected:
  1466. CRoxieServerActivity &parent;
  1467. IEngineRowAllocator *rowAllocator;
  1468. IEngineRowStream *inputStream;
  1469. ActivityTimeAccumulator totalCycles;
  1470. mutable CRuntimeStatisticCollection stats;
  1471. unsigned processed = 0;
  1472. unsigned numProcessedLastGroup = 0;
  1473. const bool timeActivities;
  1474. bool stopped = false;
  1475. std::atomic<bool> abortRequested;
  1476. public:
  1477. explicit StrandProcessor(CRoxieServerActivity &_parent, IEngineRowStream *_inputStream, bool needsAllocator)
  1478. : parent(_parent), inputStream(_inputStream), stats(parent.queryStatsMapping()), timeActivities(_parent.timeActivities), abortRequested(false)
  1479. {
  1480. if (needsAllocator)
  1481. {
  1482. rowAllocator = parent.createRowAllocatorEx(parent.queryOutputMeta(), roxiemem::RHFunique);
  1483. }
  1484. else
  1485. rowAllocator = NULL;
  1486. }
  1487. ~StrandProcessor()
  1488. {
  1489. ::Release(rowAllocator);
  1490. }
  1491. virtual void start()
  1492. {
  1493. processed = 0;
  1494. numProcessedLastGroup = 0;
  1495. totalCycles.reset();
  1496. }
  1497. virtual void stop()
  1498. {
  1499. if (!stopped)
  1500. {
  1501. if (inputStream)
  1502. inputStream->stop();
  1503. parent.stop();
  1504. //It would be preferrable to move totalCycles (+processed?) to gatherStats(), but because of
  1505. //the way firstRow is associated with startCycles it would require an extra parameter
  1506. //which is not consistent with the other gatherStats() calls, or extra logic in the stats classes.
  1507. parent.mergeStrandStats(processed, totalCycles);
  1508. }
  1509. stopped = true;
  1510. }
  1511. virtual void reset()
  1512. {
  1513. stopped = false;
  1514. abortRequested.store(false, std::memory_order_relaxed);
  1515. }
  1516. virtual void resetEOF()
  1517. {
  1518. inputStream->resetEOF();
  1519. }
  1520. inline void requestAbort() { abortRequested.store(true, std::memory_order_relaxed); }
  1521. inline bool isAborting() { return abortRequested.load(std::memory_order_relaxed); }
  1522. void gatherStats(CRuntimeStatisticCollection & mergedStats) const
  1523. {
  1524. mergedStats.merge(stats);
  1525. if (rowAllocator)
  1526. rowAllocator->gatherStats(mergedStats);
  1527. }
  1528. };
  1529. class CRoxieServerStrandedActivity : public CRoxieServerActivity
  1530. {
  1531. protected:
  1532. StrandOptions strandOptions;
  1533. IArrayOf<StrandProcessor> strands;
  1534. Owned<IStrandBranch> branch;
  1535. Owned<IStrandJunction> splitter;
  1536. Owned<IStrandJunction> sourceJunction; // A junction applied to the output of a source activity
  1537. std::atomic<unsigned> active;
  1538. public:
  1539. CRoxieServerStrandedActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const StrandOptions &_strandOptions)
  1540. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  1541. strandOptions(_strandOptions, ctx)
  1542. {
  1543. active = 0;
  1544. }
  1545. ~CRoxieServerStrandedActivity()
  1546. {
  1547. if (strands.ordinality() > 1)
  1548. {
  1549. if (factory && !debugging)
  1550. factory->noteProcessed(0, processed);
  1551. if (ctx && factory)
  1552. ctx->noteProcessed(factory->querySubgraphId(), activityId, 0, processed, strands.ordinality());
  1553. processed = 0; // To avoid reprocessing in base destructor
  1554. }
  1555. }
  1556. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  1557. {
  1558. CRoxieServerActivity::gatherStats(merged);
  1559. ForEachItemIn(i, strands)
  1560. strands.item(i).gatherStats(merged);
  1561. }
  1562. virtual void onCreate(IHThorArg *_colocalArg)
  1563. {
  1564. CRoxieServerActivity::_onCreate(_colocalArg, strands.ordinality());
  1565. }
  1566. //This function is pure (But also implemented out of line) to force the derived classes to implement it.
  1567. //After calling the base class start method, and initialising any values from the helper they must call onStartStrands(),
  1568. //this must also happen before any rows are read from the strands (e.g., by a source junction)
  1569. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused) = 0;
  1570. virtual void reset()
  1571. {
  1572. assertex(active==0);
  1573. ForEachItemIn(idx, strands)
  1574. strands.item(idx).reset();
  1575. resetJunction(splitter);
  1576. CRoxieServerActivity::reset();
  1577. resetJunction(sourceJunction);
  1578. }
  1579. virtual void stop()
  1580. {
  1581. // Called from the strands... which should ensure that stop is not called more than once per strand
  1582. //The first strand to call
  1583. if (active)
  1584. --active;
  1585. if (!active)
  1586. CRoxieServerActivity::stop();
  1587. }
  1588. void requestAbort()
  1589. {
  1590. ForEachItemIn(idx, strands)
  1591. strands.item(idx).requestAbort();
  1592. }
  1593. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  1594. {
  1595. assertex(idx == 0);
  1596. assertex(strands.empty());
  1597. CRoxieServerActivity::connectDependencies();
  1598. bool inputOrdered = isInputOrdered(consumerOrdered, idx);
  1599. //Note, numStrands == 1 is an explicit request to disable threading
  1600. if (consumerOptions && (consumerOptions->numStrands != 1) && (strandOptions.numStrands != 1))
  1601. {
  1602. //Check to see if the consumer's settings should override
  1603. if (strandOptions.numStrands == 0)
  1604. {
  1605. strandOptions.numStrands = consumerOptions->numStrands;
  1606. strandOptions.blockSize = consumerOptions->blockSize;
  1607. }
  1608. else if (consumerOptions->numStrands > strandOptions.numStrands)
  1609. {
  1610. strandOptions.numStrands = consumerOptions->numStrands;
  1611. }
  1612. }
  1613. Owned <IStrandJunction> recombiner;
  1614. if (input)
  1615. {
  1616. if (strandOptions.numStrands == 1)
  1617. {
  1618. // 1 means explicitly requested single-strand.
  1619. IEngineRowStream *instream = connectSingleStream(ctx, input, sourceIdx, junction, inputOrdered);
  1620. strands.append(*createStrandProcessor(instream));
  1621. }
  1622. else
  1623. {
  1624. PointerArrayOf<IEngineRowStream> instreams;
  1625. recombiner.setown(input->getOutputStreams(ctx, sourceIdx, instreams, &strandOptions, inputOrdered, orderedCallbacks));
  1626. if ((instreams.length() == 1) && (strandOptions.numStrands != 0)) // 0 means did not specify - we should use the strands that our upstream provides
  1627. {
  1628. assertex(recombiner == NULL);
  1629. // Create a splitter to split the input into n... and a recombiner if need to preserve sorting
  1630. if (inputOrdered)
  1631. {
  1632. branch.setown(createStrandBranch(ctx->queryRowManager(), strandOptions.numStrands, strandOptions.blockSize, true, input->queryOutputMeta()->isGrouped(), false, orderedCallbacks));
  1633. splitter.set(branch->queryInputJunction());
  1634. recombiner.set(branch->queryOutputJunction());
  1635. }
  1636. else
  1637. {
  1638. splitter.setown(createStrandJunction(ctx->queryRowManager(), 1, strandOptions.numStrands, strandOptions.blockSize, false));
  1639. }
  1640. splitter->setInput(0, instreams.item(0));
  1641. for (unsigned strandNo = 0; strandNo < strandOptions.numStrands; strandNo++)
  1642. strands.append(*createStrandProcessor(splitter->queryOutput(strandNo)));
  1643. }
  1644. else
  1645. {
  1646. // Ignore my hint and just use the width already split into...
  1647. ForEachItemIn(strandNo, instreams)
  1648. strands.append(*createStrandProcessor(instreams.item(strandNo)));
  1649. }
  1650. }
  1651. }
  1652. else
  1653. {
  1654. unsigned numStrands = strandOptions.numStrands ? strandOptions.numStrands : 1;
  1655. for (unsigned i=0; i < numStrands; i++)
  1656. strands.append(*createStrandSourceProcessor(inputOrdered));
  1657. if (inputOrdered && (numStrands > 1))
  1658. {
  1659. if (consumerOptions)
  1660. {
  1661. //If the output activities are also stranded then need to create a version of the branch
  1662. bool isGrouped = queryOutputMeta()->isGrouped();
  1663. branch.setown(createStrandBranch(ctx->queryRowManager(), strandOptions.numStrands, strandOptions.blockSize, true, isGrouped, true, orderedCallbacks));
  1664. sourceJunction.set(branch->queryInputJunction());
  1665. recombiner.set(branch->queryOutputJunction());
  1666. assertex((orderedCallbacks && !recombiner) || (!orderedCallbacks && recombiner));
  1667. //This is different from the branch above. The first "junction" has the source activity as the input, and the outputs as the result of the activity
  1668. for (unsigned strandNo = 0; strandNo < strandOptions.numStrands; strandNo++)
  1669. {
  1670. sourceJunction->setInput(strandNo, &strands.item(strandNo));
  1671. streams.append(sourceJunction->queryOutput(strandNo));
  1672. }
  1673. #ifdef TRACE_STRANDS
  1674. if (traceLevel > 2)
  1675. DBGLOG("Executing activity %u with %u strands", activityId, strands.ordinality());
  1676. #endif
  1677. return recombiner.getClear();
  1678. }
  1679. else
  1680. {
  1681. //Feeding into a non threaded activity, so create a M:1 junction to combine the source strands
  1682. recombiner.setown(createStrandJunction(ctx->queryRowManager(), numStrands, 1, strandOptions.blockSize, inputOrdered));
  1683. }
  1684. }
  1685. }
  1686. ForEachItemIn(i, strands)
  1687. streams.append(&strands.item(i));
  1688. #ifdef TRACE_STRANDS
  1689. if (traceLevel > 2)
  1690. DBGLOG("Executing activity %u with %u strands", activityId, strands.ordinality());
  1691. #endif
  1692. return recombiner.getClear();
  1693. }
  1694. virtual StrandProcessor *createStrandProcessor(IEngineRowStream *instream) = 0;
  1695. //MORE: Possibly this class should be split into two for sinks and non sinks...
  1696. virtual StrandProcessor *createStrandSourceProcessor(bool inputOrdered) = 0;
  1697. virtual const void * nextRow()
  1698. {
  1699. throwUnexpected();
  1700. }
  1701. inline unsigned numStrands() const { return strands.ordinality(); }
  1702. protected:
  1703. void onStartStrands()
  1704. {
  1705. ForEachItemIn(idx, strands)
  1706. {
  1707. strands.item(idx).start();
  1708. active++;
  1709. }
  1710. }
  1711. };
  1712. //For some reason gcc doesn't let you specify a function as pure virtual and define it at the same time.
  1713. void CRoxieServerStrandedActivity::start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  1714. {
  1715. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  1716. startJunction(splitter);
  1717. }
  1718. class CRoxieServerStrandedLateStartActivity : public CRoxieServerStrandedActivity
  1719. {
  1720. protected:
  1721. bool prefiltered;
  1722. bool eof;
  1723. void lateStart(unsigned parentExtractSize, const byte *parentExtract, bool any)
  1724. {
  1725. prefiltered = !any;
  1726. eof = prefiltered;
  1727. if (!prefiltered)
  1728. {
  1729. //At this point
  1730. input->start(parentExtractSize, parentExtract, false);
  1731. startJunction(splitter);
  1732. onStartStrands(); // Initialise the strands - the helper will have been correctly initialized by this point.
  1733. startJunction(sourceJunction);
  1734. }
  1735. else
  1736. {
  1737. if (traceStartStop)
  1738. CTXLOG("strandedLateStart activity stopping input early as prefiltered");
  1739. ForEachItemIn(idx, strands)
  1740. strands.item(idx).stop();
  1741. }
  1742. }
  1743. public:
  1744. CRoxieServerStrandedLateStartActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const StrandOptions &_strandOptions)
  1745. : CRoxieServerStrandedActivity(_ctx, _factory, _probeManager, _strandOptions)
  1746. {
  1747. prefiltered = false;
  1748. eof = false;
  1749. }
  1750. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  1751. {
  1752. IFinalRoxieInput *save = input;
  1753. input = NULL; // Make sure parent does not start the chain yet - but we do want to do the dependencies (because the decision about whether to start may depend on them)
  1754. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  1755. input = save;
  1756. }
  1757. virtual void reset()
  1758. {
  1759. CRoxieServerStrandedActivity::reset();
  1760. prefiltered = false;
  1761. }
  1762. };
  1763. //=====================================================================================================
  1764. atomic_t nextInstanceId;
  1765. extern unsigned getNextInstanceId()
  1766. {
  1767. return atomic_add_exchange(&nextInstanceId, 1)+1;
  1768. }
  1769. atomic_t nextRuid;
  1770. ruid_t getNextRuid()
  1771. {
  1772. ruid_t ret = atomic_add_exchange(&nextRuid, 1)+1;
  1773. while (ret < RUID_FIRST)
  1774. ret = atomic_add_exchange(&nextRuid, 1)+1; // ruids 0 and 1 are reserved for pings/unwanted discarder.
  1775. return ret;
  1776. }
  1777. void setStartRuid(unsigned restarts)
  1778. {
  1779. atomic_set(&nextRuid, restarts * 0x10000);
  1780. atomic_set(&nextInstanceId, restarts * 10000);
  1781. }
  1782. enum { LimitSkipErrorCode = 0, KeyedLimitSkipErrorCode = 1 };
  1783. class DECL_EXCEPTION LimitSkipException : public IException, public CInterface
  1784. {
  1785. int code;
  1786. public:
  1787. LimitSkipException(int _code) { code = _code; }
  1788. IMPLEMENT_IINTERFACE;
  1789. virtual int errorCode() const { return code; }
  1790. virtual StringBuffer & errorMessage(StringBuffer &msg) const { return msg.append("LimitSkipException"); }
  1791. virtual MessageAudience errorAudience() const { return MSGAUD_internal; }
  1792. };
  1793. IException *makeLimitSkipException(bool isKeyed)
  1794. {
  1795. // We need to make sure what we throw is IException not something derived from it....
  1796. return new LimitSkipException(isKeyed ? KeyedLimitSkipErrorCode : LimitSkipErrorCode);
  1797. }
  1798. //=================================================================================
  1799. interface IRecordPullerCallback : extends IExceptionHandler
  1800. {
  1801. virtual void processRow(const void *row) = 0;
  1802. virtual void processEOG() = 0;
  1803. virtual void processGroup(const ConstPointerArray &rows) = 0;
  1804. virtual void processDone() = 0;
  1805. };
  1806. class RecordPullerThread : public RestartableThread
  1807. {
  1808. protected:
  1809. IFinalRoxieInput *input;
  1810. Owned<IStrandJunction> junction;
  1811. unsigned sourceIdx = 0;
  1812. IEngineRowStream *inputStream;
  1813. IRecordPullerCallback *helper;
  1814. Semaphore started; // MORE: GH->RKC I'm pretty sure this can be deleted, since handled by RestartableThread
  1815. bool groupAtOnce, eof, eog;
  1816. CriticalSection crit;
  1817. public:
  1818. RecordPullerThread(bool _groupAtOnce)
  1819. : RestartableThread("RecordPullerThread"), groupAtOnce(_groupAtOnce)
  1820. {
  1821. input = NULL;
  1822. inputStream = NULL;
  1823. helper = NULL;
  1824. eof = eog = FALSE;
  1825. }
  1826. inline unsigned __int64 queryTotalCycles() const
  1827. {
  1828. return input->queryTotalCycles();
  1829. }
  1830. void setInput(IRecordPullerCallback *_helper, unsigned _sourceIdx, IFinalRoxieInput *_input)
  1831. {
  1832. helper = _helper;
  1833. input = _input;
  1834. sourceIdx = _sourceIdx;
  1835. }
  1836. IFinalRoxieInput *queryInput() const
  1837. {
  1838. return input;
  1839. }
  1840. virtual void connectInputStreams(IRoxieSlaveContext *ctx, bool consumerOrdered)
  1841. {
  1842. inputStream = connectSingleStream(ctx, input, sourceIdx, junction, consumerOrdered);
  1843. }
  1844. IEngineRowStream *queryStream() const
  1845. {
  1846. return inputStream;
  1847. }
  1848. void start(unsigned parentExtractSize, const byte *parentExtract, bool paused, unsigned preload, bool noThread, IRoxieSlaveContext *ctx)
  1849. {
  1850. eof = false;
  1851. eog = false;
  1852. input->start(parentExtractSize, parentExtract, paused);
  1853. startJunction(junction);
  1854. try
  1855. {
  1856. if (preload && !paused)
  1857. {
  1858. if (traceLevel > 4)
  1859. DBGLOG("Preload fetching first %d records", preload);
  1860. if (groupAtOnce)
  1861. pullGroups(preload);
  1862. else
  1863. pullRecords(preload);
  1864. }
  1865. if (eof)
  1866. {
  1867. if (traceLevel > 4)
  1868. DBGLOG("No need to start puller after preload");
  1869. helper->processDone();
  1870. }
  1871. else
  1872. {
  1873. if (!noThread)
  1874. {
  1875. StringBuffer logPrefix("[");
  1876. if (ctx) ctx->getLogPrefix(logPrefix);
  1877. logPrefix.append("] ");
  1878. RestartableThread::start(logPrefix);
  1879. started.wait();
  1880. }
  1881. }
  1882. }
  1883. catch (IException *e)
  1884. {
  1885. helper->fireException(e);
  1886. }
  1887. catch (...)
  1888. {
  1889. helper->fireException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unexpected exception caught in RecordPullerThread::start"));
  1890. }
  1891. }
  1892. void stop()
  1893. {
  1894. if (traceStartStop)
  1895. DBGLOG("RecordPullerThread::stop");
  1896. {
  1897. 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-nextRow etc etc.
  1898. if (inputStream)
  1899. inputStream->stop();
  1900. }
  1901. RestartableThread::join();
  1902. }
  1903. void reset()
  1904. {
  1905. input->reset();
  1906. resetJunction(junction);
  1907. }
  1908. virtual int run()
  1909. {
  1910. started.signal();
  1911. try
  1912. {
  1913. if (groupAtOnce)
  1914. pullGroups((unsigned) -1);
  1915. else
  1916. pullRecords((unsigned) -1);
  1917. helper->processDone();
  1918. }
  1919. catch (IException *e)
  1920. {
  1921. helper->fireException(e);
  1922. }
  1923. catch (...)
  1924. {
  1925. helper->fireException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unexpected exception caught in RecordPullerThread::run"));
  1926. }
  1927. return 0;
  1928. }
  1929. void done()
  1930. {
  1931. helper->processDone();
  1932. }
  1933. bool pullRecords(unsigned preload)
  1934. {
  1935. if (eof)
  1936. return false;
  1937. while (preload)
  1938. {
  1939. const void * row;
  1940. {
  1941. CriticalBlock c(crit); // See comments in stop for why this is needed
  1942. row = inputStream->nextRow();
  1943. }
  1944. if (row)
  1945. {
  1946. eog = false;
  1947. helper->processRow(row);
  1948. }
  1949. else if (!eog)
  1950. {
  1951. helper->processEOG();
  1952. eog = true;
  1953. }
  1954. else
  1955. {
  1956. eof = true;
  1957. return false;
  1958. }
  1959. if (preload != (unsigned) -1)
  1960. preload--;
  1961. }
  1962. return true;
  1963. }
  1964. void pullGroups(unsigned preload)
  1965. {
  1966. ConstPointerArray thisGroup;
  1967. unsigned rowsDone = 0;
  1968. while (preload && !eof)
  1969. {
  1970. const void *row;
  1971. {
  1972. CriticalBlock c(crit);
  1973. row = inputStream->nextRow();
  1974. }
  1975. if (row)
  1976. {
  1977. thisGroup.append(row);
  1978. rowsDone++;
  1979. }
  1980. else if (thisGroup.length())
  1981. {
  1982. helper->processGroup(thisGroup);
  1983. thisGroup.kill();
  1984. if (preload != (unsigned) -1)
  1985. {
  1986. if (preload > rowsDone)
  1987. preload -= rowsDone;
  1988. else
  1989. break;
  1990. }
  1991. rowsDone = 0;
  1992. }
  1993. else
  1994. {
  1995. eof = true;
  1996. break;
  1997. }
  1998. }
  1999. }
  2000. };
  2001. //=================================================================================
  2002. #define READAHEAD_SIZE 1000
  2003. // MORE - this code copied from ThreadedConcat code - may be able to common up some.
  2004. class CRoxieServerReadAheadInput : implements IEngineRowStream, implements IFinalRoxieInput, implements IRecordPullerCallback, public CInterface
  2005. {
  2006. QueueOf<const void, true> buffer;
  2007. InterruptableSemaphore ready;
  2008. InterruptableSemaphore space;
  2009. CriticalSection crit;
  2010. bool eof;
  2011. bool disabled;
  2012. IRoxieSlaveContext *ctx;
  2013. RecordPullerThread puller;
  2014. unsigned preload;
  2015. cycle_t totalCycles;
  2016. bool timeActivities;
  2017. public:
  2018. IMPLEMENT_IINTERFACE;
  2019. CRoxieServerReadAheadInput(IRoxieSlaveContext *_ctx, unsigned _preload) : ctx(_ctx), puller(true), preload(_preload)
  2020. {
  2021. eof = false;
  2022. disabled = (ctx->queryDebugContext() != NULL);
  2023. totalCycles = 0;
  2024. timeActivities = ctx->queryOptions().timeActivities;
  2025. }
  2026. virtual IRoxieServerActivity *queryActivity()
  2027. {
  2028. return puller.queryInput()->queryActivity();
  2029. }
  2030. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  2031. {
  2032. assertex(!idx);
  2033. puller.connectInputStreams(ctx, consumerOrdered);
  2034. streams.append(this);
  2035. return NULL;
  2036. }
  2037. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { return this; }
  2038. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { return nullptr; }
  2039. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  2040. {
  2041. return puller.queryInput()->queryIndexReadActivity();
  2042. }
  2043. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  2044. {
  2045. eof = false;
  2046. if (disabled)
  2047. puller.queryInput()->start(parentExtractSize, parentExtract, paused);
  2048. else
  2049. {
  2050. space.reinit(READAHEAD_SIZE);
  2051. ready.reinit();
  2052. puller.start(parentExtractSize, parentExtract, paused, preload, false, ctx);
  2053. }
  2054. }
  2055. virtual void stop()
  2056. {
  2057. if (disabled)
  2058. puller.queryStream()->stop();
  2059. else
  2060. {
  2061. space.interrupt();
  2062. ready.interrupt();
  2063. puller.stop();
  2064. }
  2065. }
  2066. virtual void reset()
  2067. {
  2068. if (disabled)
  2069. puller.queryInput()->reset();
  2070. else
  2071. {
  2072. puller.reset();
  2073. ForEachItemIn(idx1, buffer)
  2074. ReleaseRoxieRow(buffer.item(idx1));
  2075. buffer.clear();
  2076. }
  2077. }
  2078. virtual void resetEOF()
  2079. {
  2080. throwUnexpected();
  2081. }
  2082. virtual IOutputMetaData * queryOutputMeta() const
  2083. {
  2084. return puller.queryInput()->queryOutputMeta();
  2085. }
  2086. void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  2087. {
  2088. assertex(!idx);
  2089. puller.setInput(this, _sourceIdx, _in);
  2090. }
  2091. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  2092. {
  2093. if (idx==0)
  2094. return puller.queryInput();
  2095. else
  2096. return NULL;
  2097. }
  2098. virtual unsigned __int64 queryTotalCycles() const
  2099. {
  2100. return totalCycles;
  2101. }
  2102. virtual const void * nextRow()
  2103. {
  2104. SimpleActivityTimer t(totalCycles, timeActivities);
  2105. if (disabled)
  2106. return puller.queryStream()->nextRow();
  2107. else
  2108. {
  2109. for (;;)
  2110. {
  2111. {
  2112. CriticalBlock b(crit);
  2113. if (eof && !buffer.ordinality())
  2114. return NULL; // eof
  2115. }
  2116. ready.wait();
  2117. const void *ret;
  2118. {
  2119. CriticalBlock b(crit);
  2120. ret = buffer.dequeue();
  2121. }
  2122. space.signal();
  2123. return ret;
  2124. }
  2125. }
  2126. }
  2127. virtual bool fireException(IException *e)
  2128. {
  2129. // called from puller thread on failure
  2130. ready.interrupt(LINK(e));
  2131. space.interrupt(e);
  2132. return true;
  2133. }
  2134. virtual void processRow(const void *row)
  2135. {
  2136. {
  2137. CriticalBlock b(crit);
  2138. buffer.enqueue(row);
  2139. }
  2140. ready.signal();
  2141. space.wait();
  2142. }
  2143. virtual void processGroup(const ConstPointerArray &rows)
  2144. {
  2145. // NOTE - a bit bizarre in that it waits for the space AFTER using it.
  2146. // But the space semaphore is only there to stop infinite readahead. And otherwise it would deadlock
  2147. // if group was larger than max(space)
  2148. {
  2149. CriticalBlock b(crit);
  2150. ForEachItemIn(idx, rows)
  2151. buffer.enqueue(rows.item(idx));
  2152. buffer.enqueue(NULL);
  2153. }
  2154. for (unsigned i2 = 0; i2 <= rows.length(); i2++) // note - does 1 extra for the null
  2155. {
  2156. ready.signal();
  2157. space.wait();
  2158. }
  2159. }
  2160. virtual void processEOG()
  2161. {
  2162. // Used when output is not grouped - just ignore
  2163. }
  2164. virtual void processDone()
  2165. {
  2166. CriticalBlock b(crit);
  2167. eof = true;
  2168. ready.signal();
  2169. }
  2170. };
  2171. //=================================================================================
  2172. class CRoxieServerTwoInputActivity : public CRoxieServerActivity
  2173. {
  2174. protected:
  2175. IFinalRoxieInput *input1;
  2176. IEngineRowStream *inputStream1;
  2177. Owned<IStrandJunction> junction1;
  2178. unsigned sourceIdx1 = 0;
  2179. Owned<CRoxieServerReadAheadInput> puller;
  2180. public:
  2181. CRoxieServerTwoInputActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  2182. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  2183. {
  2184. input1 = NULL;
  2185. inputStream1 = NULL;
  2186. }
  2187. ~CRoxieServerTwoInputActivity()
  2188. {
  2189. }
  2190. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  2191. {
  2192. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  2193. input1->start(parentExtractSize, parentExtract, paused);
  2194. startJunction(junction1);
  2195. }
  2196. virtual void stop()
  2197. {
  2198. inputStream1->stop();
  2199. CRoxieServerActivity::stop();
  2200. }
  2201. virtual unsigned __int64 queryLocalCycles() const
  2202. {
  2203. __int64 ret;
  2204. __int64 inputCycles = input->queryTotalCycles();
  2205. __int64 input1Cycles = input1->queryTotalCycles();
  2206. if (puller)
  2207. ret = totalCycles.totalCycles - (inputCycles > input1Cycles ? inputCycles : input1Cycles);
  2208. else
  2209. ret = totalCycles.totalCycles - (inputCycles + input1Cycles);
  2210. if (ret < 0)
  2211. ret = 0;
  2212. return ret;
  2213. }
  2214. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  2215. {
  2216. switch (idx)
  2217. {
  2218. case 0:
  2219. return input;
  2220. case 1:
  2221. return input1;
  2222. default:
  2223. return NULL;
  2224. }
  2225. }
  2226. virtual void reset()
  2227. {
  2228. CRoxieServerActivity::reset();
  2229. if (input1)
  2230. input1->reset();
  2231. resetJunction(junction1);
  2232. }
  2233. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  2234. {
  2235. switch(idx)
  2236. {
  2237. case 0:
  2238. CRoxieServerActivity::setInput(idx, _sourceIdx, _in);
  2239. break;
  2240. case 1:
  2241. input1 = _in;
  2242. sourceIdx1 = _sourceIdx;
  2243. break;
  2244. default:
  2245. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
  2246. }
  2247. }
  2248. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  2249. {
  2250. inputStream1 = connectSingleStream(ctx, input1, sourceIdx1, junction1, isInputOrdered(consumerOrdered, 1));
  2251. //Assumes input1 will be stranded if any.
  2252. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
  2253. }
  2254. };
  2255. //=================================================================================
  2256. class CRoxieServerMultiInputBaseActivity : public CRoxieServerActivity
  2257. {
  2258. protected:
  2259. unsigned numInputs;
  2260. unsigned numStreams;
  2261. IFinalRoxieInput **inputArray;
  2262. unsigned *sourceIdxArray;
  2263. IEngineRowStream **streamArray;
  2264. Owned<IStrandJunction> *junctionArray;
  2265. public:
  2266. CRoxieServerMultiInputBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  2267. : CRoxieServerActivity(_ctx, _factory, _probeManager), numInputs(_numInputs)
  2268. {
  2269. numStreams = numInputs;
  2270. inputArray = new IFinalRoxieInput*[numInputs];
  2271. sourceIdxArray = new unsigned[numInputs];
  2272. streamArray = new IEngineRowStream*[numStreams];
  2273. junctionArray = new Owned<IStrandJunction>[numStreams];
  2274. for (unsigned i1 = 0; i1 < numInputs; i1++)
  2275. {
  2276. inputArray[i1] = NULL;
  2277. sourceIdxArray[i1] = 0;
  2278. }
  2279. for (unsigned i2 = 0; i2 < numStreams; i2++)
  2280. streamArray[i2] = NULL;
  2281. }
  2282. ~CRoxieServerMultiInputBaseActivity()
  2283. {
  2284. delete [] inputArray;
  2285. delete [] sourceIdxArray;
  2286. delete [] streamArray;
  2287. delete [] junctionArray;
  2288. }
  2289. virtual unsigned __int64 queryLocalCycles() const
  2290. {
  2291. __int64 localCycles = totalCycles.totalCycles;
  2292. for (unsigned i = 0; i < numInputs; i++)
  2293. localCycles -= inputArray[i]->queryTotalCycles();
  2294. if (localCycles < 0)
  2295. localCycles = 0;
  2296. return localCycles;
  2297. }
  2298. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  2299. {
  2300. if (idx < numInputs)
  2301. return inputArray[idx];
  2302. else
  2303. return NULL;
  2304. }
  2305. virtual IFinalRoxieInput * queryConcreteInput(unsigned idx)
  2306. {
  2307. return queryInput(idx);
  2308. }
  2309. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput)
  2310. {
  2311. if (whichInput < numInputs)
  2312. return streamArray[whichInput];
  2313. else
  2314. return NULL;
  2315. }
  2316. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const
  2317. {
  2318. if (idx < numInputs)
  2319. return junctionArray[idx];
  2320. else
  2321. return NULL;
  2322. }
  2323. virtual void reset()
  2324. {
  2325. for (unsigned i = 0; i < numInputs; i++)
  2326. inputArray[i]->reset();
  2327. for (unsigned iS = 0; iS < numStreams; iS++)
  2328. {
  2329. resetJunction(junctionArray[iS]);
  2330. }
  2331. CRoxieServerActivity::reset();
  2332. }
  2333. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  2334. {
  2335. assertex(idx < numInputs && idx < numStreams);
  2336. inputArray[idx] = _in;
  2337. sourceIdxArray[idx] = _sourceIdx;
  2338. }
  2339. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  2340. {
  2341. //There could be situations (e.g., NONEMPTY), where you might want to strand the activity.
  2342. for (unsigned i = 0; i < numInputs; i++)
  2343. streamArray[i] = connectSingleStream(ctx, inputArray[i], sourceIdxArray[i], junctionArray[i], consumerOrdered);
  2344. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, NULL, consumerOrdered, nullptr); // The input basesclass does not have an input
  2345. }
  2346. };
  2347. //=================================================================================
  2348. class CRoxieServerMultiInputActivity : public CRoxieServerMultiInputBaseActivity
  2349. {
  2350. public:
  2351. CRoxieServerMultiInputActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  2352. : CRoxieServerMultiInputBaseActivity(_ctx, _factory, _probeManager, _numInputs)
  2353. {
  2354. }
  2355. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  2356. {
  2357. CRoxieServerMultiInputBaseActivity::start(parentExtractSize, parentExtract, paused);
  2358. for (unsigned i = 0; i < numInputs; i++)
  2359. {
  2360. inputArray[i]->start(parentExtractSize, parentExtract, paused);
  2361. }
  2362. for (unsigned iS = 0; iS < numStreams; iS++)
  2363. {
  2364. startJunction(junctionArray[iS]);
  2365. }
  2366. }
  2367. virtual void stop()
  2368. {
  2369. for (unsigned i = 0; i < numStreams; i++)
  2370. {
  2371. streamArray[i]->stop();
  2372. }
  2373. CRoxieServerMultiInputBaseActivity::stop();
  2374. }
  2375. };
  2376. //=====================================================================================================
  2377. class CRoxieServerInternalSinkActivity : public CRoxieServerActivity
  2378. {
  2379. protected:
  2380. unsigned numOutputs;
  2381. bool executed;
  2382. bool *stopped;
  2383. CriticalSection ecrit;
  2384. Owned<IException> exception;
  2385. public:
  2386. CRoxieServerInternalSinkActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  2387. : CRoxieServerActivity(_ctx, _factory, _probeManager), numOutputs(_numOutputs)
  2388. {
  2389. executed = false;
  2390. stopped = new bool[numOutputs];
  2391. for (unsigned s = 0; s < numOutputs; s++)
  2392. stopped[s] = false;
  2393. }
  2394. ~CRoxieServerInternalSinkActivity()
  2395. {
  2396. delete [] stopped;
  2397. }
  2398. virtual void reset()
  2399. {
  2400. for (unsigned s = 0; s < numOutputs; s++)
  2401. stopped[s] = false;
  2402. executed = false;
  2403. exception.clear();
  2404. CRoxieServerActivity::reset();
  2405. }
  2406. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  2407. {
  2408. return NULL;
  2409. }
  2410. virtual void stopSink(unsigned outputIdx)
  2411. {
  2412. if (outputIdx < numOutputs && !stopped[outputIdx]) // Implicit dependencies on DiskWrite activities do not count as outputs
  2413. {
  2414. stopped[outputIdx] = true;
  2415. for (unsigned s = 0; s < numOutputs; s++)
  2416. if (!stopped[s])
  2417. return;
  2418. stop(); // all outputs stopped - stop parent.
  2419. }
  2420. }
  2421. virtual const void *nextRow()
  2422. {
  2423. throwUnexpected(); // I am nobody's input
  2424. }
  2425. virtual void onExecute() = 0;
  2426. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  2427. {
  2428. CriticalBlock b(ecrit);
  2429. if (exception)
  2430. throw exception.getLink();
  2431. if (!executed)
  2432. {
  2433. try
  2434. {
  2435. start(parentExtractSize, parentExtract, false);
  2436. {
  2437. ActivityTimer t(totalCycles, timeActivities); // unfortunately this is not really best place for seeing in debugger.
  2438. onExecute();
  2439. }
  2440. stop();
  2441. executed = true;
  2442. }
  2443. catch (IException *E)
  2444. {
  2445. exception.set(E); // (or maybe makeWrappedException?)
  2446. abort();
  2447. throw;
  2448. }
  2449. catch (...)
  2450. {
  2451. exception.set(MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught at %s:%d", sanitizeSourceFile(__FILE__), __LINE__));
  2452. abort();
  2453. throw;
  2454. }
  2455. }
  2456. }
  2457. };
  2458. //=================================================================================
  2459. class CRoxieServerQueryPacket : implements IRoxieServerQueryPacket, public CInterface
  2460. {
  2461. protected:
  2462. Owned<IMessageResult> result;
  2463. Owned<IRoxieQueryPacket> packet;
  2464. Linked<IRoxieServerQueryPacket> continuation;
  2465. unsigned hash;
  2466. unsigned seq;
  2467. unsigned lastDebugSequence;
  2468. Owned<IRoxieQueryPacket> lastDebugResponse;
  2469. ILRUChain *prev;
  2470. ILRUChain *next;
  2471. bool delayed;
  2472. public:
  2473. IMPLEMENT_IINTERFACE;
  2474. CRoxieServerQueryPacket(IRoxieQueryPacket *p) : packet(p)
  2475. {
  2476. hash = 0;
  2477. seq = 0;
  2478. prev = NULL;
  2479. next = NULL;
  2480. delayed = false;
  2481. lastDebugSequence = 0;
  2482. }
  2483. virtual IRoxieQueryPacket *queryPacket() const
  2484. {
  2485. return packet;
  2486. }
  2487. virtual bool isContinuation() const
  2488. {
  2489. return packet && (packet->queryHeader().continueSequence & ~CONTINUE_SEQUENCE_SKIPTO) != 0;
  2490. }
  2491. virtual bool isDelayed() const
  2492. {
  2493. return delayed;
  2494. }
  2495. virtual bool isEnd() const
  2496. {
  2497. return false;
  2498. }
  2499. virtual bool isLimit(unsigned __int64 &_rowLimit, unsigned __int64 &_keyedLimit, unsigned __int64 &_stopAfter) const
  2500. {
  2501. return false;
  2502. }
  2503. virtual bool hasResult() const
  2504. {
  2505. return result != NULL;
  2506. }
  2507. virtual bool hasContinuation() const
  2508. {
  2509. return continuation != NULL;
  2510. }
  2511. virtual void setDelayed(bool _delayed)
  2512. {
  2513. delayed = _delayed;
  2514. }
  2515. virtual void setPacket(IRoxieQueryPacket *_packet)
  2516. {
  2517. packet.setown(_packet);
  2518. }
  2519. virtual void setSequence(unsigned _seq)
  2520. {
  2521. assertex(!IsShared());
  2522. seq = _seq;
  2523. }
  2524. virtual unsigned getSequence() const
  2525. {
  2526. return seq;
  2527. }
  2528. IMessageResult *getResult()
  2529. {
  2530. return result.getLink();
  2531. }
  2532. IMessageResult *queryResult()
  2533. {
  2534. return result;
  2535. }
  2536. void setResult(IMessageResult *r)
  2537. {
  2538. result.setown(r);
  2539. }
  2540. IRoxieServerQueryPacket *queryContinuation()
  2541. {
  2542. return continuation;
  2543. }
  2544. void setContinuation(IRoxieServerQueryPacket *c)
  2545. {
  2546. continuation.setown(c);
  2547. }
  2548. virtual unsigned queryHash() const
  2549. {
  2550. return hash;
  2551. }
  2552. virtual void setHash(unsigned _hash)
  2553. {
  2554. hash = _hash;
  2555. }
  2556. virtual ILRUChain *queryPrev() const { return prev; }
  2557. virtual ILRUChain *queryNext() const { return next; }
  2558. virtual void setPrev(ILRUChain *p) { prev = p; }
  2559. virtual void setNext(ILRUChain *n) { next = n; }
  2560. virtual void unchain()
  2561. {
  2562. if (prev && next)
  2563. {
  2564. prev->setNext(next);
  2565. next->setPrev(prev);
  2566. }
  2567. next = NULL;
  2568. prev = NULL;
  2569. }
  2570. virtual IRoxieQueryPacket *getDebugResponse(unsigned sequence)
  2571. {
  2572. if (sequence == lastDebugSequence)
  2573. return lastDebugResponse.getLink();
  2574. else if (sequence > lastDebugSequence)
  2575. {
  2576. lastDebugResponse.clear();
  2577. return NULL;
  2578. }
  2579. else
  2580. throwUnexpected();
  2581. }
  2582. virtual void setDebugResponse(unsigned sequence, IRoxieQueryPacket *response)
  2583. {
  2584. lastDebugSequence = sequence;
  2585. lastDebugResponse.set(response);
  2586. }
  2587. };
  2588. class CRoxieServerQueryPacketEndMarker : public CRoxieServerQueryPacket
  2589. {
  2590. public:
  2591. CRoxieServerQueryPacketEndMarker() : CRoxieServerQueryPacket(NULL)
  2592. {
  2593. }
  2594. virtual bool isEnd() const
  2595. {
  2596. return true;
  2597. }
  2598. };
  2599. class CRoxieServerQueryPacketLimitMarker : public CRoxieServerQueryPacket
  2600. {
  2601. unsigned __int64 rowLimit;
  2602. unsigned __int64 keyedLimit;
  2603. unsigned __int64 stopAfter;
  2604. public:
  2605. CRoxieServerQueryPacketLimitMarker(unsigned __int64 _rowLimit, unsigned __int64 _keyedLimit, unsigned __int64 _stopAfter) : CRoxieServerQueryPacket(NULL)
  2606. {
  2607. rowLimit = _rowLimit;
  2608. keyedLimit = _keyedLimit;
  2609. stopAfter = _stopAfter;
  2610. }
  2611. virtual bool isLimit(unsigned __int64 &_rowLimit, unsigned __int64 &_keyedLimit, unsigned __int64 &_stopAfter) const
  2612. {
  2613. _rowLimit = rowLimit;
  2614. _keyedLimit = keyedLimit;
  2615. _stopAfter = stopAfter;
  2616. return true;
  2617. }
  2618. };
  2619. class CRoxieServerSideCache : implements IRoxieServerSideCache, implements ILRUChain
  2620. {
  2621. protected:
  2622. unsigned cacheTableSize;
  2623. unsigned cacheTableSpace;
  2624. IRoxieServerQueryPacket **cacheTable;
  2625. mutable ILRUChain *prev;
  2626. mutable ILRUChain *next;
  2627. mutable CriticalSection crit;
  2628. virtual ILRUChain *queryPrev() const { return prev; }
  2629. virtual ILRUChain *queryNext() const { return next; }
  2630. virtual void setPrev(ILRUChain *p) { prev = p; }
  2631. virtual void setNext(ILRUChain *n) { next = n; }
  2632. virtual void unchain()
  2633. {
  2634. prev->setNext(next);
  2635. next->setPrev(prev);
  2636. next = NULL;
  2637. prev = NULL;
  2638. }
  2639. void moveToHead(IRoxieServerQueryPacket *mru)
  2640. {
  2641. mru->unchain();
  2642. mru->setNext(next);
  2643. next->setPrev(mru);
  2644. mru->setPrev(this);
  2645. next = mru;
  2646. }
  2647. IRoxieServerQueryPacket *removeLRU()
  2648. {
  2649. if (next==this)
  2650. assertex(next != this);
  2651. IRoxieServerQueryPacket *goer = (IRoxieServerQueryPacket *) next;
  2652. goer->unchain(); // NOTE - this will modify the value of next
  2653. return goer;
  2654. }
  2655. void removeEntry(IRoxieServerQueryPacket *goer)
  2656. {
  2657. unsigned v = goer->queryHash() % cacheTableSize;
  2658. for (;;)
  2659. {
  2660. IRoxieServerQueryPacket *found = cacheTable[v];
  2661. assertex(found);
  2662. if (found == goer)
  2663. {
  2664. cacheTable[v] = NULL;
  2665. unsigned vn = v;
  2666. for (;;)
  2667. {
  2668. vn++;
  2669. if (vn==cacheTableSize) vn = 0;
  2670. IRoxieServerQueryPacket *found2 = cacheTable[vn];
  2671. if (!found2)
  2672. break;
  2673. unsigned vm = found2->queryHash() % cacheTableSize;
  2674. if (((vn+cacheTableSize-vm) % cacheTableSize)>=((vn+cacheTableSize-v) % cacheTableSize)) // diff(vn,vm)>=diff(vn,v)
  2675. {
  2676. cacheTable[v] = found2;
  2677. v = vn;
  2678. cacheTable[v] = NULL;
  2679. }
  2680. }
  2681. cacheTableSpace++;
  2682. break;
  2683. }
  2684. v++;
  2685. if (v==cacheTableSize)
  2686. v = 0;
  2687. }
  2688. goer->Release();
  2689. }
  2690. public:
  2691. CRoxieServerSideCache(unsigned _cacheSize)
  2692. {
  2693. cacheTableSize = (_cacheSize*4)/3;
  2694. cacheTable = new IRoxieServerQueryPacket *[cacheTableSize];
  2695. memset(cacheTable, 0, cacheTableSize * sizeof(IRoxieServerQueryPacket *));
  2696. cacheTableSpace = _cacheSize;
  2697. prev = this;
  2698. next = this;
  2699. }
  2700. ~CRoxieServerSideCache()
  2701. {
  2702. for (unsigned i = 0; i < cacheTableSize; i++)
  2703. {
  2704. ::Release(cacheTable[i]);
  2705. }
  2706. delete [] cacheTable;
  2707. }
  2708. virtual IRoxieServerQueryPacket *findCachedResult(const IRoxieContextLogger &logctx, IRoxieQueryPacket *p) const
  2709. {
  2710. unsigned hash = p->hash();
  2711. unsigned et = hash % cacheTableSize;
  2712. if (traceServerSideCache)
  2713. {
  2714. StringBuffer s;
  2715. logctx.CTXLOG("CRoxieServerSideCache::findCachedResult hash %x slot %d %s", hash, et, p->queryHeader().toString(s).str());
  2716. }
  2717. CriticalBlock b(crit);
  2718. for (;;)
  2719. {
  2720. IRoxieServerQueryPacket *found = cacheTable[et];
  2721. if (!found)
  2722. return NULL;
  2723. if (found->queryHash() == hash && found->queryPacket()->cacheMatch(p))
  2724. {
  2725. const_cast<CRoxieServerSideCache *>(this)->moveToHead(found);
  2726. if (traceServerSideCache)
  2727. logctx.CTXLOG("CRoxieServerSideCache::findCachedResult cache hit");
  2728. logctx.noteStatistic(StNumServerCacheHits, 1);
  2729. return NULL;
  2730. // Because IMessageResult cannot be replayed, this scheme is flawed. I'm leaving the code here just as a stats gatherer to see how useful it would have been....
  2731. //IRoxieServerQueryPacket *ret = new CRoxieServerQueryPacket(p);
  2732. //ret->setResult(found->getResult());
  2733. //return ret;
  2734. }
  2735. et++;
  2736. if (et == cacheTableSize)
  2737. et = 0;
  2738. }
  2739. }
  2740. virtual void noteCachedResult(IRoxieServerQueryPacket *out, IMessageResult *in)
  2741. {
  2742. if (true) //!in->getLength()) // MORE - separate caches for hits and nohits
  2743. {
  2744. unsigned hash = out->queryPacket()->hash();
  2745. out->setHash(hash);
  2746. unsigned et = hash % cacheTableSize;
  2747. if (traceServerSideCache)
  2748. {
  2749. StringBuffer s;
  2750. DBGLOG("CRoxieServerSideCache::noteCachedResult hash %x slot %d %s", hash, et, out->queryPacket()->queryHeader().toString(s).str());
  2751. }
  2752. CriticalBlock b(crit);
  2753. for (;;)
  2754. {
  2755. IRoxieServerQueryPacket *found = cacheTable[et];
  2756. if (!found)
  2757. {
  2758. if (cacheTableSpace)
  2759. {
  2760. out->setResult(LINK(in));
  2761. cacheTable[et] = LINK(out);
  2762. cacheTableSpace--;
  2763. moveToHead(out);
  2764. break;
  2765. }
  2766. else
  2767. {
  2768. IRoxieServerQueryPacket *goer = removeLRU();
  2769. removeEntry(goer);
  2770. et = hash % cacheTableSize;
  2771. continue;
  2772. }
  2773. }
  2774. else if (found->queryHash()==hash && found->queryPacket()->cacheMatch(out->queryPacket()))
  2775. {
  2776. moveToHead(found);
  2777. return; // already in the cache. Because we don't cache until we have result, this can happen where
  2778. // multiple copies of a slave query are in-flight at once.
  2779. }
  2780. et++;
  2781. if (et == cacheTableSize)
  2782. et = 0;
  2783. }
  2784. }
  2785. // MORE - do we need to worry about the attachment between the MessageUnpacker and the current row manager. May all fall out ok...
  2786. // Can I easily spot a null result? Do I want to cache null results separately? only?
  2787. }
  2788. // Note that this caching mechanism (unlike the old keyed-join specific one) does not common up cases where multiple
  2789. // identical queries are in-flight at the same time. But if we can make it persistent between queries that will
  2790. // more than make up for it
  2791. };
  2792. class CRowArrayMessageUnpackCursor : implements IMessageUnpackCursor, public CInterface
  2793. {
  2794. ConstPointerArray &data;
  2795. Linked<IMessageResult> result;
  2796. public:
  2797. IMPLEMENT_IINTERFACE;
  2798. CRowArrayMessageUnpackCursor(ConstPointerArray &_data, IMessageResult *_result)
  2799. : data(_data), result(_result)
  2800. {
  2801. }
  2802. virtual bool atEOF() const
  2803. {
  2804. return data.length()==0;
  2805. }
  2806. virtual bool isSerialized() const
  2807. {
  2808. return false;
  2809. }
  2810. virtual const void * getNext(int length)
  2811. {
  2812. if (!data.length())
  2813. return NULL;
  2814. const void *ret = data.item(0);
  2815. data.remove(0);
  2816. return ret;
  2817. }
  2818. };
  2819. // MORE - should possibly move more over to the lazy version used in indexread?
  2820. class CRowArrayMessageResult : implements IMessageResult, public CInterface
  2821. {
  2822. ConstPointerArray data;
  2823. IRowManager &rowManager;
  2824. bool variableSize;
  2825. public:
  2826. IMPLEMENT_IINTERFACE;
  2827. CRowArrayMessageResult(IRowManager &_rowManager, bool _variableSize) : rowManager(_rowManager), variableSize(_variableSize)
  2828. {
  2829. }
  2830. ~CRowArrayMessageResult()
  2831. {
  2832. ReleaseRoxieRows(data);
  2833. }
  2834. virtual IMessageUnpackCursor *getCursor(IRowManager *rowMgr) const
  2835. {
  2836. CRowArrayMessageResult *_this = (CRowArrayMessageResult *) this;
  2837. return new CRowArrayMessageUnpackCursor(_this->data, _this);
  2838. }
  2839. virtual const void *getMessageHeader(unsigned &length) const
  2840. {
  2841. throwUnexpected(); // should never get called - I don't have a header available
  2842. }
  2843. virtual const void *getMessageMetadata(unsigned &length) const
  2844. {
  2845. length = 0;
  2846. return NULL;
  2847. }
  2848. virtual void discard() const
  2849. {
  2850. throwUnexpected();
  2851. }
  2852. void append(const void *row)
  2853. {
  2854. data.append(row);
  2855. }
  2856. };
  2857. void throwRemoteException(IMessageUnpackCursor *extra)
  2858. {
  2859. RecordLengthType *rowlen = (RecordLengthType *) extra->getNext(sizeof(RecordLengthType));
  2860. if (rowlen)
  2861. {
  2862. char *xml = (char *) extra->getNext(*rowlen);
  2863. ReleaseRoxieRow(rowlen);
  2864. Owned<IPropertyTree> p = createPTreeFromXMLString(xml, ipt_fast);
  2865. ReleaseRoxieRow(xml);
  2866. unsigned code = p->getPropInt("Code", 0);
  2867. const char *msg = p->queryProp("Message");
  2868. if (!msg)
  2869. msg = xml;
  2870. throw MakeStringException(code, "%s", msg);
  2871. }
  2872. throwUnexpected();
  2873. }
  2874. class CRemoteResultAdaptor : implements IEngineRowStream, implements IFinalRoxieInput, implements IExceptionHandler, public CInterface
  2875. {
  2876. friend class CRemoteResultMerger;
  2877. class CRemoteResultMerger
  2878. {
  2879. class HeapEntry : public CInterface
  2880. {
  2881. private:
  2882. CRemoteResultAdaptor &adaptor;
  2883. IMessageUnpackCursor *cursor;
  2884. public:
  2885. const void *current;
  2886. bool isLast;
  2887. bool lastIsComplete;
  2888. IRoxieServerQueryPacket *packet;
  2889. unsigned seq;
  2890. public:
  2891. inline const void *noteResult(IMessageUnpackCursor *_cursor, bool _lastIsComplete)
  2892. {
  2893. cursor = _cursor;
  2894. lastIsComplete = _lastIsComplete;
  2895. return next();
  2896. }
  2897. public:
  2898. HeapEntry(CRemoteResultAdaptor &_adaptor, IRoxieServerQueryPacket *_packet, unsigned _seq) : adaptor(_adaptor), packet(_packet), seq(_seq)
  2899. {
  2900. cursor = NULL;
  2901. current = NULL;
  2902. isLast = false;
  2903. lastIsComplete = true;
  2904. }
  2905. ~HeapEntry()
  2906. {
  2907. ::Release(packet);
  2908. ::Release(cursor);
  2909. ReleaseRoxieRow(current);
  2910. }
  2911. bool isCompleteMatch() const
  2912. {
  2913. if (!isLast || lastIsComplete)
  2914. return true;
  2915. else
  2916. return false;
  2917. }
  2918. const void *next()
  2919. {
  2920. if (cursor)
  2921. {
  2922. ReleaseClearRoxieRow(current);
  2923. current = adaptor.getRow(cursor);
  2924. isLast = cursor->atEOF();
  2925. if (!current)
  2926. {
  2927. cursor->Release();
  2928. cursor = NULL;
  2929. }
  2930. }
  2931. return current;
  2932. }
  2933. unsigned skipTo(IRangeCompare *compare, const void *seek, unsigned numFields, bool requireExactMatch)
  2934. {
  2935. // MORE - This loop should possibly be a binchop... though it's not absolutely clear that is true (depends on term frequencies)
  2936. unsigned skipped = 0;
  2937. for (;;)
  2938. {
  2939. int c = compare->docompare(current, seek, numFields);
  2940. //If larger than the seek values, then we may be allowed to return an inexact match,
  2941. //if equal then it is required to be an exact match,
  2942. if (c > 0)
  2943. {
  2944. if (!requireExactMatch || isCompleteMatch())
  2945. break;
  2946. }
  2947. else if ((c == 0) && isCompleteMatch())
  2948. break;
  2949. skipped++;
  2950. if (!next())
  2951. break;
  2952. }
  2953. return skipped;
  2954. }
  2955. };
  2956. CRemoteResultAdaptor &adaptor;
  2957. CIArrayOf<HeapEntry> heapEntries;
  2958. UnsignedArray heap;
  2959. IRowManager *rowManager;
  2960. unsigned numPending;
  2961. unsigned numFields;
  2962. bool endSeen;
  2963. bool remakePending;
  2964. IRangeCompare *compare;
  2965. bool deferredContinuation;
  2966. inline int doCompare(unsigned l, unsigned r)
  2967. {
  2968. int ret = compare->docompare(heapEntries.item(l).current, heapEntries.item(r).current, numFields);
  2969. if (!ret) ret = heapEntries.item(l).seq - heapEntries.item(r).seq;
  2970. return ret;
  2971. }
  2972. void makeHeap()
  2973. {
  2974. /* Permute blocks to establish the heap property
  2975. For each element p, the children are p*2+1 and p*2+2 (provided these are in range)
  2976. The children of p must both be greater than or equal to p
  2977. The parent of a child c is given by p = (c-1)/2
  2978. */
  2979. unsigned i;
  2980. unsigned n = heap.length();
  2981. unsigned *s = heap.getArray();
  2982. for (i=1; i<n; i++)
  2983. {
  2984. unsigned r = s[i];
  2985. int c = i; /* child */
  2986. while (c > 0)
  2987. {
  2988. int p = (c-1)/2; /* parent */
  2989. if ( doCompare( s[c], s[p] ) >= 0 )
  2990. break;
  2991. s[c] = s[p];
  2992. s[p] = r;
  2993. c = p;
  2994. }
  2995. }
  2996. remakePending = false;
  2997. }
  2998. void remakeHeap()
  2999. {
  3000. /* The row associated with block[0] will have changed
  3001. This code restores the heap property
  3002. */
  3003. unsigned p = 0; /* parent */
  3004. unsigned n = heap.length();
  3005. unsigned *s = heap.getArray();
  3006. while (1)
  3007. {
  3008. unsigned c = p*2 + 1; /* child */
  3009. if ( c >= n )
  3010. break;
  3011. /* Select smaller child */
  3012. if ( c+1 < n && doCompare( s[c+1], s[c] ) < 0 ) c += 1;
  3013. /* If child is greater or equal than parent then we are done */
  3014. if ( doCompare( s[c], s[p] ) >= 0 )
  3015. break;
  3016. /* Swap parent and child */
  3017. unsigned r = s[c];
  3018. s[c] = s[p];
  3019. s[p] = r;
  3020. /* child becomes parent */
  3021. p = c;
  3022. }
  3023. remakePending = false;
  3024. }
  3025. void append(IRoxieServerQueryPacket *p, unsigned seq)
  3026. {
  3027. HeapEntry &h = *new HeapEntry(adaptor, LINK(p), seq);
  3028. IMessageResult *result = p->queryResult();
  3029. assertex(result);
  3030. if (h.noteResult(result->getCursor(rowManager), isCompleteMatchFlag(result)))
  3031. {
  3032. heapEntries.append(h);
  3033. heap.append(heap.ordinality());
  3034. }
  3035. else
  3036. h.Release();
  3037. }
  3038. void removeHeap(unsigned idx)
  3039. {
  3040. heapEntries.remove(idx);
  3041. ForEachItemIn(i, heap)
  3042. {
  3043. unsigned v = heap.item(i);
  3044. assertex(v != idx);
  3045. if (v > idx)
  3046. heap.replace(v-1, i);
  3047. }
  3048. }
  3049. bool isCompleteMatchFlag(IMessageResult *result)
  3050. {
  3051. unsigned metaLen;
  3052. const byte *metaInfo = (const byte *) result->getMessageMetadata(metaLen);
  3053. if (metaLen)
  3054. {
  3055. unsigned short continuationLen = *(unsigned short *) metaInfo;
  3056. if (continuationLen >= sizeof(bool))
  3057. {
  3058. metaInfo += sizeof(unsigned short);
  3059. return *(bool *) metaInfo;
  3060. }
  3061. }
  3062. return true; // if no continuation info, last row was complete.
  3063. }
  3064. public:
  3065. CRemoteResultMerger(CRemoteResultAdaptor &_adaptor) : adaptor(_adaptor)
  3066. {
  3067. init(NULL, NULL);
  3068. }
  3069. void init(ISteppingMeta *meta, IRowManager *_rowManager)
  3070. {
  3071. if (meta)
  3072. {
  3073. numFields = meta->getNumFields();
  3074. compare = meta->queryCompare();
  3075. }
  3076. else
  3077. {
  3078. numFields = 0;
  3079. compare = NULL;
  3080. }
  3081. rowManager = _rowManager;
  3082. numPending = 0;
  3083. endSeen = false;
  3084. remakePending = false;
  3085. deferredContinuation = false;
  3086. }
  3087. void reset()
  3088. {
  3089. heapEntries.kill();
  3090. heap.kill();
  3091. numPending = 0;
  3092. endSeen = false;
  3093. remakePending = false;
  3094. deferredContinuation = false;
  3095. }
  3096. inline bool noteEndSeen()
  3097. {
  3098. bool hadSeen = endSeen;
  3099. if (!endSeen)
  3100. makeHeap();
  3101. endSeen = true;
  3102. return !hadSeen;
  3103. }
  3104. void noteResult(IRoxieServerQueryPacket *p, unsigned seq)
  3105. {
  3106. if (!p->isContinuation())
  3107. append(p, seq);
  3108. else
  3109. {
  3110. ForEachItemIn(idx, heapEntries)
  3111. {
  3112. HeapEntry &h = heapEntries.item(idx);
  3113. if (h.packet == p)
  3114. {
  3115. IMessageResult *result = p->queryResult();
  3116. if (!h.noteResult(result->getCursor(rowManager), isCompleteMatchFlag(result)))
  3117. {
  3118. heap.zap(idx);
  3119. removeHeap(idx);
  3120. }
  3121. numPending--;
  3122. if (!numPending)
  3123. makeHeap();
  3124. return;
  3125. }
  3126. }
  3127. }
  3128. // If we get here it must be a continuation for one that I have not yet consumed... we don't need to do anything.
  3129. return;
  3130. }
  3131. unsigned skipRows(unsigned &idx, const void *seek, const void *rawSeek, unsigned numFields, unsigned seekLen, const SmartStepExtra & stepExtra)
  3132. {
  3133. HeapEntry &entry = heapEntries.item(idx);
  3134. unsigned skipped = entry.current ? entry.skipTo(compare, seek, numFields, !stepExtra.returnMismatches()) : 0;
  3135. if (!entry.current)
  3136. {
  3137. IRoxieServerQueryPacket *continuation = entry.packet->queryContinuation();
  3138. if (continuation)
  3139. {
  3140. continuation->Link();
  3141. entry.packet->Release();
  3142. entry.packet = continuation;
  3143. if (continuation->hasResult())
  3144. {
  3145. IMessageResult *result = continuation->queryResult();
  3146. bool lastIsCompleteMatch = isCompleteMatchFlag(result);
  3147. entry.noteResult(result->getCursor(rowManager), lastIsCompleteMatch);
  3148. }
  3149. else
  3150. {
  3151. if (continuation->isDelayed())
  3152. {
  3153. continuation->setDelayed(false);
  3154. MemoryBuffer serializedSkip;
  3155. adaptor.activity.serializeSkipInfo(serializedSkip, seekLen, rawSeek, numFields, seek, stepExtra);
  3156. continuation->setPacket(continuation->queryPacket()->insertSkipData(serializedSkip.length(), serializedSkip.toByteArray()));
  3157. ROQ->sendPacket(continuation->queryPacket(), adaptor.activity.queryLogCtx());
  3158. adaptor.sentsome.signal();
  3159. }
  3160. numPending++;
  3161. }
  3162. }
  3163. else
  3164. {
  3165. heap.zap(idx);
  3166. removeHeap(idx);
  3167. idx--;
  3168. }
  3169. }
  3170. return skipped;
  3171. }
  3172. const void * nextRowGE(const void * seek, const void *rawSeek, unsigned numFields, unsigned seeklen, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  3173. {
  3174. // We discard all rows < seekval from all entries in heap
  3175. // If this results in additional slave requests, we return NULL so that we can wait for them
  3176. // If not, we rebuild the heap (if any were skipped) and return the first row
  3177. deferredContinuation = false;
  3178. if (heap.length())
  3179. {
  3180. unsigned skipped = 0;
  3181. unsigned idx = 0;
  3182. while(heapEntries.isItem(idx))
  3183. {
  3184. skipped += skipRows(idx, seek, rawSeek, numFields, seeklen, stepExtra);
  3185. idx++;
  3186. }
  3187. if (numPending)
  3188. return NULL; // can't answer yet, need more results from slaves
  3189. else
  3190. {
  3191. if (skipped)
  3192. makeHeap();
  3193. return next(wasCompleteMatch, stepExtra);
  3194. }
  3195. }
  3196. else
  3197. return NULL;
  3198. }
  3199. bool doContinuation(HeapEntry &topEntry, bool canDefer)
  3200. {
  3201. IRoxieServerQueryPacket *continuation = topEntry.packet->queryContinuation();
  3202. if (continuation)
  3203. {
  3204. if (continuation->isDelayed() && canDefer)
  3205. {
  3206. if (adaptor.activity.queryLogCtx().queryTraceLevel() > 10)
  3207. adaptor.activity.queryLogCtx().CTXLOG("Deferring continuation");
  3208. deferredContinuation = true;
  3209. }
  3210. else
  3211. {
  3212. deferredContinuation = false;
  3213. continuation->Link();
  3214. topEntry.packet->Release();
  3215. topEntry.packet = continuation;
  3216. if (continuation->hasResult())
  3217. {
  3218. IMessageResult *result = continuation->queryResult();
  3219. bool lastIsCompleteMatch = isCompleteMatchFlag(result);
  3220. topEntry.noteResult(result->getCursor(rowManager), lastIsCompleteMatch);
  3221. }
  3222. else
  3223. {
  3224. if (continuation->isDelayed()) // has the continuation been requested yet?
  3225. {
  3226. continuation->Link();
  3227. topEntry.packet->Release();
  3228. topEntry.packet = continuation;
  3229. continuation->setDelayed(false);
  3230. if (adaptor.activity.queryLogCtx().queryTraceLevel() > 10)
  3231. adaptor.activity.queryLogCtx().CTXLOG("About to send continuation, from doContinuation");
  3232. ROQ->sendPacket(continuation->queryPacket(), adaptor.activity.queryLogCtx());
  3233. adaptor.sentsome.signal();
  3234. }
  3235. numPending++; // we are waiting for one that is already in flight
  3236. }
  3237. }
  3238. return true; // next not known yet
  3239. }
  3240. else
  3241. return false;
  3242. }
  3243. const void *next(bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  3244. {
  3245. OwnedConstRoxieRow ret;
  3246. if (heap.length())
  3247. {
  3248. if (deferredContinuation)
  3249. {
  3250. unsigned top = heap.item(0);
  3251. HeapEntry &topEntry = heapEntries.item(top);
  3252. doContinuation(topEntry, false);
  3253. return NULL;
  3254. }
  3255. if (remakePending)
  3256. remakeHeap();
  3257. unsigned top = heap.item(0);
  3258. HeapEntry &topEntry = heapEntries.item(top);
  3259. ret.set(topEntry.current);
  3260. wasCompleteMatch = topEntry.isCompleteMatch();
  3261. const void *next = topEntry.next();
  3262. if (!next)
  3263. {
  3264. if (!doContinuation(topEntry, stepExtra.returnMismatches()))
  3265. {
  3266. unsigned last = heap.popGet();
  3267. if (heap.length())
  3268. heap.replace(last, 0);
  3269. removeHeap(top);
  3270. }
  3271. }
  3272. remakePending = true;
  3273. }
  3274. return ret.getClear();
  3275. }
  3276. bool ready()
  3277. {
  3278. return endSeen && numPending == 0;
  3279. }
  3280. };
  3281. IRoxieServerQueryPacket *createRoxieServerQueryPacket(IRoxieQueryPacket *p, bool &cached)
  3282. {
  3283. if (serverSideCache && !debugContext)
  3284. {
  3285. IRoxieServerQueryPacket *ret = serverSideCache->findCachedResult(activity.queryLogCtx(), p);
  3286. if (ret)
  3287. {
  3288. p->Release();
  3289. cached = true;
  3290. return ret;
  3291. }
  3292. }
  3293. cached = false;
  3294. return new CRoxieServerQueryPacket(p);
  3295. }
  3296. #ifdef _DEBUG
  3297. void dumpPending()
  3298. {
  3299. CriticalBlock b(pendingCrit);
  3300. ForEachItemIn(idx, pending)
  3301. {
  3302. IRoxieServerQueryPacket &p = pending.item(idx);
  3303. StringBuffer s;
  3304. unsigned __int64 dummy;
  3305. if (p.isEnd())
  3306. s.append("END");
  3307. else if (p.isLimit(dummy, dummy, dummy))
  3308. s.append("LIMIT");
  3309. else
  3310. {
  3311. IRoxieQueryPacket *i = p.queryPacket();
  3312. s.appendf("%s", p.hasResult() ? "COMPLETE " : "PENDING ");
  3313. if (i)
  3314. {
  3315. RoxiePacketHeader &header = i->queryHeader();
  3316. header.toString(s);
  3317. }
  3318. }
  3319. DBGLOG("Pending %d %s", idx, s.str());
  3320. }
  3321. }
  3322. #endif
  3323. void abortPending()
  3324. {
  3325. CriticalBlock b(pendingCrit);
  3326. ForEachItemIn(idx, pending)
  3327. {
  3328. IRoxieServerQueryPacket &p = pending.item(idx);
  3329. if (!p.hasResult())
  3330. {
  3331. IRoxieQueryPacket *i = p.queryPacket();
  3332. if (i)
  3333. {
  3334. RoxiePacketHeader &header = i->queryHeader();
  3335. ROQ->sendAbort(header, activity.queryLogCtx());
  3336. }
  3337. }
  3338. }
  3339. pending.kill();
  3340. }
  3341. void checkDelayed()
  3342. {
  3343. if (ctx->queryDebugContext() && ctx->queryDebugContext()->getExecuteSequentially())
  3344. {
  3345. bool allDelayed = true;
  3346. CriticalBlock b(pendingCrit);
  3347. unsigned sendIdx = (unsigned) -1;
  3348. ForEachItemIn(idx, pending)
  3349. {
  3350. IRoxieServerQueryPacket &p = pending.item(idx);
  3351. if (p.queryPacket())
  3352. {
  3353. if (p.isDelayed())
  3354. {
  3355. if (sendIdx == (unsigned) -1)
  3356. sendIdx = idx;
  3357. }
  3358. else if (!p.hasResult())
  3359. {
  3360. allDelayed = false;
  3361. break;
  3362. }
  3363. }
  3364. }
  3365. if (allDelayed && sendIdx != (unsigned) -1)
  3366. {
  3367. if (activity.queryLogCtx().queryTraceLevel() > 10)
  3368. activity.queryLogCtx().CTXLOG("About to send debug-deferred from next");
  3369. pending.item(sendIdx).setDelayed(false);
  3370. ROQ->sendPacket(pending.item(sendIdx).queryPacket(), activity.queryLogCtx());
  3371. sentsome.signal();
  3372. }
  3373. }
  3374. else if (deferredStart)
  3375. {
  3376. CriticalBlock b(pendingCrit);
  3377. ForEachItemIn(idx, pending)
  3378. {
  3379. IRoxieServerQueryPacket &p = pending.item(idx);
  3380. if (p.isDelayed())
  3381. {
  3382. if (activity.queryLogCtx().queryTraceLevel() > 10)
  3383. activity.queryLogCtx().CTXLOG("About to send deferred start from next");
  3384. p.setDelayed(false);
  3385. ROQ->sendPacket(p.queryPacket(), activity.queryLogCtx());
  3386. sentsome.signal();
  3387. }
  3388. }
  3389. deferredStart = false;
  3390. }
  3391. }
  3392. void retryPending()
  3393. {
  3394. CriticalBlock b(pendingCrit);
  3395. checkDelayed();
  3396. ForEachItemIn(idx, pending)
  3397. {
  3398. IRoxieServerQueryPacket &p = pending.item(idx);
  3399. if (!p.hasResult() && !p.isDelayed())
  3400. {
  3401. IRoxieQueryPacket *i = p.queryPacket();
  3402. if (i)
  3403. {
  3404. if (!i->queryHeader().retry())
  3405. {
  3406. StringBuffer s;
  3407. IException *E = MakeStringException(ROXIE_MULTICAST_ERROR, "Failed to get response from slave(s) for %s in activity %d", i->queryHeader().toString(s).str(), activity.queryId());
  3408. activity.queryLogCtx().logOperatorException(E, __FILE__, __LINE__, "CRemoteResultAdaptor::retry");
  3409. throw E;
  3410. }
  3411. if (!localSlave)
  3412. {
  3413. ROQ->sendPacket(i, activity.queryLogCtx());
  3414. atomic_inc(&retriesSent);
  3415. }
  3416. }
  3417. }
  3418. }
  3419. }
  3420. class ChannelBuffer
  3421. {
  3422. protected:
  3423. unsigned bufferLeft;
  3424. MemoryBuffer buffer;
  3425. char *nextBuf;
  3426. unsigned overflowSequence;
  3427. unsigned channel; // == bonded channel
  3428. bool needsFlush;
  3429. InterruptableSemaphore flowController;
  3430. const CRemoteResultAdaptor &owner;
  3431. CriticalSection crit;
  3432. public:
  3433. ChannelBuffer(const CRemoteResultAdaptor &_owner, unsigned _channel) : owner(_owner), channel(_channel), flowController(perChannelFlowLimit)
  3434. {
  3435. overflowSequence = 0;
  3436. needsFlush = false;
  3437. bufferLeft = 0;
  3438. nextBuf = NULL;
  3439. }
  3440. void init(unsigned minSize)
  3441. {
  3442. assertex(!buffer.length());
  3443. if (minSize < MIN_PAYLOAD_SIZE)
  3444. minSize = MIN_PAYLOAD_SIZE;
  3445. unsigned headerSize = sizeof(RoxiePacketHeader)+owner.headerLength();
  3446. unsigned bufferSize = headerSize+minSize;
  3447. if (bufferSize < mtu_size)
  3448. bufferSize = mtu_size;
  3449. buffer.reserveTruncate(bufferSize);
  3450. bufferLeft = bufferSize - headerSize;
  3451. assertex(buffer.toByteArray());
  3452. nextBuf = (char *) buffer.toByteArray() + headerSize;
  3453. needsFlush = false;
  3454. }
  3455. inline IRoxieQueryPacket *flush()
  3456. {
  3457. CriticalBlock cb(crit);
  3458. Owned<IRoxieQueryPacket> ret;
  3459. if (needsFlush)
  3460. {
  3461. buffer.setLength(nextBuf - buffer.toByteArray());
  3462. RoxiePacketHeader *h = (RoxiePacketHeader *) buffer.toByteArray();
  3463. h->init(owner.remoteId, owner.ruid, channel, overflowSequence);
  3464. //patch logPrefix, cachedContext and parent extract into the place reserved in the message buffer
  3465. byte * tgt = (byte*)(h+1);
  3466. owner.copyHeader(tgt, channel);
  3467. ret.setown(createRoxiePacket(buffer));
  3468. if (overflowSequence == OVERFLOWSEQUENCE_MAX)
  3469. overflowSequence = 1; // don't wrap to 0 - that is a bit special
  3470. else
  3471. overflowSequence++;
  3472. needsFlush = false;
  3473. bufferLeft = 0;
  3474. if (owner.flowControlled)
  3475. {
  3476. CriticalUnblock cub(crit);
  3477. while (!flowController.wait(1000))
  3478. {
  3479. StringBuffer s;
  3480. owner.activity.queryLogCtx().CTXLOG("Channel %d blocked by flow control: %s", channel, h->toString(s).str());
  3481. }
  3482. }
  3483. }
  3484. return ret.getClear();
  3485. }
  3486. inline void signal()
  3487. {
  3488. if (owner.flowControlled)
  3489. flowController.signal();
  3490. }
  3491. inline void interrupt(IException *e)
  3492. {
  3493. flowController.interrupt(e);
  3494. }
  3495. inline void *getBuffer(unsigned size)
  3496. {
  3497. CriticalBlock cb(crit);
  3498. if (bufferLeft >= size)
  3499. {
  3500. needsFlush = true;
  3501. void * ret = nextBuf;
  3502. nextBuf += size;
  3503. bufferLeft -= size;
  3504. return ret;
  3505. }
  3506. else if (!needsFlush)
  3507. {
  3508. init(size);
  3509. return getBuffer(size);
  3510. }
  3511. else if (owner.mergeOrder)
  3512. {
  3513. return buffer.reserve(size); // whole query needs to go as single packet if we are to merge
  3514. }
  3515. else
  3516. return NULL; // will force it to flush and start a new packet
  3517. }
  3518. };
  3519. private:
  3520. friend class CRemoteResultMerger;
  3521. bool allread;
  3522. bool contextCached;
  3523. bool preserveOrder;
  3524. bool eogSent = false;
  3525. InterruptableSemaphore sentsome;
  3526. Owned <IMessageCollator> mc;
  3527. Owned<IMessageUnpackCursor> mu;
  3528. Owned<IMessageResult> mr;
  3529. ChannelBuffer **buffers;
  3530. IHThorArg &helper;
  3531. unsigned __int64 stopAfter;
  3532. unsigned resendSequence;
  3533. IHThorArg *colocalArg;
  3534. IArrayOf<IRoxieServerQueryPacket> pending;
  3535. CriticalSection pendingCrit;
  3536. IRoxieServerSideCache *serverSideCache;
  3537. unsigned sentSequence;
  3538. Owned<IOutputRowDeserializer> deserializer;
  3539. Owned<IEngineRowAllocator> rowAllocator;
  3540. CRemoteResultMerger merger;
  3541. // this is only used to avoid recreating a bufferStream for each row. A better solution may be needed
  3542. MemoryBuffer tempRowBuffer;
  3543. Owned<ISerialStream> bufferStream;
  3544. CThorStreamDeserializerSource rowSource;
  3545. protected:
  3546. IRowManager *rowManager;
  3547. unsigned __int64 rowLimit;
  3548. unsigned __int64 keyedLimit;
  3549. IRoxieServerErrorHandler *errorHandler;
  3550. CachedOutputMetaData meta;
  3551. public:
  3552. ISteppingMeta *mergeOrder;
  3553. IRoxieSlaveContext *ctx;
  3554. IDebuggableContext *debugContext;
  3555. IRoxieServerActivity &activity;
  3556. unsigned parentExtractSize;
  3557. const byte * parentExtract;
  3558. bool flowControlled;
  3559. bool deferredStart;
  3560. MemoryBuffer logInfo;
  3561. MemoryBuffer cachedContext;
  3562. const RemoteActivityId &remoteId;
  3563. ruid_t ruid;
  3564. mutable CriticalSection buffersCrit;
  3565. unsigned processed;
  3566. cycle_t totalCycles;
  3567. bool timeActivities;
  3568. //private: //vc6 doesn't like this being private yet accessed by nested class...
  3569. const void *getRow(IMessageUnpackCursor *mu)
  3570. {
  3571. if (!mu->isSerialized() || (meta.isFixedSize() && !deserializer))
  3572. return mu->getNext(meta.getFixedSize());
  3573. else
  3574. {
  3575. RecordLengthType *rowlen = (RecordLengthType *) mu->getNext(sizeof(RecordLengthType));
  3576. if (rowlen)
  3577. {
  3578. RecordLengthType len = *rowlen;
  3579. ReleaseRoxieRow(rowlen);
  3580. const void *slaveRec = mu->getNext(len);
  3581. if (deserializer && mu->isSerialized())
  3582. {
  3583. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  3584. tempRowBuffer.setBuffer(len, const_cast<void *>(slaveRec), false);
  3585. size_t outsize = deserializer->deserialize(rowBuilder, rowSource);
  3586. ReleaseRoxieRow(slaveRec);
  3587. return rowBuilder.finalizeRowClear(outsize);
  3588. }
  3589. else
  3590. return slaveRec;
  3591. }
  3592. else
  3593. return NULL;
  3594. }
  3595. }
  3596. private:
  3597. ChannelBuffer *queryChannelBuffer(unsigned channel, bool force=false)
  3598. {
  3599. CriticalBlock cb(buffersCrit);
  3600. ChannelBuffer *b = buffers[channel];
  3601. if (!b && force)
  3602. {
  3603. if (!contextCached)
  3604. {
  3605. logInfo.clear();
  3606. unsigned char loggingFlags = LOGGING_FLAGSPRESENT | LOGGING_TRACELEVELSET;
  3607. unsigned char ctxTraceLevel = activity.queryLogCtx().queryTraceLevel() + 1; // Avoid passing a 0
  3608. const QueryOptions &options = ctx->queryOptions();
  3609. if (activity.queryLogCtx().isIntercepted())
  3610. loggingFlags |= LOGGING_INTERCEPTED;
  3611. if (options.timeActivities)
  3612. loggingFlags |= LOGGING_TIMEACTIVITIES;
  3613. if (activity.queryLogCtx().isBlind())
  3614. loggingFlags |= LOGGING_BLIND;
  3615. if (options.checkingHeap)
  3616. loggingFlags |= LOGGING_CHECKINGHEAP;
  3617. if (ctx->queryWorkUnit())
  3618. loggingFlags |= LOGGING_WUID;
  3619. if (debugContext)
  3620. {
  3621. loggingFlags |= LOGGING_DEBUGGERACTIVE;
  3622. logInfo.append(loggingFlags).append(ctxTraceLevel);
  3623. MemoryBuffer bpInfo;
  3624. debugContext->serialize(bpInfo);
  3625. bpInfo.append((__uint64)(memsize_t) &activity);
  3626. logInfo.append((unsigned short) bpInfo.length());
  3627. logInfo.append(bpInfo.length(), bpInfo.toByteArray());
  3628. }
  3629. else
  3630. logInfo.append(loggingFlags).append(ctxTraceLevel);
  3631. StringBuffer logPrefix;
  3632. activity.queryLogCtx().getLogPrefix(logPrefix);
  3633. logInfo.append(logPrefix);
  3634. activity.serializeCreateStartContext(cachedContext.clear());
  3635. activity.serializeExtra(cachedContext);
  3636. if (activity.queryVarFileInfo())
  3637. {
  3638. activity.queryVarFileInfo()->queryTimeStamp().serialize(cachedContext);
  3639. cachedContext.append(activity.queryVarFileInfo()->queryCheckSum());
  3640. }
  3641. contextCached = true;
  3642. }
  3643. b = buffers[channel] = new ChannelBuffer(*this, channel);
  3644. }
  3645. return b;
  3646. }
  3647. void processRow(const void *got)
  3648. {
  3649. processed++;
  3650. if (processed > rowLimit)
  3651. {
  3652. ReleaseRoxieRow(got);
  3653. errorHandler->onLimitExceeded(false); // NOTE - should throw exception
  3654. throwUnexpected();
  3655. }
  3656. else if (processed > keyedLimit)
  3657. {
  3658. ReleaseRoxieRow(got);
  3659. errorHandler->onLimitExceeded(true); // NOTE - should throw exception
  3660. throwUnexpected();
  3661. }
  3662. }
  3663. public:
  3664. IMPLEMENT_IINTERFACE;
  3665. CRemoteResultAdaptor(IRoxieSlaveContext *_ctx, IRoxieServerErrorHandler *_errorHandler, const RemoteActivityId &_remoteId, IOutputMetaData *_meta, IHThorArg &_helper, IRoxieServerActivity &_activity, bool _preserveOrder, bool _flowControlled)
  3666. : remoteId(_remoteId), meta(_meta), activity(_activity), helper(_helper), preserveOrder(_preserveOrder), flowControlled(_flowControlled), merger(*this)
  3667. {
  3668. ctx = _ctx;
  3669. errorHandler = _errorHandler;
  3670. colocalArg = NULL;
  3671. allread = false;
  3672. ruid = 0;
  3673. rowLimit = (unsigned __int64) -1;
  3674. keyedLimit = (unsigned __int64) -1;
  3675. contextCached = false;
  3676. stopAfter = I64C(0x7FFFFFFFFFFFFFFF);
  3677. buffers = new ChannelBuffer*[numChannels+1];
  3678. memset(buffers, 0, (numChannels+1)*sizeof(ChannelBuffer *));
  3679. parentExtractSize = 0;
  3680. rowManager = NULL;
  3681. parentExtract = NULL;
  3682. debugContext = NULL;
  3683. mergeOrder = NULL;
  3684. deferredStart = false;
  3685. processed = 0;
  3686. sentSequence = 0;
  3687. resendSequence = 0;
  3688. totalCycles = 0;
  3689. serverSideCache = activity.queryServerSideCache();
  3690. bufferStream.setown(createMemoryBufferSerialStream(tempRowBuffer));
  3691. rowSource.setStream(bufferStream);
  3692. timeActivities = defaultTimeActivities;
  3693. }
  3694. ~CRemoteResultAdaptor()
  3695. {
  3696. if (mc)
  3697. {
  3698. ROQ->queryReceiveManager()->detachCollator(mc);
  3699. mc.clear();
  3700. }
  3701. for (unsigned channel = 0; channel <= numChannels; channel++)
  3702. {
  3703. delete(buffers[channel]);
  3704. }
  3705. delete [] buffers;
  3706. }
  3707. void setMeta(IOutputMetaData *newmeta)
  3708. {
  3709. meta.set(newmeta);
  3710. }
  3711. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { assertex(whichInput==0); return this; }
  3712. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { assertex(idx==0); return nullptr; }
  3713. virtual IRoxieServerActivity *queryActivity()
  3714. {
  3715. return &activity;
  3716. }
  3717. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  3718. {
  3719. return NULL;
  3720. }
  3721. void setMergeInfo(ISteppingMeta *_mergeOrder)
  3722. {
  3723. mergeOrder = _mergeOrder;
  3724. deferredStart = true;
  3725. }
  3726. void send(IRoxieQueryPacket *p)
  3727. {
  3728. if (p)
  3729. {
  3730. Linked<IRoxieQueryPacket> saver(p); // avoids a race with abortPending, without keeping pendingCrit locked over the send which we might prefer not to
  3731. assertex(p->queryHeader().uid==ruid);
  3732. // MORE: Maybe we should base the fastlane flag on some other
  3733. // criteria !! (i.e A Roxie server prediction based on the
  3734. // activity type/activity behaviour/expected reply size .. etc).
  3735. //
  3736. // Currently (code below) based on high priority, seq=0, and none-child activity.
  3737. // But this could still cause too many reply packets on the fatlane
  3738. // (higher priority output Q), which may cause the activities on the
  3739. // low priority output Q to not get service on time.
  3740. if ((colocalArg == 0) && // not a child query activity??
  3741. (p->queryHeader().activityId & (ROXIE_SLA_PRIORITY | ROXIE_HIGH_PRIORITY)) &&
  3742. (p->queryHeader().overflowSequence == 0) &&
  3743. (p->queryHeader().continueSequence & ~CONTINUE_SEQUENCE_SKIPTO)==0)
  3744. p->queryHeader().retries |= ROXIE_FASTLANE;
  3745. if (p->queryHeader().channel)
  3746. {
  3747. bool cached = false;
  3748. IRoxieServerQueryPacket *rsqp = createRoxieServerQueryPacket(p, cached);
  3749. if (deferredStart)
  3750. rsqp->setDelayed(true);
  3751. rsqp->setSequence(sentSequence++);
  3752. {
  3753. CriticalBlock b(pendingCrit);
  3754. pending.append(*rsqp);
  3755. }
  3756. if (!deferredStart)
  3757. {
  3758. if (!cached)
  3759. ROQ->sendPacket(p, activity.queryLogCtx());
  3760. sentsome.signal();
  3761. }
  3762. }
  3763. else
  3764. {
  3765. // 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
  3766. // Need to add first, then send
  3767. unsigned i;
  3768. bool allCached = true;
  3769. for (i = 1; i <= numChannels; i++)
  3770. {
  3771. IRoxieQueryPacket *q = p->clonePacket(i);
  3772. bool thisChannelCached;
  3773. IRoxieServerQueryPacket *rsqp = createRoxieServerQueryPacket(q, thisChannelCached);
  3774. if (!thisChannelCached)
  3775. allCached = false;
  3776. rsqp->setSequence(sentSequence++);
  3777. if (deferredStart)
  3778. {
  3779. rsqp->setDelayed(true);
  3780. }
  3781. {
  3782. CriticalBlock b(pendingCrit);
  3783. pending.append(*rsqp);
  3784. }
  3785. if (!deferredStart)
  3786. sentsome.signal();
  3787. }
  3788. if (!allCached && !deferredStart)
  3789. ROQ->sendPacket(p, activity.queryLogCtx());
  3790. buffers[0]->signal(); // since replies won't come back on that channel...
  3791. p->Release();
  3792. }
  3793. }
  3794. }
  3795. void *getMem(unsigned partNo, unsigned fileNo, unsigned size)
  3796. {
  3797. unsigned channel = partNo ? getBondedChannel(partNo) : 0;
  3798. size += sizeof(PartNoType);
  3799. ChannelBuffer *b = queryChannelBuffer(channel, true);
  3800. char *buffer = (char *) b->getBuffer(size);
  3801. if (!buffer)
  3802. {
  3803. send(b->flush());
  3804. buffer = (char *) b->getBuffer(size);
  3805. }
  3806. PartNoType sp;
  3807. sp.partNo = partNo;
  3808. sp.fileNo = fileNo;
  3809. memcpy(buffer, &sp, sizeof(sp));
  3810. buffer += sizeof(sp);
  3811. return buffer;
  3812. }
  3813. void injectResult(IMessageResult *result)
  3814. {
  3815. IRoxieServerQueryPacket *f = new CRoxieServerQueryPacket(NULL);
  3816. f->setSequence(sentSequence++);
  3817. f->setResult(result);
  3818. CriticalBlock b(pendingCrit);
  3819. pending.append(*f);
  3820. sentsome.signal(); // MORE - arguably should only send if there is any point waking up the listener thread, to save context swicth
  3821. }
  3822. void flush()
  3823. {
  3824. for (unsigned channel = 0; channel <= numChannels; channel++)
  3825. {
  3826. ChannelBuffer *b = queryChannelBuffer(channel, false);
  3827. if (b)
  3828. send(b->flush());
  3829. }
  3830. }
  3831. void interruptBuffers(IException *e)
  3832. {
  3833. for (unsigned channel = 0; channel <= numChannels; channel++)
  3834. {
  3835. ChannelBuffer *b = queryChannelBuffer(channel, false);
  3836. if (b)
  3837. b->interrupt(LINK(e));
  3838. }
  3839. }
  3840. void senddone()
  3841. {
  3842. CriticalBlock b(pendingCrit);
  3843. pending.append(*new CRoxieServerQueryPacketEndMarker);
  3844. sentsome.signal();
  3845. }
  3846. bool fireException(IException *e)
  3847. {
  3848. {
  3849. CriticalBlock b(pendingCrit);
  3850. pending.append(*new CRoxieServerQueryPacketEndMarker);
  3851. }
  3852. interruptBuffers(e);
  3853. if (mc)
  3854. mc->interrupt(LINK(e));
  3855. sentsome.interrupt(e);
  3856. return true;
  3857. }
  3858. virtual void onCreate(IHThorArg *_colocalArg)
  3859. {
  3860. debugContext = ctx->queryDebugContext();
  3861. colocalArg = _colocalArg;
  3862. if (meta.needsSerializeDisk())
  3863. {
  3864. deserializer.setown(meta.createDiskDeserializer(ctx->queryCodeContext(), activity.queryId()));
  3865. rowAllocator.setown(activity.createRowAllocator(meta.queryOriginal()));
  3866. }
  3867. if (ctx->queryDebugContext() && ctx->queryDebugContext()->getExecuteSequentially())
  3868. deferredStart = true;
  3869. timeActivities = ctx->queryOptions().timeActivities;
  3870. }
  3871. virtual void onStart(unsigned _parentExtractSize, const byte * _parentExtract)
  3872. {
  3873. #ifdef TRACE_STARTSTOP
  3874. if (traceStartStop)
  3875. activity.queryLogCtx().CTXLOG("RRAonstart");
  3876. #endif
  3877. sentsome.reinit();
  3878. ruid = getNextRuid();
  3879. rowManager = &ctx->queryRowManager();
  3880. if (mergeOrder)
  3881. merger.init(mergeOrder, rowManager);
  3882. if (mc)
  3883. {
  3884. ROQ->queryReceiveManager()->detachCollator(mc); // Should never happen - implies someone forgot to call onReset!
  3885. }
  3886. mc.setown(ROQ->queryReceiveManager()->createMessageCollator(rowManager, ruid));
  3887. allread = false;
  3888. mu.clear();
  3889. contextCached = false;
  3890. processed = 0;
  3891. resendSequence = 0;
  3892. sentSequence = 0;
  3893. for (unsigned channel = 0; channel <= numChannels; channel++)
  3894. {
  3895. delete(buffers[channel]);
  3896. buffers[channel] = NULL;
  3897. }
  3898. flush();
  3899. parentExtractSize = _parentExtractSize;
  3900. parentExtract = _parentExtract;
  3901. }
  3902. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  3903. {
  3904. #ifdef TRACE_STARTSTOP
  3905. if (traceStartStop)
  3906. activity.queryLogCtx().CTXLOG("RRAstart");
  3907. #endif
  3908. activity.start(parentExtractSize, parentExtract, paused);
  3909. }
  3910. void setLimits(unsigned __int64 _rowLimit, unsigned __int64 _keyedLimit, unsigned __int64 _stopAfter)
  3911. {
  3912. if (ctx->queryProbeManager())
  3913. {
  3914. if (_rowLimit != (unsigned __int64) -1) ctx->queryProbeManager()->setNodePropertyInt(&activity, "rowLimit", _rowLimit);
  3915. if (_keyedLimit != (unsigned __int64) -1) ctx->queryProbeManager()->setNodePropertyInt(&activity, "keyedLimit", _keyedLimit);
  3916. if (_stopAfter != I64C(0x7FFFFFFFFFFFFFFF)) ctx->queryProbeManager()->setNodePropertyInt(&activity, "choosenLimit", _stopAfter);
  3917. }
  3918. {
  3919. CriticalBlock b(pendingCrit);
  3920. if (pending.length())
  3921. {
  3922. #ifdef _DEBUG
  3923. dumpPending(); // MORE - only defined in debug build - could have put the ifdef inside the dumpPending method
  3924. #endif
  3925. assertex(pending.length()==0);
  3926. }
  3927. pending.append(*new CRoxieServerQueryPacketLimitMarker(_rowLimit, _keyedLimit, _stopAfter));
  3928. }
  3929. sentsome.signal();
  3930. rowLimit = _rowLimit;
  3931. keyedLimit = _keyedLimit;
  3932. stopAfter = _stopAfter;
  3933. }
  3934. virtual void stop()
  3935. {
  3936. #ifdef TRACE_STARTSTOP
  3937. if (traceStartStop)
  3938. activity.queryLogCtx().CTXLOG("RRAstop");
  3939. #endif
  3940. onStop();
  3941. activity.stop();
  3942. }
  3943. void onStop()
  3944. {
  3945. #ifdef TRACE_STARTSTOP
  3946. if (traceStartStop)
  3947. activity.queryLogCtx().CTXLOG("RRAonstop");
  3948. #endif
  3949. abortPending();
  3950. interruptBuffers(NULL);
  3951. sentsome.interrupt();
  3952. if (mc) // May not be set if start() chain threw exception
  3953. mc->interrupt();
  3954. }
  3955. virtual void reset()
  3956. {
  3957. #ifdef TRACE_STARTSTOP
  3958. if (traceStartStop)
  3959. activity.queryLogCtx().CTXLOG("RRAreset");
  3960. #endif
  3961. activity.reset();
  3962. onReset();
  3963. }
  3964. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  3965. {
  3966. // Make sure parent activity calls up the tree
  3967. PointerArrayOf<IEngineRowStream> instreams;
  3968. IStrandJunction *junction = activity.getOutputStreams(ctx, idx, instreams, consumerOptions, consumerOrdered, orderedCallbacks);
  3969. assertex (junction == NULL);
  3970. // I return a single strand (we could change that sometime I guess...)
  3971. streams.append(this);
  3972. return NULL;
  3973. }
  3974. virtual void resetEOF()
  3975. {
  3976. throwUnexpected();
  3977. }
  3978. virtual void onReset()
  3979. {
  3980. #ifdef TRACE_STARTSTOP
  3981. if (traceStartStop)
  3982. activity.queryLogCtx().CTXLOG("RRAonreset");
  3983. #endif
  3984. if (mc)
  3985. ROQ->queryReceiveManager()->detachCollator(mc);
  3986. merger.reset();
  3987. pending.kill();
  3988. if (mc && ctx)
  3989. ctx->addSlavesReplyLen(mc->queryBytesReceived());
  3990. mc.clear(); // Or we won't free memory for graphs that get recreated
  3991. mu.clear(); //ditto
  3992. deferredStart = false;
  3993. // NOTE: do NOT clear mergeOrder - this is set at create time not per child query
  3994. }
  3995. virtual IOutputMetaData * queryOutputMeta() const
  3996. {
  3997. return helper.queryOutputMeta();
  3998. }
  3999. virtual unsigned __int64 queryTotalCycles() const
  4000. {
  4001. return totalCycles;
  4002. }
  4003. void gatherStats(CRuntimeStatisticCollection & merged) const
  4004. {
  4005. if (rowAllocator)
  4006. rowAllocator->gatherStats(merged);
  4007. }
  4008. const void * nextRowGE(const void *seek, const void *rawSeek, unsigned numFields, unsigned seekLen, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  4009. {
  4010. if (activity.queryLogCtx().queryTraceLevel() > 20)
  4011. {
  4012. StringBuffer recstr;
  4013. unsigned i;
  4014. for (i = 0; i < seekLen; i++)
  4015. {
  4016. recstr.appendf("%02x ", ((unsigned char *) rawSeek)[i]);
  4017. }
  4018. activity.queryLogCtx().CTXLOG("CRemoteResultAdaptor::nextRowGE(rawSeek=%s numFields=%d, seeklen=%d, returnMismatches=%d)", recstr.str(), numFields, seekLen, stepExtra.returnMismatches());
  4019. }
  4020. assertex(mergeOrder);
  4021. if (deferredStart)
  4022. {
  4023. CriticalBlock b(pendingCrit);
  4024. ForEachItemIn(idx, pending)
  4025. {
  4026. IRoxieServerQueryPacket &p = pending.item(idx);
  4027. if (p.isDelayed())
  4028. {
  4029. p.setDelayed(false);
  4030. if (activity.queryLogCtx().queryTraceLevel() > 10)
  4031. activity.queryLogCtx().CTXLOG("About to send deferred start from nextRowGE, setting requireExact to %d", !stepExtra.returnMismatches());
  4032. MemoryBuffer serializedSkip;
  4033. activity.serializeSkipInfo(serializedSkip, seekLen, rawSeek, numFields, seek, stepExtra);
  4034. p.setPacket(p.queryPacket()->insertSkipData(serializedSkip.length(), serializedSkip.toByteArray()));
  4035. ROQ->sendPacket(p.queryPacket(), activity.queryLogCtx());
  4036. sentsome.signal();
  4037. }
  4038. }
  4039. deferredStart = false;
  4040. }
  4041. SimpleActivityTimer t(totalCycles, timeActivities);
  4042. if (processed==stopAfter)
  4043. return NULL;
  4044. if (allread)
  4045. return NULL;
  4046. for (;;)
  4047. {
  4048. if (merger.ready())
  4049. {
  4050. const void *got = merger.nextRowGE(seek, rawSeek, numFields, seekLen, wasCompleteMatch, stepExtra);
  4051. if (got)
  4052. {
  4053. processRow(got);
  4054. return got;
  4055. }
  4056. }
  4057. if (!reload()) // MORE - should pass the seek info here...
  4058. return NULL;
  4059. }
  4060. }
  4061. virtual const void *nextRow()
  4062. {
  4063. // If we are merging then we need to do a heapsort on all
  4064. SimpleActivityTimer t(totalCycles, timeActivities);
  4065. if (activity.queryLogCtx().queryTraceLevel() > 10)
  4066. {
  4067. activity.queryLogCtx().CTXLOG("CRemoteResultAdaptor::nextRow()");
  4068. }
  4069. for (;;)
  4070. {
  4071. checkDelayed();
  4072. if (processed==stopAfter)
  4073. return NULL;
  4074. if (allread)
  4075. return NULL;
  4076. // If we can still consume from the merger or the most recently retrieved mu, do so.
  4077. const void *got = NULL;
  4078. if (mergeOrder && merger.ready())
  4079. {
  4080. bool matched = true;
  4081. got = merger.next(matched, dummySmartStepExtra);
  4082. }
  4083. else if (mu)
  4084. {
  4085. got = getRow(mu);
  4086. if (!got && meta.isGrouped() && !eogSent)
  4087. {
  4088. eogSent = true;
  4089. return NULL;
  4090. }
  4091. }
  4092. if (got)
  4093. {
  4094. processRow(got);
  4095. return got;
  4096. }
  4097. eogSent = false;
  4098. if (!reload())
  4099. return NULL;
  4100. }
  4101. }
  4102. bool reload()
  4103. {
  4104. // Wait for something to be returned from a slave....
  4105. mu.clear();
  4106. sentsome.wait();
  4107. // must be at least an endMarker on the queue since sentsome was signalled
  4108. {
  4109. CriticalBlock b(pendingCrit);
  4110. IRoxieServerQueryPacket &top = pending.item(0);
  4111. if (top.isLimit(rowLimit, keyedLimit, stopAfter)) // This is really a start marker...
  4112. {
  4113. pending.remove(0);
  4114. return true;
  4115. }
  4116. else if (top.isEnd())
  4117. {
  4118. pending.remove(0);
  4119. allread = true;
  4120. if (activity.queryLogCtx().queryTraceLevel() > 5)
  4121. activity.queryLogCtx().CTXLOG("All read on ruid %x", ruid);
  4122. return false;
  4123. }
  4124. else if (mergeOrder)
  4125. {
  4126. unsigned idx = 0;
  4127. bool added = false;
  4128. while (pending.isItem(idx))
  4129. {
  4130. IRoxieServerQueryPacket &item = pending.item(idx);
  4131. if (item.isEnd())
  4132. {
  4133. if (merger.noteEndSeen())
  4134. {
  4135. sentsome.signal(); // Because we waited, yet didn't actually consume anything
  4136. added = true;
  4137. }
  4138. break;
  4139. }
  4140. else if (item.hasResult())
  4141. {
  4142. merger.noteResult(&item, item.getSequence());
  4143. pending.remove(idx);
  4144. added = true;
  4145. }
  4146. else if (item.isContinuation())
  4147. idx++;
  4148. else
  4149. break;
  4150. }
  4151. if (added)
  4152. return true;
  4153. }
  4154. else if (top.hasResult())
  4155. {
  4156. mr.setown(pending.item(0).getResult());
  4157. mu.setown(mr->getCursor(rowManager));
  4158. pending.remove(0);
  4159. return true;
  4160. }
  4161. }
  4162. getNextUnpacker();
  4163. return true;
  4164. }
  4165. void getNextUnpacker()
  4166. {
  4167. mu.clear();
  4168. unsigned ctxTraceLevel = activity.queryLogCtx().queryTraceLevel();
  4169. for (;;)
  4170. {
  4171. checkDelayed();
  4172. unsigned timeout = remoteId.isSLAPriority() ? slaTimeout : (remoteId.isHighPriority() ? highTimeout : lowTimeout);
  4173. activity.queryContext()->checkAbort();
  4174. bool anyActivity;
  4175. if (ctxTraceLevel > 5)
  4176. activity.queryLogCtx().CTXLOG("Calling getNextUnpacker(%d)", timeout);
  4177. mr.setown(mc->getNextResult(timeout, anyActivity));
  4178. if (ctxTraceLevel > 6)
  4179. activity.queryLogCtx().CTXLOG("Called getNextUnpacker(%d), activity=%d", timeout, anyActivity);
  4180. activity.queryContext()->checkAbort();
  4181. if (mr)
  4182. {
  4183. unsigned roxieHeaderLen;
  4184. const RoxiePacketHeader &header = *(const RoxiePacketHeader *) mr->getMessageHeader(roxieHeaderLen);
  4185. #ifdef _DEBUG
  4186. assertex(roxieHeaderLen == sizeof(RoxiePacketHeader));
  4187. #endif
  4188. if (ctxTraceLevel > 5)
  4189. {
  4190. StringBuffer s;
  4191. activity.queryLogCtx().CTXLOG("getNextUnpacker got packet %s", header.toString(s).str());
  4192. }
  4193. CriticalBlock b(pendingCrit);
  4194. unsigned idx = 0;
  4195. IRoxieServerQueryPacket *original = NULL;
  4196. IRoxieQueryPacket *op;
  4197. while (pending.isItem(idx))
  4198. {
  4199. original = &pending.item(idx);
  4200. op = original->queryPacket();
  4201. if (op && header.matchPacket(op->queryHeader()))
  4202. break;
  4203. original = NULL;
  4204. idx++;
  4205. }
  4206. if (!original || original->hasResult())
  4207. {
  4208. switch (header.activityId)
  4209. {
  4210. case ROXIE_FILECALLBACK:
  4211. {
  4212. // tell slave to abort
  4213. //if (ctxTraceLevel > 5)
  4214. {
  4215. StringBuffer s;
  4216. activity.queryLogCtx().CTXLOG("Redundant callback on query %s", header.toString(s).str());
  4217. }
  4218. Owned<IMessageUnpackCursor> callbackData = mr->getCursor(rowManager);
  4219. OwnedConstRoxieRow len = callbackData->getNext(sizeof(RecordLengthType));
  4220. if (len)
  4221. {
  4222. RecordLengthType *rowlen = (RecordLengthType *) len.get();
  4223. OwnedConstRoxieRow row = callbackData->getNext(*rowlen);
  4224. const char *rowdata = (const char *) row.get();
  4225. // bool isOpt = * (bool *) rowdata;
  4226. // bool isLocal = * (bool *) (rowdata+1);
  4227. ROQ->sendAbortCallback(header, rowdata+2, activity.queryLogCtx());
  4228. }
  4229. else
  4230. throwUnexpected();
  4231. break;
  4232. }
  4233. // MORE - ROXIE_ALIVE perhaps should go here too
  4234. default:
  4235. if (ctxTraceLevel > 3)
  4236. activity.queryLogCtx().CTXLOG("Discarding packet %p - original %p is NULL or has result already", mr.get(), original);
  4237. mr->discard();
  4238. break;
  4239. }
  4240. mr.clear();
  4241. }
  4242. else
  4243. {
  4244. atomic_inc(&resultsReceived);
  4245. switch (header.activityId)
  4246. {
  4247. case ROXIE_DEBUGCALLBACK:
  4248. {
  4249. Owned<IMessageUnpackCursor> callbackData = mr->getCursor(rowManager);
  4250. OwnedConstRoxieRow len = callbackData->getNext(sizeof(RecordLengthType));
  4251. if (len)
  4252. {
  4253. RecordLengthType *rowlen = (RecordLengthType *) len.get();
  4254. OwnedConstRoxieRow row = callbackData->getNext(*rowlen);
  4255. char *rowdata = (char *) row.get();
  4256. if (ctxTraceLevel > 5)
  4257. {
  4258. StringBuffer s;
  4259. activity.queryLogCtx().CTXLOG("Callback on query %s for debug", header.toString(s).str());
  4260. }
  4261. MemoryBuffer slaveInfo;
  4262. slaveInfo.setBuffer(*rowlen, rowdata, false);
  4263. unsigned debugSequence;
  4264. slaveInfo.read(debugSequence);
  4265. Owned<IRoxieQueryPacket> reply = original->getDebugResponse(debugSequence);
  4266. if (!reply)
  4267. reply.setown(activity.queryContext()->queryDebugContext()->onDebugCallback(header, *rowlen, rowdata));
  4268. if (reply)
  4269. {
  4270. original->setDebugResponse(debugSequence, reply);
  4271. ROQ->sendPacket(reply, activity.queryLogCtx());
  4272. }
  4273. }
  4274. else
  4275. throwUnexpected();
  4276. // MORE - somehow we need to make sure slave gets a reply even if I'm not waiting (in udp layer)
  4277. // Leave original message on pending queue in original location - this is not a reply to it.
  4278. break;
  4279. }
  4280. case ROXIE_FILECALLBACK:
  4281. {
  4282. // we need to send back to the slave a message containing the file info requested.
  4283. Owned<IMessageUnpackCursor> callbackData = mr->getCursor(rowManager);
  4284. OwnedConstRoxieRow len = callbackData->getNext(sizeof(RecordLengthType));
  4285. if (len)
  4286. {
  4287. RecordLengthType *rowlen = (RecordLengthType *) len.get();
  4288. OwnedConstRoxieRow row = callbackData->getNext(*rowlen);
  4289. const char *rowdata = (const char *) row.get();
  4290. bool isOpt = * (bool *) rowdata;
  4291. bool isLocal = * (bool *) (rowdata+1);
  4292. const char *lfn = rowdata+2;
  4293. if (ctxTraceLevel > 5)
  4294. {
  4295. StringBuffer s;
  4296. activity.queryLogCtx().CTXLOG("Callback on query %s file %s", header.toString(s).str(),(const char *) lfn);
  4297. }
  4298. activity.queryContext()->onFileCallback(header, lfn, isOpt, isLocal);
  4299. }
  4300. else
  4301. throwUnexpected();
  4302. // MORE - somehow we need to make sure slave gets a reply even if I'm not waiting (in udp layer)
  4303. // Leave original message on pending queue in original location - this is not a reply to it.
  4304. break;
  4305. }
  4306. case ROXIE_KEYEDLIMIT_EXCEEDED:
  4307. activity.queryLogCtx().CTXLOG("ROXIE_KEYEDLIMIT_EXCEEDED");
  4308. errorHandler->onLimitExceeded(true); // NOTE - should throw exception!
  4309. throwUnexpected();
  4310. case ROXIE_LIMIT_EXCEEDED:
  4311. activity.queryLogCtx().CTXLOG("ROXIE_LIMIT_EXCEEDED");
  4312. errorHandler->onLimitExceeded(false); // NOTE - should throw exception!
  4313. throwUnexpected();
  4314. case ROXIE_TRACEINFO:
  4315. {
  4316. Owned<IMessageUnpackCursor> extra = mr->getCursor(rowManager);
  4317. for (;;)
  4318. {
  4319. RecordLengthType *rowlen = (RecordLengthType *) extra->getNext(sizeof(RecordLengthType));
  4320. if (rowlen)
  4321. {
  4322. char *logInfo = (char *) extra->getNext(*rowlen);
  4323. MemoryBuffer buf;
  4324. buf.setBuffer(*rowlen, logInfo, false);
  4325. switch ((TracingCategory) *logInfo)
  4326. {
  4327. case LOG_TRACING:
  4328. case LOG_ERROR:
  4329. activity.queryLogCtx().CTXLOGl(new LogItem(buf));
  4330. break;
  4331. case LOG_STATVALUES:
  4332. buf.skip(1);
  4333. activity.mergeStats(buf);
  4334. break;
  4335. case LOG_CHILDCOUNT:
  4336. case LOG_CHILDSTATS:
  4337. unsigned graphId, childId;
  4338. buf.skip(1);
  4339. buf.read(graphId);
  4340. buf.read(childId);
  4341. if (*logInfo == LOG_CHILDCOUNT)
  4342. {
  4343. unsigned idx;
  4344. unsigned childProcessed;
  4345. unsigned childStrands;
  4346. buf.read(idx);
  4347. buf.read(childProcessed);
  4348. buf.read(childStrands);
  4349. if (traceLevel > 5)
  4350. activity.queryLogCtx().CTXLOG("Processing ChildCount %d idx %d strands %d for child %d subgraph %d", childProcessed, idx, childStrands, childId, graphId);
  4351. activity.queryContext()->noteProcessed(graphId, childId, idx, childProcessed, childStrands);
  4352. }
  4353. else
  4354. {
  4355. CRuntimeStatisticCollection childStats(allStatistics);
  4356. childStats.deserialize(buf);
  4357. if (traceLevel > 5)
  4358. {
  4359. StringBuffer s;
  4360. activity.queryLogCtx().CTXLOG("Processing ChildStats for child %d subgraph %d: %s", childId, graphId, childStats.toStr(s).str());
  4361. }
  4362. activity.queryContext()->mergeActivityStats(childStats, graphId, childId);
  4363. }
  4364. }
  4365. ReleaseRoxieRow(rowlen);
  4366. ReleaseRoxieRow(logInfo);
  4367. }
  4368. else
  4369. break;
  4370. }
  4371. break;
  4372. }
  4373. case ROXIE_EXCEPTION:
  4374. if (ctxTraceLevel > 1)
  4375. {
  4376. StringBuffer s;
  4377. activity.queryLogCtx().CTXLOG("Exception on query %s", header.toString(s).str());
  4378. }
  4379. op->queryHeader().noteException(header.retries);
  4380. if (op->queryHeader().allChannelsFailed())
  4381. {
  4382. activity.queryLogCtx().CTXLOG("Multiple exceptions on query - aborting");
  4383. Owned<IMessageUnpackCursor> exceptionData = mr->getCursor(rowManager);
  4384. throwRemoteException(exceptionData);
  4385. }
  4386. // Leave it on pending queue in original location
  4387. break;
  4388. case ROXIE_ALIVE:
  4389. if (ctxTraceLevel > 4)
  4390. {
  4391. StringBuffer s;
  4392. activity.queryLogCtx().CTXLOG("ROXIE_ALIVE: %s", header.toString(s).str());
  4393. }
  4394. op->queryHeader().noteAlive(header.retries & ROXIE_RETRIES_MASK);
  4395. // Leave it on pending queue in original location
  4396. break;
  4397. default:
  4398. if (header.retries & ROXIE_RETRIES_MASK)
  4399. atomic_inc(&retriesNeeded);
  4400. unsigned metaLen;
  4401. const void *metaData = mr->getMessageMetadata(metaLen);
  4402. if (metaLen)
  4403. {
  4404. // We got back first chunk but there is more.
  4405. // resend the packet, with the cursor info provided.
  4406. // MORE - if smart-stepping, we don't want to send the continuation immediately. Other cases it's not clear that we do.
  4407. if (ctxTraceLevel > 1)
  4408. {
  4409. StringBuffer s;
  4410. activity.queryLogCtx().CTXLOG("Additional data size %d on query %s mergeOrder %p", metaLen, header.toString(s).str(), mergeOrder);
  4411. }
  4412. if (*((unsigned short *) metaData) + sizeof(unsigned short) != metaLen)
  4413. {
  4414. StringBuffer s;
  4415. activity.queryLogCtx().CTXLOG("Additional data size %d on query %s mergeOrder %p", metaLen, header.toString(s).str(), mergeOrder);
  4416. activity.queryLogCtx().CTXLOG("Additional data is corrupt");
  4417. throwUnexpected();
  4418. }
  4419. MemoryBuffer nextQuery;
  4420. nextQuery.append(sizeof(RoxiePacketHeader), &header);
  4421. nextQuery.append(metaLen, metaData);
  4422. nextQuery.append(op->getTraceLength(), op->queryTraceInfo());
  4423. nextQuery.append(op->getContextLength(), op->queryContextData());
  4424. if (resendSequence == CONTINUESEQUENCE_MAX)
  4425. {
  4426. activity.queryLogCtx().CTXLOG("ERROR: Continuation sequence wrapped"); // shouldn't actually matter.... but suggests a very iffy query!
  4427. resendSequence = 1;
  4428. }
  4429. else
  4430. resendSequence++;
  4431. RoxiePacketHeader *newHeader = (RoxiePacketHeader *) nextQuery.toByteArray();
  4432. newHeader->continueSequence = resendSequence; // NOTE - we clear the skipTo flag since continuation of a skip is NOT a skip...
  4433. newHeader->retries &= ~ROXIE_RETRIES_MASK;
  4434. IRoxieQueryPacket *resend = createRoxiePacket(nextQuery);
  4435. CRoxieServerQueryPacket *fqp = new CRoxieServerQueryPacket(resend);
  4436. fqp->setSequence(original->getSequence());
  4437. pending.add(*fqp, idx+1); // note that pending takes ownership. sendPacket does not release.
  4438. original->setContinuation(LINK(fqp));
  4439. if (mergeOrder)
  4440. fqp->setDelayed(true);
  4441. else
  4442. {
  4443. ROQ->sendPacket(resend, activity.queryLogCtx());
  4444. sentsome.signal();
  4445. }
  4446. // Note that we don't attempt to cache results that have continuation records - too tricky !
  4447. }
  4448. else
  4449. {
  4450. if (serverSideCache)
  4451. serverSideCache->noteCachedResult(original, mr);
  4452. }
  4453. unsigned channel = header.channel;
  4454. {
  4455. ChannelBuffer *b = queryChannelBuffer(channel); // If not something is wrong, or we sent out on channel 0?
  4456. if (b)
  4457. b->signal();
  4458. }
  4459. original->setResult(mr.getClear());
  4460. sentsome.signal();
  4461. return;
  4462. }
  4463. }
  4464. }
  4465. else
  4466. {
  4467. if (!anyActivity && !localSlave)
  4468. {
  4469. activity.queryLogCtx().CTXLOG("Input has stalled - retry required?");
  4470. retryPending();
  4471. }
  4472. }
  4473. }
  4474. }
  4475. inline unsigned headerLength() const
  4476. {
  4477. return logInfo.length() + cachedContext.length() + sizeof(unsigned) + parentExtractSize;
  4478. }
  4479. void copyHeader(byte *tgt, unsigned channel) const
  4480. {
  4481. unsigned len = logInfo.length();
  4482. memcpy(tgt, logInfo.toByteArray(), len);
  4483. tgt += len;
  4484. *(unsigned *) tgt = parentExtractSize;
  4485. tgt += sizeof(unsigned);
  4486. memcpy(tgt, parentExtract, parentExtractSize);
  4487. tgt += parentExtractSize;
  4488. memcpy(tgt, cachedContext.toByteArray(), cachedContext.length());
  4489. tgt += cachedContext.length();
  4490. }
  4491. };
  4492. class CSkippableRemoteResultAdaptor : public CRemoteResultAdaptor
  4493. {
  4494. Owned <IException> exception;
  4495. bool skipping;
  4496. ConstPointerArray buff;
  4497. unsigned index;
  4498. bool pulled;
  4499. void pullInput()
  4500. {
  4501. try
  4502. {
  4503. if (exception)
  4504. throw exception.getClear();
  4505. unsigned __int64 count = 0;
  4506. for (;;)
  4507. {
  4508. const void * next = CRemoteResultAdaptor::nextRow();
  4509. if (next == NULL)
  4510. {
  4511. next = CRemoteResultAdaptor::nextRow();
  4512. if(next == NULL)
  4513. break;
  4514. buff.append(NULL);
  4515. }
  4516. count++;
  4517. if (count > rowLimit)
  4518. {
  4519. ReleaseRoxieRow(next);
  4520. ReleaseRoxieRows(buff);
  4521. errorHandler->onLimitExceeded(false); // throws an exception - user or LimitSkipException
  4522. throwUnexpected();
  4523. }
  4524. else if (count > keyedLimit)
  4525. {
  4526. ReleaseRoxieRow(next);
  4527. ReleaseRoxieRows(buff);
  4528. errorHandler->onLimitExceeded(true); // throws an exception - user or LimitSkipException
  4529. throwUnexpected();
  4530. }
  4531. buff.append(next);
  4532. }
  4533. }
  4534. catch (IException *E)
  4535. {
  4536. if (QUERYINTERFACE(E, LimitSkipException))
  4537. {
  4538. Owned<IException> cleanup = E;
  4539. ReleaseRoxieRows(buff);
  4540. const void *onfail = errorHandler->createLimitFailRow(E->errorCode() == KeyedLimitSkipErrorCode);
  4541. if (onfail)
  4542. buff.append(onfail);
  4543. }
  4544. else
  4545. throw;
  4546. }
  4547. pulled = true;
  4548. }
  4549. public:
  4550. CSkippableRemoteResultAdaptor(IRoxieSlaveContext *_ctx, IRoxieServerErrorHandler *_errorHandler, const RemoteActivityId &_remoteId, IOutputMetaData *_meta, IHThorArg &_helper, IRoxieServerActivity &_activity, bool _preserveOrder, bool _flowControlled, bool _skipping) :
  4551. CRemoteResultAdaptor(_ctx, _errorHandler, _remoteId, _meta, _helper, _activity, _preserveOrder, _flowControlled)
  4552. {
  4553. skipping = _skipping;
  4554. index = 0;
  4555. pulled = false;
  4556. }
  4557. void setException(IException *E)
  4558. {
  4559. exception.setown(E);
  4560. }
  4561. virtual void onReset()
  4562. {
  4563. roxiemem::ReleaseRoxieRowRange(buff.getArray(), index, buff.ordinality());
  4564. buff.kill();
  4565. index = 0;
  4566. pulled = false;
  4567. exception.clear();
  4568. CRemoteResultAdaptor::onReset();
  4569. }
  4570. void onStart(unsigned _parentExtractSize, const byte * _parentExtract)
  4571. {
  4572. index = 0;
  4573. pulled = false;
  4574. CRemoteResultAdaptor::onStart(_parentExtractSize, _parentExtract);
  4575. }
  4576. virtual const void * nextRowGE(const void *seek, const void *rawSeek, unsigned numFields, unsigned seeklen, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  4577. {
  4578. // 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
  4579. if (exception)
  4580. throw exception.getClear();
  4581. return CRemoteResultAdaptor::nextRowGE(seek, rawSeek, numFields, seeklen, wasCompleteMatch, stepExtra);
  4582. }
  4583. virtual const void *nextRow()
  4584. {
  4585. if (skipping)
  4586. {
  4587. if(!pulled)
  4588. pullInput();
  4589. if(buff.isItem(index))
  4590. {
  4591. const void * next = buff.item(index++);
  4592. if(next)
  4593. processed++;
  4594. return next;
  4595. }
  4596. return NULL;
  4597. }
  4598. else
  4599. {
  4600. if (exception)
  4601. throw exception.getClear();
  4602. return CRemoteResultAdaptor::nextRow();
  4603. }
  4604. }
  4605. };
  4606. //=================================================================================
  4607. class CRoxieServerApplyActivity : public CRoxieServerInternalSinkActivity
  4608. {
  4609. IHThorApplyArg &helper;
  4610. public:
  4611. CRoxieServerApplyActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4612. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, 0), helper((IHThorApplyArg &) basehelper)
  4613. {
  4614. }
  4615. virtual void onExecute()
  4616. {
  4617. helper.start();
  4618. for (;;)
  4619. {
  4620. const void * next = inputStream->ungroupedNextRow();
  4621. if (!next)
  4622. break;
  4623. helper.apply(next);
  4624. ReleaseRoxieRow(next);
  4625. }
  4626. helper.end();
  4627. }
  4628. };
  4629. class CRoxieServerApplyActivityFactory : public CRoxieServerActivityFactory
  4630. {
  4631. bool isRoot;
  4632. public:
  4633. CRoxieServerApplyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  4634. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  4635. {
  4636. }
  4637. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  4638. {
  4639. return new CRoxieServerApplyActivity(_ctx, this, _probeManager);
  4640. }
  4641. virtual bool isSink() const
  4642. {
  4643. return isRoot;
  4644. }
  4645. };
  4646. IRoxieServerActivityFactory *createRoxieServerApplyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  4647. {
  4648. return new CRoxieServerApplyActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  4649. }
  4650. //=================================================================================
  4651. class CRoxieServerNullActivity : public CRoxieServerActivity
  4652. {
  4653. public:
  4654. CRoxieServerNullActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4655. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  4656. {
  4657. }
  4658. virtual const void *nextRow()
  4659. {
  4660. return NULL;
  4661. }
  4662. };
  4663. IRoxieServerActivity * createRoxieServerNullActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4664. {
  4665. return new CRoxieServerNullActivity(_ctx, _factory, _probeManager);
  4666. }
  4667. class CRoxieServerNullActivityFactory : public CRoxieServerActivityFactory
  4668. {
  4669. public:
  4670. CRoxieServerNullActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4671. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  4672. {
  4673. }
  4674. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  4675. {
  4676. return new CRoxieServerNullActivity(_ctx, this, _probeManager);
  4677. }
  4678. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  4679. {
  4680. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for null activity");
  4681. }
  4682. };
  4683. IRoxieServerActivityFactory *createRoxieServerNullActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4684. {
  4685. return new CRoxieServerNullActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  4686. }
  4687. //=================================================================================
  4688. class CRoxieServerPassThroughActivity : public CRoxieServerActivity
  4689. {
  4690. public:
  4691. CRoxieServerPassThroughActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4692. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  4693. {
  4694. }
  4695. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  4696. {
  4697. return input->gatherConjunctions(collector);
  4698. }
  4699. virtual void resetEOF()
  4700. {
  4701. inputStream->resetEOF();
  4702. }
  4703. virtual const void *nextRow()
  4704. {
  4705. const void * next = inputStream->nextRow();
  4706. if (next)
  4707. processed++;
  4708. return next;
  4709. }
  4710. virtual bool isPassThrough()
  4711. {
  4712. return true;
  4713. }
  4714. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  4715. {
  4716. ActivityTimer t(totalCycles, timeActivities);
  4717. const void * next = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  4718. if (next)
  4719. processed++;
  4720. return next;
  4721. }
  4722. IInputSteppingMeta * querySteppingMeta()
  4723. {
  4724. return input->querySteppingMeta();
  4725. }
  4726. };
  4727. IRoxieServerActivity * createRoxieServerPassThroughActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4728. {
  4729. return new CRoxieServerPassThroughActivity(_ctx, _factory, _probeManager);
  4730. }
  4731. //=================================================================================
  4732. class CRoxieServerChildBaseActivity : public CRoxieServerActivity
  4733. {
  4734. protected:
  4735. bool eof;
  4736. bool first;
  4737. public:
  4738. CRoxieServerChildBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4739. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  4740. {
  4741. eof = false;
  4742. first = true;
  4743. }
  4744. ~CRoxieServerChildBaseActivity()
  4745. {
  4746. }
  4747. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4748. {
  4749. eof = false;
  4750. first = true;
  4751. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  4752. }
  4753. };
  4754. class CRoxieServerChildBaseActivityFactory : public CRoxieServerActivityFactory
  4755. {
  4756. public:
  4757. CRoxieServerChildBaseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4758. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  4759. {
  4760. }
  4761. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  4762. {
  4763. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  4764. }
  4765. };
  4766. //=================================================================================
  4767. class CRoxieServerChildIteratorActivity : public CRoxieServerChildBaseActivity
  4768. {
  4769. IHThorChildIteratorArg &helper;
  4770. public:
  4771. CRoxieServerChildIteratorActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4772. : CRoxieServerChildBaseActivity(_ctx, _factory, _probeManager), helper((IHThorChildIteratorArg &) basehelper)
  4773. {
  4774. }
  4775. virtual bool needsAllocator() const { return true; }
  4776. virtual const void *nextRow()
  4777. {
  4778. ActivityTimer t(totalCycles, timeActivities);
  4779. if (eof)
  4780. return NULL;
  4781. bool ok;
  4782. if (first)
  4783. {
  4784. ok = helper.first();
  4785. first = false;
  4786. }
  4787. else
  4788. ok = helper.next();
  4789. try
  4790. {
  4791. while (ok)
  4792. {
  4793. processed++;
  4794. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  4795. unsigned outSize = helper.transform(rowBuilder);
  4796. if (outSize)
  4797. return rowBuilder.finalizeRowClear(outSize);
  4798. ok = helper.next();
  4799. }
  4800. }
  4801. catch (IException *E)
  4802. {
  4803. throw makeWrappedException(E);
  4804. }
  4805. eof = true;
  4806. return NULL;
  4807. }
  4808. };
  4809. class CRoxieServerChildIteratorActivityFactory : public CRoxieServerChildBaseActivityFactory
  4810. {
  4811. public:
  4812. CRoxieServerChildIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4813. : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  4814. {
  4815. }
  4816. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  4817. {
  4818. return new CRoxieServerChildIteratorActivity(_ctx, this, _probeManager);
  4819. }
  4820. };
  4821. IRoxieServerActivityFactory *createRoxieServerChildIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4822. {
  4823. return new CRoxieServerChildIteratorActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  4824. }
  4825. //=================================================================================
  4826. class CRoxieServerChildNormalizeActivity : public CRoxieServerChildBaseActivity
  4827. {
  4828. IHThorChildNormalizeArg &helper;
  4829. public:
  4830. CRoxieServerChildNormalizeActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4831. : CRoxieServerChildBaseActivity(_ctx, _factory, _probeManager), helper((IHThorChildNormalizeArg &) basehelper)
  4832. {
  4833. }
  4834. virtual bool needsAllocator() const { return true; }
  4835. virtual const void *nextRow()
  4836. {
  4837. ActivityTimer t(totalCycles, timeActivities);
  4838. if (eof)
  4839. return NULL;
  4840. bool ok;
  4841. if (first)
  4842. {
  4843. ok = helper.first();
  4844. first = false;
  4845. }
  4846. else
  4847. ok = helper.next();
  4848. if (ok)
  4849. {
  4850. try
  4851. {
  4852. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  4853. do {
  4854. unsigned outSize = helper.transform(rowBuilder);
  4855. if (outSize)
  4856. {
  4857. processed++;
  4858. return rowBuilder.finalizeRowClear(outSize);
  4859. }
  4860. ok = helper.next();
  4861. }
  4862. while (ok);
  4863. }
  4864. catch (IException *E)
  4865. {
  4866. throw makeWrappedException(E);
  4867. }
  4868. }
  4869. eof = true;
  4870. return NULL;
  4871. }
  4872. };
  4873. class CRoxieServerChildNormalizeActivityFactory : public CRoxieServerChildBaseActivityFactory
  4874. {
  4875. public:
  4876. CRoxieServerChildNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4877. : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  4878. {
  4879. }
  4880. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  4881. {
  4882. return new CRoxieServerChildNormalizeActivity(_ctx, this, _probeManager);
  4883. }
  4884. };
  4885. IRoxieServerActivityFactory *createRoxieServerNewChildNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4886. {
  4887. return new CRoxieServerChildNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  4888. }
  4889. //=================================================================================
  4890. class CRoxieServerChildAggregateActivity : public CRoxieServerChildBaseActivity
  4891. {
  4892. IHThorChildAggregateArg &helper;
  4893. public:
  4894. CRoxieServerChildAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4895. : CRoxieServerChildBaseActivity(_ctx, _factory, _probeManager), helper((IHThorChildAggregateArg &) basehelper)
  4896. {
  4897. }
  4898. virtual bool needsAllocator() const { return true; }
  4899. virtual const void *nextRow()
  4900. {
  4901. ActivityTimer t(totalCycles, timeActivities);
  4902. if (eof)
  4903. return NULL;
  4904. eof = true;
  4905. processed++;
  4906. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  4907. helper.clearAggregate(rowBuilder);
  4908. helper.processRows(rowBuilder);
  4909. size32_t finalSize = meta.getRecordSize(rowBuilder.getSelf());
  4910. return rowBuilder.finalizeRowClear(finalSize);
  4911. }
  4912. };
  4913. class CRoxieServerChildAggregateActivityFactory : public CRoxieServerChildBaseActivityFactory
  4914. {
  4915. public:
  4916. CRoxieServerChildAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4917. : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  4918. {
  4919. }
  4920. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  4921. {
  4922. return new CRoxieServerChildAggregateActivity(_ctx, this, _probeManager);
  4923. }
  4924. };
  4925. IRoxieServerActivityFactory *createRoxieServerNewChildAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4926. {
  4927. return new CRoxieServerChildAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  4928. }
  4929. //=================================================================================
  4930. class CRoxieServerChildGroupAggregateActivity : public CRoxieServerChildBaseActivity, public IHThorGroupAggregateCallback
  4931. {
  4932. IHThorChildGroupAggregateArg &helper;
  4933. RowAggregator aggregated;
  4934. public:
  4935. IMPLEMENT_IINTERFACE_USING(CRoxieServerChildBaseActivity)
  4936. CRoxieServerChildGroupAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4937. : CRoxieServerChildBaseActivity(_ctx, _factory, _probeManager), helper((IHThorChildGroupAggregateArg &) basehelper),
  4938. aggregated(helper, helper)
  4939. {
  4940. }
  4941. void processRow(const void * next)
  4942. {
  4943. aggregated.addRow(next);
  4944. }
  4945. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4946. {
  4947. CRoxieServerChildBaseActivity::start(parentExtractSize, parentExtract, paused);
  4948. aggregated.start(rowAllocator);
  4949. }
  4950. virtual void reset()
  4951. {
  4952. aggregated.reset();
  4953. CRoxieServerChildBaseActivity::reset();
  4954. }
  4955. virtual bool needsAllocator() const { return true; }
  4956. virtual const void *nextRow()
  4957. {
  4958. ActivityTimer t(totalCycles, timeActivities);
  4959. if (eof)
  4960. return NULL;
  4961. if (first)
  4962. {
  4963. helper.processRows(this);
  4964. first = false;
  4965. }
  4966. Owned<AggregateRowBuilder> next = aggregated.nextResult();
  4967. if (next)
  4968. {
  4969. processed++;
  4970. return next->finalizeRowClear();
  4971. }
  4972. eof = true;
  4973. return NULL;
  4974. }
  4975. };
  4976. class CRoxieServerChildGroupAggregateActivityFactory : public CRoxieServerChildBaseActivityFactory
  4977. {
  4978. public:
  4979. CRoxieServerChildGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4980. : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  4981. {
  4982. }
  4983. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  4984. {
  4985. return new CRoxieServerChildGroupAggregateActivity(_ctx, this, _probeManager);
  4986. }
  4987. };
  4988. IRoxieServerActivityFactory *createRoxieServerNewChildGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4989. {
  4990. return new CRoxieServerChildGroupAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  4991. }
  4992. //=================================================================================
  4993. class CRoxieServerChildThroughNormalizeActivity : public CRoxieServerChildBaseActivity
  4994. {
  4995. IHThorChildThroughNormalizeArg &helper;
  4996. const void * lastInput;
  4997. unsigned numProcessedLastGroup;
  4998. bool ok;
  4999. public:
  5000. CRoxieServerChildThroughNormalizeActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5001. : CRoxieServerChildBaseActivity(_ctx, _factory, _probeManager), helper((IHThorChildThroughNormalizeArg &) basehelper)
  5002. {
  5003. lastInput = NULL;
  5004. numProcessedLastGroup = 0;
  5005. ok = false;
  5006. }
  5007. virtual void stop()
  5008. {
  5009. CRoxieServerChildBaseActivity::stop();
  5010. ReleaseRoxieRow(lastInput);
  5011. lastInput = NULL;
  5012. }
  5013. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5014. {
  5015. CRoxieServerChildBaseActivity::start(parentExtractSize, parentExtract, paused);
  5016. numProcessedLastGroup = processed;
  5017. ok = false;
  5018. }
  5019. virtual bool needsAllocator() const { return true; }
  5020. virtual const void *nextRow()
  5021. {
  5022. ActivityTimer t(totalCycles, timeActivities);
  5023. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  5024. for (;;)
  5025. {
  5026. if (ok)
  5027. ok = helper.next();
  5028. while (!ok)
  5029. {
  5030. ReleaseRoxieRow(lastInput);
  5031. lastInput = inputStream->nextRow();
  5032. if (!lastInput)
  5033. {
  5034. if (numProcessedLastGroup != processed)
  5035. {
  5036. numProcessedLastGroup = processed;
  5037. return NULL;
  5038. }
  5039. lastInput = inputStream->nextRow();
  5040. if (!lastInput)
  5041. return NULL;
  5042. }
  5043. ok = helper.first(lastInput);
  5044. }
  5045. try
  5046. {
  5047. do
  5048. {
  5049. unsigned outSize = helper.transform(rowBuilder);
  5050. if (outSize)
  5051. {
  5052. processed++;
  5053. return rowBuilder.finalizeRowClear(outSize);
  5054. }
  5055. ok = helper.next();
  5056. } while (ok);
  5057. }
  5058. catch (IException *E)
  5059. {
  5060. throw makeWrappedException(E);
  5061. }
  5062. }
  5063. }
  5064. };
  5065. class CRoxieServerChildThroughNormalizeActivityFactory : public CRoxieServerActivityFactory
  5066. {
  5067. public:
  5068. CRoxieServerChildThroughNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5069. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  5070. {
  5071. }
  5072. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  5073. {
  5074. return new CRoxieServerChildThroughNormalizeActivity(_ctx, this, _probeManager);
  5075. }
  5076. };
  5077. IRoxieServerActivityFactory *createRoxieServerNewChildThroughNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5078. {
  5079. return new CRoxieServerChildThroughNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  5080. }
  5081. //=================================================================================
  5082. class CRoxieServerDistributionActivity : public CRoxieServerInternalSinkActivity
  5083. {
  5084. IHThorDistributionArg &helper;
  5085. public:
  5086. CRoxieServerDistributionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5087. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, 0), helper((IHThorDistributionArg &)basehelper)
  5088. {
  5089. }
  5090. virtual void onExecute()
  5091. {
  5092. MemoryAttr ma;
  5093. IDistributionTable * * accumulator = (IDistributionTable * *)ma.allocate(helper.queryInternalRecordSize()->getMinRecordSize());
  5094. helper.clearAggregate(accumulator);
  5095. OwnedConstRoxieRow nextrec(inputStream->nextRow());
  5096. for (;;)
  5097. {
  5098. if (!nextrec)
  5099. {
  5100. nextrec.setown(inputStream->nextRow());
  5101. if (!nextrec)
  5102. break;
  5103. }
  5104. helper.process(accumulator, nextrec);
  5105. nextrec.setown(inputStream->nextRow());
  5106. }
  5107. StringBuffer result;
  5108. result.append("<XML>");
  5109. helper.gatherResult(accumulator, result);
  5110. result.append("</XML>");
  5111. helper.sendResult(result.length(), result.str());
  5112. helper.destruct(accumulator);
  5113. }
  5114. };
  5115. class CRoxieServerDistributionActivityFactory : public CRoxieServerActivityFactory
  5116. {
  5117. bool isRoot;
  5118. public:
  5119. CRoxieServerDistributionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  5120. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  5121. {
  5122. }
  5123. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  5124. {
  5125. return new CRoxieServerDistributionActivity(_ctx, this, _probeManager);
  5126. }
  5127. virtual bool isSink() const
  5128. {
  5129. return isRoot;
  5130. }
  5131. };
  5132. IRoxieServerActivityFactory *createRoxieServerDistributionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  5133. {
  5134. return new CRoxieServerDistributionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  5135. }
  5136. //=================================================================================
  5137. class CRoxieServerLinkedRawIteratorActivity : public CRoxieServerActivity
  5138. {
  5139. IHThorLinkedRawIteratorArg &helper;
  5140. public:
  5141. CRoxieServerLinkedRawIteratorActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5142. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorLinkedRawIteratorArg &) basehelper)
  5143. {
  5144. }
  5145. virtual const void *nextRow()
  5146. {
  5147. ActivityTimer t(totalCycles, timeActivities);
  5148. const void *ret =helper.next();
  5149. if (ret)
  5150. {
  5151. LinkRoxieRow(ret);
  5152. processed++;
  5153. }
  5154. return ret;
  5155. }
  5156. };
  5157. class CRoxieServerLinkedRawIteratorActivityFactory : public CRoxieServerActivityFactory
  5158. {
  5159. public:
  5160. CRoxieServerLinkedRawIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5161. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  5162. {
  5163. }
  5164. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  5165. {
  5166. return new CRoxieServerLinkedRawIteratorActivity(_ctx, this, _probeManager);
  5167. }
  5168. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  5169. {
  5170. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  5171. }
  5172. };
  5173. IRoxieServerActivityFactory *createRoxieServerLinkedRawIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5174. {
  5175. return new CRoxieServerLinkedRawIteratorActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  5176. }
  5177. //=================================================================================
  5178. class CRoxieServerDatasetResultActivity : public CRoxieServerActivity
  5179. {
  5180. public:
  5181. CRoxieServerDatasetResultActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5182. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  5183. {
  5184. }
  5185. virtual const void *nextRow()
  5186. {
  5187. throwUnexpected();
  5188. }
  5189. virtual void executeChild(size32_t & retSize, void * & ret, unsigned parentExtractSize, const byte * parentExtract)
  5190. {
  5191. try
  5192. {
  5193. start(parentExtractSize, parentExtract, false);
  5194. {
  5195. ActivityTimer t(totalCycles, timeActivities);
  5196. MemoryBuffer result;
  5197. IRecordSize * inputMeta = input->queryOutputMeta();
  5198. for (;;)
  5199. {
  5200. const void *nextrec = inputStream->ungroupedNextRow();
  5201. if (!nextrec)
  5202. break;
  5203. result.append(inputMeta->getRecordSize(nextrec), nextrec);
  5204. ReleaseRoxieRow(nextrec);
  5205. }
  5206. retSize = result.length();
  5207. ret = result.detach();
  5208. }
  5209. stop();
  5210. reset();
  5211. }
  5212. catch(IException *E)
  5213. {
  5214. ctx->notifyAbort(E);
  5215. abort();
  5216. reset();
  5217. throw;
  5218. }
  5219. catch(...)
  5220. {
  5221. Owned<IException> E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught at %s:%d", sanitizeSourceFile(__FILE__), __LINE__);
  5222. ctx->notifyAbort(E);
  5223. abort();
  5224. reset();
  5225. throw;
  5226. }
  5227. }
  5228. };
  5229. class CRoxieServerDatasetResultActivityFactory : public CRoxieServerActivityFactory
  5230. {
  5231. bool isRoot;
  5232. public:
  5233. CRoxieServerDatasetResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  5234. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  5235. {
  5236. }
  5237. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  5238. {
  5239. return new CRoxieServerDatasetResultActivity(_ctx, this, _probeManager);
  5240. }
  5241. virtual bool isSink() const
  5242. {
  5243. return isRoot;
  5244. }
  5245. };
  5246. IRoxieServerActivityFactory *createRoxieServerDatasetResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  5247. {
  5248. return new CRoxieServerDatasetResultActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  5249. }
  5250. //=================================================================================
  5251. class CRoxieServerInlineTableActivity : public CRoxieServerActivity
  5252. {
  5253. IHThorInlineTableArg &helper;
  5254. __uint64 curRow;
  5255. __uint64 numRows;
  5256. public:
  5257. CRoxieServerInlineTableActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5258. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorInlineTableArg &) basehelper)
  5259. {
  5260. curRow = 0;
  5261. numRows = 0;
  5262. }
  5263. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5264. {
  5265. curRow = 0;
  5266. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5267. numRows = helper.numRows();
  5268. }
  5269. virtual bool needsAllocator() const { return true; }
  5270. virtual const void *nextRow()
  5271. {
  5272. ActivityTimer t(totalCycles, timeActivities);
  5273. // Filtering empty rows, returns the next valid row
  5274. while (curRow < numRows)
  5275. {
  5276. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  5277. unsigned outSize = helper.getRow(rowBuilder, curRow++);
  5278. if (outSize)
  5279. {
  5280. processed++;
  5281. return rowBuilder.finalizeRowClear(outSize);
  5282. }
  5283. }
  5284. return NULL;
  5285. }
  5286. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  5287. {
  5288. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  5289. }
  5290. };
  5291. class CRoxieServerStrandedInlineTableActivity : public CRoxieServerStrandedActivity
  5292. {
  5293. IHThorInlineTableArg &helper;
  5294. __uint64 numRows;
  5295. //An inline table that isn't stranded
  5296. class InlineTableSimpleProcessor : public StrandProcessor
  5297. {
  5298. protected:
  5299. IHThorInlineTableArg &helper;
  5300. __uint64 curRow;
  5301. __uint64 maxRows;
  5302. public:
  5303. InlineTableSimpleProcessor(CRoxieServerActivity &_parent, IHThorInlineTableArg &_helper)
  5304. : StrandProcessor(_parent, NULL, true), helper(_helper), curRow(0), maxRows(0)
  5305. {
  5306. }
  5307. virtual void start() override
  5308. {
  5309. StrandProcessor::start();
  5310. curRow = 0;
  5311. maxRows = queryParent().numRows;
  5312. }
  5313. virtual const void * nextRow()
  5314. {
  5315. ActivityTimer t(totalCycles, timeActivities);
  5316. //Return rows while the current section is active
  5317. while (curRow < maxRows)
  5318. {
  5319. RtlDynamicRowBuilder rowBuilder(*rowAllocator);
  5320. unsigned outSize = helper.getRow(rowBuilder, curRow++);
  5321. if (outSize)
  5322. {
  5323. processed++;
  5324. return rowBuilder.finalizeRowClear(outSize);
  5325. }
  5326. }
  5327. return NULL;
  5328. }
  5329. CRoxieServerStrandedInlineTableActivity & queryParent() { return static_cast<CRoxieServerStrandedInlineTableActivity&>(parent); }
  5330. };
  5331. class InlineTableStrandProcessor : public StrandProcessor
  5332. {
  5333. protected:
  5334. IHThorInlineTableArg &helper;
  5335. unsigned whichStrand;
  5336. unsigned numStrands = 0;
  5337. __uint64 sectionSize;
  5338. __uint64 curRow = 0;
  5339. __uint64 sectionMaxRows = 0;
  5340. __uint64 maxRows = 0;
  5341. bool isOrdered;
  5342. bool eosPending;
  5343. public:
  5344. InlineTableStrandProcessor(CRoxieServerActivity &_parent, IHThorInlineTableArg &_helper, unsigned _whichStrand, bool _isOrdered)
  5345. : StrandProcessor(_parent, NULL, true), helper(_helper), whichStrand(_whichStrand), isOrdered(_isOrdered)
  5346. {
  5347. sectionSize = queryParent().strandOptions.blockSize;
  5348. eosPending = false;
  5349. }
  5350. virtual void start() override
  5351. {
  5352. StrandProcessor::start();
  5353. numStrands = queryParent().numStrands();
  5354. maxRows = queryParent().numRows;
  5355. curRow = std::min(whichStrand * sectionSize, maxRows);
  5356. sectionMaxRows = std::min(curRow + sectionSize, maxRows);
  5357. eosPending = isOrdered && (curRow != maxRows);
  5358. }
  5359. virtual const void * nextRow()
  5360. {
  5361. ActivityTimer t(totalCycles, timeActivities);
  5362. for (;;)
  5363. {
  5364. //Return rows while the current section is active
  5365. while (curRow < sectionMaxRows)
  5366. {
  5367. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  5368. unsigned outSize = helper.getRow(rowBuilder, curRow++);
  5369. if (outSize)
  5370. {
  5371. processed++;
  5372. return rowBuilder.finalizeRowClear(outSize);
  5373. }
  5374. }
  5375. if (curRow == maxRows)
  5376. return NULL;
  5377. //Update current position to the next section
  5378. curRow += (numStrands - 1) * sectionSize;
  5379. if (curRow > maxRows)
  5380. curRow = maxRows;
  5381. sectionMaxRows = std::min(curRow + sectionSize, maxRows);
  5382. //If we have output a block of rows, then send the block as a unit - results now come from the next strand
  5383. if (eosPending)
  5384. {
  5385. //If there is another block, then second an end of section marker after it, otherwise make sure NULL is returned next.
  5386. eosPending = isOrdered && (curRow != maxRows);
  5387. return queryEndOfSectionMarker();
  5388. }
  5389. }
  5390. }
  5391. CRoxieServerStrandedInlineTableActivity & queryParent() { return static_cast<CRoxieServerStrandedInlineTableActivity&>(parent); }
  5392. };
  5393. public:
  5394. CRoxieServerStrandedInlineTableActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const StrandOptions &_strandOptions)
  5395. : CRoxieServerStrandedActivity(_ctx, _factory, _probeManager, _strandOptions), helper((IHThorInlineTableArg &) basehelper)
  5396. {
  5397. numRows = 0;
  5398. }
  5399. virtual StrandProcessor *createStrandProcessor(IEngineRowStream *instream) { throwUnexpected(); }
  5400. virtual StrandProcessor *createStrandSourceProcessor(bool inputOrdered)
  5401. {
  5402. if (strandOptions.numStrands <= 1)
  5403. return new InlineTableSimpleProcessor(*this, helper);
  5404. return new InlineTableStrandProcessor(*this, helper, strands.ordinality(), inputOrdered);
  5405. }
  5406. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5407. {
  5408. CRoxieServerStrandedActivity::start(parentExtractSize, parentExtract, paused);
  5409. numRows = helper.numRows();
  5410. onStartStrands();
  5411. startJunction(sourceJunction); // This must be started *after* all the strands have been initialised
  5412. }
  5413. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  5414. {
  5415. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  5416. }
  5417. };
  5418. class CRoxieServerInlineTableActivityFactory : public CRoxieServerActivityFactory
  5419. {
  5420. StrandOptions strandOptions;
  5421. public:
  5422. CRoxieServerInlineTableActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5423. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), strandOptions(_graphNode)
  5424. {
  5425. optStableInput = false; // do not force the output to be ordered
  5426. }
  5427. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  5428. {
  5429. return new CRoxieServerStrandedInlineTableActivity(_ctx, this, _probeManager, strandOptions);
  5430. }
  5431. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  5432. {
  5433. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for InlineTable activity");
  5434. }
  5435. };
  5436. IRoxieServerActivityFactory *createRoxieServerInlineTableActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5437. {
  5438. return new CRoxieServerInlineTableActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  5439. }
  5440. //=================================================================================
  5441. class CRoxieServerWorkUnitReadActivity : public CRoxieServerActivity
  5442. {
  5443. IHThorWorkunitReadArg &helper;
  5444. CriticalSection readerCrit;
  5445. Owned<IWorkUnitRowReader> wuReader;
  5446. public:
  5447. CRoxieServerWorkUnitReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5448. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorWorkunitReadArg &)basehelper)
  5449. {
  5450. }
  5451. virtual void onCreate(IHThorArg *_colocalParent)
  5452. {
  5453. CRoxieServerActivity::onCreate(_colocalParent);
  5454. if (!ctx->queryServerContext())
  5455. {
  5456. throw MakeStringException(ROXIE_INTERNAL_ERROR, "Workunit read activity cannot be executed in slave context");
  5457. }
  5458. }
  5459. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5460. {
  5461. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5462. IXmlToRowTransformer * xmlTransformer = helper.queryXmlTransformer();
  5463. OwnedRoxieString fromWuid(helper.getWUID());
  5464. wuReader.setown(ctx->getWorkunitRowReader(fromWuid, helper.queryName(), helper.querySequence(), xmlTransformer, rowAllocator, meta.isGrouped()));
  5465. // MORE _ should that be in onCreate?
  5466. }
  5467. virtual void reset()
  5468. {
  5469. {
  5470. CriticalBlock b(readerCrit);
  5471. wuReader.clear();
  5472. }
  5473. CRoxieServerActivity::reset();
  5474. };
  5475. virtual bool needsAllocator() const { return true; }
  5476. virtual const void *nextRow()
  5477. {
  5478. ActivityTimer t(totalCycles, timeActivities);
  5479. Linked<IWorkUnitRowReader> useReader;
  5480. {
  5481. CriticalBlock b(readerCrit);
  5482. if (!wuReader)
  5483. return NULL;
  5484. useReader.set(wuReader);
  5485. }
  5486. const void *ret = useReader->nextRow();
  5487. if (ret)
  5488. processed++;
  5489. return ret;
  5490. }
  5491. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  5492. {
  5493. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  5494. }
  5495. };
  5496. class CRoxieServerWorkUnitReadActivityFactory : public CRoxieServerActivityFactory
  5497. {
  5498. public:
  5499. CRoxieServerWorkUnitReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5500. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  5501. {
  5502. }
  5503. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  5504. {
  5505. return new CRoxieServerWorkUnitReadActivity(_ctx, this, _probeManager);
  5506. }
  5507. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  5508. {
  5509. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for WorkUnitRead activity");
  5510. }
  5511. };
  5512. IRoxieServerActivityFactory *createRoxieServerWorkUnitReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5513. {
  5514. return new CRoxieServerWorkUnitReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  5515. }
  5516. //=================================================================================
  5517. interface ILocalGraphEx : public IEclGraphResults
  5518. {
  5519. public:
  5520. virtual void setResult(unsigned id, IGraphResult * result) = 0;
  5521. virtual IEngineRowStream * createResultIterator(unsigned id) = 0;
  5522. virtual void setGraphLoopResult(IGraphResult * result) = 0;
  5523. virtual IEngineRowStream * createGraphLoopResultIterator(unsigned id) = 0;
  5524. };
  5525. class CSafeRoxieInput : implements IEngineRowStream, implements IFinalRoxieInput, public CInterface
  5526. {
  5527. public:
  5528. CSafeRoxieInput(unsigned _sourceIdx, IFinalRoxieInput * _input) : input(_input), inputStream(NULL), sourceIdx(_sourceIdx) {}
  5529. IMPLEMENT_IINTERFACE
  5530. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  5531. {
  5532. connectInputStreams(ctx, consumerOrdered);
  5533. streams.append(this);
  5534. return NULL;
  5535. }
  5536. void connectInputStreams(IRoxieSlaveContext *ctx, bool consumerOrdered)
  5537. {
  5538. inputStream.set(connectSingleStream(ctx, input, sourceIdx, junction, consumerOrdered));
  5539. }
  5540. virtual IOutputMetaData * queryOutputMeta() const
  5541. {
  5542. return input->queryOutputMeta();
  5543. }
  5544. virtual unsigned __int64 queryTotalCycles() const
  5545. {
  5546. return input->queryTotalCycles();
  5547. }
  5548. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { assertex(whichInput==0); return this; }
  5549. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { assertex(idx==0); return nullptr; }
  5550. virtual IRoxieServerActivity *queryActivity()
  5551. {
  5552. return input->queryActivity();
  5553. }
  5554. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  5555. {
  5556. return input->queryIndexReadActivity();
  5557. }
  5558. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5559. {
  5560. CriticalBlock procedure(cs);
  5561. input->start(parentExtractSize, parentExtract, paused);
  5562. startJunction(junction);
  5563. }
  5564. virtual void stop()
  5565. {
  5566. CriticalBlock procedure(cs);
  5567. inputStream->stop();
  5568. }
  5569. virtual void reset()
  5570. {
  5571. CriticalBlock procedure(cs);
  5572. input->reset();
  5573. resetJunction(junction);
  5574. }
  5575. virtual void resetEOF()
  5576. {
  5577. CriticalBlock procedure(cs);
  5578. inputStream->resetEOF();
  5579. }
  5580. virtual const void *nextRow()
  5581. {
  5582. CriticalBlock procedure(cs);
  5583. return inputStream->nextRow();
  5584. }
  5585. virtual bool nextGroup(ConstPointerArray & group)
  5586. {
  5587. CriticalBlock procedure(cs);
  5588. return inputStream->nextGroup(group);
  5589. }
  5590. private:
  5591. CriticalSection cs;
  5592. Linked<IFinalRoxieInput> input;
  5593. Linked<IEngineRowStream> inputStream;
  5594. Owned<IStrandJunction> junction;
  5595. unsigned sourceIdx;
  5596. };
  5597. //=================================================================================
  5598. class CPseudoRoxieInput : implements IEngineRowStream, implements IFinalRoxieInput, public CInterface
  5599. {
  5600. public:
  5601. IMPLEMENT_IINTERFACE;
  5602. CPseudoRoxieInput()
  5603. {
  5604. }
  5605. virtual unsigned __int64 queryTotalCycles() const
  5606. {
  5607. return 0;
  5608. }
  5609. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { assertex(whichInput==0); return this; }
  5610. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { assertex(idx==0); return nullptr; }
  5611. virtual IRoxieServerActivity *queryActivity()
  5612. {
  5613. throwUnexpected();
  5614. }
  5615. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  5616. {
  5617. throwUnexpected();
  5618. }
  5619. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  5620. {
  5621. assertex(!idx);
  5622. streams.append(this);
  5623. return NULL;
  5624. }
  5625. virtual IOutputMetaData * queryOutputMeta() const { throwUnexpected(); }
  5626. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused) { }
  5627. virtual void stop() { }
  5628. virtual void reset() { }
  5629. virtual void checkAbort() { }
  5630. virtual void resetEOF() { }
  5631. };
  5632. class CIndirectRoxieInput : public CPseudoRoxieInput
  5633. {
  5634. public:
  5635. CIndirectRoxieInput() : input(NULL)
  5636. {
  5637. stream = NULL;
  5638. sourceIdx = 0;
  5639. }
  5640. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5641. {
  5642. input->start(parentExtractSize, parentExtract, paused);
  5643. startJunction(junction);
  5644. }
  5645. virtual void stop()
  5646. {
  5647. stream->stop();
  5648. }
  5649. virtual void reset()
  5650. {
  5651. input->reset();
  5652. resetJunction(junction);
  5653. }
  5654. virtual const void * nextRow()
  5655. {
  5656. return stream->nextRow();
  5657. }
  5658. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  5659. {
  5660. return stream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  5661. }
  5662. virtual unsigned __int64 queryTotalCycles() const
  5663. {
  5664. return input->queryTotalCycles();
  5665. }
  5666. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  5667. {
  5668. return input->gatherConjunctions(collector);
  5669. }
  5670. virtual void resetEOF()
  5671. {
  5672. stream->resetEOF();
  5673. }
  5674. virtual unsigned numConcreteOutputs() const
  5675. {
  5676. return input->numConcreteOutputs();
  5677. }
  5678. virtual IFinalRoxieInput * queryConcreteInput(unsigned idx)
  5679. {
  5680. return input->queryConcreteInput(idx);
  5681. }
  5682. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput)
  5683. {
  5684. return input->queryConcreteOutputStream(whichInput);
  5685. }
  5686. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const
  5687. {
  5688. return input->queryConcreteOutputJunction(idx);
  5689. }
  5690. virtual IOutputMetaData * queryOutputMeta() const
  5691. {
  5692. return input->queryOutputMeta();
  5693. }
  5694. virtual IRoxieServerActivity *queryActivity()
  5695. {
  5696. return input->queryActivity();
  5697. }
  5698. inline void setInput(unsigned _sourceIdx, IFinalRoxieInput * _input)
  5699. {
  5700. input = _input;
  5701. sourceIdx = _sourceIdx;
  5702. }
  5703. inline void connectInputStreams(IRoxieSlaveContext *ctx, bool consumerOrdered)
  5704. {
  5705. stream = connectSingleStream(ctx, input, sourceIdx, junction, consumerOrdered);
  5706. }
  5707. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  5708. {
  5709. assertex(idx == 0);
  5710. connectInputStreams(ctx, consumerOrdered);
  5711. streams.append(this);
  5712. return NULL;
  5713. }
  5714. inline IFinalRoxieInput *queryInput() const
  5715. {
  5716. return input;
  5717. }
  5718. protected:
  5719. unsigned sourceIdx;
  5720. IFinalRoxieInput *input;
  5721. IEngineRowStream *stream;
  5722. Owned<IStrandJunction> junction;
  5723. };
  5724. class CExtractMapperInput : public CIndirectRoxieInput
  5725. {
  5726. unsigned savedParentExtractSize;
  5727. const byte * savedParentExtract;
  5728. public:
  5729. CExtractMapperInput()
  5730. {
  5731. savedParentExtractSize = 0;
  5732. savedParentExtract = NULL;
  5733. }
  5734. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5735. {
  5736. CIndirectRoxieInput::start(savedParentExtractSize, savedParentExtract, paused);
  5737. }
  5738. void setParentExtract(unsigned _savedParentExtractSize, const byte * _savedParentExtract)
  5739. {
  5740. savedParentExtractSize = _savedParentExtractSize;
  5741. savedParentExtract = _savedParentExtract;
  5742. }
  5743. };
  5744. class CGraphResult : implements IGraphResult, public CInterface
  5745. {
  5746. CriticalSection cs;
  5747. byte **rowset;
  5748. size32_t count;
  5749. bool complete;
  5750. void clear()
  5751. {
  5752. CriticalBlock func(cs);
  5753. rtlReleaseRowset(count, rowset);
  5754. rowset = NULL;
  5755. count = 0;
  5756. complete = false;
  5757. }
  5758. public:
  5759. IMPLEMENT_IINTERFACE
  5760. CGraphResult()
  5761. {
  5762. complete = false; // dummy result is not supposed to be used...
  5763. rowset = NULL;
  5764. count = 0;
  5765. }
  5766. CGraphResult(size32_t _count, byte **_rowset)
  5767. : count(_count), rowset(_rowset)
  5768. {
  5769. complete = true;
  5770. }
  5771. ~CGraphResult()
  5772. {
  5773. clear();
  5774. }
  5775. // interface IGraphResult
  5776. virtual IEngineRowStream * createIterator()
  5777. {
  5778. if (!complete)
  5779. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Internal Error: Reading uninitialised graph result");
  5780. return new CGraphResultIterator(this);
  5781. }
  5782. virtual void getLinkedResult(unsigned & countResult, byte * * & result)
  5783. {
  5784. if (!complete)
  5785. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Internal Error: Reading uninitialised graph result");
  5786. result = rtlLinkRowset(rowset);
  5787. countResult = count;
  5788. }
  5789. virtual const void * getLinkedRowResult()
  5790. {
  5791. if (!complete)
  5792. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Internal Error: Reading uninitialised graph result");
  5793. if (count != 1)
  5794. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Internal Error: Expected a single row result");
  5795. const void * ret = rowset[0];
  5796. LinkRoxieRow(ret);
  5797. return ret;
  5798. }
  5799. //other
  5800. const void * getRow(unsigned i)
  5801. {
  5802. CriticalBlock func(cs);
  5803. if (i >= count)
  5804. return NULL;
  5805. const void * ret = rowset[i];
  5806. if (ret) LinkRoxieRow(ret);
  5807. return ret;
  5808. }
  5809. protected:
  5810. class CGraphResultIterator : public CInterfaceOf<IEngineRowStream>
  5811. {
  5812. unsigned i;
  5813. Linked<CGraphResult> result;
  5814. public:
  5815. CGraphResultIterator(CGraphResult * _result) : result(_result) { i = 0; }
  5816. public:
  5817. virtual const void * nextRow()
  5818. {
  5819. return result->getRow(i++);
  5820. }
  5821. virtual void stop()
  5822. {
  5823. }
  5824. virtual void resetEOF()
  5825. {
  5826. throwUnexpected();
  5827. }
  5828. };
  5829. };
  5830. //=================================================================================
  5831. class CRoxieServerLocalResultReadActivity : public CRoxieServerActivity
  5832. {
  5833. IHThorLocalResultReadArg &helper;
  5834. CriticalSection iterCrit;
  5835. Owned<IEngineRowStream> iter;
  5836. ILocalGraphEx * graph;
  5837. unsigned graphId;
  5838. unsigned sequence;
  5839. public:
  5840. CRoxieServerLocalResultReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId)
  5841. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorLocalResultReadArg &)basehelper), graphId(_graphId)
  5842. {
  5843. graph = NULL;
  5844. sequence = 0;
  5845. }
  5846. virtual void onCreate(IHThorArg *_colocalParent)
  5847. {
  5848. CRoxieServerActivity::onCreate(_colocalParent);
  5849. graph = static_cast<ILocalGraphEx *>(ctx->queryCodeContext()->resolveLocalQuery(graphId));
  5850. sequence = helper.querySequence();
  5851. }
  5852. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5853. {
  5854. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5855. iter.setown(graph->createResultIterator(sequence));
  5856. }
  5857. virtual void reset()
  5858. {
  5859. {
  5860. CriticalBlock b(iterCrit);
  5861. iter.clear();
  5862. }
  5863. CRoxieServerActivity::reset();
  5864. };
  5865. virtual const void *nextRow()
  5866. {
  5867. ActivityTimer t(totalCycles, timeActivities);
  5868. Linked<IEngineRowStream> useIter;
  5869. {
  5870. CriticalBlock b(iterCrit);
  5871. if (!iter)
  5872. return NULL;
  5873. useIter.set(iter);
  5874. }
  5875. const void * next = useIter->nextRow();
  5876. if (next)
  5877. {
  5878. processed++;
  5879. atomic_inc(&rowsIn);
  5880. }
  5881. return next;
  5882. }
  5883. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  5884. {
  5885. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  5886. }
  5887. };
  5888. class CRoxieServerLocalResultReadActivityFactory : public CRoxieServerActivityFactory
  5889. {
  5890. unsigned graphId;
  5891. public:
  5892. CRoxieServerLocalResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _graphId)
  5893. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), graphId(_graphId)
  5894. {
  5895. }
  5896. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  5897. {
  5898. return new CRoxieServerLocalResultReadActivity(_ctx, this, _probeManager, graphId);
  5899. }
  5900. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  5901. {
  5902. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for LocalResultRead activity");
  5903. }
  5904. };
  5905. IRoxieServerActivityFactory *createRoxieServerLocalResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned graphId)
  5906. {
  5907. return new CRoxieServerLocalResultReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, graphId);
  5908. }
  5909. //=================================================================================
  5910. class CRoxieServerLocalResultStreamReadActivity : public CRoxieServerActivity
  5911. {
  5912. IHThorLocalResultReadArg &helper;
  5913. unsigned sequence;
  5914. public:
  5915. CRoxieServerLocalResultStreamReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5916. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorLocalResultReadArg &)basehelper)
  5917. {
  5918. sequence = 0;
  5919. }
  5920. virtual void onCreate(IHThorArg *_colocalParent)
  5921. {
  5922. CRoxieServerActivity::onCreate(_colocalParent);
  5923. sequence = helper.querySequence();
  5924. }
  5925. virtual const void *nextRow()
  5926. {
  5927. ActivityTimer t(totalCycles, timeActivities);
  5928. const void * next = inputStream->nextRow();
  5929. if (next)
  5930. {
  5931. processed++;
  5932. atomic_inc(&rowsIn);
  5933. }
  5934. return next;
  5935. }
  5936. virtual bool querySetStreamInput(unsigned id, unsigned _sourceIdx, IFinalRoxieInput * _input)
  5937. {
  5938. if (id == sequence)
  5939. {
  5940. CRoxieServerActivity::setInput(0, _sourceIdx, _input);
  5941. connectInputStreams(true);
  5942. return true;
  5943. }
  5944. return false;
  5945. }
  5946. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  5947. {
  5948. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  5949. }
  5950. };
  5951. class CRoxieServerLocalResultStreamReadActivityFactory : public CRoxieServerActivityFactory
  5952. {
  5953. public:
  5954. CRoxieServerLocalResultStreamReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5955. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  5956. {
  5957. }
  5958. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  5959. {
  5960. return new CRoxieServerLocalResultStreamReadActivity(_ctx, this, _probeManager);
  5961. }
  5962. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  5963. {
  5964. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for LocalResultRead activity");
  5965. }
  5966. };
  5967. IRoxieServerActivityFactory *createRoxieServerLocalResultStreamReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5968. {
  5969. return new CRoxieServerLocalResultStreamReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  5970. }
  5971. //=====================================================================================================
  5972. class CRoxieServerLocalResultWriteActivity : public CRoxieServerInternalSinkActivity
  5973. {
  5974. IHThorLocalResultWriteArg &helper;
  5975. ILocalGraphEx * graph;
  5976. unsigned graphId;
  5977. public:
  5978. CRoxieServerLocalResultWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId, unsigned _numOutputs)
  5979. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _numOutputs), helper((IHThorLocalResultWriteArg &)basehelper), graphId(_graphId)
  5980. {
  5981. graph = NULL;
  5982. }
  5983. virtual bool needsAllocator() const { return true; }
  5984. virtual void onCreate(IHThorArg *_colocalParent)
  5985. {
  5986. CRoxieServerInternalSinkActivity::onCreate(_colocalParent);
  5987. graph = static_cast<ILocalGraphEx *>(ctx->queryCodeContext()->resolveLocalQuery(graphId));
  5988. }
  5989. virtual void onExecute()
  5990. {
  5991. RtlLinkedDatasetBuilder builder(rowAllocator);
  5992. inputStream->readAll(builder);
  5993. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  5994. graph->setResult(helper.querySequence(), result);
  5995. }
  5996. virtual const void *nextRow()
  5997. {
  5998. return inputStream->nextRow(); // I can act as a passthrough input
  5999. }
  6000. IFinalRoxieInput * querySelectOutput(unsigned id)
  6001. {
  6002. if (id == helper.querySequence())
  6003. {
  6004. executed = true; // Ensure that we don't try to pull as a sink as well as via the passthrough
  6005. return LINK(this);
  6006. }
  6007. return NULL;
  6008. }
  6009. };
  6010. class CRoxieServerLocalResultWriteActivityFactory : public CRoxieServerInternalSinkFactory
  6011. {
  6012. unsigned graphId;
  6013. public:
  6014. CRoxieServerLocalResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, unsigned _graphId, bool _isRoot)
  6015. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot), graphId(_graphId)
  6016. {
  6017. isInternal = true;
  6018. Owned<IHThorLocalResultWriteArg> helper = (IHThorLocalResultWriteArg *) helperFactory();
  6019. }
  6020. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  6021. {
  6022. return new CRoxieServerLocalResultWriteActivity(_ctx, this, _probeManager, graphId, usageCount);
  6023. }
  6024. };
  6025. IRoxieServerActivityFactory *createRoxieServerLocalResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, unsigned _graphId, bool _isRoot)
  6026. {
  6027. return new CRoxieServerLocalResultWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _graphId, _isRoot);
  6028. }
  6029. //=====================================================================================================
  6030. class CRoxieServerDictionaryResultWriteActivity : public CRoxieServerInternalSinkActivity
  6031. {
  6032. IHThorDictionaryResultWriteArg &helper;
  6033. ILocalGraphEx * graph;
  6034. unsigned graphId;
  6035. public:
  6036. CRoxieServerDictionaryResultWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _usageCount, unsigned _graphId)
  6037. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _usageCount), helper((IHThorDictionaryResultWriteArg &)basehelper), graphId(_graphId)
  6038. {
  6039. graph = NULL;
  6040. }
  6041. virtual bool needsAllocator() const { return true; }
  6042. virtual void onCreate(IHThorArg *_colocalParent)
  6043. {
  6044. CRoxieServerInternalSinkActivity::onCreate(_colocalParent);
  6045. graph = static_cast<ILocalGraphEx *>(ctx->queryCodeContext()->resolveLocalQuery(graphId));
  6046. }
  6047. virtual void onExecute()
  6048. {
  6049. unsigned sequence = helper.querySequence();
  6050. RtlLinkedDictionaryBuilder builder(rowAllocator, helper.queryHashLookupInfo());
  6051. for (;;)
  6052. {
  6053. const void *row = inputStream->ungroupedNextRow();
  6054. if (!row)
  6055. break;
  6056. builder.appendOwn(row);
  6057. processed++;
  6058. }
  6059. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  6060. graph->setResult(helper.querySequence(), result);
  6061. }
  6062. virtual const void *nextRow()
  6063. {
  6064. return inputStream->nextRow(); // I can act as a passthrough input
  6065. }
  6066. IFinalRoxieInput * querySelectOutput(unsigned id)
  6067. {
  6068. if (id == helper.querySequence())
  6069. {
  6070. executed = true; // Ensure that we don't try to pull as a sink as well as via the passthrough
  6071. return LINK(this);
  6072. }
  6073. return NULL;
  6074. }
  6075. };
  6076. class CRoxieServerDictionaryResultWriteActivityFactory : public CRoxieServerInternalSinkFactory
  6077. {
  6078. unsigned graphId;
  6079. public:
  6080. CRoxieServerDictionaryResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, unsigned _graphId, bool _isRoot)
  6081. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot), graphId(_graphId)
  6082. {
  6083. isInternal = true;
  6084. }
  6085. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  6086. {
  6087. return new CRoxieServerDictionaryResultWriteActivity(_ctx, this, _probeManager, usageCount, graphId);
  6088. }
  6089. };
  6090. IRoxieServerActivityFactory *createRoxieServerDictionaryResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, unsigned _graphId, bool _isRoot)
  6091. {
  6092. return new CRoxieServerDictionaryResultWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _graphId, _isRoot);
  6093. }
  6094. //=================================================================================
  6095. class CRoxieServerGraphLoopResultReadActivity : public CRoxieServerActivity
  6096. {
  6097. protected:
  6098. IHThorGraphLoopResultReadArg &helper;
  6099. CriticalSection iterCrit;
  6100. Owned<IFinalRoxieInput> iterInput;
  6101. Owned<IEngineRowStream> iterStream;
  6102. Owned<IStrandJunction> iterJunction;
  6103. ILocalGraphEx * graph;
  6104. unsigned graphId;
  6105. unsigned sequence;
  6106. public:
  6107. CRoxieServerGraphLoopResultReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId)
  6108. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorGraphLoopResultReadArg &)basehelper), graphId(_graphId)
  6109. {
  6110. graph = NULL;
  6111. sequence = 0;
  6112. }
  6113. virtual void onCreate(IHThorArg *_colocalParent)
  6114. {
  6115. CRoxieServerActivity::onCreate(_colocalParent);
  6116. graph = static_cast<ILocalGraphEx *>(ctx->queryCodeContext()->resolveLocalQuery(graphId));
  6117. }
  6118. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6119. {
  6120. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6121. if (iterInput)
  6122. iterInput->start(parentExtractSize, parentExtract, paused);
  6123. else
  6124. {
  6125. sequence = helper.querySequence();
  6126. if ((int)sequence >= 0)
  6127. {
  6128. try
  6129. {
  6130. iterStream.setown(graph->createGraphLoopResultIterator(sequence));
  6131. iterInput.clear();
  6132. }
  6133. catch (IException * E)
  6134. {
  6135. throw makeWrappedException(E);
  6136. }
  6137. }
  6138. }
  6139. startJunction(iterJunction);
  6140. }
  6141. virtual void stop()
  6142. {
  6143. if (iterStream)
  6144. iterStream->stop();
  6145. CRoxieServerActivity::stop();
  6146. }
  6147. virtual void reset()
  6148. {
  6149. {
  6150. CriticalBlock b(iterCrit);
  6151. if (iterInput)
  6152. iterInput->reset();
  6153. resetJunction(iterJunction);
  6154. iterInput.clear();
  6155. iterStream.clear();
  6156. iterJunction.clear();
  6157. }
  6158. CRoxieServerActivity::reset();
  6159. };
  6160. virtual const void *nextRow()
  6161. {
  6162. ActivityTimer t(totalCycles, timeActivities);
  6163. Linked<IEngineRowStream> useStream;
  6164. {
  6165. CriticalBlock b(iterCrit);
  6166. if (!iterStream)
  6167. return NULL;
  6168. useStream.set(iterStream);
  6169. }
  6170. const void * next = useStream->nextRow();
  6171. if (next)
  6172. {
  6173. processed++;
  6174. atomic_inc(&rowsIn);
  6175. }
  6176. return next;
  6177. }
  6178. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  6179. {
  6180. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  6181. }
  6182. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract)
  6183. {
  6184. ensureCreated();
  6185. basehelper.onStart(parentExtract, NULL);
  6186. processor.noteUseIteration(helper.querySequence());
  6187. }
  6188. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract, IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes)
  6189. {
  6190. //helper already initialised from the gatherIterationUsage() call.
  6191. CRoxieServerActivity::connectInputStreams(true);
  6192. iterInput.set(processor.connectIterationOutput(helper.querySequence(), probeManager, probes, this, 0));
  6193. iterStream.set(connectSingleStream(ctx, iterInput, 0, iterJunction, true));
  6194. }
  6195. virtual IInputSteppingMeta * querySteppingMeta()
  6196. {
  6197. assertex(iterInput);
  6198. return iterInput->querySteppingMeta();
  6199. }
  6200. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  6201. {
  6202. assertex(iterStream);
  6203. return iterStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  6204. }
  6205. };
  6206. //variety of CRoxieServerGraphLoopResultReadActivity created internally with a predefined sequence number
  6207. class CRoxieServerInternalGraphLoopResultReadActivity : public CRoxieServerGraphLoopResultReadActivity
  6208. {
  6209. public:
  6210. CRoxieServerInternalGraphLoopResultReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId, unsigned _sequence)
  6211. : CRoxieServerGraphLoopResultReadActivity(_ctx, _factory, _probeManager, _graphId)
  6212. {
  6213. sequence = _sequence;
  6214. }
  6215. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6216. {
  6217. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6218. if ((int)sequence >= 0)
  6219. {
  6220. try
  6221. {
  6222. iterStream.setown(graph->createGraphLoopResultIterator(sequence));
  6223. iterInput.clear();
  6224. }
  6225. catch (IException * E)
  6226. {
  6227. throw makeWrappedException(E);
  6228. }
  6229. }
  6230. }
  6231. };
  6232. class CRoxieServerGraphLoopResultReadActivityFactory : public CRoxieServerActivityFactory
  6233. {
  6234. unsigned graphId;
  6235. public:
  6236. CRoxieServerGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _graphId)
  6237. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), graphId(_graphId)
  6238. {
  6239. }
  6240. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  6241. {
  6242. return new CRoxieServerGraphLoopResultReadActivity(_ctx, this, _probeManager, graphId);
  6243. }
  6244. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  6245. {
  6246. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for GraphLoopResultRead activity");
  6247. }
  6248. };
  6249. IRoxieServerActivityFactory *createRoxieServerGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned graphId)
  6250. {
  6251. return new CRoxieServerGraphLoopResultReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, graphId);
  6252. }
  6253. //=====================================================================================================
  6254. class CRoxieServerGraphLoopResultWriteActivity : public CRoxieServerInternalSinkActivity
  6255. {
  6256. IHThorGraphLoopResultWriteArg &helper;
  6257. ILocalGraphEx * graph;
  6258. unsigned graphId;
  6259. public:
  6260. CRoxieServerGraphLoopResultWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId, unsigned _numOutputs)
  6261. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _numOutputs), helper((IHThorGraphLoopResultWriteArg &)basehelper), graphId(_graphId)
  6262. {
  6263. graph = NULL;
  6264. }
  6265. virtual bool needsAllocator() const { return true; }
  6266. virtual void onCreate(IHThorArg *_colocalParent)
  6267. {
  6268. CRoxieServerInternalSinkActivity::onCreate(_colocalParent);
  6269. graph = static_cast<ILocalGraphEx *>(ctx->queryCodeContext()->resolveLocalQuery(graphId));
  6270. }
  6271. virtual void onExecute()
  6272. {
  6273. RtlLinkedDatasetBuilder builder(rowAllocator);
  6274. inputStream->readAll(builder);
  6275. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  6276. graph->setGraphLoopResult(result);
  6277. }
  6278. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  6279. {
  6280. if (idx==0)
  6281. return this;
  6282. else
  6283. return NULL;
  6284. }
  6285. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  6286. {
  6287. return input->gatherConjunctions(collector);
  6288. }
  6289. virtual void resetEOF()
  6290. {
  6291. inputStream->resetEOF();
  6292. }
  6293. virtual const void *nextRow()
  6294. {
  6295. const void * next = inputStream->nextRow();
  6296. if (next)
  6297. processed++;
  6298. return next;
  6299. }
  6300. virtual bool isPassThrough()
  6301. {
  6302. return true;
  6303. }
  6304. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  6305. {
  6306. ActivityTimer t(totalCycles, timeActivities);
  6307. const void * next = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  6308. if (next)
  6309. processed++;
  6310. return next;
  6311. }
  6312. IInputSteppingMeta * querySteppingMeta()
  6313. {
  6314. return input->querySteppingMeta();
  6315. }
  6316. virtual IOutputMetaData * queryOutputMeta() const
  6317. {
  6318. return input->queryOutputMeta();
  6319. }
  6320. };
  6321. class CRoxieServerGraphLoopResultWriteActivityFactory : public CRoxieServerInternalSinkFactory
  6322. {
  6323. unsigned graphId;
  6324. public:
  6325. CRoxieServerGraphLoopResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, unsigned _graphId)
  6326. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, true), graphId(_graphId)
  6327. {
  6328. isInternal = true;
  6329. Owned<IHThorGraphLoopResultWriteArg> helper = (IHThorGraphLoopResultWriteArg *) helperFactory();
  6330. }
  6331. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  6332. {
  6333. return new CRoxieServerGraphLoopResultWriteActivity(_ctx, this, _probeManager, graphId, usageCount);
  6334. }
  6335. };
  6336. IRoxieServerActivityFactory *createRoxieServerGraphLoopResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, unsigned _graphId)
  6337. {
  6338. return new CRoxieServerGraphLoopResultWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _graphId);
  6339. }
  6340. //=================================================================================
  6341. class CRoxieServerDedupActivity : public CRoxieServerActivity
  6342. {
  6343. protected:
  6344. IHThorDedupArg &helper;
  6345. unsigned numKept;
  6346. unsigned numToKeep;
  6347. public:
  6348. CRoxieServerDedupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6349. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorDedupArg &)basehelper)
  6350. {
  6351. numKept = 0;
  6352. numToKeep = 0;
  6353. }
  6354. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6355. {
  6356. numKept = 0;
  6357. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6358. numToKeep = helper.numToKeep();
  6359. }
  6360. };
  6361. class CRoxieServerDedupKeepLeftActivity : public CRoxieServerDedupActivity
  6362. {
  6363. IRangeCompare * stepCompare;
  6364. const void *prev;
  6365. public:
  6366. CRoxieServerDedupKeepLeftActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6367. : CRoxieServerDedupActivity(_ctx, _factory, _probeManager)
  6368. {
  6369. prev = NULL;
  6370. stepCompare = NULL;
  6371. }
  6372. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6373. {
  6374. prev = NULL;
  6375. CRoxieServerDedupActivity::start(parentExtractSize, parentExtract, paused);
  6376. IInputSteppingMeta * stepMeta = input->querySteppingMeta();
  6377. stepCompare = NULL;
  6378. if (stepMeta)
  6379. stepCompare = stepMeta->queryCompare();
  6380. }
  6381. virtual void reset()
  6382. {
  6383. ReleaseClearRoxieRow(prev);
  6384. CRoxieServerDedupActivity::reset();
  6385. }
  6386. virtual const void * nextRow()
  6387. {
  6388. ActivityTimer t(totalCycles, timeActivities);
  6389. const void * next;
  6390. for (;;)
  6391. {
  6392. next = inputStream->nextRow();
  6393. if (!prev || !next || !helper.matches(prev,next))
  6394. {
  6395. numKept = 0;
  6396. break;
  6397. }
  6398. if (numKept < numToKeep-1)
  6399. {
  6400. numKept++;
  6401. break;
  6402. }
  6403. ReleaseRoxieRow(next);
  6404. }
  6405. ReleaseRoxieRow(prev);
  6406. prev = next;
  6407. if (next)
  6408. {
  6409. LinkRoxieRow(next);
  6410. processed++;
  6411. }
  6412. return next;
  6413. }
  6414. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  6415. {
  6416. ActivityTimer t(totalCycles, timeActivities);
  6417. const void * next;
  6418. for (;;)
  6419. {
  6420. next = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  6421. //If the record was an in-exact match from the index then return it immediately
  6422. //and don't cause it to dedup following legal records.
  6423. if (!wasCompleteMatch)
  6424. {
  6425. assertex(stepExtra.returnMismatches());
  6426. return next;
  6427. }
  6428. if (!prev || !next || !helper.matches(prev,next))
  6429. {
  6430. numKept = 0;
  6431. break;
  6432. }
  6433. if (numKept < numToKeep-1)
  6434. {
  6435. numKept++;
  6436. break;
  6437. }
  6438. //Unusual - deduping by x,y stepped on x,y,z - still want any record back as soon as possible.
  6439. if (stepExtra.returnMismatches())
  6440. {
  6441. //If asked to return mismatches we are only interested in mismatches that will force the stepped
  6442. //condition to advance
  6443. if (stepCompare->docompare(next, seek, numFields) != 0)
  6444. {
  6445. wasCompleteMatch = false;
  6446. break;
  6447. }
  6448. }
  6449. ReleaseRoxieRow(next);
  6450. }
  6451. ReleaseRoxieRow(prev);
  6452. prev = next;
  6453. if (next)
  6454. {
  6455. LinkRoxieRow(next);
  6456. processed++;
  6457. }
  6458. return next;
  6459. }
  6460. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  6461. {
  6462. return input->gatherConjunctions(collector);
  6463. }
  6464. virtual void resetEOF()
  6465. {
  6466. inputStream->resetEOF();
  6467. }
  6468. IInputSteppingMeta * querySteppingMeta()
  6469. {
  6470. return input->querySteppingMeta();
  6471. }
  6472. };
  6473. //=================================================================================
  6474. class CRoxieServerDedupKeepRightActivity : public CRoxieServerDedupActivity
  6475. {
  6476. const void *kept;
  6477. bool first;
  6478. ICompare * compareBest;
  6479. public:
  6480. CRoxieServerDedupKeepRightActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6481. : CRoxieServerDedupActivity(_ctx, _factory, _probeManager), compareBest(nullptr)
  6482. {
  6483. kept = nullptr;
  6484. first = true;
  6485. if (helper.keepBest())
  6486. compareBest = helper.queryCompareBest();
  6487. }
  6488. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6489. {
  6490. first = true;
  6491. kept = nullptr;
  6492. CRoxieServerDedupActivity::start(parentExtractSize, parentExtract, paused);
  6493. if (numToKeep>1)
  6494. throw MakeStringException(ROXIE_UNIMPLEMENTED_ERROR, "DEDUP with RIGHT and NumToKeep>1 not supported");
  6495. }
  6496. virtual void reset()
  6497. {
  6498. ReleaseClearRoxieRow(kept);
  6499. CRoxieServerActivity::reset();
  6500. }
  6501. virtual const void * nextRow()
  6502. {
  6503. ActivityTimer t(totalCycles, timeActivities);
  6504. if (first)
  6505. {
  6506. kept = inputStream->nextRow();
  6507. first = false;
  6508. }
  6509. const void * next;
  6510. for (;;)
  6511. {
  6512. next = inputStream->nextRow();
  6513. if (!kept || !next || !helper.matches(kept,next))
  6514. break;
  6515. if (compareBest && compareBest->docompare(kept,next) <= 0)
  6516. continue;
  6517. ReleaseRoxieRow(kept);
  6518. kept = next;
  6519. }
  6520. const void * ret = kept;
  6521. kept = next;
  6522. // CTXLOG("dedup returns %p", ret);
  6523. if (ret) processed++;
  6524. return ret;
  6525. }
  6526. };
  6527. class CRoxieServerDedupAllActivity : public CRoxieServerActivity
  6528. {
  6529. IHThorDedupArg &helper;
  6530. unsigned survivorIndex;
  6531. ConstPointerArray survivors;
  6532. bool keepLeft;
  6533. bool eof;
  6534. bool first;
  6535. ICompare *primaryCompare;
  6536. public:
  6537. CRoxieServerDedupAllActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _keepLeft)
  6538. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorDedupArg &)basehelper)
  6539. {
  6540. keepLeft = _keepLeft;
  6541. primaryCompare = helper.queryComparePrimary();
  6542. eof = false;
  6543. first = true;
  6544. survivorIndex = 0;
  6545. }
  6546. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6547. {
  6548. eof = false;
  6549. first = true;
  6550. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6551. }
  6552. virtual void reset()
  6553. {
  6554. while (survivors.isItem(survivorIndex))
  6555. {
  6556. ReleaseRoxieRow(survivors.item(survivorIndex++));
  6557. }
  6558. survivors.kill();
  6559. eof = false;
  6560. first = true;
  6561. CRoxieServerActivity::reset();
  6562. }
  6563. void dedupRange(unsigned first, unsigned last, ConstPointerArray & group)
  6564. {
  6565. for (unsigned idxL = first; idxL < last; idxL++)
  6566. {
  6567. const void * left = group.item(idxL);
  6568. if (left)
  6569. {
  6570. for (unsigned idxR = first; idxR < last; idxR++)
  6571. {
  6572. const void * right = group.item(idxR);
  6573. if ((idxL != idxR) && right)
  6574. {
  6575. if (helper.matches(left, right))
  6576. {
  6577. if (keepLeft)
  6578. {
  6579. group.replace(NULL, idxR);
  6580. ReleaseRoxieRow(right);
  6581. }
  6582. else
  6583. {
  6584. group.replace(NULL, idxL);
  6585. ReleaseRoxieRow(left);
  6586. break;
  6587. }
  6588. }
  6589. }
  6590. }
  6591. }
  6592. }
  6593. }
  6594. void dedupRange(unsigned first, unsigned last, void ** rows)
  6595. {
  6596. for (unsigned idxL = first; idxL < last; idxL++)
  6597. {
  6598. void * left = rows[idxL];
  6599. if (left)
  6600. {
  6601. for (unsigned idxR = first; idxR < last; idxR++)
  6602. {
  6603. void * right = rows[idxR];
  6604. if ((idxL != idxR) && right)
  6605. {
  6606. if (helper.matches(left, right))
  6607. {
  6608. if (keepLeft)
  6609. {
  6610. rows[idxR] = NULL;
  6611. ReleaseRoxieRow(right);
  6612. }
  6613. else
  6614. {
  6615. rows[idxL] = NULL;
  6616. ReleaseRoxieRow(left);
  6617. break;
  6618. }
  6619. }
  6620. }
  6621. }
  6622. }
  6623. }
  6624. }
  6625. bool calcNextDedupAll()
  6626. {
  6627. survivors.kill();
  6628. survivorIndex = 0;
  6629. ConstPointerArray group;
  6630. if (eof || !inputStream->nextGroup(group))
  6631. {
  6632. eof = true;
  6633. return false;
  6634. }
  6635. unsigned max = group.ordinality();
  6636. if (primaryCompare)
  6637. {
  6638. //hard, if not impossible, to hit this code once optimisations in place
  6639. MemoryAttr indexbuff(max*sizeof(void *));
  6640. void ** temp = (void **)indexbuff.bufferBase();
  6641. void * *rows = const_cast<void * *>(group.getArray());
  6642. msortvecstableinplace(rows, max, *primaryCompare, temp);
  6643. unsigned first = 0;
  6644. for (unsigned idx = 1; idx < max; idx++)
  6645. {
  6646. if (primaryCompare->docompare(rows[first], rows[idx]) != 0)
  6647. {
  6648. dedupRange(first, idx, rows);
  6649. first = idx;
  6650. }
  6651. }
  6652. dedupRange(first, max, rows);
  6653. for(unsigned idx2=0; idx2<max; ++idx2)
  6654. {
  6655. void * cur = rows[idx2];
  6656. if(cur)
  6657. survivors.append(cur);
  6658. }
  6659. }
  6660. else
  6661. {
  6662. dedupRange(0, max, group);
  6663. for(unsigned idx=0; idx<max; ++idx)
  6664. {
  6665. const void * cur = group.item(idx);
  6666. if(cur)
  6667. survivors.append(cur);
  6668. }
  6669. }
  6670. return true;
  6671. }
  6672. virtual const void *nextRow()
  6673. {
  6674. ActivityTimer t(totalCycles, timeActivities);
  6675. if (first)
  6676. {
  6677. calcNextDedupAll();
  6678. first = false;
  6679. }
  6680. while (survivors.isItem(survivorIndex))
  6681. {
  6682. const void *ret = survivors.item(survivorIndex++);
  6683. if (ret)
  6684. {
  6685. processed++;
  6686. return ret;
  6687. }
  6688. }
  6689. calcNextDedupAll();
  6690. return NULL;
  6691. }
  6692. };
  6693. class CRoxieServerDedupActivityFactory : public CRoxieServerActivityFactory
  6694. {
  6695. bool compareAll;
  6696. bool keepLeft;
  6697. bool keepBest;
  6698. unsigned flags;
  6699. public:
  6700. CRoxieServerDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  6701. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  6702. {
  6703. Owned<IHThorDedupArg> helper = (IHThorDedupArg *) helperFactory();
  6704. compareAll = helper->compareAll();
  6705. keepLeft = helper->keepLeft();
  6706. keepBest = helper->keepBest();
  6707. }
  6708. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  6709. {
  6710. if (compareAll)
  6711. return new CRoxieServerDedupAllActivity(_ctx, this, _probeManager, keepLeft);
  6712. else if (keepLeft && !keepBest)
  6713. return new CRoxieServerDedupKeepLeftActivity(_ctx, this, _probeManager);
  6714. else
  6715. return new CRoxieServerDedupKeepRightActivity(_ctx, this, _probeManager);
  6716. }
  6717. };
  6718. IRoxieServerActivityFactory *createRoxieServerDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  6719. {
  6720. return new CRoxieServerDedupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  6721. }
  6722. //=================================================================================
  6723. class CRoxieServerHashDedupActivity : public CRoxieServerActivity
  6724. {
  6725. bool eof;
  6726. IHThorHashDedupArg &helper;
  6727. class HashDedupElement
  6728. {
  6729. public:
  6730. HashDedupElement(unsigned _hash, const void *_keyRow)
  6731. : hash(_hash), keyRow(_keyRow)
  6732. {
  6733. }
  6734. ~HashDedupElement()
  6735. {
  6736. ReleaseRoxieRow(keyRow);
  6737. }
  6738. inline unsigned queryHash() const
  6739. {
  6740. return hash;
  6741. }
  6742. inline const void *queryRow() const
  6743. {
  6744. return keyRow;
  6745. }
  6746. inline const void *getRowClear()
  6747. {
  6748. const void * row = keyRow;
  6749. keyRow = nullptr;
  6750. return row;
  6751. }
  6752. private:
  6753. unsigned hash;
  6754. const void *keyRow;
  6755. };
  6756. class HashDedupTable : public SuperHashTable
  6757. {
  6758. public:
  6759. HashDedupTable(IHThorHashDedupArg & _helper, CRoxieServerHashDedupActivity & _activity)
  6760. : helper(_helper),
  6761. activity(_activity),
  6762. keySize(helper.queryKeySize())
  6763. {
  6764. bestCompare=helper.queryCompareBest();
  6765. }
  6766. virtual ~HashDedupTable() { _releaseAll(); }
  6767. virtual unsigned getHashFromElement(const void *et) const
  6768. {
  6769. const HashDedupElement *element = reinterpret_cast<const HashDedupElement *>(et);
  6770. return element->queryHash();
  6771. }
  6772. virtual unsigned getHashFromFindParam(const void *fp) const { throwUnexpected(); }
  6773. virtual const void * getFindParam(const void *et) const { throwUnexpected(); }
  6774. virtual bool matchesElement(const void *et, const void *searchET) const { throwUnexpected(); }
  6775. virtual bool matchesFindParam(const void *et, const void *key, unsigned fphash) const
  6776. {
  6777. const HashDedupElement *element = reinterpret_cast<const HashDedupElement *>(et);
  6778. if (fphash != element->queryHash())
  6779. return false;
  6780. return (helper.queryKeyCompare()->docompare(element->queryRow(), key) == 0);
  6781. }
  6782. virtual void onAdd(void *et) {}
  6783. virtual void onRemove(void *et)
  6784. {
  6785. const HashDedupElement *element = reinterpret_cast<const HashDedupElement *>(et);
  6786. delete element;
  6787. }
  6788. void onCreate(IRoxieSlaveContext *ctx)
  6789. {
  6790. keyRowAllocator.setown(activity.createRowAllocator(keySize.queryOriginal()));
  6791. }
  6792. void reset()
  6793. {
  6794. kill();
  6795. }
  6796. bool insert(const void * row)
  6797. {
  6798. unsigned hash = helper.queryHash()->hash(row);
  6799. RtlDynamicRowBuilder keyRowBuilder(keyRowAllocator, true);
  6800. size32_t thisKeySize = helper.recordToKey(keyRowBuilder, row);
  6801. OwnedConstRoxieRow keyRow = keyRowBuilder.finalizeRowClear(thisKeySize);
  6802. if (find(hash, keyRow.get()))
  6803. return false;
  6804. addNew(new HashDedupElement(hash, keyRow.getClear()), hash);
  6805. return true;
  6806. }
  6807. bool insertBest(const void * nextrow)
  6808. {
  6809. unsigned hash = helper.queryHash()->hash(nextrow);
  6810. const void *et = find(hash, nextrow);
  6811. if (et)
  6812. {
  6813. const HashDedupElement *element = reinterpret_cast<const HashDedupElement *>(et);
  6814. const void * row = element->queryRow();
  6815. if (bestCompare->docompare(row,nextrow) <= 0)
  6816. return false;
  6817. removeExact( const_cast<void *>(et));
  6818. // drop-through to add new row
  6819. }
  6820. addNew(new HashDedupElement(hash, nextrow), hash);
  6821. return true;
  6822. }
  6823. void gatherStats(CRuntimeStatisticCollection & merged) const
  6824. {
  6825. if (keyRowAllocator)
  6826. keyRowAllocator->gatherStats(merged);
  6827. }
  6828. private:
  6829. IHThorHashDedupArg & helper;
  6830. CachedOutputMetaData keySize;
  6831. Owned<IEngineRowAllocator> keyRowAllocator;
  6832. CRoxieServerHashDedupActivity & activity;
  6833. ICompare * bestCompare;
  6834. } table;
  6835. public:
  6836. CRoxieServerHashDedupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6837. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorHashDedupArg &)basehelper), table(helper, *this), hashTableFilled(false), hashDedupTableIter(table)
  6838. {
  6839. eof = false;
  6840. keepBest = helper.keepBest();
  6841. }
  6842. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6843. {
  6844. eof = false;
  6845. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6846. }
  6847. virtual void onCreate(IHThorArg *_colocalParent)
  6848. {
  6849. CRoxieServerActivity::onCreate(colocalParent);
  6850. table.onCreate(ctx);
  6851. }
  6852. virtual void reset()
  6853. {
  6854. table.reset();
  6855. eof = false;
  6856. CRoxieServerActivity::reset();
  6857. hashTableFilled = false;
  6858. }
  6859. virtual const void *nextRow()
  6860. {
  6861. ActivityTimer t(totalCycles, timeActivities);
  6862. if (keepBest)
  6863. {
  6864. if (eof)
  6865. return NULL;
  6866. // Populate hash table with best rows
  6867. if (!hashTableFilled)
  6868. {
  6869. const void * next = inputStream->nextRow();
  6870. while(next)
  6871. {
  6872. if (!table.insertBest(next))
  6873. ReleaseRoxieRow(next);
  6874. next = inputStream->nextRow();
  6875. }
  6876. if (table.count() == 0)
  6877. eof = true;
  6878. hashTableFilled = true;
  6879. hashDedupTableIter.first();
  6880. }
  6881. // Iterate throw hash table returning rows
  6882. if (hashDedupTableIter.isValid())
  6883. {
  6884. HashDedupElement &el = hashDedupTableIter.query();
  6885. const void * row = el.getRowClear();
  6886. hashDedupTableIter.next();
  6887. return row;
  6888. }
  6889. table.reset();
  6890. hashTableFilled = false;
  6891. return NULL;
  6892. }
  6893. else
  6894. {
  6895. while(!eof)
  6896. {
  6897. const void * next = inputStream->nextRow();
  6898. if(!next)
  6899. {
  6900. if (table.count() == 0)
  6901. eof = true;
  6902. table.reset();
  6903. return NULL;
  6904. }
  6905. if(table.insert(next))
  6906. return next;
  6907. else
  6908. ReleaseRoxieRow(next);
  6909. }
  6910. return NULL;
  6911. }
  6912. }
  6913. private:
  6914. bool keepBest;
  6915. bool hashTableFilled;
  6916. SuperHashIteratorOf<HashDedupElement> hashDedupTableIter;
  6917. };
  6918. class CRoxieServerHashDedupActivityFactory : public CRoxieServerActivityFactory
  6919. {
  6920. public:
  6921. CRoxieServerHashDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  6922. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  6923. {
  6924. }
  6925. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  6926. {
  6927. return new CRoxieServerHashDedupActivity(_ctx, this, _probeManager);
  6928. }
  6929. };
  6930. IRoxieServerActivityFactory *createRoxieServerHashDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  6931. {
  6932. return new CRoxieServerHashDedupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  6933. }
  6934. //=================================================================================
  6935. class CRoxieServerRollupActivity : public CRoxieServerActivity
  6936. {
  6937. IHThorRollupArg &helper;
  6938. OwnedConstRoxieRow left;
  6939. OwnedConstRoxieRow prev;
  6940. OwnedConstRoxieRow right;
  6941. bool readFirstRow;
  6942. public:
  6943. CRoxieServerRollupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6944. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorRollupArg &)basehelper)
  6945. {
  6946. readFirstRow = false;
  6947. }
  6948. ~CRoxieServerRollupActivity()
  6949. {
  6950. }
  6951. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6952. {
  6953. readFirstRow = false;
  6954. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6955. }
  6956. virtual void reset()
  6957. {
  6958. left.clear();
  6959. prev.clear();
  6960. right.clear();
  6961. CRoxieServerActivity::reset();
  6962. }
  6963. virtual bool needsAllocator() const { return true; }
  6964. virtual const void * nextRow()
  6965. {
  6966. ActivityTimer t(totalCycles, timeActivities);
  6967. if (!readFirstRow)
  6968. {
  6969. left.setown(inputStream->nextRow());
  6970. prev.set(left);
  6971. readFirstRow = true;
  6972. }
  6973. for (;;)
  6974. {
  6975. right.setown(inputStream->nextRow());
  6976. if(!prev || !right || !helper.matches(prev,right))
  6977. {
  6978. const void * ret = left.getClear();
  6979. if(ret)
  6980. processed++;
  6981. left.setown(right.getClear());
  6982. prev.set(left);
  6983. return ret;
  6984. }
  6985. try
  6986. {
  6987. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  6988. unsigned outSize = helper.transform(rowBuilder, left, right);
  6989. if (outSize)
  6990. left.setown(rowBuilder.finalizeRowClear(outSize));
  6991. if (helper.getFlags() & RFrolledismatchleft)
  6992. prev.set(left);
  6993. else
  6994. prev.set(right);
  6995. }
  6996. catch(IException * E)
  6997. {
  6998. throw makeWrappedException(E);
  6999. }
  7000. }
  7001. }
  7002. };
  7003. class CRoxieServerRollupActivityFactory : public CRoxieServerActivityFactory
  7004. {
  7005. public:
  7006. CRoxieServerRollupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7007. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  7008. {
  7009. }
  7010. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  7011. {
  7012. return new CRoxieServerRollupActivity(_ctx, this, _probeManager);
  7013. }
  7014. };
  7015. IRoxieServerActivityFactory *createRoxieServerRollupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7016. {
  7017. return new CRoxieServerRollupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  7018. }
  7019. //=================================================================================
  7020. class CRoxieServerNormalizeActivity : public CRoxieServerActivity
  7021. {
  7022. IHThorNormalizeArg &helper;
  7023. unsigned numThisRow;
  7024. unsigned curRow;
  7025. const void *buffer;
  7026. unsigned numProcessedLastGroup;
  7027. public:
  7028. CRoxieServerNormalizeActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  7029. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorNormalizeArg &)basehelper)
  7030. {
  7031. buffer = NULL;
  7032. numThisRow = 0;
  7033. curRow = 0;
  7034. numProcessedLastGroup = 0;
  7035. }
  7036. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7037. {
  7038. numThisRow = 0;
  7039. curRow = 0;
  7040. numProcessedLastGroup = 0;
  7041. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7042. }
  7043. virtual void reset()
  7044. {
  7045. ReleaseClearRoxieRow(buffer);
  7046. CRoxieServerActivity::reset();
  7047. }
  7048. virtual bool needsAllocator() const { return true; }
  7049. virtual const void * nextRow()
  7050. {
  7051. ActivityTimer t(totalCycles, timeActivities);
  7052. for (;;)
  7053. {
  7054. while (curRow == numThisRow)
  7055. {
  7056. if (buffer)
  7057. ReleaseClearRoxieRow(buffer);
  7058. buffer = inputStream->nextRow();
  7059. if (!buffer && (processed == numProcessedLastGroup))
  7060. buffer = inputStream->nextRow();
  7061. if (!buffer)
  7062. {
  7063. numProcessedLastGroup = processed;
  7064. return NULL;
  7065. }
  7066. curRow = 0;
  7067. numThisRow = helper.numExpandedRows(buffer);
  7068. }
  7069. try
  7070. {
  7071. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  7072. unsigned actualSize = helper.transform(rowBuilder, buffer, ++curRow);
  7073. if (actualSize != 0)
  7074. {
  7075. processed++;
  7076. return rowBuilder.finalizeRowClear(actualSize);
  7077. }
  7078. }
  7079. catch (IException *E)
  7080. {
  7081. throw makeWrappedException(E);
  7082. }
  7083. }
  7084. }
  7085. };
  7086. class CRoxieServerNormalizeActivityFactory : public CRoxieServerActivityFactory
  7087. {
  7088. public:
  7089. CRoxieServerNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7090. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  7091. {
  7092. }
  7093. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  7094. {
  7095. return new CRoxieServerNormalizeActivity(_ctx, this, _probeManager);
  7096. }
  7097. };
  7098. IRoxieServerActivityFactory *createRoxieServerNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7099. {
  7100. return new CRoxieServerNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  7101. }
  7102. //=================================================================================
  7103. class CRoxieServerNormalizeChildActivity : public CRoxieServerActivity
  7104. {
  7105. IHThorNormalizeChildArg &helper;
  7106. unsigned numThisRow;
  7107. unsigned curRow;
  7108. const void *buffer;
  7109. unsigned numProcessedLastGroup;
  7110. INormalizeChildIterator * cursor;
  7111. const void * curChildRow;
  7112. bool advanceInput()
  7113. {
  7114. for (;;)
  7115. {
  7116. ReleaseClearRoxieRow(buffer);
  7117. buffer = inputStream->nextRow();
  7118. if (!buffer && (processed == numProcessedLastGroup))
  7119. buffer = inputStream->nextRow();
  7120. if (!buffer)
  7121. {
  7122. numProcessedLastGroup = processed;
  7123. return false;
  7124. }
  7125. curChildRow = cursor->first(buffer);
  7126. if (curChildRow)
  7127. {
  7128. curRow = 0;
  7129. return true;
  7130. }
  7131. }
  7132. }
  7133. public:
  7134. CRoxieServerNormalizeChildActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  7135. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorNormalizeChildArg &)basehelper)
  7136. {
  7137. buffer = NULL;
  7138. cursor = NULL;
  7139. numThisRow = 0;
  7140. curRow = 0;
  7141. numProcessedLastGroup = 0;
  7142. curChildRow = NULL;
  7143. }
  7144. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7145. {
  7146. numThisRow = 0;
  7147. curRow = 0;
  7148. numProcessedLastGroup = 0;
  7149. curChildRow = NULL;
  7150. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7151. cursor = helper.queryIterator();
  7152. }
  7153. virtual void stop()
  7154. {
  7155. CRoxieServerActivity::stop();
  7156. }
  7157. virtual void reset()
  7158. {
  7159. cursor = NULL;
  7160. ReleaseClearRoxieRow(buffer);
  7161. CRoxieServerActivity::reset();
  7162. }
  7163. virtual bool needsAllocator() const { return true; }
  7164. const void *nextRow()
  7165. {
  7166. ActivityTimer t(totalCycles, timeActivities);
  7167. for (;;)
  7168. {
  7169. if (!buffer)
  7170. {
  7171. if (!advanceInput())
  7172. return NULL;
  7173. }
  7174. try
  7175. {
  7176. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  7177. size32_t outSize = helper.transform(rowBuilder, buffer, curChildRow, ++curRow);
  7178. curChildRow = cursor->next();
  7179. if (!curChildRow)
  7180. ReleaseClearRoxieRow(buffer);
  7181. if (outSize != 0)
  7182. {
  7183. processed++;
  7184. return rowBuilder.finalizeRowClear(outSize);
  7185. }
  7186. }
  7187. catch (IException *E)
  7188. {
  7189. throw makeWrappedException(E);
  7190. }
  7191. }
  7192. }
  7193. };
  7194. class CRoxieServerNormalizeChildActivityFactory : public CRoxieServerActivityFactory
  7195. {
  7196. public:
  7197. CRoxieServerNormalizeChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7198. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  7199. {
  7200. }
  7201. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  7202. {
  7203. return new CRoxieServerNormalizeChildActivity(_ctx, this, _probeManager);
  7204. }
  7205. };
  7206. IRoxieServerActivityFactory *createRoxieServerNormalizeChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7207. {
  7208. return new CRoxieServerNormalizeChildActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  7209. }
  7210. //=================================================================================
  7211. class CRoxieServerNormalizeLinkedChildActivity : public CRoxieServerActivity
  7212. {
  7213. IHThorNormalizeLinkedChildArg &helper;
  7214. OwnedConstRoxieRow curParent;
  7215. OwnedConstRoxieRow curChild;
  7216. unsigned numProcessedLastGroup;
  7217. bool advanceInput()
  7218. {
  7219. for (;;)
  7220. {
  7221. curParent.setown(inputStream->nextRow());
  7222. if (!curParent && (processed == numProcessedLastGroup))
  7223. curParent.setown(inputStream->nextRow());
  7224. if (!curParent)
  7225. {
  7226. numProcessedLastGroup = processed;
  7227. return false;
  7228. }
  7229. curChild.set(helper.first(curParent));
  7230. if (curChild)
  7231. return true;
  7232. }
  7233. }
  7234. public:
  7235. CRoxieServerNormalizeLinkedChildActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  7236. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorNormalizeLinkedChildArg &)basehelper)
  7237. {
  7238. numProcessedLastGroup = 0;
  7239. }
  7240. ~CRoxieServerNormalizeLinkedChildActivity()
  7241. {
  7242. }
  7243. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7244. {
  7245. numProcessedLastGroup = 0;
  7246. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7247. }
  7248. virtual void reset()
  7249. {
  7250. curParent.clear();
  7251. curChild.clear();
  7252. CRoxieServerActivity::reset();
  7253. }
  7254. const void *nextRow()
  7255. {
  7256. ActivityTimer t(totalCycles, timeActivities);
  7257. for (;;)
  7258. {
  7259. if (!curParent)
  7260. {
  7261. if (!advanceInput())
  7262. return NULL;
  7263. }
  7264. try
  7265. {
  7266. const void *ret = curChild.getClear();
  7267. curChild.set(helper.next());
  7268. if (!curChild)
  7269. curParent.clear();
  7270. if (ret)
  7271. {
  7272. processed++;
  7273. return ret;
  7274. }
  7275. }
  7276. catch (IException *E)
  7277. {
  7278. throw makeWrappedException(E);
  7279. }
  7280. }
  7281. }
  7282. };
  7283. class CRoxieServerNormalizeLinkedChildActivityFactory : public CRoxieServerActivityFactory
  7284. {
  7285. public:
  7286. CRoxieServerNormalizeLinkedChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7287. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  7288. {
  7289. }
  7290. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  7291. {
  7292. return new CRoxieServerNormalizeLinkedChildActivity(_ctx, this, _probeManager);
  7293. }
  7294. };
  7295. IRoxieServerActivityFactory *createRoxieServerNormalizeLinkedChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7296. {
  7297. return new CRoxieServerNormalizeLinkedChildActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  7298. }
  7299. //=================================================================================
  7300. class CRoxieServerSortActivity : public CRoxieServerActivity
  7301. {
  7302. protected:
  7303. IHThorSortArg &helper;
  7304. ICompare *compare;
  7305. Owned<ISortAlgorithm> sorter;
  7306. bool readInput;
  7307. RoxieSortAlgorithm sortAlgorithm;
  7308. unsigned sortFlags;
  7309. public:
  7310. CRoxieServerSortActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, RoxieSortAlgorithm _sortAlgorithm, unsigned _sortFlags)
  7311. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorSortArg &)basehelper), sortAlgorithm(_sortAlgorithm), sortFlags(_sortFlags)
  7312. {
  7313. compare = helper.queryCompare();
  7314. readInput = false;
  7315. }
  7316. virtual void onCreate(IHThorArg *_colocalParent)
  7317. {
  7318. CRoxieServerActivity::onCreate(_colocalParent);
  7319. if (sortAlgorithm==unknownSortAlgorithm)
  7320. sorter.clear();
  7321. else
  7322. sorter.setown(createSortAlgorithm(sortAlgorithm, compare, ctx->queryRowManager(), meta, ctx->queryCodeContext(), tempDirectory, activityId));
  7323. }
  7324. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7325. {
  7326. assertex(!readInput);
  7327. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7328. }
  7329. virtual void reset()
  7330. {
  7331. if (sorter)
  7332. sorter->reset();
  7333. readInput = false;
  7334. CRoxieServerActivity::reset();
  7335. }
  7336. static RoxieSortAlgorithm useAlgorithm(const char *algorithmName, unsigned sortFlags)
  7337. {
  7338. RoxieSortAlgorithm sortAlgorithm = unknownSortAlgorithm;
  7339. if (!algorithmName)
  7340. algorithmName = "";
  7341. if (stricmp(algorithmName, "quicksort")==0)
  7342. {
  7343. switch (sortFlags & (TAFstable|TAFspill))
  7344. {
  7345. case 0: sortAlgorithm = quickSortAlgorithm; break;
  7346. case TAFstable: sortAlgorithm = stableQuickSortAlgorithm; break;
  7347. case TAFspill: sortAlgorithm = spillingQuickSortAlgorithm; break;
  7348. case TAFstable|TAFspill: sortAlgorithm = stableSpillingQuickSortAlgorithm; break;
  7349. }
  7350. }
  7351. else if (stricmp(algorithmName, "parquicksort")==0)
  7352. {
  7353. switch (sortFlags & TAFstable)
  7354. {
  7355. case 0: sortAlgorithm = parallelQuickSortAlgorithm; break;
  7356. case TAFstable: sortAlgorithm = parallelStableQuickSortAlgorithm; break;
  7357. default: throwUnexpected();
  7358. }
  7359. }
  7360. else if (stricmp(algorithmName, "heapsort")==0)
  7361. sortAlgorithm = heapSortAlgorithm; // NOTE - we do allow UNSTABLE('heapsort') in order to facilitate runtime selection. Also explicit selection of heapsort overrides request to spill
  7362. else if (stricmp(algorithmName, "mergesort")==0)
  7363. sortAlgorithm = (sortFlags & TAFspill) ? spillingMergeSortAlgorithm : mergeSortAlgorithm;
  7364. else if (stricmp(algorithmName, "parmergesort")==0)
  7365. sortAlgorithm = (sortFlags & TAFspill) ? spillingParallelMergeSortAlgorithm : parallelMergeSortAlgorithm;
  7366. else if (stricmp(algorithmName, "tbbqsort")==0)
  7367. sortAlgorithm = tbbQuickSortAlgorithm;
  7368. else if (stricmp(algorithmName, "tbbstableqsort")==0)
  7369. sortAlgorithm = tbbStableQuickSortAlgorithm;
  7370. else
  7371. {
  7372. if (*algorithmName)
  7373. WARNLOG(ROXIE_UNKNOWN_ALGORITHM, "Ignoring unsupported sort order algorithm '%s', using default", algorithmName);
  7374. if (sortFlags & TAFspill)
  7375. sortAlgorithm = ((sortFlags & TAFunstable) != 0) ? spillingQuickSortAlgorithm : stableSpillingQuickSortAlgorithm;
  7376. else if (sortFlags & TAFunstable)
  7377. sortAlgorithm = quickSortAlgorithm;
  7378. else
  7379. sortAlgorithm = heapSortAlgorithm;
  7380. }
  7381. return sortAlgorithm;
  7382. }
  7383. virtual const void * nextRow()
  7384. {
  7385. ActivityTimer t(totalCycles, timeActivities);
  7386. if (!readInput)
  7387. {
  7388. if (sortAlgorithm == unknownSortAlgorithm)
  7389. {
  7390. sorter.clear();
  7391. IHThorAlgorithm *sortMethod = static_cast<IHThorAlgorithm *>(helper.selectInterface(TAIalgorithm_1));
  7392. OwnedRoxieString algorithmName(sortMethod->getAlgorithm());
  7393. sortAlgorithm = useAlgorithm(algorithmName, sortFlags);
  7394. sorter.setown(createSortAlgorithm(sortAlgorithm, compare, ctx->queryRowManager(), meta, ctx->queryCodeContext(), tempDirectory, activityId));
  7395. }
  7396. sorter->prepare(inputStream);
  7397. noteStatistic(StTimeSortElapsed, cycle_to_nanosec(sorter->getElapsedCycles(true)));
  7398. readInput = true;
  7399. }
  7400. const void *ret = sorter->next();
  7401. if (ret)
  7402. processed++;
  7403. else
  7404. {
  7405. sorter->reset();
  7406. readInput = false; // ready for next group
  7407. }
  7408. return ret;
  7409. }
  7410. };
  7411. class CRoxieServerSortActivityFactory : public CRoxieServerActivityFactory
  7412. {
  7413. RoxieSortAlgorithm sortAlgorithm;
  7414. unsigned sortFlags;
  7415. public:
  7416. CRoxieServerSortActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7417. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  7418. {
  7419. Owned<IHThorSortArg> sortHelper = (IHThorSortArg *) helperFactory();
  7420. const char *algorithmName = NULL;
  7421. IHThorAlgorithm *sortMethod = static_cast<IHThorAlgorithm *>(sortHelper->selectInterface(TAIalgorithm_1));
  7422. if (sortMethod)
  7423. {
  7424. sortFlags = sortMethod->getAlgorithmFlags();
  7425. if (sortFlags & TAFconstant)
  7426. algorithmName = sortMethod->getAlgorithm();
  7427. }
  7428. else
  7429. sortFlags = TAFstable|TAFconstant;
  7430. bool forceSpill = _queryFactory.queryOptions().allSortsMaySpill || _graphNode.getPropBool("hint[@name='spill']/@value", false);
  7431. if (forceSpill)
  7432. sortFlags |= TAFspill;
  7433. if (!(sortFlags & TAFunstable))
  7434. sortFlags |= TAFstable; // Assume stable unless specifically requested otherwise
  7435. if (sortFlags & TAFconstant)
  7436. sortAlgorithm = CRoxieServerSortActivity::useAlgorithm(algorithmName, sortFlags);
  7437. else
  7438. sortAlgorithm = unknownSortAlgorithm;
  7439. }
  7440. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  7441. {
  7442. return new CRoxieServerSortActivity(_ctx, this, _probeManager, sortAlgorithm, sortFlags);
  7443. }
  7444. virtual const StatisticsMapping &queryStatsMapping() const
  7445. {
  7446. return sortStatistics;
  7447. }
  7448. };
  7449. IRoxieServerActivityFactory *createRoxieServerSortActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7450. {
  7451. return new CRoxieServerSortActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  7452. }
  7453. //=====================================================================================================
  7454. static int compareUint64(const void * _left, const void * _right)
  7455. {
  7456. const unsigned __int64 left = *static_cast<const unsigned __int64 *>(_left);
  7457. const unsigned __int64 right = *static_cast<const unsigned __int64 *>(_right);
  7458. if (left < right)
  7459. return -1;
  7460. if (left > right)
  7461. return -1;
  7462. return 0;
  7463. }
  7464. class CRoxieServerQuantileActivity : public CRoxieServerActivity
  7465. {
  7466. protected:
  7467. Owned<ISortAlgorithm> sorter;
  7468. IHThorQuantileArg &helper;
  7469. ConstPointerArray sorted;
  7470. ICompare *compare;
  7471. unsigned flags;
  7472. double skew;
  7473. unsigned __int64 numDivisions;
  7474. bool rangeIsAll;
  7475. size32_t rangeSize;
  7476. rtlDataAttr rangeValues;
  7477. bool calculated;
  7478. bool processedAny;
  7479. bool anyThisGroup;
  7480. bool eof;
  7481. unsigned curQuantile;
  7482. unsigned curIndex;
  7483. unsigned curIndexExtra;
  7484. unsigned skipSize;
  7485. unsigned skipExtra;
  7486. unsigned prevIndex;
  7487. public:
  7488. CRoxieServerQuantileActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _flags)
  7489. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorQuantileArg &)basehelper), flags(_flags)
  7490. {
  7491. compare = helper.queryCompare();
  7492. skew = 0.0;
  7493. numDivisions = 0;
  7494. calculated = false;
  7495. processedAny = false;
  7496. anyThisGroup = false;
  7497. eof = false;
  7498. rangeIsAll = true;
  7499. rangeSize = 0;
  7500. curQuantile = 0;
  7501. prevIndex = 0;
  7502. curIndex = 0;
  7503. curIndexExtra = 0;
  7504. skipSize = 0;
  7505. skipExtra = 0;
  7506. if (flags & TQFunstable)
  7507. sorter.setown(createQuickSortAlgorithm(compare));
  7508. else
  7509. sorter.setown(createMergeSortAlgorithm(compare));
  7510. }
  7511. virtual void reset()
  7512. {
  7513. sorter->reset();
  7514. calculated = false;
  7515. processedAny = false;
  7516. anyThisGroup = false;
  7517. ReleaseRoxieRows(sorted);
  7518. CRoxieServerActivity::reset();
  7519. }
  7520. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7521. {
  7522. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7523. skew = helper.getSkew();
  7524. numDivisions = helper.getNumDivisions();
  7525. //Check for -ve integer values and treat as out of range
  7526. if ((__int64)numDivisions < 1)
  7527. numDivisions = 1;
  7528. if (flags & TQFhasrange)
  7529. helper.getRange(rangeIsAll, rangeSize, rangeValues.refdata());
  7530. else
  7531. {
  7532. rangeIsAll = true;
  7533. rangeSize = 0;
  7534. }
  7535. if (rangeSize)
  7536. {
  7537. //Sort the range items into order to allow quick comparison
  7538. qsort(rangeValues.getdata(), rangeSize / sizeof(unsigned __int64), sizeof(unsigned __int64), compareUint64);
  7539. }
  7540. calculated = false;
  7541. processedAny = false;
  7542. anyThisGroup = false;
  7543. eof = false;
  7544. curQuantile = 0;
  7545. prevIndex = 0;
  7546. curIndex = 0;
  7547. curIndexExtra = 0;
  7548. }
  7549. virtual bool needsAllocator() const { return true; }
  7550. virtual const void * nextRow()
  7551. {
  7552. ActivityTimer t(totalCycles, timeActivities);
  7553. if (eof)
  7554. return NULL;
  7555. const void * ret = NULL;
  7556. for(;;)
  7557. {
  7558. if (!calculated)
  7559. {
  7560. if (flags & TQFlocalsorted)
  7561. {
  7562. for (;;)
  7563. {
  7564. const void * next = inputStream->nextRow();
  7565. if (!next)
  7566. break;
  7567. sorted.append(next);
  7568. }
  7569. }
  7570. else
  7571. {
  7572. sorter->prepare(inputStream);
  7573. sorter->getSortedGroup(sorted);
  7574. }
  7575. if (sorted.ordinality() == 0)
  7576. {
  7577. if (processedAny)
  7578. {
  7579. eof = true;
  7580. return NULL;
  7581. }
  7582. //Unusual case 0 rows - add a default row instead
  7583. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  7584. size32_t thisSize = helper.createDefault(rowBuilder);
  7585. sorted.append(rowBuilder.finalizeRowClear(thisSize));
  7586. }
  7587. calculated = true;
  7588. processedAny = true;
  7589. anyThisGroup = false;
  7590. curQuantile = 0;
  7591. curIndex = 0;
  7592. curIndexExtra = (numDivisions-1) / 2; // to ensure correctly rounded up
  7593. prevIndex = curIndex-1; // Ensure it doesn't match
  7594. skipSize = (sorted.ordinality() / numDivisions);
  7595. skipExtra = (sorted.ordinality() % numDivisions);
  7596. }
  7597. if (isQuantileIncluded(curQuantile))
  7598. {
  7599. if (!(flags & TQFdedup) || (prevIndex != curIndex))
  7600. {
  7601. const void * lhs = sorted.item(curIndex);
  7602. if (flags & TQFneedtransform)
  7603. {
  7604. unsigned outSize;
  7605. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  7606. try
  7607. {
  7608. outSize = helper.transform(rowBuilder, lhs, curQuantile);
  7609. }
  7610. catch (IException *E)
  7611. {
  7612. throw makeWrappedException(E);
  7613. }
  7614. if (outSize)
  7615. ret = rowBuilder.finalizeRowClear(outSize);
  7616. }
  7617. else
  7618. {
  7619. LinkRoxieRow(lhs);
  7620. ret = lhs;
  7621. }
  7622. prevIndex = curIndex; // even if output was skipped?
  7623. }
  7624. }
  7625. curIndex += skipSize;
  7626. curIndexExtra += skipExtra;
  7627. if (curIndexExtra >= numDivisions)
  7628. {
  7629. curIndex++;
  7630. curIndexExtra -= numDivisions;
  7631. }
  7632. //Ensure the current index always stays valid.
  7633. if (curIndex >= sorted.ordinality())
  7634. curIndex = sorted.ordinality()-1;
  7635. curQuantile++;
  7636. if (curQuantile > numDivisions)
  7637. {
  7638. ReleaseRoxieRows(sorted);
  7639. sorter->reset();
  7640. calculated = false; // ready for next group
  7641. }
  7642. if (ret)
  7643. {
  7644. anyThisGroup = true;
  7645. processed++;
  7646. return ret;
  7647. }
  7648. if (curQuantile > numDivisions)
  7649. {
  7650. if (anyThisGroup)
  7651. return NULL;
  7652. }
  7653. }
  7654. }
  7655. bool isQuantileIncluded(unsigned quantile) const
  7656. {
  7657. if (quantile == 0)
  7658. return (flags & TQFfirst) != 0;
  7659. if (quantile == numDivisions)
  7660. return (flags & TQFlast) != 0;
  7661. if (rangeIsAll)
  7662. return true;
  7663. //Compare against the list of ranges provided
  7664. //MORE: Since the list is sorted should only need to compare the next (and allow for dups)
  7665. unsigned rangeNum = rangeSize / sizeof(unsigned __int64);
  7666. const unsigned __int64 * ranges = static_cast<const unsigned __int64 *>(rangeValues.getdata());
  7667. for (unsigned i = 0; i < rangeNum; i++)
  7668. {
  7669. if (ranges[i] == quantile)
  7670. return true;
  7671. }
  7672. return false;
  7673. }
  7674. };
  7675. class CRoxieServerQuantileActivityFactory : public CRoxieServerActivityFactory
  7676. {
  7677. unsigned flags;
  7678. public:
  7679. CRoxieServerQuantileActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7680. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  7681. {
  7682. Owned<IHThorQuantileArg> quantileHelper = (IHThorQuantileArg *) helperFactory();
  7683. flags = quantileHelper->getFlags();
  7684. }
  7685. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  7686. {
  7687. return new CRoxieServerQuantileActivity(_ctx, this, _probeManager, flags);
  7688. }
  7689. };
  7690. IRoxieServerActivityFactory *createRoxieServerQuantileActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7691. {
  7692. return new CRoxieServerQuantileActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  7693. }
  7694. //=====================================================================================================
  7695. class CRoxieServerSortedActivity : public CRoxieServerActivity
  7696. {
  7697. IHThorSortedArg &helper;
  7698. ICompare * compare;
  7699. const void *prev;
  7700. IRangeCompare * stepCompare;
  7701. public:
  7702. CRoxieServerSortedActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  7703. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorSortedArg &)basehelper)
  7704. {
  7705. prev = NULL;
  7706. compare = helper.queryCompare();
  7707. stepCompare = NULL;
  7708. }
  7709. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7710. {
  7711. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7712. IInputSteppingMeta * stepMeta = input->querySteppingMeta();
  7713. if (stepMeta)
  7714. stepCompare = stepMeta->queryCompare();
  7715. prev = NULL;
  7716. }
  7717. virtual void reset()
  7718. {
  7719. ReleaseClearRoxieRow(prev);
  7720. CRoxieServerActivity::reset();
  7721. }
  7722. virtual const void * nextRow()
  7723. {
  7724. ActivityTimer t(totalCycles, timeActivities);
  7725. const void *ret = inputStream->nextRow();
  7726. if (ret && prev && compare->docompare(prev, ret) > 0)
  7727. {
  7728. // MORE - better to give mismatching rows that indexes?
  7729. throw MakeStringException(ROXIE_NOT_SORTED, "SORTED(%u) detected incorrectly sorted rows (row %d, %d))", activityId, processed, processed+1);
  7730. }
  7731. ReleaseRoxieRow(prev);
  7732. prev = ret;
  7733. if (ret)
  7734. {
  7735. LinkRoxieRow(prev);
  7736. processed++;
  7737. }
  7738. return ret;
  7739. }
  7740. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  7741. {
  7742. ActivityTimer t(totalCycles, timeActivities);
  7743. const void *ret = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  7744. if (ret && prev && compare->docompare(prev, ret) > 0)
  7745. {
  7746. // MORE - better to give mismatching rows that indexes?
  7747. throw MakeStringException(ROXIE_NOT_SORTED, "SORTED(%u) detected incorrectly sorted rows (row %d, %d))", activityId, processed, processed+1);
  7748. }
  7749. ReleaseRoxieRow(prev);
  7750. prev = ret;
  7751. if (ret)
  7752. {
  7753. LinkRoxieRow(prev);
  7754. processed++;
  7755. }
  7756. return ret;
  7757. }
  7758. IInputSteppingMeta * querySteppingMeta()
  7759. {
  7760. return input->querySteppingMeta();
  7761. }
  7762. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  7763. {
  7764. return input->gatherConjunctions(collector);
  7765. }
  7766. virtual void resetEOF()
  7767. {
  7768. inputStream->resetEOF();
  7769. }
  7770. };
  7771. class CRoxieServerSortedActivityFactory : public CRoxieServerActivityFactory
  7772. {
  7773. public:
  7774. CRoxieServerSortedActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7775. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  7776. {
  7777. }
  7778. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  7779. {
  7780. return new CRoxieServerSortedActivity(_ctx, this, _probeManager);
  7781. }
  7782. };
  7783. IRoxieServerActivityFactory *createRoxieServerSortedActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7784. {
  7785. return new CRoxieServerSortedActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  7786. }
  7787. //=====================================================================================================
  7788. class CRoxieServerThroughSpillActivity : public CRoxieServerActivity
  7789. {
  7790. /*
  7791. BE VERY CAREFUL - this code is tricky.
  7792. Note that starts and stops (and resets) can occur in strange orders
  7793. The FIRST start OR stop must initialize the activity but only the first START should call the upstream start.
  7794. The last stop should call the upstream stop.
  7795. The first reset should call the upstream reset.
  7796. 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
  7797. not yet had start or stop called - for this to happen init() is called on all outputs on the first start or stop.
  7798. Some outputs may be completely pruned away when used in a GRAPH - these outputs should not receive any start/stop/reset and should be
  7799. ignored in the minIndex calculation
  7800. */
  7801. public:
  7802. IHThorArg &helper;
  7803. unsigned activeOutputs;
  7804. unsigned numOutputs;
  7805. unsigned numOriginalOutputs;
  7806. QueueOf<const void, true> buffer;
  7807. CriticalSection crit;
  7808. CriticalSection crit2;
  7809. unsigned tailIdx;
  7810. unsigned headIdx;
  7811. Owned<IException> error;
  7812. class OutputAdaptor : implements IEngineRowStream, implements IFinalRoxieInput, public CInterface
  7813. {
  7814. bool eof, eofpending, stopped;
  7815. public:
  7816. CRoxieServerThroughSpillActivity *parent;
  7817. unsigned idx;
  7818. unsigned oid;
  7819. unsigned processed;
  7820. cycle_t totalCycles; // We track this per output so that the pullers get a meaningful value to use when calculating their localtime
  7821. public:
  7822. IMPLEMENT_IINTERFACE;
  7823. OutputAdaptor()
  7824. {
  7825. parent = NULL;
  7826. oid = 0;
  7827. idx = 0;
  7828. processed = 0;
  7829. totalCycles = 0;
  7830. eofpending = false;
  7831. eof = false;
  7832. stopped = false;
  7833. }
  7834. ~OutputAdaptor()
  7835. {
  7836. if (traceStartStop)
  7837. DBGLOG("%p ~OutputAdaptor %d", this, oid);
  7838. if (processed && parent && parent->factory)
  7839. {
  7840. parent->factory->noteProcessed(oid, processed);
  7841. if (parent->ctx)
  7842. parent->ctx->noteProcessed(parent->querySubgraphId(), parent->activityId, oid, processed, 0);
  7843. }
  7844. }
  7845. void init()
  7846. {
  7847. if (traceStartStop)
  7848. DBGLOG("%p init Input adaptor %d", this, oid);
  7849. idx = 0;
  7850. processed = 0;
  7851. eofpending = false;
  7852. eof = false;
  7853. stopped = false;
  7854. }
  7855. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { assertex(idx==0); return this; }
  7856. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { assertex(idx==0); return nullptr; }
  7857. virtual IRoxieServerActivity *queryActivity()
  7858. {
  7859. return parent;
  7860. }
  7861. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  7862. {
  7863. return parent->queryIndexReadActivity();
  7864. }
  7865. virtual unsigned __int64 queryTotalCycles() const
  7866. {
  7867. return totalCycles;
  7868. }
  7869. virtual const void * nextRow()
  7870. {
  7871. SimpleActivityTimer t(totalCycles, parent->timeActivities);
  7872. if (eof)
  7873. return NULL;
  7874. const void *ret = parent->readBuffered(idx, oid);
  7875. #ifdef TRACE_SPLIT
  7876. parent->CTXLOG("Adaptor %d got back %p for record %d", oid, ret, idx);
  7877. #endif
  7878. if (ret)
  7879. {
  7880. processed++;
  7881. eofpending = false;
  7882. }
  7883. else if (eofpending)
  7884. eof = true;
  7885. else
  7886. eofpending = true;
  7887. return ret;
  7888. }
  7889. virtual IOutputMetaData * queryOutputMeta() const
  7890. {
  7891. return parent->queryOutputMeta();
  7892. }
  7893. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7894. {
  7895. // NOTE: it is tempting to move the init() of all output adaptors here. However that is not a good idea,
  7896. // since adaptors that have not yet started or stopped (but are going to) still need to have been init()'ed
  7897. // for minIndex to give the correct answers
  7898. // therefore, we call init() on all adaptors on receipt of the first start() or stop()
  7899. if (traceStartStop)
  7900. parent->CTXLOG("%p start Input adaptor %d stopped = %d", this, oid, stopped);
  7901. parent->start(oid, parentExtractSize, parentExtract, paused);
  7902. }
  7903. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  7904. {
  7905. parent->connectInputStreams(consumerOrdered);
  7906. streams.append(this);
  7907. return NULL;
  7908. }
  7909. virtual void stop()
  7910. {
  7911. if (traceStartStop)
  7912. parent->CTXLOG("%p stop Input adaptor %d stopped = %d", this, oid, stopped);
  7913. if (!stopped)
  7914. {
  7915. parent->stop(oid, idx); // NOTE - may call init()
  7916. stopped = true; // parent code relies on stop being called exactly once per adaptor, so make sure it is!
  7917. }
  7918. };
  7919. virtual void reset()
  7920. {
  7921. if (traceStartStop)
  7922. parent->CTXLOG("%p reset Input adaptor %d stopped = %d", this, oid, stopped);
  7923. parent->reset(oid);
  7924. idx = 0; // value should not be relevant really but this is the safest...
  7925. stopped = false;
  7926. };
  7927. virtual void resetEOF()
  7928. {
  7929. parent->resetEOF();
  7930. }
  7931. virtual void checkAbort()
  7932. {
  7933. parent->checkAbort();
  7934. }
  7935. } *adaptors;
  7936. bool *used;
  7937. unsigned nextFreeOutput()
  7938. {
  7939. unsigned i = numOutputs;
  7940. while (i)
  7941. {
  7942. i--;
  7943. if (!used[i])
  7944. return i;
  7945. }
  7946. throwUnexpected();
  7947. }
  7948. unsigned minIndex(unsigned exceptOid)
  7949. {
  7950. // MORE - yukky code (and slow). Could keep them heapsorted by idx or something
  7951. // this is trying to determine whether any of the adaptors will in the future read a given record
  7952. unsigned minIdx = (unsigned) -1;
  7953. for (unsigned i = 0; i < numOutputs; i++)
  7954. {
  7955. if (i != exceptOid && used[i] && adaptors[i].idx < minIdx)
  7956. minIdx = adaptors[i].idx;
  7957. }
  7958. return minIdx;
  7959. }
  7960. inline bool isLastTailReader(unsigned exceptOid)
  7961. {
  7962. for (unsigned i = 0; i < numOutputs; i++)
  7963. {
  7964. if (i != exceptOid && adaptors[i].idx == tailIdx && used[i])
  7965. return false;
  7966. }
  7967. return true;
  7968. }
  7969. void initOutputs()
  7970. {
  7971. activeOutputs = numOutputs;
  7972. for (unsigned i = 0; i < numOriginalOutputs; i++)
  7973. if (used[i])
  7974. adaptors[i].init();
  7975. state = STATEstarting;
  7976. }
  7977. public:
  7978. CRoxieServerThroughSpillActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  7979. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper(basehelper), numOutputs(_numOutputs)
  7980. {
  7981. numOriginalOutputs = numOutputs;
  7982. adaptors = new OutputAdaptor[numOutputs];
  7983. used = new bool[numOutputs];
  7984. for (unsigned i = 0; i < numOutputs; i++)
  7985. {
  7986. adaptors[i].parent = this;
  7987. adaptors[i].oid = i;
  7988. used[i] = false;
  7989. }
  7990. tailIdx = 0;
  7991. headIdx = 0;
  7992. activeOutputs = numOutputs;
  7993. }
  7994. ~CRoxieServerThroughSpillActivity()
  7995. {
  7996. delete [] adaptors;
  7997. delete [] used;
  7998. }
  7999. const void *readBuffered(unsigned &idx, unsigned oid)
  8000. {
  8001. //False positives are fine, false negatives are not.. so headIdx must only be updated when a row will be available.
  8002. const unsigned curIdx = idx;
  8003. if (curIdx == headIdx) // test once without getting the crit2 sec
  8004. {
  8005. CriticalBlock b2(crit2); // but only one puller gets to read the head
  8006. if (curIdx == headIdx) // test again now that we have it
  8007. {
  8008. ActivityTimer t(totalCycles, timeActivities); // NOTE - time spent waiting for crit not included here. But it will have been included on the totalTime of the person holding the crit, so that is right
  8009. if (error)
  8010. throw error.getLink();
  8011. try
  8012. {
  8013. const void *row = inputStream->nextRow();
  8014. if (activeOutputs==1)
  8015. {
  8016. #ifdef TRACE_SPLIT
  8017. CTXLOG("spill %d optimised return of %p", activityId, row);
  8018. #endif
  8019. headIdx++;
  8020. idx++;
  8021. return row; // optimization for the case where only one output still active.
  8022. }
  8023. CriticalBlock b(crit);
  8024. headIdx++;
  8025. idx++;
  8026. if (activeOutputs==1)
  8027. return row; // optimization for the case where only one output still active.
  8028. buffer.enqueue(row);
  8029. if (row) LinkRoxieRow(row);
  8030. return row;
  8031. }
  8032. catch (IException *E)
  8033. {
  8034. #ifdef TRACE_SPLIT
  8035. CTXLOG("spill %d caught exception", activityId);
  8036. #endif
  8037. error.set(E);
  8038. throw;
  8039. }
  8040. catch (...)
  8041. {
  8042. IException *E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught in CRoxieServerThroughSpillActivity::readBuffered");
  8043. error.set(E);
  8044. throw E;
  8045. }
  8046. }
  8047. }
  8048. CriticalBlock b(crit);
  8049. ActivityTimer t(totalCycles, timeActivities); // NOTE - time spent waiting for crit not included here. But it will have been included on the totalTime of the person holding the crit, so that is right
  8050. unsigned lidx = curIdx - tailIdx;
  8051. idx++;
  8052. if (!lidx)
  8053. {
  8054. // The numOutputs <= 2 check optimizes slightly the common case of 2-way splitters.
  8055. // The rationale is that I MUST be the last reader if there are only 2 - the other guy must have put the record there in the first place
  8056. if (numOutputs <= 2 || isLastTailReader(oid)) // NOTE - this includes the case where minIndex returns (unsigned) -1, meaning no other active pullers
  8057. {
  8058. tailIdx++;
  8059. const void *ret = buffer.dequeue(); // no need to link - last puller
  8060. #ifdef TRACE_SPLIT
  8061. CTXLOG("last puller return of %p", ret);
  8062. #endif
  8063. return ret;
  8064. }
  8065. }
  8066. const void *ret = buffer.item(lidx);
  8067. if (ret) LinkRoxieRow(ret);
  8068. #ifdef TRACE_SPLIT
  8069. CTXLOG("standard return of %p", ret);
  8070. #endif
  8071. return ret;
  8072. }
  8073. virtual void start(unsigned oid, unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8074. {
  8075. CriticalBlock b(crit);
  8076. if (error)
  8077. throw error.getLink();
  8078. if (factory)
  8079. factory->noteStarted(oid);
  8080. if (traceStartStop)
  8081. CTXLOG("SPLIT %p: start %d child %d activeOutputs %d numOutputs %d numOriginalOutputs %d state %s", this, activityId, oid, activeOutputs, numOutputs, numOriginalOutputs, queryStateText(state));
  8082. if (state != STATEstarted)
  8083. {
  8084. if (state != STATEstarting)
  8085. initOutputs();
  8086. tailIdx = 0;
  8087. headIdx = 0;
  8088. error.clear();
  8089. try
  8090. {
  8091. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8092. }
  8093. catch (IException *E)
  8094. {
  8095. #ifdef TRACE_SPLIT
  8096. CTXLOG("spill %d caught exception in start", activityId);
  8097. #endif
  8098. error.set(E);
  8099. throw;
  8100. }
  8101. catch (...)
  8102. {
  8103. IException *E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught in CRoxieServerThroughSpillActivity::start");
  8104. error.set(E);
  8105. throw E;
  8106. }
  8107. }
  8108. }
  8109. void stop(unsigned oid, unsigned & idx)
  8110. {
  8111. // Note that OutputAdaptor code ensures that stop is not called more than once per adaptor
  8112. CriticalBlock b(crit);
  8113. #ifdef TRACE_STARTSTOP
  8114. if (traceStartStop)
  8115. {
  8116. CTXLOG("SPLIT %p: stop %d child %d activeOutputs %d numOutputs %d numOriginalOutputs %d state %s", this, activityId, oid, activeOutputs, numOutputs, numOriginalOutputs, queryStateText(state));
  8117. if (watchActivityId && watchActivityId==activityId)
  8118. {
  8119. CTXLOG("WATCH: stop %d", activityId);
  8120. }
  8121. }
  8122. #endif
  8123. if (state != STATEstarting && state != STATEstarted)
  8124. initOutputs();
  8125. if (activeOutputs > 1)
  8126. {
  8127. if (tailIdx==idx)
  8128. {
  8129. // Discard all buffered rows that are there purely for this adaptor to read them
  8130. unsigned min = minIndex(oid);
  8131. if (min != (unsigned) -1)
  8132. // what does -1 signify?? No-one wants anything? In which case can't we kill all rows??
  8133. // Should never happen though if there are still some active.
  8134. // there may be a small window where adaptors are blocked on the semaphore...
  8135. {
  8136. #ifdef TRACE_SPLIT
  8137. CTXLOG("%p: Discarding buffered rows from %d to %d for oid %x (%d outputs active)", this, idx, min, oid, activeOutputs);
  8138. #endif
  8139. while (tailIdx < min)
  8140. {
  8141. ReleaseRoxieRow(buffer.dequeue());
  8142. tailIdx++;
  8143. }
  8144. }
  8145. }
  8146. activeOutputs--;
  8147. idx = (unsigned) -1; // causes minIndex not to save rows for me...
  8148. return;
  8149. }
  8150. #ifdef TRACE_SPLIT
  8151. CTXLOG("%p: All outputs done", this);
  8152. #endif
  8153. activeOutputs = numOutputs;
  8154. CRoxieServerActivity::stop();
  8155. };
  8156. void reset(unsigned oid)
  8157. {
  8158. if (traceStartStop)
  8159. CTXLOG("SPLIT %p: reset %d child %d activeOutputs %d numOutputs %d numOriginalOutputs %d state %s", this, activityId, oid, activeOutputs, numOutputs, numOriginalOutputs, queryStateText(state));
  8160. activeOutputs = numOutputs;
  8161. while (buffer.ordinality())
  8162. ReleaseRoxieRow(buffer.dequeue());
  8163. error.clear();
  8164. if (state != STATEreset) // make sure input is only reset once
  8165. CRoxieServerActivity::reset();
  8166. };
  8167. void connectInputStreams(bool consumerOrdered)
  8168. {
  8169. if (!inputStream)
  8170. CRoxieServerActivity::connectInputStreams(consumerOrdered);
  8171. }
  8172. virtual const void *nextRow()
  8173. {
  8174. throwUnexpected(); // Internal logic error - we are not anybody's input
  8175. }
  8176. virtual IOutputMetaData * queryOutputMeta() const
  8177. {
  8178. // if (outputMeta)
  8179. // return outputMeta;
  8180. // else
  8181. return input->queryOutputMeta(); // not always known (e.g. disk write - though Gavin _could_ fill it in)
  8182. }
  8183. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  8184. {
  8185. if (idx==(unsigned)-1)
  8186. idx = nextFreeOutput(); // MORE - what is this used for?
  8187. assertex(idx < numOriginalOutputs);
  8188. assertex(!used[idx]);
  8189. used[idx] = true;
  8190. return &adaptors[idx];
  8191. }
  8192. virtual void resetOutputsUsed()
  8193. {
  8194. numOutputs = 1;
  8195. activeOutputs = 1;
  8196. // MORE RKC->GH should we be clearing the used array here? anywhere?
  8197. }
  8198. virtual void noteOutputUsed()
  8199. {
  8200. assertex(numOutputs < numOriginalOutputs);
  8201. numOutputs++;
  8202. activeOutputs = numOutputs;
  8203. }
  8204. virtual bool isPassThrough()
  8205. {
  8206. return numOutputs==1;
  8207. }
  8208. };
  8209. class CRoxieServerThroughSpillActivityFactory : public CRoxieServerMultiOutputFactory
  8210. {
  8211. public:
  8212. CRoxieServerThroughSpillActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8213. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  8214. {
  8215. Owned<IHThorSpillArg> helper = (IHThorSpillArg *) helperFactory();
  8216. setNumOutputs(helper->getTempUsageCount() + 1);
  8217. }
  8218. CRoxieServerThroughSpillActivityFactory(IQueryFactory &_queryFactory, HelperFactory *_helperFactory, unsigned _numOutputs, IPropertyTree &_graphNode)
  8219. : CRoxieServerMultiOutputFactory(0, 0, _queryFactory, _helperFactory, TAKsplit, _graphNode)
  8220. {
  8221. setNumOutputs(_numOutputs);
  8222. }
  8223. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  8224. {
  8225. return new CRoxieServerThroughSpillActivity(_ctx, this, _probeManager, numOutputs);
  8226. }
  8227. };
  8228. IRoxieServerActivityFactory *createRoxieServerThroughSpillActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8229. {
  8230. return new CRoxieServerThroughSpillActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  8231. }
  8232. IRoxieServerActivityFactory *createRoxieServerThroughSpillActivityFactory(IQueryFactory &_queryFactory, HelperFactory *_factory, unsigned _numOutputs, IPropertyTree &_graphNode)
  8233. {
  8234. return new CRoxieServerThroughSpillActivityFactory(_queryFactory, _factory, _numOutputs, _graphNode);
  8235. }
  8236. //----------------------------------------------------------------------------------------------
  8237. class CRoxieServerSplitActivityFactory : public CRoxieServerMultiOutputFactory
  8238. {
  8239. public:
  8240. CRoxieServerSplitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8241. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  8242. {
  8243. Owned<IHThorSplitArg> helper = (IHThorSplitArg *) helperFactory();
  8244. setNumOutputs(helper->numBranches());
  8245. }
  8246. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  8247. {
  8248. return new CRoxieServerThroughSpillActivity(_ctx, this, _probeManager, numOutputs);
  8249. }
  8250. };
  8251. IRoxieServerActivityFactory *createRoxieServerSplitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8252. {
  8253. return new CRoxieServerSplitActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  8254. }
  8255. //=====================================================================================================
  8256. #define PIPE_BUFSIZE 0x8000
  8257. static IException *createPipeFailureException(const char *cmd, unsigned retcode, IPipeProcess *pipe)
  8258. {
  8259. StringBuffer msg;
  8260. if(pipe->hasError())
  8261. {
  8262. try
  8263. {
  8264. char error[512];
  8265. size32_t sz = pipe->readError(sizeof(error), error);
  8266. if(sz && sz!=(size32_t)-1)
  8267. msg.append(", stderr: '").append(sz, error).append("'");
  8268. }
  8269. catch (IException *e)
  8270. {
  8271. EXCLOG(e, "Error reading pipe stderr");
  8272. e->Release();
  8273. }
  8274. }
  8275. return MakeStringException(ROXIE_PIPE_ERROR, "Pipe process %s returned error %u%s", cmd, retcode, msg.str());
  8276. }
  8277. class CRoxieServerPipeReadActivity : public CRoxieServerActivity
  8278. {
  8279. IHThorPipeReadArg &helper;
  8280. Owned<IPipeProcess> pipe;
  8281. StringAttr pipeCommand;
  8282. Owned<IOutputRowDeserializer> rowDeserializer;
  8283. Owned<IReadRowStream> readTransformer;
  8284. bool groupSignalled;
  8285. public:
  8286. CRoxieServerPipeReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8287. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorPipeReadArg &)basehelper)
  8288. {
  8289. groupSignalled = true;
  8290. }
  8291. virtual bool needsAllocator() const { return true; }
  8292. virtual void onCreate(IHThorArg *_colocalParent)
  8293. {
  8294. CRoxieServerActivity::onCreate(_colocalParent);
  8295. rowDeserializer.setown(rowAllocator->createDiskDeserializer(ctx->queryCodeContext()));
  8296. }
  8297. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8298. {
  8299. groupSignalled = true; // i.e. don't start with a NULL row
  8300. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8301. if (!readTransformer)
  8302. {
  8303. OwnedRoxieString xmlIteratorPath(helper.getXmlIteratorPath());
  8304. readTransformer.setown(createReadRowStream(rowAllocator, rowDeserializer, helper.queryXmlTransformer(), helper.queryCsvTransformer(), xmlIteratorPath, helper.getPipeFlags()));
  8305. }
  8306. OwnedRoxieString pipeProgram(helper.getPipeProgram());
  8307. openPipe(pipeProgram);
  8308. }
  8309. virtual void stop()
  8310. {
  8311. CRoxieServerActivity::stop();
  8312. pipe.clear();
  8313. readTransformer->setStream(NULL);
  8314. }
  8315. virtual const void *nextRow()
  8316. {
  8317. ActivityTimer t(totalCycles, timeActivities);
  8318. while (!waitForPipe())
  8319. {
  8320. if (!pipe)
  8321. return NULL;
  8322. if (helper.getPipeFlags() & TPFgroupeachrow)
  8323. {
  8324. if (!groupSignalled)
  8325. {
  8326. groupSignalled = true;
  8327. return NULL;
  8328. }
  8329. }
  8330. }
  8331. const void *ret = readTransformer->next();
  8332. assertex(ret != NULL); // if ret can ever be NULL then we need to recode this logic
  8333. processed++;
  8334. groupSignalled = false;
  8335. return ret;
  8336. }
  8337. protected:
  8338. bool waitForPipe()
  8339. {
  8340. if (!pipe)
  8341. return false; // done
  8342. if (!readTransformer->eos())
  8343. return true;
  8344. verifyPipe();
  8345. return false;
  8346. }
  8347. void openPipe(char const * cmd)
  8348. {
  8349. pipeCommand.setown(cmd);
  8350. pipe.setown(createPipeProcess());
  8351. if(!pipe->run(NULL, cmd, ".", false, true, true, 0x10000))
  8352. throw MakeStringException(ROXIE_PIPE_ERROR, "Could not run pipe process %s", cmd);
  8353. Owned<ISimpleReadStream> pipeReader = pipe->getOutputStream();
  8354. readTransformer->setStream(pipeReader.get());
  8355. }
  8356. void verifyPipe()
  8357. {
  8358. if (pipe)
  8359. {
  8360. unsigned err = pipe->wait();
  8361. if(err && !(helper.getPipeFlags() & TPFnofail))
  8362. {
  8363. throw createPipeFailureException(pipeCommand.get(), err, pipe);
  8364. }
  8365. pipe.clear();
  8366. }
  8367. }
  8368. };
  8369. class CRoxieServerPipeThroughActivity : public CRoxieServerActivity, implements IRecordPullerCallback
  8370. {
  8371. IHThorPipeThroughArg &helper;
  8372. RecordPullerThread puller;
  8373. Owned<IPipeProcess> pipe;
  8374. StringAttr pipeCommand;
  8375. InterruptableSemaphore pipeVerified;
  8376. InterruptableSemaphore pipeOpened;
  8377. CachedOutputMetaData inputMeta;
  8378. Owned<IOutputRowSerializer> rowSerializer;
  8379. Owned<IOutputRowDeserializer> rowDeserializer;
  8380. Owned<IPipeWriteXformHelper> writeTransformer;
  8381. Owned<IReadRowStream> readTransformer;
  8382. bool firstRead;
  8383. bool recreate;
  8384. bool inputExhausted;
  8385. bool groupSignalled;
  8386. public:
  8387. CRoxieServerPipeThroughActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8388. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorPipeThroughArg &)basehelper), puller(false)
  8389. {
  8390. recreate = helper.recreateEachRow();
  8391. groupSignalled = true;
  8392. firstRead = false;
  8393. inputExhausted = false;
  8394. }
  8395. virtual bool needsAllocator() const { return true; }
  8396. virtual void onCreate(IHThorArg *_colocalParent)
  8397. {
  8398. CRoxieServerActivity::onCreate(_colocalParent);
  8399. rowSerializer.setown(inputMeta.createDiskSerializer(ctx->queryCodeContext(), activityId));
  8400. rowDeserializer.setown(rowAllocator->createDiskDeserializer(ctx->queryCodeContext()));
  8401. writeTransformer.setown(createPipeWriteXformHelper(helper.getPipeFlags(), helper.queryXmlOutput(), helper.queryCsvOutput(), rowSerializer));
  8402. }
  8403. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8404. {
  8405. firstRead = true;
  8406. inputExhausted = false;
  8407. groupSignalled = true; // i.e. don't start with a NULL row
  8408. pipeVerified.reinit();
  8409. pipeOpened.reinit();
  8410. writeTransformer->ready();
  8411. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8412. if (!readTransformer)
  8413. {
  8414. OwnedRoxieString xmlIterator(helper.getXmlIteratorPath());
  8415. readTransformer.setown(createReadRowStream(rowAllocator, rowDeserializer, helper.queryXmlTransformer(), helper.queryCsvTransformer(), xmlIterator, helper.getPipeFlags()));
  8416. }
  8417. if(!recreate)
  8418. {
  8419. OwnedRoxieString pipeProgram(helper.getPipeProgram());
  8420. openPipe(pipeProgram);
  8421. }
  8422. puller.start(parentExtractSize, parentExtract, paused, 0, false, ctx); // Pipe does not support preload presently - locks up
  8423. }
  8424. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  8425. {
  8426. if (idx)
  8427. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
  8428. puller.setInput(this, _sourceIdx, _in);
  8429. inputMeta.set(_in->queryOutputMeta());
  8430. }
  8431. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  8432. {
  8433. puller.connectInputStreams(ctx, consumerOrdered);
  8434. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
  8435. }
  8436. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  8437. {
  8438. if (idx==0)
  8439. return puller.queryInput();
  8440. else
  8441. return NULL;
  8442. }
  8443. virtual void stop()
  8444. {
  8445. pipeVerified.interrupt(NULL);
  8446. pipeOpened.interrupt(NULL);
  8447. puller.stop();
  8448. CRoxieServerActivity::stop();
  8449. pipe.clear();
  8450. if (readTransformer)
  8451. readTransformer->setStream(NULL);
  8452. }
  8453. virtual void reset()
  8454. {
  8455. puller.reset();
  8456. CRoxieServerActivity::reset();
  8457. }
  8458. virtual const void *nextRow()
  8459. {
  8460. ActivityTimer t(totalCycles, timeActivities);
  8461. while (!waitForPipe())
  8462. {
  8463. if (!pipe)
  8464. return NULL;
  8465. if (helper.getPipeFlags() & TPFgroupeachrow)
  8466. {
  8467. if (!groupSignalled)
  8468. {
  8469. groupSignalled = true;
  8470. return NULL;
  8471. }
  8472. }
  8473. }
  8474. const void *ret = readTransformer->next();
  8475. assertex(ret != NULL); // if ret can ever be NULL then we need to recode this logic
  8476. processed++;
  8477. groupSignalled = false;
  8478. return ret;
  8479. }
  8480. virtual void processRow(const void *row)
  8481. {
  8482. // called from puller thread
  8483. if(recreate)
  8484. openPipe(helper.getNameFromRow(row));
  8485. writeTransformer->writeTranslatedText(row, pipe);
  8486. ReleaseRoxieRow(row);
  8487. if(recreate)
  8488. {
  8489. closePipe();
  8490. pipeVerified.wait();
  8491. }
  8492. }
  8493. virtual void processDone()
  8494. {
  8495. // called from puller thread
  8496. if(recreate)
  8497. {
  8498. inputExhausted = true;
  8499. pipeOpened.signal();
  8500. }
  8501. else
  8502. {
  8503. closePipe();
  8504. pipeVerified.wait();
  8505. }
  8506. }
  8507. virtual void processEOG()
  8508. {
  8509. }
  8510. void processGroup(const ConstPointerArray &)
  8511. {
  8512. throwUnexpected();
  8513. }
  8514. virtual bool fireException(IException *e)
  8515. {
  8516. pipeOpened.interrupt(LINK(e));
  8517. pipeVerified.interrupt(e);
  8518. return true;
  8519. }
  8520. private:
  8521. bool waitForPipe()
  8522. {
  8523. if (firstRead)
  8524. {
  8525. pipeOpened.wait();
  8526. firstRead = false;
  8527. }
  8528. if (!pipe)
  8529. return false; // done
  8530. if (!readTransformer->eos())
  8531. return true;
  8532. verifyPipe();
  8533. if (recreate && !inputExhausted)
  8534. pipeOpened.wait();
  8535. return false;
  8536. }
  8537. void openPipe(char const * cmd)
  8538. {
  8539. pipeCommand.setown(cmd);
  8540. pipe.setown(createPipeProcess());
  8541. if(!pipe->run(NULL, cmd, ".", true, true, true, 0x10000))
  8542. throw MakeStringException(ROXIE_PIPE_ERROR, "Could not run pipe process %s", cmd);
  8543. writeTransformer->writeHeader(pipe);
  8544. Owned<ISimpleReadStream> pipeReader = pipe->getOutputStream();
  8545. readTransformer->setStream(pipeReader.get());
  8546. pipeOpened.signal();
  8547. }
  8548. void closePipe()
  8549. {
  8550. writeTransformer->writeFooter(pipe);
  8551. pipe->closeInput();
  8552. }
  8553. void verifyPipe()
  8554. {
  8555. if (pipe)
  8556. {
  8557. unsigned err = pipe->wait();
  8558. if(err && !(helper.getPipeFlags() & TPFnofail))
  8559. {
  8560. throw createPipeFailureException(pipeCommand.get(), err, pipe);
  8561. }
  8562. pipe.clear();
  8563. pipeVerified.signal();
  8564. }
  8565. }
  8566. };
  8567. class CRoxieServerPipeWriteActivity : public CRoxieServerInternalSinkActivity
  8568. {
  8569. IHThorPipeWriteArg &helper;
  8570. Owned<IPipeProcess> pipe;
  8571. StringAttr pipeCommand;
  8572. CachedOutputMetaData inputMeta;
  8573. Owned<IOutputRowSerializer> rowSerializer;
  8574. Owned<IPipeWriteXformHelper> writeTransformer;
  8575. bool firstRead;
  8576. bool recreate;
  8577. bool inputExhausted;
  8578. public:
  8579. CRoxieServerPipeWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  8580. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _numOutputs), helper((IHThorPipeWriteArg &)basehelper)
  8581. {
  8582. recreate = helper.recreateEachRow();
  8583. firstRead = false;
  8584. inputExhausted = false;
  8585. }
  8586. virtual bool needsAllocator() const { return true; }
  8587. virtual void onCreate(IHThorArg *_colocalParent)
  8588. {
  8589. CRoxieServerActivity::onCreate(_colocalParent);
  8590. inputMeta.set(input->queryOutputMeta());
  8591. rowSerializer.setown(inputMeta.createDiskSerializer(ctx->queryCodeContext(), activityId));
  8592. writeTransformer.setown(createPipeWriteXformHelper(helper.getPipeFlags(), helper.queryXmlOutput(), helper.queryCsvOutput(), rowSerializer));
  8593. }
  8594. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8595. {
  8596. firstRead = true;
  8597. inputExhausted = false;
  8598. writeTransformer->ready();
  8599. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8600. if(!recreate)
  8601. {
  8602. OwnedRoxieString pipeProgram(helper.getPipeProgram());
  8603. openPipe(pipeProgram);
  8604. }
  8605. }
  8606. virtual void stop()
  8607. {
  8608. if (!aborted && helper.getSequence() >= 0)
  8609. {
  8610. WorkunitUpdate wu = ctx->updateWorkUnit();
  8611. if (wu)
  8612. {
  8613. Owned<IWUResult> result = wu->updateResultBySequence(helper.getSequence());
  8614. if (result)
  8615. {
  8616. result->setResultTotalRowCount(processed);
  8617. result->setResultStatus(ResultStatusCalculated);
  8618. }
  8619. }
  8620. }
  8621. CRoxieServerActivity::stop();
  8622. pipe.clear();
  8623. }
  8624. virtual void onExecute()
  8625. {
  8626. for (;;)
  8627. {
  8628. const void *row = inputStream->ungroupedNextRow();
  8629. if (!row)
  8630. break;
  8631. processed++;
  8632. if(recreate)
  8633. openPipe(helper.getNameFromRow(row));
  8634. writeTransformer->writeTranslatedText(row, pipe);
  8635. ReleaseRoxieRow(row);
  8636. if(recreate)
  8637. closePipe();
  8638. }
  8639. closePipe();
  8640. }
  8641. private:
  8642. void openPipe(char const * cmd)
  8643. {
  8644. pipeCommand.setown(cmd);
  8645. pipe.setown(createPipeProcess());
  8646. if(!pipe->run(NULL, cmd, ".", true, false, true, 0x10000))
  8647. throw MakeStringException(ROXIE_PIPE_ERROR, "Could not run pipe process %s", cmd);
  8648. writeTransformer->writeHeader(pipe);
  8649. }
  8650. void closePipe()
  8651. {
  8652. writeTransformer->writeFooter(pipe);
  8653. pipe->closeInput();
  8654. unsigned err = pipe->wait();
  8655. if(err && !(helper.getPipeFlags() & TPFnofail))
  8656. {
  8657. throw createPipeFailureException(pipeCommand.get(), err, pipe);
  8658. }
  8659. pipe.clear();
  8660. }
  8661. };
  8662. class CRoxieServerPipeReadActivityFactory : public CRoxieServerActivityFactory
  8663. {
  8664. public:
  8665. CRoxieServerPipeReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8666. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  8667. {
  8668. }
  8669. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  8670. {
  8671. return new CRoxieServerPipeReadActivity(_ctx, this, _probeManager);
  8672. }
  8673. };
  8674. class CRoxieServerPipeThroughActivityFactory : public CRoxieServerActivityFactory
  8675. {
  8676. public:
  8677. CRoxieServerPipeThroughActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8678. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  8679. {
  8680. }
  8681. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  8682. {
  8683. return new CRoxieServerPipeThroughActivity(_ctx, this, _probeManager);
  8684. }
  8685. };
  8686. class CRoxieServerPipeWriteActivityFactory : public CRoxieServerInternalSinkFactory
  8687. {
  8688. public:
  8689. CRoxieServerPipeWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  8690. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot)
  8691. {
  8692. }
  8693. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  8694. {
  8695. return new CRoxieServerPipeWriteActivity(_ctx, this, _probeManager, usageCount);
  8696. }
  8697. };
  8698. IRoxieServerActivityFactory *createRoxieServerPipeReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8699. {
  8700. return new CRoxieServerPipeReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  8701. }
  8702. IRoxieServerActivityFactory *createRoxieServerPipeThroughActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8703. {
  8704. return new CRoxieServerPipeThroughActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  8705. }
  8706. IRoxieServerActivityFactory *createRoxieServerPipeWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  8707. {
  8708. return new CRoxieServerPipeWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot);
  8709. }
  8710. //=====================================================================================================
  8711. class CRoxieServerStreamedIteratorActivity : public CRoxieServerActivity
  8712. {
  8713. IHThorStreamedIteratorArg &helper;
  8714. Owned<IRowStream> rows;
  8715. public:
  8716. CRoxieServerStreamedIteratorActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8717. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorStreamedIteratorArg &)basehelper)
  8718. {
  8719. }
  8720. ~CRoxieServerStreamedIteratorActivity()
  8721. {
  8722. }
  8723. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8724. {
  8725. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8726. rows.setown(helper.createInput());
  8727. }
  8728. virtual void stop()
  8729. {
  8730. if (rows)
  8731. {
  8732. rows->stop();
  8733. rows.clear();
  8734. }
  8735. CRoxieServerActivity::stop();
  8736. }
  8737. virtual const void *nextRow()
  8738. {
  8739. ActivityTimer t(totalCycles, timeActivities);
  8740. assertex(rows != NULL);
  8741. const void * next = rows->nextRow();
  8742. if (next)
  8743. processed++;
  8744. return next;
  8745. }
  8746. };
  8747. class CRoxieServerStreamedIteratorActivityFactory : public CRoxieServerActivityFactory
  8748. {
  8749. public:
  8750. CRoxieServerStreamedIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8751. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  8752. {
  8753. }
  8754. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  8755. {
  8756. return new CRoxieServerStreamedIteratorActivity(_ctx, this, _probeManager);
  8757. }
  8758. };
  8759. IRoxieServerActivityFactory *createRoxieServerStreamedIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8760. {
  8761. return new CRoxieServerStreamedIteratorActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  8762. }
  8763. //=====================================================================================================
  8764. class CRoxieServerFilterActivity : public CRoxieServerLateStartActivity
  8765. {
  8766. IHThorFilterArg &helper;
  8767. bool anyThisGroup;
  8768. IRangeCompare * stepCompare;
  8769. public:
  8770. CRoxieServerFilterActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8771. : CRoxieServerLateStartActivity(_ctx, _factory, _probeManager), helper((IHThorFilterArg &)basehelper)
  8772. {
  8773. anyThisGroup = false;
  8774. stepCompare = NULL;
  8775. }
  8776. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8777. {
  8778. anyThisGroup = false;
  8779. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  8780. lateStart(parentExtractSize, parentExtract, helper.canMatchAny());
  8781. stepCompare = NULL;
  8782. if (!eof)
  8783. {
  8784. IInputSteppingMeta * stepMeta = input->querySteppingMeta();
  8785. if (stepMeta)
  8786. stepCompare = stepMeta->queryCompare();
  8787. }
  8788. }
  8789. virtual const void * nextRow()
  8790. {
  8791. ActivityTimer t(totalCycles, timeActivities);
  8792. if (eof)
  8793. return NULL;
  8794. for (;;)
  8795. {
  8796. OwnedConstRoxieRow ret(inputStream->nextRow());
  8797. if (!ret)
  8798. {
  8799. //stop returning two NULLs in a row.
  8800. if (anyThisGroup)
  8801. {
  8802. anyThisGroup = false;
  8803. return NULL;
  8804. }
  8805. ret.setown(inputStream->nextRow());
  8806. if (!ret)
  8807. {
  8808. eof = true;
  8809. return NULL; // eof...
  8810. }
  8811. }
  8812. if (helper.isValid(ret))
  8813. {
  8814. anyThisGroup = true;
  8815. processed++;
  8816. return ret.getClear();
  8817. }
  8818. }
  8819. }
  8820. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  8821. {
  8822. //Could assert that this isn't grouped
  8823. // MORE - will need rethinking once we rethink the nextRowGE interface for global smart-stepping.
  8824. ActivityTimer t(totalCycles, timeActivities);
  8825. if (eof)
  8826. return NULL;
  8827. for (;;)
  8828. {
  8829. OwnedConstRoxieRow ret(inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra));
  8830. if (!ret)
  8831. {
  8832. eof = true;
  8833. return NULL;
  8834. }
  8835. if (!wasCompleteMatch)
  8836. {
  8837. anyThisGroup = false; // RKC->GH - is this right??
  8838. return ret.getClear();
  8839. }
  8840. if (helper.isValid(ret))
  8841. {
  8842. anyThisGroup = true;
  8843. processed++;
  8844. return ret.getClear();
  8845. }
  8846. if (!stepExtra.returnMismatches())
  8847. {
  8848. ret.clear();
  8849. return nextRow();
  8850. }
  8851. //If asked to return mismatches we are only interested in mismatches that will force the stepped
  8852. //condition to advance
  8853. if (stepCompare->docompare(ret, seek, numFields) != 0)
  8854. {
  8855. wasCompleteMatch = false;
  8856. anyThisGroup = false; // WHY?
  8857. return ret.getClear();
  8858. }
  8859. }
  8860. }
  8861. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  8862. {
  8863. return input->gatherConjunctions(collector);
  8864. }
  8865. virtual void resetEOF()
  8866. {
  8867. eof = prefiltered;
  8868. anyThisGroup = false;
  8869. inputStream->resetEOF();
  8870. }
  8871. IInputSteppingMeta * querySteppingMeta()
  8872. {
  8873. return input->querySteppingMeta();
  8874. }
  8875. };
  8876. class CRoxieServerFilterActivityFactory : public CRoxieServerActivityFactory
  8877. {
  8878. public:
  8879. CRoxieServerFilterActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8880. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  8881. {
  8882. optStableInput = false;
  8883. }
  8884. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  8885. {
  8886. return new CRoxieServerFilterActivity(_ctx, this, _probeManager);
  8887. }
  8888. };
  8889. IRoxieServerActivityFactory *createRoxieServerFilterActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8890. {
  8891. return new CRoxieServerFilterActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  8892. }
  8893. //=====================================================================================================
  8894. class CRoxieServerFilterGroupActivity : public CRoxieServerLateStartActivity
  8895. {
  8896. IHThorFilterGroupArg &helper;
  8897. unsigned curIndex;
  8898. ConstPointerArray gathered;
  8899. IRangeCompare * stepCompare;
  8900. public:
  8901. CRoxieServerFilterGroupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8902. : CRoxieServerLateStartActivity(_ctx, _factory, _probeManager), helper((IHThorFilterGroupArg &)basehelper)
  8903. {
  8904. curIndex = 0;
  8905. stepCompare = NULL;
  8906. }
  8907. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8908. {
  8909. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  8910. lateStart(parentExtractSize, parentExtract, helper.canMatchAny());//sets eof
  8911. assertex(eof == !helper.canMatchAny());
  8912. curIndex = 0;
  8913. stepCompare = NULL;
  8914. if (!eof)
  8915. {
  8916. IInputSteppingMeta * inputStepping = input->querySteppingMeta();
  8917. if (inputStepping)
  8918. stepCompare = inputStepping->queryCompare();
  8919. }
  8920. }
  8921. virtual void reset()
  8922. {
  8923. releaseGathered();
  8924. CRoxieServerLateStartActivity::reset();
  8925. }
  8926. inline void releaseGathered()
  8927. {
  8928. roxiemem::ReleaseRoxieRowRange(gathered.getArray(), curIndex, gathered.ordinality());
  8929. gathered.kill();
  8930. curIndex = 0;
  8931. }
  8932. virtual const void * nextRow()
  8933. {
  8934. ActivityTimer t(totalCycles, timeActivities);
  8935. for (;;)
  8936. {
  8937. if (eof)
  8938. return NULL;
  8939. if (gathered.ordinality())
  8940. {
  8941. if (gathered.isItem(curIndex))
  8942. {
  8943. const void * ret = gathered.item(curIndex++);
  8944. processed++;
  8945. return ret;
  8946. }
  8947. curIndex = 0;
  8948. gathered.kill();
  8949. return NULL;
  8950. }
  8951. const void * ret = inputStream->nextRow();
  8952. while (ret)
  8953. {
  8954. gathered.append(ret);
  8955. ret = inputStream->nextRow();
  8956. }
  8957. unsigned num = gathered.ordinality();
  8958. if (num != 0)
  8959. {
  8960. if (!helper.isValid(num, (const void * *)gathered.getArray()))
  8961. ReleaseRoxieRows(gathered); // read next group
  8962. }
  8963. else
  8964. eof = true;
  8965. }
  8966. }
  8967. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  8968. {
  8969. ActivityTimer t(totalCycles, timeActivities);
  8970. if (eof)
  8971. return NULL;
  8972. if (gathered.ordinality())
  8973. {
  8974. while (gathered.isItem(curIndex))
  8975. {
  8976. const void * ret = gathered.item(curIndex++);
  8977. if (stepCompare->docompare(ret, seek, numFields) >= 0)
  8978. {
  8979. processed++;
  8980. return ret;
  8981. }
  8982. ReleaseRoxieRow(ret);
  8983. }
  8984. curIndex = 0;
  8985. gathered.kill();
  8986. //nextRowGE never returns an end of group marker.
  8987. }
  8988. //Not completely sure about this - it could lead the the start of a group being skipped,
  8989. //so the group filter could potentially work on a different group. If so, we'd need to check the
  8990. //next fields were a subset of the grouping fields - more an issue for the group activity.
  8991. //MORE: What do we do with wasCompleteMatch? something like the following????
  8992. #if 0
  8993. for (;;)
  8994. {
  8995. const void * ret;
  8996. if (stepExtra.returnMismatches())
  8997. {
  8998. bool matchedCompletely = true;
  8999. ret = input->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  9000. if (!wasCompleteMatch)
  9001. return ret;
  9002. }
  9003. else
  9004. ret = input->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  9005. #endif
  9006. const void * ret = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  9007. while (ret)
  9008. {
  9009. gathered.append(ret);
  9010. ret = inputStream->nextRow();
  9011. }
  9012. unsigned num = gathered.ordinality();
  9013. if (num != 0)
  9014. {
  9015. if (!helper.isValid(num, (const void * *)gathered.getArray()))
  9016. ReleaseRoxieRows(gathered); // read next group
  9017. }
  9018. else
  9019. eof = true;
  9020. return IEngineRowStream::ungroupedNextRow();
  9021. }
  9022. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  9023. {
  9024. return input->gatherConjunctions(collector);
  9025. }
  9026. virtual void resetEOF()
  9027. {
  9028. eof = false;
  9029. releaseGathered();
  9030. inputStream->resetEOF();
  9031. }
  9032. IInputSteppingMeta * querySteppingMeta()
  9033. {
  9034. return input->querySteppingMeta();
  9035. }
  9036. };
  9037. class CRoxieServerFilterGroupActivityFactory : public CRoxieServerActivityFactory
  9038. {
  9039. public:
  9040. CRoxieServerFilterGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9041. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  9042. {
  9043. }
  9044. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9045. {
  9046. return new CRoxieServerFilterGroupActivity(_ctx, this, _probeManager);
  9047. }
  9048. };
  9049. IRoxieServerActivityFactory *createRoxieServerFilterGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9050. {
  9051. return new CRoxieServerFilterGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9052. }
  9053. //=================================================================================
  9054. class CRoxieServerSideEffectActivity : public CRoxieServerActivity
  9055. {
  9056. IHThorSideEffectArg &helper;
  9057. CriticalSection ecrit;
  9058. Owned<IException> exception;
  9059. bool executed;
  9060. public:
  9061. CRoxieServerSideEffectActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9062. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorSideEffectArg &)basehelper)
  9063. {
  9064. executed = false;
  9065. }
  9066. virtual const void * nextRow()
  9067. {
  9068. ActivityTimer t(totalCycles, timeActivities);
  9069. CriticalBlock b(ecrit);
  9070. if (exception)
  9071. throw(exception.getLink());
  9072. if (!executed)
  9073. {
  9074. try
  9075. {
  9076. executed = true;
  9077. helper.action();
  9078. }
  9079. catch(IException *E)
  9080. {
  9081. exception.set(E);
  9082. throw;
  9083. }
  9084. }
  9085. return NULL;
  9086. }
  9087. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  9088. {
  9089. CriticalBlock b(ecrit);
  9090. if (exception)
  9091. throw(exception.getLink());
  9092. if (!executed)
  9093. {
  9094. try
  9095. {
  9096. ActivityTimer t(totalCycles, timeActivities);
  9097. executed = true;
  9098. start(parentExtractSize, parentExtract, false);
  9099. helper.action();
  9100. stop();
  9101. }
  9102. catch(IException *E)
  9103. {
  9104. ctx->notifyAbort(E);
  9105. abort();
  9106. exception.set(E);
  9107. throw;
  9108. }
  9109. }
  9110. }
  9111. virtual void reset()
  9112. {
  9113. executed = false;
  9114. exception.clear();
  9115. CRoxieServerActivity::reset();
  9116. }
  9117. };
  9118. class CRoxieServerSideEffectActivityFactory : public CRoxieServerActivityFactory
  9119. {
  9120. bool isRoot;
  9121. public:
  9122. CRoxieServerSideEffectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  9123. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  9124. {
  9125. }
  9126. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9127. {
  9128. return new CRoxieServerSideEffectActivity(_ctx, this, _probeManager);
  9129. }
  9130. virtual bool isSink() const
  9131. {
  9132. return isRoot && !meta.queryOriginal();
  9133. }
  9134. };
  9135. IRoxieServerActivityFactory *createRoxieServerSideEffectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  9136. {
  9137. return new CRoxieServerSideEffectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  9138. }
  9139. //=================================================================================
  9140. class CRoxieServerActionActivity : public CRoxieServerInternalSinkActivity
  9141. {
  9142. IHThorActionArg &helper;
  9143. public:
  9144. CRoxieServerActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  9145. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _numOutputs), helper((IHThorActionArg &)basehelper)
  9146. {
  9147. }
  9148. virtual void onExecute()
  9149. {
  9150. helper.action();
  9151. }
  9152. };
  9153. class CRoxieServerActionActivityFactory : public CRoxieServerInternalSinkFactory
  9154. {
  9155. public:
  9156. CRoxieServerActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  9157. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot)
  9158. {
  9159. }
  9160. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9161. {
  9162. return new CRoxieServerActionActivity(_ctx, this, _probeManager, usageCount);
  9163. }
  9164. };
  9165. IRoxieServerActivityFactory *createRoxieServerActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  9166. {
  9167. return new CRoxieServerActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot);
  9168. }
  9169. //=================================================================================
  9170. class CRoxieServerSampleActivity : public CRoxieServerActivity
  9171. {
  9172. IHThorSampleArg &helper;
  9173. unsigned numSamples;
  9174. unsigned numToSkip;
  9175. unsigned whichSample;
  9176. bool anyThisGroup;
  9177. bool eof;
  9178. public:
  9179. CRoxieServerSampleActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9180. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorSampleArg &)basehelper)
  9181. {
  9182. numSamples = 0;
  9183. numToSkip = 0;
  9184. whichSample = 0;
  9185. anyThisGroup = false;
  9186. eof = false;
  9187. }
  9188. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9189. {
  9190. anyThisGroup = false;
  9191. eof = false;
  9192. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9193. numSamples = helper.getProportion();
  9194. whichSample = helper.getSampleNumber();
  9195. numToSkip = (whichSample ? whichSample-1 : 0);
  9196. }
  9197. virtual const void * nextRow()
  9198. {
  9199. ActivityTimer t(totalCycles, timeActivities);
  9200. if (eof)
  9201. return NULL;
  9202. for (;;)
  9203. {
  9204. const void * ret = inputStream->nextRow();
  9205. if (!ret)
  9206. {
  9207. //this does work with groups - may or may not be useful...
  9208. //reset the sample for each group.... probably best.
  9209. numToSkip = (whichSample ? whichSample-1 : 0);
  9210. if (anyThisGroup)
  9211. {
  9212. anyThisGroup = false;
  9213. return NULL;
  9214. }
  9215. ret = inputStream->nextRow();
  9216. if (!ret)
  9217. {
  9218. eof = true;
  9219. return NULL; // eof...
  9220. }
  9221. }
  9222. if (numToSkip == 0)
  9223. {
  9224. anyThisGroup = true;
  9225. numToSkip = numSamples-1;
  9226. processed++;
  9227. return ret;
  9228. }
  9229. numToSkip--;
  9230. ReleaseRoxieRow(ret);
  9231. }
  9232. }
  9233. };
  9234. class CRoxieServerSampleActivityFactory : public CRoxieServerActivityFactory
  9235. {
  9236. public:
  9237. CRoxieServerSampleActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9238. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  9239. {
  9240. }
  9241. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9242. {
  9243. return new CRoxieServerSampleActivity(_ctx, this, _probeManager);
  9244. }
  9245. };
  9246. IRoxieServerActivityFactory *createRoxieServerSampleActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9247. {
  9248. return new CRoxieServerSampleActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9249. }
  9250. //=================================================================================
  9251. class CRoxieServerChooseSetsActivity : public CRoxieServerActivity
  9252. {
  9253. IHThorChooseSetsArg &helper;
  9254. unsigned numSets;
  9255. unsigned * setCounts;
  9256. bool done;
  9257. public:
  9258. CRoxieServerChooseSetsActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9259. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorChooseSetsArg &)basehelper)
  9260. {
  9261. setCounts = NULL;
  9262. numSets = 0;
  9263. done = false;
  9264. }
  9265. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9266. {
  9267. done = false;
  9268. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9269. numSets = helper.getNumSets();
  9270. setCounts = new unsigned[numSets];
  9271. memset(setCounts, 0, sizeof(unsigned)*numSets);
  9272. helper.setCounts(setCounts);
  9273. }
  9274. virtual void reset()
  9275. {
  9276. delete [] setCounts;
  9277. setCounts = NULL;
  9278. CRoxieServerActivity::reset();
  9279. }
  9280. virtual const void * nextRow()
  9281. {
  9282. ActivityTimer t(totalCycles, timeActivities);
  9283. if (done)
  9284. return NULL;
  9285. for (;;)
  9286. {
  9287. const void * ret = inputStream->ungroupedNextRow();
  9288. if (!ret)
  9289. {
  9290. done = true;
  9291. return NULL;
  9292. }
  9293. processed++;
  9294. switch (helper.getRecordAction(ret))
  9295. {
  9296. case 2:
  9297. done = true;
  9298. return ret;
  9299. case 1:
  9300. return ret;
  9301. }
  9302. ReleaseRoxieRow(ret);
  9303. }
  9304. }
  9305. };
  9306. class CRoxieServerChooseSetsActivityFactory : public CRoxieServerActivityFactory
  9307. {
  9308. public:
  9309. CRoxieServerChooseSetsActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9310. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  9311. {
  9312. }
  9313. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9314. {
  9315. return new CRoxieServerChooseSetsActivity(_ctx, this, _probeManager);
  9316. }
  9317. };
  9318. IRoxieServerActivityFactory *createRoxieServerChooseSetsActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9319. {
  9320. return new CRoxieServerChooseSetsActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9321. }
  9322. //=================================================================================
  9323. class CRoxieServerChooseSetsExActivity : public CRoxieServerActivity
  9324. {
  9325. protected:
  9326. IHThorChooseSetsExArg &helper;
  9327. unsigned numSets;
  9328. unsigned curIndex;
  9329. unsigned * setCounts;
  9330. count_t * limits;
  9331. bool done;
  9332. ConstPointerArray gathered;
  9333. virtual bool includeRow(const void * row) = 0;
  9334. virtual void calculateSelection() = 0;
  9335. public:
  9336. CRoxieServerChooseSetsExActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9337. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorChooseSetsExArg &)basehelper)
  9338. {
  9339. setCounts = NULL;
  9340. limits = NULL;
  9341. done = false;
  9342. curIndex = 0;
  9343. numSets = 0;
  9344. }
  9345. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9346. {
  9347. done = false;
  9348. curIndex = 0;
  9349. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9350. numSets = helper.getNumSets();
  9351. setCounts = new unsigned[numSets];
  9352. memset(setCounts, 0, sizeof(unsigned)*numSets);
  9353. limits = (count_t *)calloc(sizeof(count_t), numSets);
  9354. helper.getLimits(limits);
  9355. }
  9356. virtual void reset()
  9357. {
  9358. delete [] setCounts;
  9359. setCounts = NULL;
  9360. free(limits);
  9361. limits = NULL;
  9362. roxiemem::ReleaseRoxieRowRange(gathered.getArray(), curIndex, gathered.ordinality());
  9363. gathered.kill();
  9364. curIndex = 0;
  9365. CRoxieServerActivity::reset();
  9366. }
  9367. virtual const void * nextRow()
  9368. {
  9369. ActivityTimer t(totalCycles, timeActivities);
  9370. if (gathered.ordinality() == 0)
  9371. {
  9372. curIndex = 0;
  9373. if (!inputStream->nextGroup(gathered))
  9374. {
  9375. done = true;
  9376. return NULL;
  9377. }
  9378. ForEachItemIn(idx1, gathered)
  9379. {
  9380. unsigned category = helper.getCategory(gathered.item(idx1));
  9381. if (category)
  9382. setCounts[category-1]++;
  9383. }
  9384. calculateSelection();
  9385. }
  9386. while (gathered.isItem(curIndex))
  9387. {
  9388. const void * row = gathered.item(curIndex);
  9389. gathered.replace(NULL, curIndex);
  9390. curIndex++;
  9391. if (includeRow(row))
  9392. {
  9393. processed++;
  9394. return row;
  9395. }
  9396. ReleaseRoxieRow(row);
  9397. }
  9398. gathered.kill();
  9399. return NULL;
  9400. }
  9401. };
  9402. class CRoxieServerChooseSetsLastActivity : public CRoxieServerChooseSetsExActivity
  9403. {
  9404. unsigned * numToSkip;
  9405. public:
  9406. CRoxieServerChooseSetsLastActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager) : CRoxieServerChooseSetsExActivity(_ctx, _factory, _probeManager)
  9407. {
  9408. numToSkip = NULL;
  9409. }
  9410. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9411. {
  9412. CRoxieServerChooseSetsExActivity::start(parentExtractSize, parentExtract, paused);
  9413. numToSkip = (unsigned *)calloc(sizeof(unsigned), numSets);
  9414. }
  9415. virtual void reset()
  9416. {
  9417. free(numToSkip);
  9418. numToSkip = NULL;
  9419. CRoxieServerChooseSetsExActivity::reset();
  9420. }
  9421. protected:
  9422. virtual void calculateSelection()
  9423. {
  9424. for (unsigned idx=0; idx < numSets; idx++)
  9425. {
  9426. if (setCounts[idx] < limits[idx])
  9427. numToSkip[idx] = 0;
  9428. else
  9429. numToSkip[idx] = (unsigned)(setCounts[idx] - limits[idx]);
  9430. }
  9431. }
  9432. virtual bool includeRow(const void * row)
  9433. {
  9434. unsigned category = helper.getCategory(row);
  9435. if (category)
  9436. {
  9437. if (numToSkip[category-1] == 0)
  9438. return true;
  9439. numToSkip[category-1]--;
  9440. }
  9441. return false;
  9442. }
  9443. };
  9444. class CRoxieServerChooseSetsEnthActivity : public CRoxieServerChooseSetsExActivity
  9445. {
  9446. count_t * counter;
  9447. public:
  9448. CRoxieServerChooseSetsEnthActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager) : CRoxieServerChooseSetsExActivity(_ctx, _factory, _probeManager)
  9449. {
  9450. counter = NULL;
  9451. }
  9452. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9453. {
  9454. CRoxieServerChooseSetsExActivity::start(parentExtractSize, parentExtract, paused);
  9455. counter = (count_t *)calloc(sizeof(count_t), numSets);
  9456. }
  9457. virtual void reset()
  9458. {
  9459. free(counter);
  9460. counter = NULL;
  9461. CRoxieServerChooseSetsExActivity::reset();
  9462. }
  9463. protected:
  9464. virtual void calculateSelection()
  9465. {
  9466. }
  9467. virtual bool includeRow(const void * row)
  9468. {
  9469. unsigned category = helper.getCategory(row);
  9470. if (category)
  9471. {
  9472. assertex(category <= numSets);
  9473. counter[category-1] += limits[category-1];
  9474. if(counter[category-1] >= setCounts[category-1])
  9475. {
  9476. counter[category-1] -= setCounts[category-1];
  9477. return true;
  9478. }
  9479. }
  9480. return false;
  9481. }
  9482. };
  9483. class CRoxieServerChooseSetsEnthActivityFactory : public CRoxieServerActivityFactory
  9484. {
  9485. public:
  9486. CRoxieServerChooseSetsEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9487. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  9488. {
  9489. }
  9490. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9491. {
  9492. return new CRoxieServerChooseSetsEnthActivity(_ctx, this, _probeManager);
  9493. }
  9494. };
  9495. IRoxieServerActivityFactory *createRoxieServerChooseSetsEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9496. {
  9497. return new CRoxieServerChooseSetsEnthActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9498. }
  9499. class CRoxieServerChooseSetsLastActivityFactory : public CRoxieServerActivityFactory
  9500. {
  9501. public:
  9502. CRoxieServerChooseSetsLastActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9503. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  9504. {
  9505. }
  9506. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9507. {
  9508. return new CRoxieServerChooseSetsLastActivity(_ctx, this, _probeManager);
  9509. }
  9510. };
  9511. IRoxieServerActivityFactory *createRoxieServerChooseSetsLastActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9512. {
  9513. return new CRoxieServerChooseSetsLastActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9514. }
  9515. //=================================================================================
  9516. class CRoxieServerEnthActivity : public CRoxieServerActivity
  9517. {
  9518. IHThorEnthArg &helper;
  9519. unsigned __int64 numerator;
  9520. unsigned __int64 denominator;
  9521. unsigned __int64 counter;
  9522. bool eof;
  9523. public:
  9524. CRoxieServerEnthActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9525. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorEnthArg &)basehelper)
  9526. {
  9527. eof = false;
  9528. numerator = denominator = counter = 0;
  9529. }
  9530. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9531. {
  9532. eof = false;
  9533. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9534. numerator = helper.getProportionNumerator();
  9535. denominator = helper.getProportionDenominator();
  9536. if(denominator == 0) denominator = 1; //MORE: simplest way to avoid disaster in this case
  9537. counter = (helper.getSampleNumber()-1) * greatestCommonDivisor(numerator, denominator);
  9538. if (counter >= denominator)
  9539. counter %= denominator;
  9540. }
  9541. inline bool wanted()
  9542. {
  9543. counter += numerator;
  9544. if(counter >= denominator)
  9545. {
  9546. counter -= denominator;
  9547. return true;
  9548. }
  9549. return false;
  9550. }
  9551. virtual const void * nextRow()
  9552. {
  9553. ActivityTimer t(totalCycles, timeActivities);
  9554. if (eof)
  9555. return NULL;
  9556. const void * ret;
  9557. for (;;)
  9558. {
  9559. ret = inputStream->ungroupedNextRow();
  9560. if (!ret) //eof
  9561. {
  9562. eof = true;
  9563. return ret;
  9564. }
  9565. if (wanted())
  9566. return ret;
  9567. ReleaseRoxieRow(ret);
  9568. }
  9569. }
  9570. };
  9571. class CRoxieServerEnthActivityFactory : public CRoxieServerActivityFactory
  9572. {
  9573. public:
  9574. CRoxieServerEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9575. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  9576. {
  9577. }
  9578. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9579. {
  9580. return new CRoxieServerEnthActivity(_ctx, this, _probeManager);
  9581. }
  9582. };
  9583. IRoxieServerActivityFactory *createRoxieServerEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9584. {
  9585. return new CRoxieServerEnthActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9586. }
  9587. //=================================================================================
  9588. class CRoxieServerAggregateActivity : public CRoxieServerActivity
  9589. {
  9590. IHThorAggregateArg &helper;
  9591. bool eof;
  9592. bool isInputGrouped;
  9593. bool abortEarly;
  9594. public:
  9595. CRoxieServerAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9596. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorAggregateArg &)basehelper)
  9597. {
  9598. eof = false;
  9599. isInputGrouped = false;
  9600. abortEarly = false;
  9601. }
  9602. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9603. {
  9604. eof = false;
  9605. isInputGrouped = input->queryOutputMeta()->isGrouped(); // could be done earlier, in setInput?
  9606. abortEarly = !isInputGrouped && (factory->getKind() == TAKexistsaggregate); // ditto
  9607. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9608. }
  9609. virtual bool needsAllocator() const { return true; }
  9610. virtual const void * nextRow()
  9611. {
  9612. ActivityTimer t(totalCycles, timeActivities);
  9613. if (eof)
  9614. return NULL;
  9615. const void * next = inputStream->nextRow();
  9616. if (!next && isInputGrouped)
  9617. {
  9618. eof = true;
  9619. return NULL;
  9620. }
  9621. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  9622. size32_t finalSize = helper.clearAggregate(rowBuilder);
  9623. if (next)
  9624. {
  9625. finalSize = helper.processFirst(rowBuilder, next);
  9626. ReleaseRoxieRow(next);
  9627. if (!abortEarly)
  9628. {
  9629. for (;;)
  9630. {
  9631. next = inputStream->nextRow();
  9632. if (!next)
  9633. break;
  9634. finalSize = helper.processNext(rowBuilder, next);
  9635. ReleaseRoxieRow(next);
  9636. }
  9637. }
  9638. }
  9639. if (!isInputGrouped) // either read all, or aborted early
  9640. eof = true;
  9641. processed++;
  9642. return rowBuilder.finalizeRowClear(finalSize);
  9643. }
  9644. };
  9645. class CRoxieServerStrandedAggregateActivity : public CRoxieServerStrandedActivity, implements IOrderedCallbackCollection
  9646. {
  9647. class AggregateProcessor : public StrandProcessor, implements IStrandThreaded, implements IOrderedOutputCallback
  9648. {
  9649. protected:
  9650. IHThorAggregateArg &helper;
  9651. OwnedConstRoxieRow result;
  9652. bool eof = false;
  9653. bool isInputGrouped = false;
  9654. bool abortEarly = false;
  9655. public:
  9656. AggregateProcessor(CRoxieServerActivity &_parent, IEngineRowStream *_inputStream, IHThorAggregateArg &_helper, bool _isInputGrouped, bool _abortEarly)
  9657. : StrandProcessor(_parent, _inputStream, true), helper(_helper), isInputGrouped(_isInputGrouped), abortEarly(_abortEarly)
  9658. {
  9659. }
  9660. virtual const void * nextRow() override
  9661. {
  9662. ActivityTimer t(totalCycles, timeActivities);
  9663. if (eof || isAborting())
  9664. return NULL;
  9665. const void * next = inputStream->nextRow();
  9666. if (!next && isInputGrouped)
  9667. {
  9668. eof = true;
  9669. return NULL;
  9670. }
  9671. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  9672. size32_t finalSize = helper.clearAggregate(rowBuilder);
  9673. if (next)
  9674. {
  9675. finalSize = helper.processFirst(rowBuilder, next);
  9676. ReleaseRoxieRow(next);
  9677. if (!abortEarly)
  9678. {
  9679. for (;;)
  9680. {
  9681. next = inputStream->nextRow();
  9682. if (!next)
  9683. break;
  9684. finalSize = helper.processNext(rowBuilder, next);
  9685. ReleaseRoxieRow(next);
  9686. if (isAborting())
  9687. break;
  9688. }
  9689. }
  9690. }
  9691. if (!isInputGrouped) // either read all, or aborted early
  9692. eof = true;
  9693. processed++;
  9694. return rowBuilder.finalizeRowClear(finalSize);
  9695. }
  9696. virtual void main() override
  9697. {
  9698. isInputGrouped = true; // gather no row if there are no input rows.
  9699. result.setown(nextRow());
  9700. queryActivity().noteStrandFinished(inputStream);
  9701. }
  9702. virtual void reset() override
  9703. {
  9704. StrandProcessor::reset();
  9705. result.clear();
  9706. eof = false;
  9707. }
  9708. //interface IOutputOutputCallback
  9709. virtual bool noteEndOfInputChunk() { return true; }
  9710. virtual void noteEndOfInput() {}
  9711. virtual void stopStream()
  9712. {
  9713. inputStream->stop();
  9714. }
  9715. const void * queryResult() const { return result; }
  9716. CRoxieServerStrandedAggregateActivity & queryActivity() { return static_cast<CRoxieServerStrandedAggregateActivity &>(parent); }
  9717. };
  9718. //This class is only used when a single aggregate is being calculated.
  9719. class AggregateCombiner : public CInterfaceOf<IEngineRowStream>
  9720. {
  9721. public:
  9722. explicit AggregateCombiner(CRoxieServerStrandedAggregateActivity & _parent) : parent(_parent)
  9723. {
  9724. }
  9725. virtual const void *nextRow()
  9726. {
  9727. return parent.getCombinedAggregate();
  9728. }
  9729. virtual void stop()
  9730. {
  9731. parent.outputStopped();
  9732. }
  9733. virtual void resetEOF()
  9734. {
  9735. throwUnexpected();
  9736. }
  9737. protected:
  9738. CRoxieServerStrandedAggregateActivity & parent;
  9739. } combiner;
  9740. class NullCallback : implements IOrderedOutputCallback
  9741. {
  9742. public:
  9743. virtual bool noteEndOfInputChunk() { return true; }
  9744. virtual void noteEndOfInput() {}
  9745. } nullCallback;
  9746. public:
  9747. CRoxieServerStrandedAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const StrandOptions &_strandOptions)
  9748. : CRoxieServerStrandedActivity(_ctx, _factory, _probeManager, _strandOptions), helper((IHThorAggregateArg &)basehelper), combiner(*this)
  9749. {
  9750. isInputGrouped = false;
  9751. abortEarly = false;
  9752. }
  9753. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  9754. {
  9755. CRoxieServerStrandedActivity::setInput(idx, _sourceIdx, _in);
  9756. isInputGrouped = input->queryOutputMeta()->isGrouped(); // could be done earlier, in setInput?
  9757. abortEarly = !isInputGrouped && (factory->getKind() == TAKexistsaggregate); // ditto
  9758. //For EXISTS(), and aggregates that rely on the input order, force to execute single threaded
  9759. //MORE: Ordered should be able to process a block at a time and then merge them, similar to disk write processing.
  9760. if (abortEarly || (!isInputGrouped && queryFactory()->isInputOrdered(false, 0)))
  9761. strandOptions.numStrands = 1;
  9762. else if (!isInputGrouped)
  9763. combineStreams = true;
  9764. }
  9765. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  9766. {
  9767. PointerArrayOf<IEngineRowStream> localStreams;
  9768. //If streams are being combined, this class should be notified of end of sections, otherwise grouped aggregates can inform a downstream activity.
  9769. IOrderedCallbackCollection * callbacks = combineStreams ? static_cast<IOrderedCallbackCollection *>(this) : orderedCallbacks;
  9770. Owned<IStrandJunction> outJunction = CRoxieServerStrandedActivity::getOutputStreams(ctx, idx, localStreams, consumerOptions, consumerOrdered, callbacks);
  9771. if (localStreams.ordinality() == 1)
  9772. combineStreams = false; // Select a more efficient/simpler code path
  9773. if (combineStreams)
  9774. {
  9775. assertex(!outJunction); // this needs more thought!
  9776. streams.append(&combiner);
  9777. }
  9778. else
  9779. {
  9780. streams.swapWith(localStreams);
  9781. }
  9782. return outJunction.getClear();
  9783. }
  9784. virtual StrandProcessor *createStrandProcessor(IEngineRowStream *instream)
  9785. {
  9786. if (traceLevel > 4)
  9787. DBGLOG("Create aggregate strand processor %u", strandOptions.numStrands);
  9788. return new AggregateProcessor(*this, instream, (IHThorAggregateArg &) basehelper, isInputGrouped && !combineStreams, abortEarly);
  9789. }
  9790. virtual StrandProcessor *createStrandSourceProcessor(bool inputOrdered) { throwUnexpected(); }
  9791. virtual bool needsAllocator() const { return true; }
  9792. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused) override
  9793. {
  9794. CRoxieServerStrandedActivity::start(parentExtractSize, parentExtract, paused);
  9795. if (combineStreams)
  9796. {
  9797. barrier.setown(createStrandBarrier());
  9798. ForEachItemIn(i, strands)
  9799. barrier->startStrand(queryAggregate(i));
  9800. active.store(1);
  9801. }
  9802. else
  9803. active.store(0);
  9804. }
  9805. virtual void reset() override
  9806. {
  9807. CRoxieServerStrandedActivity::reset();
  9808. barrier.clear();
  9809. calculated = false;
  9810. }
  9811. //Helper functions for the single aggregate case
  9812. const void * getCombinedAggregate()
  9813. {
  9814. if (calculated)
  9815. return NULL;
  9816. calculated= true;
  9817. barrier->waitForStrands();
  9818. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  9819. size32_t finalSize = helper.clearAggregate(rowBuilder);
  9820. bool isFirst = true;
  9821. for (unsigned i=0; i < numStrands(); i++)
  9822. {
  9823. const void * next = queryAggregate(i).queryResult();
  9824. if (next)
  9825. {
  9826. if (isFirst)
  9827. {
  9828. finalSize = cloneRow(rowBuilder, next, helper.queryOutputMeta());
  9829. isFirst = false;
  9830. }
  9831. else
  9832. finalSize = helper.mergeAggregate(rowBuilder, next);
  9833. }
  9834. }
  9835. return rowBuilder.finalizeRowClear(finalSize);
  9836. }
  9837. void outputStopped()
  9838. {
  9839. //only called if generating a single result.
  9840. assertex(combineStreams);
  9841. if (barrier)
  9842. {
  9843. requestAbort(); // if strands are still running, abort them
  9844. barrier->waitForStrands();
  9845. }
  9846. else
  9847. {
  9848. ForEachItemIn(i, strands)
  9849. queryAggregate(i).stopStream();
  9850. }
  9851. CRoxieServerStrandedActivity::stop();
  9852. }
  9853. void noteStrandFinished(IRowStream * stream)
  9854. {
  9855. barrier->noteStrandFinished(stream);
  9856. }
  9857. virtual IOrderedOutputCallback * queryCallback(unsigned i)
  9858. {
  9859. //The non-ordered aggregate does not need to process the ordered call back information.
  9860. //If the ordered single aggregate was implemented then it would need to be processed instead of ignored,
  9861. //however it needs some care since the strands are not yet created. So cannot return strand(i).
  9862. return &nullCallback;
  9863. }
  9864. inline AggregateProcessor & queryAggregate(unsigned i)
  9865. {
  9866. return static_cast<AggregateProcessor &>(strands.item(i));
  9867. }
  9868. protected:
  9869. IHThorAggregateArg &helper;
  9870. Owned<IStrandBarrier> barrier;
  9871. IEngineRowStream * combinedStream = nullptr;
  9872. bool isInputGrouped;
  9873. bool abortEarly;
  9874. bool combineStreams = false;
  9875. bool calculated = false;
  9876. };
  9877. class CRoxieServerAggregateActivityFactory : public CRoxieServerActivityFactory
  9878. {
  9879. StrandOptions strandOptions;
  9880. public:
  9881. CRoxieServerAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9882. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), strandOptions(_graphNode)
  9883. {
  9884. Owned<IHThorAggregateArg> helper = (IHThorAggregateArg *) helperFactory();
  9885. if (!(helper->getAggregateFlags() & TAForderedmerge))
  9886. optStableInput = false;
  9887. }
  9888. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9889. {
  9890. return new CRoxieServerStrandedAggregateActivity(_ctx, this, _probeManager, strandOptions);
  9891. }
  9892. };
  9893. IRoxieServerActivityFactory *createRoxieServerAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9894. {
  9895. return new CRoxieServerAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9896. }
  9897. //=================================================================================
  9898. typedef unsigned t_hashPrefix;
  9899. class CRoxieServerHashAggregateActivity : public CRoxieServerActivity
  9900. {
  9901. IHThorHashAggregateArg &helper;
  9902. RowAggregator aggregated;
  9903. bool eof;
  9904. bool gathered;
  9905. bool isGroupedAggregate;
  9906. public:
  9907. CRoxieServerHashAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, bool _isGroupedAggregate, IProbeManager *_probeManager)
  9908. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorHashAggregateArg &)basehelper),
  9909. isGroupedAggregate(_isGroupedAggregate),
  9910. aggregated(helper, helper)
  9911. {
  9912. eof = false;
  9913. gathered = false;
  9914. }
  9915. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9916. {
  9917. eof = false;
  9918. gathered = false;
  9919. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9920. }
  9921. virtual void reset()
  9922. {
  9923. aggregated.reset();
  9924. CRoxieServerActivity::reset();
  9925. }
  9926. virtual bool needsAllocator() const { return true; }
  9927. virtual const void * nextRow()
  9928. {
  9929. ActivityTimer t(totalCycles, timeActivities);
  9930. if (eof)
  9931. return NULL;
  9932. if (!gathered)
  9933. {
  9934. aggregated.start(rowAllocator);
  9935. bool eog = true;
  9936. for (;;)
  9937. {
  9938. const void * next = inputStream->nextRow();
  9939. if (!next)
  9940. {
  9941. if (isGroupedAggregate)
  9942. {
  9943. if (eog)
  9944. eof = true;
  9945. break;
  9946. }
  9947. next = inputStream->nextRow();
  9948. if (!next)
  9949. break;
  9950. }
  9951. eog = false;
  9952. aggregated.addRow(next);
  9953. ReleaseRoxieRow(next);
  9954. }
  9955. gathered = true;
  9956. }
  9957. Owned<AggregateRowBuilder> next = aggregated.nextResult();
  9958. if (next)
  9959. {
  9960. processed++;
  9961. return next->finalizeRowClear();
  9962. }
  9963. if (!isGroupedAggregate)
  9964. eof = true;
  9965. aggregated.reset();
  9966. gathered = false;
  9967. return NULL;
  9968. }
  9969. };
  9970. class CRoxieServerHashAggregateActivityFactory : public CRoxieServerActivityFactory
  9971. {
  9972. public:
  9973. CRoxieServerHashAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9974. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  9975. {
  9976. isGroupedAggregate = _graphNode.getPropBool("att[@name='grouped']/@value");
  9977. }
  9978. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9979. {
  9980. return new CRoxieServerHashAggregateActivity(_ctx, this, isGroupedAggregate, _probeManager);
  9981. }
  9982. protected:
  9983. bool isGroupedAggregate;
  9984. };
  9985. IRoxieServerActivityFactory *createRoxieServerHashAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9986. {
  9987. return new CRoxieServerHashAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9988. }
  9989. //=================================================================================
  9990. class CRoxieServerDegroupActivity : public CRoxieServerActivity
  9991. {
  9992. IHThorDegroupArg &helper;
  9993. bool eof;
  9994. public:
  9995. CRoxieServerDegroupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9996. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorDegroupArg &)basehelper)
  9997. {
  9998. eof = false;
  9999. }
  10000. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10001. {
  10002. eof = false;
  10003. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  10004. }
  10005. virtual const void * nextRow()
  10006. {
  10007. ActivityTimer t(totalCycles, timeActivities);
  10008. if (eof)
  10009. return NULL;
  10010. const void * ret = inputStream->ungroupedNextRow();
  10011. if (ret)
  10012. processed++;
  10013. else
  10014. eof = true;
  10015. return ret;
  10016. }
  10017. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  10018. {
  10019. ActivityTimer t(totalCycles, timeActivities);
  10020. if (eof)
  10021. return NULL;
  10022. const void * ret = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  10023. if (ret)
  10024. processed++;
  10025. else
  10026. eof = true;
  10027. return ret;
  10028. }
  10029. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  10030. {
  10031. return input->gatherConjunctions(collector);
  10032. }
  10033. virtual void resetEOF()
  10034. {
  10035. eof = false;
  10036. inputStream->resetEOF();
  10037. }
  10038. IInputSteppingMeta * querySteppingMeta()
  10039. {
  10040. return input->querySteppingMeta();
  10041. }
  10042. };
  10043. class CRoxieServerDegroupActivityFactory : public CRoxieServerActivityFactory
  10044. {
  10045. public:
  10046. CRoxieServerDegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  10047. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  10048. {
  10049. }
  10050. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  10051. {
  10052. return new CRoxieServerDegroupActivity(_ctx, this, _probeManager);
  10053. }
  10054. };
  10055. IRoxieServerActivityFactory *createRoxieServerDegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  10056. {
  10057. return new CRoxieServerDegroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  10058. }
  10059. //=================================================================================
  10060. class CRoxieServerSpillReadActivity : public CRoxieServerActivity
  10061. {
  10062. IHThorDiskReadArg &helper;
  10063. bool needTransform;
  10064. bool eof;
  10065. bool anyThisGroup;
  10066. unsigned __int64 rowLimit;
  10067. unsigned __int64 choosenLimit;
  10068. public:
  10069. CRoxieServerSpillReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  10070. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorDiskReadArg &)basehelper)
  10071. {
  10072. needTransform = helper.needTransform();
  10073. rowLimit = (unsigned __int64) -1;
  10074. choosenLimit = 0;
  10075. eof = false;
  10076. anyThisGroup = false;
  10077. }
  10078. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10079. {
  10080. anyThisGroup = false;
  10081. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  10082. if (helper.canMatchAny())
  10083. eof = false;
  10084. else
  10085. eof = true;
  10086. choosenLimit = helper.getChooseNLimit();
  10087. rowLimit = helper.getRowLimit();
  10088. helper.setCallback(NULL); // members should not be called - change if they are
  10089. }
  10090. virtual bool needsAllocator() const { return true; }
  10091. virtual const void * nextRow()
  10092. {
  10093. ActivityTimer t(totalCycles, timeActivities);
  10094. if (eof)
  10095. return NULL;
  10096. if (processed==choosenLimit)
  10097. {
  10098. eof = true;
  10099. return NULL;
  10100. }
  10101. if (needTransform)
  10102. {
  10103. for (;;)
  10104. {
  10105. const void *in = inputStream->nextRow();
  10106. if (!in)
  10107. {
  10108. if (anyThisGroup)
  10109. {
  10110. anyThisGroup = false;
  10111. return NULL;
  10112. }
  10113. in = inputStream->nextRow();
  10114. if (!in)
  10115. {
  10116. eof = true;
  10117. return NULL; // eof...
  10118. }
  10119. }
  10120. unsigned outSize;
  10121. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  10122. try
  10123. {
  10124. outSize = helper.transform(rowBuilder, in);
  10125. ReleaseRoxieRow(in);
  10126. }
  10127. catch (IException *E)
  10128. {
  10129. throw makeWrappedException(E);
  10130. }
  10131. if (outSize)
  10132. {
  10133. anyThisGroup = true;
  10134. processed++;
  10135. if (processed==rowLimit)
  10136. {
  10137. if (traceLevel > 4)
  10138. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  10139. helper.onLimitExceeded();
  10140. }
  10141. return rowBuilder.finalizeRowClear(outSize);
  10142. }
  10143. }
  10144. }
  10145. else
  10146. {
  10147. const void *ret = inputStream->nextRow();
  10148. if (ret)
  10149. {
  10150. processed++;
  10151. if (processed==rowLimit)
  10152. {
  10153. if (traceLevel > 4)
  10154. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  10155. ReleaseClearRoxieRow(ret);
  10156. helper.onLimitExceeded(); // should not return
  10157. throwUnexpected();
  10158. }
  10159. }
  10160. return ret;
  10161. }
  10162. }
  10163. };
  10164. class CRoxieServerSpillReadActivityFactory : public CRoxieServerActivityFactory
  10165. {
  10166. public:
  10167. CRoxieServerSpillReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  10168. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  10169. {
  10170. }
  10171. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  10172. {
  10173. return new CRoxieServerSpillReadActivity(_ctx, this, _probeManager);
  10174. }
  10175. virtual void addDependency(unsigned source, ThorActivityKind sourceKind, unsigned sourceIdx, int controlId, const char *edgeId)
  10176. {
  10177. if (sourceKind==TAKspill || sourceKind==TAKdiskwrite) // Bit of a hack - codegen probably should differentiate
  10178. setInput(0, source, sourceIdx);
  10179. else
  10180. CRoxieServerActivityFactory::addDependency(source, kind, sourceIdx, controlId, edgeId);
  10181. }
  10182. };
  10183. IRoxieServerActivityFactory *createRoxieServerSpillReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  10184. {
  10185. return new CRoxieServerSpillReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  10186. }
  10187. //=================================================================================
  10188. class CRoxieServerSpillWriteActivity : public CRoxieServerActivity
  10189. {
  10190. public:
  10191. CRoxieServerSpillWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  10192. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  10193. {
  10194. }
  10195. ~CRoxieServerSpillWriteActivity()
  10196. {
  10197. }
  10198. virtual const void *nextRow()
  10199. {
  10200. ActivityTimer t(totalCycles, timeActivities);
  10201. return inputStream->nextRow();
  10202. }
  10203. };
  10204. //==================================================================================
  10205. class CRoxieServerDiskWriteActivity : public CRoxieServerInternalSinkActivity, implements IRoxiePublishCallback
  10206. {
  10207. protected:
  10208. Owned<IExtRowWriter> outSeq;
  10209. Owned<IOutputRowSerializer> rowSerializer;
  10210. Linked<IFileIOStream> diskout;
  10211. bool blockcompressed;
  10212. bool extend;
  10213. bool overwrite;
  10214. bool encrypted;
  10215. bool grouped;
  10216. IHThorDiskWriteArg &helper;
  10217. Owned<IRecordSize> diskmeta;
  10218. Owned<IRoxieWriteHandler> writer;
  10219. bool tallycrc;
  10220. unsigned __int64 uncompressedBytesWritten;
  10221. CRC32 crc;
  10222. void updateWorkUnitResult(unsigned __int64 reccount)
  10223. {
  10224. assertex(writer);
  10225. // MORE - a lot of this is common with hthor
  10226. WorkunitUpdate wu = ctx->updateWorkUnit();
  10227. if (wu)
  10228. {
  10229. OwnedRoxieString rawLogicalName = helper.getFileName();
  10230. StringBuffer lfn; // logical filename
  10231. expandLogicalFilename(lfn, rawLogicalName, wu, false, false);
  10232. if (lfn.length())
  10233. {
  10234. unsigned flags = helper.getFlags();
  10235. WUFileKind fileKind;
  10236. if (TDXtemporary & flags)
  10237. fileKind = WUFileTemporary;
  10238. else if(TDXjobtemp & flags)
  10239. fileKind = WUFileJobOwned;
  10240. else if(TDWowned & flags)
  10241. fileKind = WUFileOwned;
  10242. else
  10243. fileKind = WUFileStandard;
  10244. StringArray clusters;
  10245. writer->getClusters(clusters);
  10246. wu->addFile(lfn.str(), &clusters, helper.getTempUsageCount(), fileKind, NULL);
  10247. if (!(flags & TDXtemporary) && helper.getSequence() >= 0)
  10248. {
  10249. Owned<IWUResult> result = wu->updateResultBySequence(helper.getSequence());
  10250. if (result)
  10251. {
  10252. result->setResultTotalRowCount(reccount);
  10253. result->setResultStatus(ResultStatusCalculated);
  10254. if (helper.getFlags() & TDWresult)
  10255. result->setResultFilename(lfn.str());
  10256. else
  10257. result->setResultLogicalName(lfn.str());
  10258. }
  10259. }
  10260. }
  10261. }
  10262. }
  10263. void resolve()
  10264. {
  10265. OwnedRoxieString rawLogicalName = helper.getFileName();
  10266. assertex(rawLogicalName);
  10267. assertex((helper.getFlags() & TDXtemporary) == 0);
  10268. StringArray clusters;
  10269. unsigned clusterIdx = 0;
  10270. while(true)
  10271. {
  10272. OwnedRoxieString cluster(helper.getCluster(clusterIdx));
  10273. if(!cluster)
  10274. break;
  10275. clusters.append(cluster);
  10276. clusterIdx++;
  10277. }
  10278. if (clusters.length())
  10279. {
  10280. if (extend)
  10281. throw MakeStringException(0, "Cannot combine EXTEND and CLUSTER flags on disk write of file %s", rawLogicalName.get());
  10282. }
  10283. else
  10284. {
  10285. if (roxieName.length())
  10286. clusters.append(roxieName.str());
  10287. else
  10288. clusters.append(".");
  10289. }
  10290. writer.setown(ctx->createLFN(rawLogicalName, overwrite, extend, clusters));
  10291. // MORE - need to check somewhere that single part if it's an existing file or an external one...
  10292. }
  10293. public:
  10294. CRoxieServerDiskWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  10295. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, 0), helper((IHThorDiskWriteArg &) basehelper)
  10296. {
  10297. extend = ((helper.getFlags() & TDWextend) != 0);
  10298. overwrite = ((helper.getFlags() & TDWoverwrite) != 0);
  10299. grouped = (helper.getFlags() & TDXgrouped) != 0;
  10300. diskmeta.set(helper.queryDiskRecordSize()->querySerializedDiskMeta());
  10301. if (grouped)
  10302. diskmeta.setown(createDeltaRecordSize(diskmeta, +1));
  10303. blockcompressed = (((helper.getFlags() & TDWnewcompress) != 0) || (((helper.getFlags() & TDXcompress) != 0) && (diskmeta->getFixedSize() >= MIN_ROWCOMPRESS_RECSIZE))); //always use new compression
  10304. encrypted = false; // set later
  10305. tallycrc = true;
  10306. uncompressedBytesWritten = 0;
  10307. }
  10308. ~CRoxieServerDiskWriteActivity()
  10309. {
  10310. }
  10311. virtual bool needsAllocator() const
  10312. {
  10313. return true;
  10314. }
  10315. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10316. {
  10317. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  10318. resolve();
  10319. Owned<IFileIO> io;
  10320. void *ekey;
  10321. size32_t ekeylen;
  10322. helper.getEncryptKey(ekeylen, ekey);
  10323. Owned<ICompressor> ecomp;
  10324. if (ekeylen!=0)
  10325. {
  10326. ecomp.setown(createAESCompressor256(ekeylen,ekey));
  10327. memset(ekey,0,ekeylen);
  10328. rtlFree(ekey);
  10329. encrypted = true;
  10330. blockcompressed = true;
  10331. }
  10332. if (blockcompressed)
  10333. io.setown(createCompressedFileWriter(writer->queryFile(), (diskmeta->isFixedSize() ? diskmeta->getFixedSize() : 0), extend, true, ecomp));
  10334. else
  10335. io.setown(writer->queryFile()->open(extend ? IFOwrite : IFOcreate));
  10336. if (!io)
  10337. throw MakeStringException(errno, "Failed to create%s file %s for writing", (encrypted ? " encrypted" : (blockcompressed ? " compressed" : "")), writer->queryFile()->queryFilename());
  10338. diskout.setown(createBufferedIOStream(io));
  10339. if (extend)
  10340. diskout->seek(0, IFSend);
  10341. tallycrc = !factory->queryQueryFactory().queryOptions().skipFileFormatCrcCheck && !(helper.getFlags() & TDRnocrccheck) && !blockcompressed;
  10342. Owned<IRowInterfaces> rowIf = createRowInterfaces(input->queryOutputMeta(), activityId, factory->getHeapFlags(), ctx->queryCodeContext());
  10343. rowSerializer.set(rowIf->queryRowSerializer());
  10344. unsigned rwFlags = rw_autoflush;
  10345. if(grouped)
  10346. rwFlags |= rw_grouped;
  10347. if(tallycrc)
  10348. rwFlags |= rw_crc;
  10349. outSeq.setown(createRowWriter(diskout, rowIf, rwFlags));
  10350. }
  10351. virtual void stop()
  10352. {
  10353. if (aborted)
  10354. {
  10355. if (writer)
  10356. writer->finish(false, this);
  10357. }
  10358. else
  10359. {
  10360. if (outSeq)
  10361. outSeq->flush(&crc);
  10362. if (outSeq)
  10363. uncompressedBytesWritten = outSeq->getPosition();
  10364. outSeq.clear();
  10365. diskout.clear(); // Make sure file is properly closed or date may not match published info
  10366. if (writer)
  10367. {
  10368. updateWorkUnitResult(processed);
  10369. writer->finish(true, this);
  10370. }
  10371. }
  10372. writer.clear();
  10373. CRoxieServerActivity::stop();
  10374. }
  10375. virtual void reset()
  10376. {
  10377. CRoxieServerActivity::reset();
  10378. diskout.clear();
  10379. outSeq.clear();
  10380. writer.clear();
  10381. uncompressedBytesWritten = 0;
  10382. crc.reset();
  10383. }
  10384. virtual void onExecute()
  10385. {
  10386. for (;;)
  10387. {
  10388. const void *row = inputStream->nextRow();
  10389. if (!row)
  10390. {
  10391. row = inputStream->nextRow();
  10392. if (!row)
  10393. break;
  10394. if (grouped)
  10395. outSeq->putRow(NULL);
  10396. }
  10397. processed++;
  10398. outSeq->putRow(row);
  10399. }
  10400. }
  10401. virtual void setFileProperties(IFileDescriptor *desc) const
  10402. {
  10403. IPropertyTree &partProps = desc->queryPart(0)->queryProperties(); //properties of the first file part.
  10404. IPropertyTree &fileProps = desc->queryProperties(); // properties of the logical file
  10405. if (blockcompressed)
  10406. {
  10407. // caller has already set @size from file size...
  10408. fileProps.setPropBool("@blockCompressed", true);
  10409. fileProps.setPropInt64("@compressedSize", partProps.getPropInt64("@size", 0));
  10410. partProps.setPropInt64("@compressedSize", partProps.getPropInt64("@size", 0));
  10411. fileProps.setPropInt64("@size", uncompressedBytesWritten);
  10412. partProps.setPropInt64("@size", uncompressedBytesWritten);
  10413. }
  10414. else if (tallycrc && crc.get())
  10415. partProps.setPropInt64("@fileCrc", crc.get());
  10416. if (encrypted)
  10417. fileProps.setPropBool("@encrypted", true);
  10418. fileProps.setPropInt64("@recordCount", processed);
  10419. unsigned flags = helper.getFlags();
  10420. if (flags & TDWpersist)
  10421. fileProps.setPropBool("@persistent", true);
  10422. if (grouped)
  10423. fileProps.setPropBool("@grouped", true);
  10424. if (flags & (TDWowned|TDXjobtemp|TDXtemporary))
  10425. fileProps.setPropBool("@owned", true);
  10426. if (flags & TDWresult)
  10427. fileProps.setPropBool("@result", true);
  10428. IConstWorkUnit *workUnit = ctx->queryWorkUnit();
  10429. if (workUnit)
  10430. {
  10431. fileProps.setProp("@owner", workUnit->queryUser());
  10432. fileProps.setProp("@workunit", workUnit->queryWuid());
  10433. fileProps.setProp("@job", workUnit->queryJobName());
  10434. }
  10435. if (flags & TDWexpires)
  10436. setExpiryTime(fileProps, helper.getExpiryDays());
  10437. if (flags & TDWupdate)
  10438. {
  10439. unsigned eclCRC;
  10440. unsigned __int64 totalCRC;
  10441. helper.getUpdateCRCs(eclCRC, totalCRC);
  10442. fileProps.setPropInt("@eclCRC", eclCRC);
  10443. fileProps.setPropInt64("@totalCRC", totalCRC);
  10444. }
  10445. fileProps.setPropInt("@formatCrc", helper.getFormatCrc());
  10446. IRecordSize * inputMeta = input->queryOutputMeta();
  10447. if ((inputMeta->isFixedSize()) && !isOutputTransformed())
  10448. fileProps.setPropInt("@recordSize", inputMeta->getFixedSize() + (grouped ? 1 : 0));
  10449. const char *recordECL = helper.queryRecordECL();
  10450. if (recordECL && *recordECL)
  10451. fileProps.setProp("ECL", recordECL);
  10452. fileProps.setProp("@kind", "flat"); // default, derivitives may override
  10453. }
  10454. virtual IUserDescriptor *queryUserDescriptor() const
  10455. {
  10456. IConstWorkUnit *workUnit = ctx->queryWorkUnit();
  10457. if (workUnit)
  10458. return workUnit->queryUserDescriptor();
  10459. else
  10460. return NULL;
  10461. }
  10462. virtual bool isOutputTransformed() const { return false; }
  10463. };
  10464. //=================================================================================
  10465. class CRoxieServerCsvWriteActivity : public CRoxieServerDiskWriteActivity
  10466. {
  10467. IHThorCsvWriteArg &csvHelper;
  10468. CSVOutputStream csvOutput;
  10469. public:
  10470. CRoxieServerCsvWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  10471. : CRoxieServerDiskWriteActivity(_ctx, _factory, _probeManager), csvHelper(static_cast<IHThorCsvWriteArg &>(helper))
  10472. {
  10473. csvOutput.init(csvHelper.queryCsvParameters(), false);
  10474. }
  10475. virtual void onExecute()
  10476. {
  10477. OwnedRoxieString header(csvHelper.queryCsvParameters()->getHeader());
  10478. if (header)
  10479. {
  10480. csvOutput.beginLine();
  10481. csvOutput.writeHeaderLn(strlen(header), header);
  10482. diskout->write(csvOutput.length(), csvOutput.str());
  10483. }
  10484. for (;;)
  10485. {
  10486. const void *nextrec = inputStream->ungroupedNextRow();
  10487. if (!nextrec)
  10488. break;
  10489. processed++;
  10490. csvOutput.beginLine();
  10491. csvHelper.writeRow((const byte *)nextrec, &csvOutput);
  10492. csvOutput.endLine();
  10493. diskout->write(csvOutput.length(), csvOutput.str());
  10494. ReleaseRoxieRow(nextrec);
  10495. }
  10496. OwnedRoxieString footer(csvHelper.queryCsvParameters()->getFooter());
  10497. if (footer)
  10498. {
  10499. csvOutput.beginLine();
  10500. csvOutput.writeHeaderLn(strlen(footer), footer);
  10501. diskout->write(csvOutput.length(), csvOutput.str());
  10502. }
  10503. }
  10504. virtual void setFileProperties(IFileDescriptor *desc) const
  10505. {
  10506. CRoxieServerDiskWriteActivity::setFileProperties(desc);
  10507. IPropertyTree &props = desc->queryProperties();
  10508. props.setProp("@format","utf8n");
  10509. ICsvParameters *csvParameters = csvHelper.queryCsvParameters();
  10510. StringBuffer separator;
  10511. OwnedRoxieString rs(csvParameters->getSeparator(0));
  10512. const char *s = rs;
  10513. while (s && *s)
  10514. {
  10515. if (',' == *s)
  10516. separator.append("\\,");
  10517. else
  10518. separator.append(*s);
  10519. ++s;
  10520. }
  10521. props.setProp("@csvSeparate", separator.str());
  10522. props.setProp("@csvQuote", rs.setown(csvParameters->getQuote(0)));
  10523. props.setProp("@csvTerminate", rs.setown(csvParameters->getTerminator(0)));
  10524. props.setProp("@csvEscape", rs.setown(csvParameters->getEscape(0)));
  10525. props.setProp("@kind", "csv");
  10526. }
  10527. virtual bool isOutputTransformed() const { return true; }
  10528. };
  10529. class CRoxieServerXmlWriteActivity : public CRoxieServerDiskWriteActivity
  10530. {
  10531. IHThorXmlWriteArg &xmlHelper;
  10532. StringAttr rowTag;
  10533. ThorActivityKind kind;
  10534. unsigned headerLength;
  10535. unsigned footerLength;
  10536. public:
  10537. CRoxieServerXmlWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, ThorActivityKind _kind)
  10538. : CRoxieServerDiskWriteActivity(_ctx, _factory, _probeManager), xmlHelper(static_cast<IHThorXmlWriteArg &>(helper)), kind(_kind), headerLength(0), footerLength(0)
  10539. {
  10540. }
  10541. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10542. {
  10543. CRoxieServerDiskWriteActivity::start(parentExtractSize, parentExtract, paused);
  10544. OwnedRoxieString xmlpath(xmlHelper.getXmlIteratorPath());
  10545. if (!xmlpath)
  10546. rowTag.set(DEFAULTXMLROWTAG);
  10547. else
  10548. {
  10549. const char *path = xmlpath;
  10550. if (*path == '/') path++;
  10551. if (strchr(path, '/')) UNIMPLEMENTED; // more what do we do with /mydata/row
  10552. rowTag.set(path);
  10553. }
  10554. }
  10555. virtual void onExecute()
  10556. {
  10557. StringBuffer header;
  10558. OwnedRoxieString suppliedHeader(xmlHelper.getHeader());
  10559. if (kind==TAKjsonwrite)
  10560. buildJsonHeader(header, suppliedHeader, rowTag);
  10561. else if (suppliedHeader)
  10562. header.set(suppliedHeader);
  10563. else
  10564. header.append(DEFAULTXMLHEADER).newline();
  10565. headerLength = header.length();
  10566. diskout->write(header.length(), header.str());
  10567. Owned<IXmlWriterExt> writer = createIXmlWriterExt(xmlHelper.getXmlFlags(), 0, NULL, (kind==TAKjsonwrite) ? WTJSON : WTStandard);
  10568. writer->outputBeginArray(rowTag); //need to set this
  10569. writer->clear(); //but not output it
  10570. for (;;)
  10571. {
  10572. OwnedConstRoxieRow nextrec = inputStream->ungroupedNextRow();
  10573. if (!nextrec)
  10574. break;
  10575. processed++;
  10576. writer->clear().outputBeginNested(rowTag, false);
  10577. xmlHelper.toXML((const byte *)nextrec.get(), *writer);
  10578. writer->outputEndNested(rowTag);
  10579. diskout->write(writer->length(), writer->str());
  10580. }
  10581. OwnedRoxieString suppliedFooter(xmlHelper.getFooter());
  10582. StringBuffer footer;
  10583. if (kind==TAKjsonwrite)
  10584. buildJsonFooter(footer.newline(), suppliedFooter, rowTag);
  10585. else if (suppliedFooter)
  10586. footer.append(suppliedFooter);
  10587. else
  10588. footer.append(DEFAULTXMLFOOTER);
  10589. footerLength=footer.length();
  10590. diskout->write(footer.length(), footer);
  10591. }
  10592. virtual void reset()
  10593. {
  10594. CRoxieServerDiskWriteActivity::reset();
  10595. rowTag.clear();
  10596. }
  10597. virtual void setFileProperties(IFileDescriptor *desc) const
  10598. {
  10599. CRoxieServerDiskWriteActivity::setFileProperties(desc);
  10600. desc->queryProperties().setProp("@format","utf8n");
  10601. desc->queryProperties().setProp("@rowTag",rowTag.get());
  10602. desc->queryProperties().setProp("@kind", (kind==TAKjsonwrite) ? "json" : "xml");
  10603. desc->queryProperties().setPropInt(FPheaderLength, headerLength);
  10604. desc->queryProperties().setPropInt(FPfooterLength, footerLength);
  10605. }
  10606. virtual bool isOutputTransformed() const { return true; }
  10607. };
  10608. class CRoxieServerDiskWriteActivityFactory : public CRoxieServerMultiOutputFactory
  10609. {
  10610. bool isRoot;
  10611. bool isTemp;
  10612. public:
  10613. CRoxieServerDiskWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  10614. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  10615. {
  10616. Owned<IHThorDiskWriteArg> helper = (IHThorDiskWriteArg *) helperFactory();
  10617. isTemp = (helper->getFlags() & TDXtemporary) != 0;
  10618. setNumOutputs(helper->getTempUsageCount());
  10619. if (_kind!=TAKdiskwrite)
  10620. assertex(numOutputs == 0);
  10621. }
  10622. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  10623. {
  10624. switch (numOutputs)
  10625. {
  10626. case 0:
  10627. switch (kind)
  10628. {
  10629. case TAKdiskwrite: return new CRoxieServerDiskWriteActivity(_ctx, this, _probeManager);
  10630. case TAKcsvwrite: return new CRoxieServerCsvWriteActivity(_ctx, this, _probeManager);
  10631. case TAKxmlwrite:
  10632. case TAKjsonwrite:
  10633. return new CRoxieServerXmlWriteActivity(_ctx, this, _probeManager, kind);
  10634. };
  10635. throwUnexpected();
  10636. case 1:
  10637. return new CRoxieServerSpillWriteActivity(_ctx, this, _probeManager);
  10638. default:
  10639. return new CRoxieServerThroughSpillActivity(_ctx, this, _probeManager, numOutputs);
  10640. }
  10641. }
  10642. virtual bool isSink() const
  10643. {
  10644. return numOutputs == 0 && !isTemp; // MORE - check with Gavin if this is right if not a temp but reread in same job...
  10645. }
  10646. };
  10647. IRoxieServerActivityFactory *createRoxieServerDiskWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  10648. {
  10649. return new CRoxieServerDiskWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  10650. }
  10651. //=================================================================================
  10652. class CRoxieServerIndexWriteActivity : public CRoxieServerInternalSinkActivity, implements IRoxiePublishCallback
  10653. {
  10654. IHThorIndexWriteArg &helper;
  10655. bool overwrite;
  10656. Owned<ClusterWriteHandler> clusterHandler;
  10657. Owned<IRoxieWriteHandler> writer;
  10658. unsigned __int64 reccount;
  10659. unsigned int fileCrc;
  10660. StringBuffer filename;
  10661. void updateWorkUnitResult()
  10662. {
  10663. // MORE - a lot of this is common with hthor
  10664. WorkunitUpdate wu = ctx->updateWorkUnit();
  10665. if (wu)
  10666. {
  10667. OwnedRoxieString rawLogicalName = helper.getFileName();
  10668. StringBuffer lfn; // logical filename
  10669. expandLogicalFilename(lfn, rawLogicalName, wu, false, false);
  10670. if (lfn.length())
  10671. {
  10672. if (helper.getSequence() >= 0)
  10673. {
  10674. Owned<IWUResult> result = wu->updateResultBySequence(helper.getSequence());
  10675. if (result)
  10676. {
  10677. result->setResultTotalRowCount(reccount);
  10678. result->setResultStatus(ResultStatusCalculated);
  10679. result->setResultLogicalName(lfn.str());
  10680. }
  10681. }
  10682. if(clusterHandler)
  10683. clusterHandler->finish(writer->queryFile());
  10684. CTXLOG("Created roxie index file %s", lfn.str());
  10685. }
  10686. }
  10687. }
  10688. virtual void resolve()
  10689. {
  10690. StringArray clusters;
  10691. unsigned clusterIdx = 0;
  10692. while(true)
  10693. {
  10694. OwnedRoxieString cluster(helper.getCluster(clusterIdx));
  10695. if(!cluster)
  10696. break;
  10697. clusters.append(cluster);
  10698. clusterIdx++;
  10699. }
  10700. if (roxieName.length())
  10701. clusters.append(roxieName.str());
  10702. else
  10703. clusters.append(".");
  10704. OwnedRoxieString fname(helper.getFileName());
  10705. writer.setown(ctx->createLFN(fname, overwrite, false, clusters)); // MORE - if there's a workunit, use if for scope.
  10706. filename.set(writer->queryFile()->queryFilename());
  10707. if (writer->queryFile()->exists())
  10708. {
  10709. if (overwrite)
  10710. {
  10711. CTXLOG("Removing existing %s from DFS",filename.str());
  10712. writer->queryFile()->remove();
  10713. }
  10714. else
  10715. throw MakeStringException(99, "Cannot write index file %s, file already exists (missing OVERWRITE attribute?)", filename.str());
  10716. }
  10717. }
  10718. void buildUserMetadata(Owned<IPropertyTree> & metadata)
  10719. {
  10720. size32_t nameLen;
  10721. char * nameBuff;
  10722. size32_t valueLen;
  10723. char * valueBuff;
  10724. unsigned idx = 0;
  10725. while(helper.getIndexMeta(nameLen, nameBuff, valueLen, valueBuff, idx++))
  10726. {
  10727. StringBuffer name(nameLen, nameBuff);
  10728. StringBuffer value(valueLen, valueBuff);
  10729. if(*nameBuff == '_' && strcmp(name, "_nodeSize") != 0)
  10730. {
  10731. OwnedRoxieString fname(helper.getFileName());
  10732. throw MakeStringException(0, "Invalid name %s in user metadata for index %s (names beginning with underscore are reserved)", name.str(), fname.get());
  10733. }
  10734. if(!validateXMLTag(name.str()))
  10735. {
  10736. OwnedRoxieString fname(helper.getFileName());
  10737. throw MakeStringException(0, "Invalid name %s in user metadata for index %s (not legal XML element name)", name.str(), fname.get());
  10738. }
  10739. if(!metadata)
  10740. metadata.setown(createPTree("metadata", ipt_fast));
  10741. metadata->setProp(name.str(), value.str());
  10742. }
  10743. }
  10744. void buildLayoutMetadata(Owned<IPropertyTree> & metadata)
  10745. {
  10746. if(!metadata)
  10747. metadata.setown(createPTree("metadata", ipt_fast));
  10748. metadata->setProp("_record_ECL", helper.queryRecordECL());
  10749. void * layoutMetaBuff;
  10750. size32_t layoutMetaSize;
  10751. if(helper.getIndexLayout(layoutMetaSize, layoutMetaBuff))
  10752. {
  10753. metadata->setPropBin("_record_layout", layoutMetaSize, layoutMetaBuff);
  10754. rtlFree(layoutMetaBuff);
  10755. }
  10756. }
  10757. public:
  10758. CRoxieServerIndexWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  10759. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, 0), helper(static_cast<IHThorIndexWriteArg &>(basehelper))
  10760. {
  10761. overwrite = ((helper.getFlags() & TIWoverwrite) != 0);
  10762. reccount = 0;
  10763. fileCrc = 0;
  10764. }
  10765. ~CRoxieServerIndexWriteActivity()
  10766. {
  10767. }
  10768. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10769. {
  10770. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  10771. resolve();
  10772. }
  10773. virtual void onExecute()
  10774. {
  10775. bool isVariable = helper.queryDiskRecordSize()->isVariableSize();
  10776. size32_t maxDiskRecordSize;
  10777. if (isVariable)
  10778. {
  10779. if (helper.getFlags() & TIWmaxlength)
  10780. maxDiskRecordSize = helper.getMaxKeySize();
  10781. else
  10782. maxDiskRecordSize = KEYBUILD_MAXLENGTH; // Current default behaviour, could be improved in the future
  10783. }
  10784. else
  10785. maxDiskRecordSize = helper.queryDiskRecordSize()->getFixedSize();
  10786. if (maxDiskRecordSize > KEYBUILD_MAXLENGTH)
  10787. throw MakeStringException(99, "Index maximum record length (%d) exceeds 32k internal limit", maxDiskRecordSize);
  10788. OwnedMalloc<char> rowBuffer(maxDiskRecordSize, true);
  10789. fileCrc = -1;
  10790. {
  10791. Owned<IFileIO> io;
  10792. try
  10793. {
  10794. io.setown(writer->queryFile()->open(IFOcreate));
  10795. }
  10796. catch(IException * e)
  10797. {
  10798. e->Release();
  10799. clearKeyStoreCache(false);
  10800. io.setown(writer->queryFile()->open(IFOcreate));
  10801. }
  10802. if(!io)
  10803. throw MakeStringException(errno, "Failed to create file %s for writing", filename.str());
  10804. Owned<IFileIOStream> out = createIOStream(io);
  10805. unsigned flags = COL_PREFIX | HTREE_FULLSORT_KEY;
  10806. if (helper.getFlags() & TIWrowcompress)
  10807. flags |= HTREE_COMPRESSED_KEY|HTREE_QUICK_COMPRESSED_KEY;
  10808. else if (!(helper.getFlags() & TIWnolzwcompress))
  10809. flags |= HTREE_COMPRESSED_KEY;
  10810. if (isVariable)
  10811. flags |= HTREE_VARSIZE;
  10812. Owned<IPropertyTree> metadata;
  10813. buildUserMetadata(metadata);
  10814. buildLayoutMetadata(metadata);
  10815. unsigned nodeSize = metadata ? metadata->getPropInt("_nodeSize", NODESIZE) : NODESIZE;
  10816. Owned<IKeyBuilder> builder = createKeyBuilder(out, flags, maxDiskRecordSize, nodeSize, helper.getKeyedSize(), 0);
  10817. class BcWrapper : implements IBlobCreator
  10818. {
  10819. IKeyBuilder *builder;
  10820. public:
  10821. BcWrapper(IKeyBuilder *_builder) : builder(_builder) {}
  10822. virtual unsigned __int64 createBlob(size32_t size, const void * ptr)
  10823. {
  10824. return builder->createBlob(size, (const char *) ptr);
  10825. }
  10826. } bc(builder);
  10827. // Loop thru the results
  10828. for (;;)
  10829. {
  10830. OwnedConstRoxieRow nextrec(inputStream->ungroupedNextRow());
  10831. if (!nextrec)
  10832. break;
  10833. try
  10834. {
  10835. unsigned __int64 fpos=0;
  10836. RtlStaticRowBuilder rowBuilder(rowBuffer, maxDiskRecordSize);
  10837. size32_t thisSize = helper.transform(rowBuilder, nextrec, &bc, fpos);
  10838. builder->processKeyData(rowBuffer, fpos, thisSize);
  10839. }
  10840. catch(IException * e)
  10841. {
  10842. throw makeWrappedException(e);
  10843. }
  10844. reccount++;
  10845. }
  10846. if(metadata)
  10847. builder->finish(metadata,&fileCrc);
  10848. else
  10849. builder->finish(&fileCrc);
  10850. }
  10851. }
  10852. virtual void stop()
  10853. {
  10854. if (writer)
  10855. {
  10856. if (!aborted)
  10857. updateWorkUnitResult();
  10858. writer->finish(!aborted, this);
  10859. writer.clear();
  10860. }
  10861. CRoxieServerActivity::stop();
  10862. }
  10863. virtual void reset()
  10864. {
  10865. CRoxieServerActivity::reset();
  10866. writer.clear();
  10867. }
  10868. //interface IRoxiePublishCallback
  10869. virtual void setFileProperties(IFileDescriptor *desc) const
  10870. {
  10871. IPropertyTree &partProps = desc->queryPart(0)->queryProperties(); //properties of the first file part.
  10872. IPropertyTree &fileProps = desc->queryProperties(); // properties of the logical file
  10873. // Now publish to name services
  10874. StringBuffer dir,base;
  10875. offset_t indexFileSize = writer->queryFile()->size();
  10876. if(clusterHandler)
  10877. clusterHandler->splitPhysicalFilename(dir, base);
  10878. else
  10879. splitFilename(filename.str(), &dir, &dir, &base, &base);
  10880. desc->setDefaultDir(dir.str());
  10881. //properties of the first file part.
  10882. Owned<IPropertyTree> attrs;
  10883. if(clusterHandler)
  10884. attrs.setown(createPTree("Part", ipt_fast)); // clusterHandler is going to set attributes
  10885. else
  10886. {
  10887. // add cluster
  10888. StringBuffer mygroupname;
  10889. desc->setNumParts(1);
  10890. desc->setPartMask(base.str());
  10891. attrs.set(&desc->queryPart(0)->queryProperties());
  10892. }
  10893. attrs->setPropInt64("@size", indexFileSize);
  10894. CDateTime createTime, modifiedTime, accessedTime;
  10895. writer->queryFile()->getTime(&createTime, &modifiedTime, &accessedTime);
  10896. // round file time down to nearest sec. Nanosec accurancy is not preserved elsewhere and can lead to mismatch later.
  10897. unsigned hour, min, sec, nanosec;
  10898. modifiedTime.getTime(hour, min, sec, nanosec);
  10899. modifiedTime.setTime(hour, min, sec, 0);
  10900. StringBuffer timestr;
  10901. modifiedTime.getString(timestr);
  10902. if(timestr.length())
  10903. attrs->setProp("@modified", timestr.str());
  10904. if(clusterHandler)
  10905. clusterHandler->setDescriptorParts(desc, base.str(), attrs);
  10906. // properties of the logical file
  10907. IPropertyTree & properties = desc->queryProperties();
  10908. properties.setProp("@kind", "key");
  10909. properties.setPropInt64("@size", indexFileSize);
  10910. properties.setPropInt64("@recordCount", reccount);
  10911. WorkunitUpdate workUnit = ctx->updateWorkUnit();
  10912. if (workUnit)
  10913. {
  10914. properties.setProp("@owner", workUnit->queryUser());
  10915. properties.setProp("@workunit", workUnit->queryWuid());
  10916. properties.setProp("@job", workUnit->queryJobName());
  10917. }
  10918. char const * rececl = helper.queryRecordECL();
  10919. if(rececl && *rececl)
  10920. properties.setProp("ECL", rececl);
  10921. if (helper.getFlags() & TIWexpires)
  10922. setExpiryTime(properties, helper.getExpiryDays());
  10923. if (helper.getFlags() & TIWupdate)
  10924. {
  10925. unsigned eclCRC;
  10926. unsigned __int64 totalCRC;
  10927. helper.getUpdateCRCs(eclCRC, totalCRC);
  10928. properties.setPropInt("@eclCRC", eclCRC);
  10929. properties.setPropInt64("@totalCRC", totalCRC);
  10930. }
  10931. properties.setPropInt("@fileCrc", fileCrc);
  10932. properties.setPropInt("@formatCrc", helper.getFormatCrc());
  10933. void * layoutMetaBuff;
  10934. size32_t layoutMetaSize;
  10935. if(helper.getIndexLayout(layoutMetaSize, layoutMetaBuff))
  10936. {
  10937. properties.setPropBin("_record_layout", layoutMetaSize, layoutMetaBuff);
  10938. rtlFree(layoutMetaBuff);
  10939. }
  10940. }
  10941. IUserDescriptor *queryUserDescriptor() const
  10942. {
  10943. IConstWorkUnit *workUnit = ctx->queryWorkUnit();
  10944. if (workUnit)
  10945. return workUnit->queryUserDescriptor();
  10946. else
  10947. return NULL;
  10948. }
  10949. };
  10950. //=================================================================================
  10951. class CRoxieServerIndexWriteActivityFactory : public CRoxieServerMultiOutputFactory
  10952. {
  10953. public:
  10954. CRoxieServerIndexWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  10955. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  10956. {
  10957. setNumOutputs(0);
  10958. }
  10959. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  10960. {
  10961. return new CRoxieServerIndexWriteActivity(_ctx, this, _probeManager);
  10962. }
  10963. virtual bool isSink() const
  10964. {
  10965. return true;
  10966. }
  10967. };
  10968. IRoxieServerActivityFactory *createRoxieServerIndexWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  10969. {
  10970. return new CRoxieServerIndexWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  10971. }
  10972. //=================================================================================
  10973. static inline void getLimitType(unsigned flags, bool & limitFail, bool & limitOnFail)
  10974. {
  10975. if((flags & JFmatchAbortLimitSkips) != 0)
  10976. {
  10977. limitFail = false;
  10978. limitOnFail = false;
  10979. }
  10980. else
  10981. {
  10982. limitOnFail = ((flags & JFonfail) != 0);
  10983. limitFail = !limitOnFail;
  10984. }
  10985. }
  10986. class CRoxieServerJoinActivity : public CRoxieServerTwoInputActivity
  10987. {
  10988. enum { JSfill, JSfillleft, JSfillright, JScollate, JScompare, JSleftonly, JSrightonly } state;
  10989. IHThorJoinArg &helper;
  10990. ICompare * collate;
  10991. ICompare * collateupper;
  10992. ThorActivityKind activityKind;
  10993. bool leftOuterJoin;
  10994. bool rightOuterJoin;
  10995. bool exclude;
  10996. bool limitFail;
  10997. bool limitOnFail;
  10998. bool forceSpill;
  10999. unsigned keepLimit;
  11000. unsigned joinLimit;
  11001. unsigned atmostLimit;
  11002. unsigned abortLimit;
  11003. unsigned atmostsTriggered;
  11004. bool betweenjoin;
  11005. OwnedRowArray right;
  11006. const void * left;
  11007. const void * pendingRight;
  11008. unsigned rightIndex;
  11009. unsigned joinCounter;
  11010. BoolArray matchedRight;
  11011. bool matchedLeft;
  11012. Owned<IException> failingLimit;
  11013. ConstPointerArray filteredRight;
  11014. Owned<IRHLimitedCompareHelper> limitedhelper;
  11015. OwnedConstRoxieRow defaultLeft;
  11016. OwnedConstRoxieRow defaultRight;
  11017. Owned<IEngineRowAllocator> defaultLeftAllocator;
  11018. Owned<IEngineRowAllocator> defaultRightAllocator;
  11019. Owned<IGroupedInput> sortedLeft;
  11020. Owned<IGroupedInput> groupedSortedRight;
  11021. bool cloneLeft;
  11022. void createDefaultLeft()
  11023. {
  11024. if (!defaultLeft)
  11025. {
  11026. if (!defaultLeftAllocator)
  11027. defaultLeftAllocator.setown(createRowAllocator(input->queryOutputMeta()));
  11028. RtlDynamicRowBuilder rowBuilder(defaultLeftAllocator);
  11029. size32_t thisSize = helper.createDefaultLeft(rowBuilder);
  11030. defaultLeft.setown(rowBuilder.finalizeRowClear(thisSize));
  11031. }
  11032. }
  11033. void createDefaultRight()
  11034. {
  11035. if (!defaultRight)
  11036. {
  11037. if (!defaultRightAllocator)
  11038. defaultRightAllocator.setown(createRowAllocator(input1->queryOutputMeta()));
  11039. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  11040. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  11041. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  11042. }
  11043. }
  11044. public:
  11045. CRoxieServerJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _forceSpill)
  11046. : CRoxieServerTwoInputActivity(_ctx, _factory, _probeManager), helper((IHThorJoinArg &)basehelper), forceSpill(_forceSpill)
  11047. {
  11048. // MORE - some of this should be done in factory
  11049. unsigned joinFlags = helper.getJoinFlags();
  11050. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  11051. rightOuterJoin = (joinFlags & JFrightouter) != 0;
  11052. exclude = (joinFlags & JFexclude) != 0;
  11053. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  11054. getLimitType(joinFlags, limitFail, limitOnFail);
  11055. if (joinFlags & JFslidingmatch)
  11056. {
  11057. betweenjoin = true;
  11058. collate = helper.queryCompareLeftRightLower();
  11059. collateupper = helper.queryCompareLeftRightUpper();
  11060. }
  11061. else
  11062. {
  11063. betweenjoin = false;
  11064. collate = collateupper = helper.queryCompareLeftRight();
  11065. }
  11066. rightIndex = 0;
  11067. joinCounter = 0;
  11068. state = JSfill;
  11069. matchedLeft = false;
  11070. joinLimit = 0;
  11071. keepLimit = 0; // wait until ctx available
  11072. atmostLimit = 0; // wait until ctx available
  11073. abortLimit = 0; // wait until ctx available
  11074. atmostsTriggered = 0;
  11075. assertex((joinFlags & (JFfirst | JFfirstleft | JFfirstright)) == 0);
  11076. left = NULL;
  11077. pendingRight = NULL;
  11078. activityKind = _factory->getKind();
  11079. }
  11080. virtual bool needsAllocator() const { return true; }
  11081. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11082. {
  11083. left = NULL;
  11084. rightIndex = 0;
  11085. joinCounter = 0;
  11086. state = JSfill;
  11087. matchedLeft = false;
  11088. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  11089. keepLimit = helper.getKeepLimit();
  11090. if (keepLimit == 0)
  11091. keepLimit = (unsigned)-1;
  11092. atmostsTriggered = 0;
  11093. atmostLimit = helper.getJoinLimit();
  11094. if(atmostLimit == 0)
  11095. atmostLimit = (unsigned)-1;
  11096. else
  11097. assertex(!rightOuterJoin && !betweenjoin);
  11098. abortLimit = helper.getMatchAbortLimit();
  11099. if (abortLimit == 0)
  11100. abortLimit = (unsigned)-1;
  11101. if (rightOuterJoin)
  11102. createDefaultLeft();
  11103. if ((leftOuterJoin && (activityKind==TAKjoin || activityKind==TAKjoinlight || activityKind==TAKdenormalizegroup)) || limitOnFail)
  11104. createDefaultRight();
  11105. bool isStable = (helper.getJoinFlags() & JFunstable) == 0;
  11106. RoxieSortAlgorithm sortAlgorithm;
  11107. if (forceSpill)
  11108. sortAlgorithm = isStable ? stableSpillingQuickSortAlgorithm : spillingQuickSortAlgorithm;
  11109. else
  11110. sortAlgorithm = isStable ? stableQuickSortAlgorithm : quickSortAlgorithm;
  11111. if (helper.isLeftAlreadySorted())
  11112. sortedLeft.setown(createDegroupedInputReader(inputStream));
  11113. else
  11114. sortedLeft.setown(createSortedInputReader(inputStream, createSortAlgorithm(sortAlgorithm, helper.queryCompareLeft(), ctx->queryRowManager(), input->queryOutputMeta(), ctx->queryCodeContext(), tempDirectory, activityId)));
  11115. ICompare *compareRight = helper.queryCompareRight();
  11116. if (helper.isRightAlreadySorted())
  11117. groupedSortedRight.setown(createGroupedInputReader(inputStream1, compareRight));
  11118. else
  11119. groupedSortedRight.setown(createSortedGroupedInputReader(inputStream1, compareRight, createSortAlgorithm(sortAlgorithm, compareRight, ctx->queryRowManager(), input1->queryOutputMeta(), ctx->queryCodeContext(), tempDirectory, activityId)));
  11120. if ((helper.getJoinFlags() & JFlimitedprefixjoin) && helper.getJoinLimit())
  11121. { //limited match join (s[1..n])
  11122. limitedhelper.setown(createRHLimitedCompareHelper());
  11123. limitedhelper->init( helper.getJoinLimit(), groupedSortedRight, collate, helper.queryPrefixCompare() );
  11124. }
  11125. }
  11126. virtual void reset()
  11127. {
  11128. if (atmostsTriggered)
  11129. noteStatistic(StNumAtmostTriggered, atmostsTriggered);
  11130. right.clear();
  11131. ReleaseClearRoxieRow(left);
  11132. ReleaseClearRoxieRow(pendingRight);
  11133. defaultRight.clear();
  11134. defaultLeft.clear();
  11135. sortedLeft.clear();
  11136. groupedSortedRight.clear();
  11137. CRoxieServerTwoInputActivity::reset();
  11138. }
  11139. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  11140. {
  11141. if (!idx && (helper.getJoinFlags() & JFparallel) != 0)
  11142. {
  11143. puller.setown(new CRoxieServerReadAheadInput(ctx, ctx->queryOptions().parallelJoinPreload));
  11144. puller->setInput(0, _sourceIdx, _in);
  11145. _in = puller;
  11146. _sourceIdx = 0;
  11147. }
  11148. CRoxieServerTwoInputActivity::setInput(idx, _sourceIdx, _in);
  11149. }
  11150. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  11151. {
  11152. if (idx==(unsigned)-1)
  11153. idx = 0;
  11154. return idx ? NULL : this;
  11155. }
  11156. void fillLeft()
  11157. {
  11158. matchedLeft = false;
  11159. left = sortedLeft->nextRow(); // NOTE: already degrouped by the IGroupedInput we attached
  11160. if (betweenjoin && left && pendingRight && (collate->docompare(left, pendingRight) >= 0))
  11161. fillRight();
  11162. if (limitedhelper && 0==rightIndex)
  11163. {
  11164. rightIndex = 0;
  11165. joinCounter = 0;
  11166. right.clear();
  11167. matchedRight.kill();
  11168. if (left)
  11169. {
  11170. limitedhelper->getGroup(right,left);
  11171. ForEachItemIn(idx, right)
  11172. matchedRight.append(false);
  11173. }
  11174. }
  11175. }
  11176. void fillRight()
  11177. {
  11178. if (limitedhelper)
  11179. return;
  11180. failingLimit.clear();
  11181. if(betweenjoin && left)
  11182. {
  11183. aindex_t start = 0;
  11184. while(right.isItem(start) && (collateupper->docompare(left, right.item(start)) > 0))
  11185. start++;
  11186. if(start>0)
  11187. right.clearPart(0, start);
  11188. }
  11189. else
  11190. right.clear();
  11191. rightIndex = 0;
  11192. joinCounter = 0;
  11193. unsigned groupCount = 0;
  11194. const void * next;
  11195. while(true)
  11196. {
  11197. if(pendingRight)
  11198. {
  11199. next = pendingRight;
  11200. pendingRight = NULL;
  11201. }
  11202. else
  11203. {
  11204. next = groupedSortedRight->nextRow();
  11205. }
  11206. if(!rightOuterJoin && next && (!left || (collateupper->docompare(left, next) > 0))) // if right is less than left, and not right outer, can skip group
  11207. {
  11208. while(next)
  11209. {
  11210. ReleaseClearRoxieRow(next);
  11211. next = groupedSortedRight->nextRow();
  11212. }
  11213. continue;
  11214. }
  11215. while(next)
  11216. {
  11217. if(groupCount==abortLimit)
  11218. {
  11219. if(limitFail)
  11220. failLimit();
  11221. if (ctx->queryDebugContext())
  11222. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  11223. if(limitOnFail)
  11224. {
  11225. assertex(!failingLimit);
  11226. try
  11227. {
  11228. failLimit();
  11229. }
  11230. catch(IException * except)
  11231. {
  11232. failingLimit.setown(except);
  11233. }
  11234. assertex(failingLimit != NULL);
  11235. }
  11236. right.append(next);
  11237. do
  11238. {
  11239. next = groupedSortedRight->nextRow();
  11240. ReleaseRoxieRow(next);
  11241. } while(next);
  11242. break;
  11243. }
  11244. else if(groupCount==atmostLimit)
  11245. {
  11246. atmostsTriggered++;
  11247. right.clear();
  11248. groupCount = 0;
  11249. while(next)
  11250. {
  11251. ReleaseRoxieRow(next);
  11252. next = groupedSortedRight->nextRow();
  11253. }
  11254. }
  11255. else
  11256. {
  11257. right.append(next);
  11258. groupCount++;
  11259. }
  11260. next = groupedSortedRight->nextRow();
  11261. }
  11262. // 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
  11263. if(betweenjoin && left)
  11264. {
  11265. pendingRight = groupedSortedRight->nextRow();
  11266. if(!pendingRight || (collate->docompare(left, pendingRight) < 0))
  11267. break;
  11268. }
  11269. else
  11270. break;
  11271. }
  11272. matchedRight.kill();
  11273. ForEachItemIn(idx, right)
  11274. matchedRight.append(false);
  11275. }
  11276. const void * joinRecords(const void * curLeft, const void * curRight, unsigned counter)
  11277. {
  11278. if (cloneLeft)
  11279. {
  11280. LinkRoxieRow(curLeft);
  11281. return curLeft;
  11282. }
  11283. try
  11284. {
  11285. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11286. size32_t thisSize = helper.transform(rowBuilder, curLeft, curRight, counter);
  11287. if (thisSize)
  11288. return rowBuilder.finalizeRowClear(thisSize);
  11289. else
  11290. return NULL;
  11291. }
  11292. catch (IException *E)
  11293. {
  11294. throw makeWrappedException(E);
  11295. }
  11296. }
  11297. const void * denormalizeRecords(const void * curLeft, ConstPointerArray & rows)
  11298. {
  11299. try
  11300. {
  11301. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11302. unsigned numRows = rows.ordinality();
  11303. const void * right = numRows ? rows.item(0) : defaultRight.get();
  11304. size32_t thisSize = helper.transform(rowBuilder, curLeft, right, numRows, (const void * *)rows.getArray());
  11305. if (thisSize)
  11306. return rowBuilder.finalizeRowClear(thisSize);
  11307. else
  11308. return NULL;
  11309. }
  11310. catch (IException *E)
  11311. {
  11312. throw makeWrappedException(E);
  11313. }
  11314. }
  11315. const void * joinException(const void * curLeft, IException * except)
  11316. {
  11317. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11318. size32_t thisSize = helper.onFailTransform(rowBuilder, curLeft, defaultRight, except);
  11319. return rowBuilder.finalizeRowClear(thisSize);
  11320. }
  11321. void failLimit()
  11322. {
  11323. helper.onMatchAbortLimitExceeded();
  11324. CommonXmlWriter xmlwrite(0);
  11325. if (input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  11326. {
  11327. input->queryOutputMeta()->toXML((byte *) left, xmlwrite);
  11328. }
  11329. throw MakeStringException(ROXIE_TOO_MANY_RESULTS, "More than %d match candidates in join %d for row %s", abortLimit, queryId(), xmlwrite.str());
  11330. }
  11331. virtual const void * nextRow()
  11332. {
  11333. ActivityTimer t(totalCycles, timeActivities);
  11334. for (;;)
  11335. {
  11336. switch (state)
  11337. {
  11338. case JSfill:
  11339. fillLeft();
  11340. state = JSfillright;
  11341. break;
  11342. case JSfillright:
  11343. fillRight();
  11344. state = JScollate;
  11345. break;
  11346. case JSfillleft:
  11347. fillLeft();
  11348. state = JScollate;
  11349. break;
  11350. case JScollate:
  11351. if (right.ordinality() == 0)
  11352. {
  11353. if (left == NULL)
  11354. return NULL;
  11355. state = JSleftonly;
  11356. }
  11357. else
  11358. {
  11359. if (!left)
  11360. state = JSrightonly;
  11361. else
  11362. {
  11363. int diff;
  11364. if(betweenjoin)
  11365. diff = ((collate->docompare(left, right.item(0)) < 0) ? -1 : ((collateupper->docompare(left, right.item(right.ordinality()-1)) > 0) ? +1 : 0));
  11366. else
  11367. diff = collate->docompare(left, right.item(0));
  11368. bool limitExceeded = right.ordinality()>abortLimit;
  11369. if (diff == 0)
  11370. {
  11371. if (limitExceeded)
  11372. {
  11373. const void * ret = NULL;
  11374. if(failingLimit)
  11375. ret = joinException(left, failingLimit);
  11376. ReleaseRoxieRow(left);
  11377. left = NULL;
  11378. state = JSfillleft;
  11379. ForEachItemIn(idx, right)
  11380. matchedRight.replace(true, idx);
  11381. if(ret)
  11382. {
  11383. processed++;
  11384. return ret;
  11385. }
  11386. }
  11387. else
  11388. {
  11389. state = JScompare;
  11390. joinLimit = keepLimit;
  11391. }
  11392. }
  11393. else if (diff < 0)
  11394. state = JSleftonly;
  11395. else if (limitExceeded)
  11396. {
  11397. // MORE - Roxie code seems to think there should be a destroyRowset(right) here....
  11398. state = JSfillright;
  11399. }
  11400. else
  11401. state = JSrightonly;
  11402. }
  11403. }
  11404. break;
  11405. case JSrightonly:
  11406. if (rightOuterJoin)
  11407. {
  11408. switch (activityKind)
  11409. {
  11410. case TAKjoin:
  11411. {
  11412. while (right.isItem(rightIndex))
  11413. {
  11414. if (!matchedRight.item(rightIndex))
  11415. {
  11416. const void * rhs = right.item(rightIndex++);
  11417. const void *ret = joinRecords(defaultLeft, rhs, 0);
  11418. if (ret)
  11419. {
  11420. processed++;
  11421. return ret;
  11422. }
  11423. }
  11424. else
  11425. rightIndex++;
  11426. }
  11427. break;
  11428. }
  11429. //Probably excessive to implement the following, but possibly useful
  11430. case TAKdenormalize:
  11431. {
  11432. OwnedConstRoxieRow newLeft;
  11433. newLeft.set(defaultLeft);
  11434. unsigned rowSize = 0;
  11435. unsigned leftCount = 0;
  11436. while (right.isItem(rightIndex))
  11437. {
  11438. if (!matchedRight.item(rightIndex))
  11439. {
  11440. const void * rhs = right.item(rightIndex);
  11441. try
  11442. {
  11443. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11444. unsigned thisSize = helper.transform(rowBuilder, newLeft, rhs, ++leftCount);
  11445. if (thisSize)
  11446. {
  11447. rowSize = thisSize;
  11448. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  11449. }
  11450. }
  11451. catch (IException *E)
  11452. {
  11453. throw makeWrappedException(E);
  11454. }
  11455. }
  11456. rightIndex++;
  11457. }
  11458. state = JSfillright;
  11459. if (rowSize)
  11460. {
  11461. processed++;
  11462. return newLeft.getClear();
  11463. }
  11464. break;
  11465. }
  11466. case TAKdenormalizegroup:
  11467. {
  11468. filteredRight.kill();
  11469. while (right.isItem(rightIndex))
  11470. {
  11471. if (!matchedRight.item(rightIndex))
  11472. filteredRight.append(right.item(rightIndex));
  11473. rightIndex++;
  11474. }
  11475. state = JSfillright;
  11476. if (filteredRight.ordinality())
  11477. {
  11478. const void * ret = denormalizeRecords(defaultLeft, filteredRight);
  11479. filteredRight.kill();
  11480. if (ret)
  11481. {
  11482. processed++;
  11483. return ret;
  11484. }
  11485. }
  11486. break;
  11487. }
  11488. }
  11489. }
  11490. state = JSfillright;
  11491. break;
  11492. case JSleftonly:
  11493. {
  11494. const void * ret = NULL;
  11495. if (!matchedLeft && leftOuterJoin)
  11496. {
  11497. switch (activityKind)
  11498. {
  11499. case TAKjoin:
  11500. ret = joinRecords(left, defaultRight, 0);
  11501. break;
  11502. case TAKdenormalize:
  11503. ret = left;
  11504. left = NULL;
  11505. break;
  11506. case TAKdenormalizegroup:
  11507. filteredRight.kill();
  11508. ret = denormalizeRecords(left, filteredRight);
  11509. break;
  11510. }
  11511. }
  11512. ReleaseRoxieRow(left);
  11513. left = NULL;
  11514. state = JSfillleft;
  11515. if (ret)
  11516. {
  11517. processed++;
  11518. return ret;
  11519. }
  11520. break;
  11521. }
  11522. case JScompare:
  11523. if (joinLimit != 0)
  11524. {
  11525. switch (activityKind)
  11526. {
  11527. case TAKjoin:
  11528. {
  11529. while (right.isItem(rightIndex))
  11530. {
  11531. const void * rhs = right.item(rightIndex++);
  11532. if (helper.match(left, rhs))
  11533. {
  11534. matchedRight.replace(true, rightIndex-1);
  11535. matchedLeft = true;
  11536. if (!exclude)
  11537. {
  11538. const void *ret = joinRecords(left, rhs, ++joinCounter);
  11539. if (ret)
  11540. {
  11541. processed++;
  11542. joinLimit--;
  11543. return ret;
  11544. }
  11545. }
  11546. }
  11547. }
  11548. break;
  11549. }
  11550. case TAKdenormalize:
  11551. {
  11552. OwnedConstRoxieRow newLeft;
  11553. newLeft.set(left);
  11554. unsigned rowSize = 0;
  11555. unsigned leftCount = 0;
  11556. while (right.isItem(rightIndex) && joinLimit)
  11557. {
  11558. try
  11559. {
  11560. const void * rhs = right.item(rightIndex++);
  11561. if (helper.match(left, rhs))
  11562. {
  11563. matchedRight.replace(true, rightIndex-1);
  11564. matchedLeft = true;
  11565. if (!exclude)
  11566. {
  11567. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11568. unsigned thisSize = helper.transform(rowBuilder, newLeft, rhs, ++leftCount);
  11569. if (thisSize)
  11570. {
  11571. rowSize = thisSize;
  11572. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  11573. joinLimit--;
  11574. }
  11575. }
  11576. }
  11577. }
  11578. catch (IException *E)
  11579. {
  11580. throw makeWrappedException(E);
  11581. }
  11582. }
  11583. state = JSleftonly;
  11584. rightIndex = 0;
  11585. if (rowSize)
  11586. {
  11587. processed++;
  11588. return newLeft.getClear();
  11589. }
  11590. break;
  11591. }
  11592. case TAKdenormalizegroup:
  11593. {
  11594. filteredRight.kill();
  11595. while (right.isItem(rightIndex))
  11596. {
  11597. const void * rhs = right.item(rightIndex++);
  11598. if (helper.match(left, rhs))
  11599. {
  11600. matchedRight.replace(true, rightIndex-1);
  11601. filteredRight.append(rhs);
  11602. matchedLeft = true;
  11603. if (filteredRight.ordinality()==joinLimit)
  11604. break;
  11605. }
  11606. }
  11607. state = JSleftonly;
  11608. rightIndex = 0;
  11609. if (!exclude && filteredRight.ordinality())
  11610. {
  11611. const void * ret = denormalizeRecords(left, filteredRight);
  11612. filteredRight.kill();
  11613. if (ret)
  11614. {
  11615. processed++;
  11616. return ret;
  11617. }
  11618. }
  11619. break;
  11620. }
  11621. }
  11622. }
  11623. state = JSleftonly;
  11624. rightIndex = 0;
  11625. joinCounter = 0;
  11626. break;
  11627. }
  11628. }
  11629. }
  11630. };
  11631. class CRoxieServerJoinActivityFactory : public CRoxieServerActivityFactory
  11632. {
  11633. unsigned input2;
  11634. unsigned input2idx;
  11635. bool forceSpill;
  11636. public:
  11637. CRoxieServerJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  11638. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  11639. {
  11640. forceSpill = _graphNode.getPropBool("hint[@name='spill']/@value", _queryFactory.queryOptions().allSortsMaySpill);
  11641. input2 = 0;
  11642. input2idx = 0;
  11643. }
  11644. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  11645. {
  11646. return new CRoxieServerJoinActivity(_ctx, this, _probeManager, forceSpill);
  11647. }
  11648. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  11649. {
  11650. if (idx==1)
  11651. {
  11652. input2 = source;
  11653. input2idx = sourceidx;
  11654. }
  11655. else
  11656. CRoxieServerActivityFactory::setInput(idx, source, sourceidx);
  11657. }
  11658. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  11659. {
  11660. switch (idx)
  11661. {
  11662. case 1:
  11663. sourceidx = input2idx;
  11664. return input2;
  11665. case 0:
  11666. return CRoxieServerActivityFactory::getInput(idx, sourceidx);
  11667. default:
  11668. return (unsigned) -1;
  11669. }
  11670. }
  11671. virtual unsigned numInputs() const { return 2; }
  11672. virtual const StatisticsMapping &queryStatsMapping() const
  11673. {
  11674. return joinStatistics;
  11675. }
  11676. };
  11677. IRoxieServerActivityFactory *createRoxieServerJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  11678. {
  11679. return new CRoxieServerJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  11680. }
  11681. //=================================================================================
  11682. #define CONCAT_READAHEAD 1000
  11683. class CRoxieThreadedConcatReader : implements IRecordPullerCallback, public CInterface
  11684. {
  11685. public:
  11686. IMPLEMENT_IINTERFACE;
  11687. CRoxieThreadedConcatReader(InterruptableSemaphore &_ready, bool _grouped)
  11688. : puller(false), grouped(_grouped), atEog(true), ready(_ready), eof(false)
  11689. {
  11690. }
  11691. void start(unsigned parentExtractSize, const byte *parentExtract, bool paused, IRoxieSlaveContext *ctx)
  11692. {
  11693. space.reinit(CONCAT_READAHEAD);
  11694. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().concatPreload, false, ctx);
  11695. }
  11696. void stop()
  11697. {
  11698. space.interrupt();
  11699. puller.stop();
  11700. }
  11701. IFinalRoxieInput *queryInput() const
  11702. {
  11703. return puller.queryInput();
  11704. }
  11705. void reset()
  11706. {
  11707. puller.reset();
  11708. ForEachItemIn(idx, buffer)
  11709. ReleaseRoxieRow(buffer.item(idx));
  11710. buffer.clear();
  11711. eof = false;
  11712. atEog = true;
  11713. }
  11714. void setInput(unsigned _sourceIdx, IFinalRoxieInput *_in)
  11715. {
  11716. puller.setInput(this, _sourceIdx, _in);
  11717. }
  11718. void connectInputStreams(IRoxieSlaveContext *ctx, bool consumerOrdered)
  11719. {
  11720. puller.connectInputStreams(ctx, consumerOrdered);
  11721. }
  11722. virtual void processRow(const void *row)
  11723. {
  11724. buffer.enqueue(row);
  11725. ready.signal();
  11726. space.wait();
  11727. }
  11728. virtual void processGroup(const ConstPointerArray &rows)
  11729. {
  11730. // We use record-by-record input mode of the puller thread even in grouped mode.
  11731. throwUnexpected();
  11732. }
  11733. virtual void processEOG()
  11734. {
  11735. if (grouped)
  11736. processRow(NULL);
  11737. }
  11738. virtual void processDone()
  11739. {
  11740. processRow(NULL);
  11741. }
  11742. virtual bool fireException(IException *e)
  11743. {
  11744. // called from puller thread on failure
  11745. ready.interrupt(LINK(e));
  11746. space.interrupt(e);
  11747. return true;
  11748. }
  11749. bool peek(const void * &row, bool &anyActive)
  11750. {
  11751. if (!eof)
  11752. {
  11753. if (buffer.ordinality())
  11754. {
  11755. space.signal();
  11756. row = buffer.dequeue();
  11757. if (row==NULL)
  11758. {
  11759. if (atEog)
  11760. {
  11761. eof = true;
  11762. return false;
  11763. }
  11764. else
  11765. atEog = true;
  11766. }
  11767. else if (grouped)
  11768. atEog = false;
  11769. return true;
  11770. }
  11771. anyActive = true;
  11772. }
  11773. return false;
  11774. }
  11775. protected:
  11776. RecordPullerThread puller;
  11777. InterruptableSemaphore space;
  11778. InterruptableSemaphore &ready;
  11779. SafeQueueOf<const void, true> buffer;
  11780. bool atEog;
  11781. bool eof;
  11782. bool grouped;
  11783. };
  11784. typedef CopyReferenceArrayOf<CRoxieThreadedConcatReader> ReaderArray;
  11785. class CRoxieServerThreadedConcatActivity : public CRoxieServerActivity
  11786. {
  11787. InterruptableSemaphore ready;
  11788. ReaderArray pullers;
  11789. unsigned numInputs;
  11790. unsigned nextPuller; // for round robin
  11791. unsigned readyPending;
  11792. bool eof;
  11793. bool inGroup;
  11794. bool grouped;
  11795. public:
  11796. CRoxieServerThreadedConcatActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _grouped, unsigned _numInputs)
  11797. : CRoxieServerActivity(_ctx, _factory, _probeManager), grouped(_grouped)
  11798. {
  11799. numInputs = _numInputs;
  11800. eof = (numInputs==0);
  11801. inGroup = false;
  11802. nextPuller = 0;
  11803. readyPending = 0;
  11804. for (unsigned i = 0; i < numInputs; i++)
  11805. pullers.append(*new CRoxieThreadedConcatReader(ready, _grouped));
  11806. }
  11807. ~CRoxieServerThreadedConcatActivity()
  11808. {
  11809. ForEachItemIn(idx, pullers)
  11810. delete &pullers.item(idx);
  11811. }
  11812. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11813. {
  11814. eof = (numInputs==0);
  11815. inGroup = false;
  11816. nextPuller = 0;
  11817. readyPending = 0;
  11818. ready.reinit();
  11819. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  11820. ForEachItemIn(idx, pullers)
  11821. {
  11822. pullers.item(idx).start(parentExtractSize, parentExtract, paused, ctx);
  11823. // NOTE - it is ok to start the thread running while parts of the subgraph are still being started, since everything
  11824. // in the part of the subgraph that the thread uses has been started.
  11825. // Note that splitters are supposed to cope with being used when only some outputs have been started.
  11826. }
  11827. }
  11828. virtual void stop()
  11829. {
  11830. ready.interrupt();
  11831. ForEachItemIn(idx, pullers)
  11832. pullers.item(idx).stop();
  11833. CRoxieServerActivity::stop();
  11834. }
  11835. virtual unsigned __int64 queryLocalCycles() const
  11836. {
  11837. return 0;
  11838. }
  11839. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  11840. {
  11841. if (pullers.isItem(idx))
  11842. return pullers.item(idx).queryInput();
  11843. else
  11844. return NULL;
  11845. }
  11846. virtual void reset()
  11847. {
  11848. CRoxieServerActivity::reset();
  11849. ForEachItemIn(idx, pullers)
  11850. pullers.item(idx).reset();
  11851. eof = false;
  11852. inGroup = false;
  11853. nextPuller = 0;
  11854. readyPending = 0;
  11855. }
  11856. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  11857. {
  11858. if (pullers.isItem(idx))
  11859. pullers.item(idx).setInput(_sourceIdx, _in);
  11860. else
  11861. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
  11862. }
  11863. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  11864. {
  11865. ForEachItemIn(i, pullers)
  11866. pullers.item(i).connectInputStreams(ctx, consumerOrdered);
  11867. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, nullptr, consumerOrdered, nullptr); // No input actually connected
  11868. }
  11869. virtual const void * nextRow()
  11870. {
  11871. ActivityTimer t(totalCycles, timeActivities);
  11872. if (eof)
  11873. return NULL;
  11874. for (;;)
  11875. {
  11876. if (readyPending && !inGroup)
  11877. {
  11878. if (readyPending > 1)
  11879. ready.signal(readyPending-1);
  11880. readyPending = 0;
  11881. }
  11882. else
  11883. ready.wait();
  11884. bool anyActive = false;
  11885. ForEachItemIn(unused_index, pullers)
  11886. {
  11887. // NOTE - we round robin not just because it's more efficient, but because it ensures the preservation of grouping information
  11888. const void *ret;
  11889. bool fetched = pullers.item(nextPuller).peek(ret, anyActive);
  11890. if (fetched)
  11891. {
  11892. inGroup = (ret != NULL);
  11893. return ret;
  11894. }
  11895. if (inGroup && grouped)
  11896. {
  11897. // Some other puller has data, but we can't consume it until the group we are reading is complete.
  11898. readyPending++;
  11899. anyActive = true;
  11900. break;
  11901. }
  11902. nextPuller++;
  11903. if (nextPuller==pullers.ordinality())
  11904. nextPuller = 0;
  11905. }
  11906. if (!anyActive)
  11907. break;
  11908. // A ready signal without anything being ready means someone reached end-of-file.
  11909. }
  11910. eof = true;
  11911. return NULL;
  11912. }
  11913. };
  11914. class CRoxieServerOrderedConcatActivity : public CRoxieServerMultiInputActivity
  11915. {
  11916. IEngineRowStream *curStream;
  11917. bool eogSeen;
  11918. bool anyThisGroup;
  11919. bool grouped;
  11920. unsigned streamIdx;
  11921. public:
  11922. CRoxieServerOrderedConcatActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _grouped, unsigned _numInputs)
  11923. : CRoxieServerMultiInputActivity(_ctx, _factory, _probeManager, _numInputs)
  11924. {
  11925. eogSeen = false;
  11926. anyThisGroup = false;
  11927. grouped = _grouped;
  11928. streamIdx = 0;
  11929. curStream = NULL;
  11930. }
  11931. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11932. {
  11933. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  11934. streamIdx = 0;
  11935. curStream = streamArray[streamIdx];
  11936. eogSeen = false;
  11937. anyThisGroup = false;
  11938. }
  11939. virtual const void * nextRow()
  11940. {
  11941. ActivityTimer t(totalCycles, timeActivities);
  11942. if (!curStream)
  11943. return NULL; // eof
  11944. const void * next = curStream->nextRow();
  11945. if (next)
  11946. {
  11947. anyThisGroup = true;
  11948. eogSeen = false;
  11949. processed++;
  11950. return next;
  11951. }
  11952. else if (!eogSeen)
  11953. {
  11954. eogSeen = true;
  11955. if (grouped)
  11956. {
  11957. if (anyThisGroup)
  11958. {
  11959. anyThisGroup = false;
  11960. return NULL;
  11961. }
  11962. else
  11963. return nextRow();
  11964. }
  11965. else
  11966. return nextRow();
  11967. }
  11968. else if (streamIdx < numStreams-1)
  11969. {
  11970. streamIdx++;
  11971. curStream = streamArray[streamIdx];
  11972. eogSeen = false;
  11973. return nextRow();
  11974. }
  11975. else
  11976. {
  11977. curStream = NULL;
  11978. return NULL;
  11979. }
  11980. }
  11981. };
  11982. class CRoxieServerConcatActivityFactory : public CRoxieServerMultiInputFactory
  11983. {
  11984. bool ordered;
  11985. bool grouped;
  11986. public:
  11987. CRoxieServerConcatActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  11988. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  11989. {
  11990. Owned <IHThorFunnelArg> helper = (IHThorFunnelArg *) helperFactory();
  11991. ordered = helper->isOrdered();
  11992. grouped = helper->queryOutputMeta()->isGrouped();
  11993. }
  11994. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  11995. {
  11996. if (ordered || (_probeManager && _probeManager->queryDebugManager()))
  11997. return new CRoxieServerOrderedConcatActivity(_ctx, this, _probeManager, grouped, numInputs());
  11998. else
  11999. return new CRoxieServerThreadedConcatActivity(_ctx, this, _probeManager, grouped, numInputs());
  12000. }
  12001. };
  12002. IRoxieServerActivityFactory *createRoxieServerConcatActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12003. {
  12004. return new CRoxieServerConcatActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12005. }
  12006. //=================================================================================
  12007. class CRoxieServerNonEmptyActivity : public CRoxieServerMultiInputBaseActivity
  12008. {
  12009. IEngineRowStream* selectedStream;
  12010. unsigned savedParentExtractSize;
  12011. const byte * savedParentExtract;
  12012. bool foundInput;
  12013. bool unusedStopped;
  12014. public:
  12015. CRoxieServerNonEmptyActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  12016. : CRoxieServerMultiInputBaseActivity(_ctx, _factory, _probeManager, _numInputs)
  12017. {
  12018. foundInput = false;
  12019. unusedStopped = false;
  12020. selectedStream = NULL;
  12021. savedParentExtractSize = 0;;
  12022. savedParentExtract = NULL;
  12023. }
  12024. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12025. {
  12026. //Don't start the inputs yet so we can short-circuit...
  12027. CRoxieServerMultiInputBaseActivity::start(parentExtractSize, parentExtract, paused);
  12028. savedParentExtractSize = parentExtractSize;
  12029. savedParentExtract = parentExtract;
  12030. }
  12031. virtual void stop()
  12032. {
  12033. if (unusedStopped)
  12034. {
  12035. if (selectedStream)
  12036. selectedStream->stop();
  12037. }
  12038. else
  12039. {
  12040. //May possibly call stop too many times if input->start() throws an exception (e.g. due to a dependency)
  12041. for (unsigned i = 0; i < numStreams; i++)
  12042. streamArray[i]->stop();
  12043. }
  12044. CRoxieServerMultiInputBaseActivity::stop();
  12045. }
  12046. virtual void reset()
  12047. {
  12048. CRoxieServerMultiInputBaseActivity::reset();
  12049. foundInput = false;
  12050. unusedStopped = false;
  12051. selectedStream = NULL;
  12052. }
  12053. virtual unsigned __int64 queryLocalCycles() const
  12054. {
  12055. return 0; // Can't easily calculate anything reliable but local processing is negligible
  12056. }
  12057. virtual const void * nextRow()
  12058. {
  12059. ActivityTimer t(totalCycles, timeActivities);
  12060. if (!foundInput)
  12061. {
  12062. foundInput = true;
  12063. assertex(numInputs == numStreams); // If this ceases to be true we will need to rethink some of this
  12064. //If we get an exception in this loop then stop() will stop any started inputs
  12065. for (unsigned i=0; i < numStreams; i++)
  12066. {
  12067. selectedStream = streamArray[i];
  12068. inputArray[i]->start(savedParentExtractSize, savedParentExtract, false); // Assumes 1:1 mapping streams to inputs
  12069. startJunction(junctionArray[i]);
  12070. const void * next = selectedStream->nextRow();
  12071. if (next)
  12072. {
  12073. //Found a row so stop remaining
  12074. for (unsigned j=i+1; j < numInputs; j++)
  12075. streamArray[j]->stop();
  12076. unusedStopped = true;
  12077. processed++;
  12078. return next;
  12079. }
  12080. selectedStream->stop();
  12081. }
  12082. unusedStopped = true;
  12083. selectedStream = NULL;
  12084. return NULL;
  12085. }
  12086. if (!selectedStream)
  12087. return NULL;
  12088. const void * next = selectedStream->nextRow();
  12089. if (next)
  12090. processed++;
  12091. return next;
  12092. }
  12093. };
  12094. class CRoxieServerNonEmptyActivityFactory : public CRoxieServerMultiInputFactory
  12095. {
  12096. public:
  12097. CRoxieServerNonEmptyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12098. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12099. {
  12100. }
  12101. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12102. {
  12103. return new CRoxieServerNonEmptyActivity(_ctx, this, _probeManager, numInputs());
  12104. }
  12105. };
  12106. IRoxieServerActivityFactory *createRoxieServerNonEmptyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12107. {
  12108. return new CRoxieServerNonEmptyActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12109. }
  12110. //=================================================================================
  12111. class CRoxieServerMergeActivity : public CRoxieServerMultiInputActivity
  12112. {
  12113. IHThorMergeArg &helper;
  12114. unsigned *mergeheap;
  12115. unsigned activeInputs;
  12116. const void **pending;
  12117. bool first;
  12118. ICompare *compare;
  12119. bool dedup;
  12120. void permute()
  12121. {
  12122. assertex(activeInputs == 0);
  12123. for(unsigned i = 0; i < numStreams; i++)
  12124. if(pullInput(i))
  12125. mergeheap[activeInputs++] = i;
  12126. // the tree structure: element p has children p*2+1 and p*2+2, or element c has parent (unsigned)(c-1)/2
  12127. // the heap property: no element should be smaller than its parent
  12128. // the dedup variant: if(dedup), the top of the heap should also not be equal to either child
  12129. // 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
  12130. if (activeInputs >= 2)
  12131. for(unsigned p = (activeInputs-2)/2; p > 0; --p)
  12132. siftDown(p);
  12133. if(dedup)
  12134. siftDownDedupTop();
  12135. else
  12136. siftDown(0);
  12137. }
  12138. void readNext()
  12139. {
  12140. if(!pullInput(mergeheap[0]))
  12141. if(!promote(0))
  12142. return;
  12143. // we have changed the element at the top of the heap, so need to sift it down to maintain the heap property
  12144. if(dedup)
  12145. siftDownDedupTop();
  12146. else
  12147. siftDown(0);
  12148. }
  12149. bool pullInput(unsigned i)
  12150. {
  12151. const void *next = streamArray[i]->ungroupedNextRow();
  12152. pending[i] = next;
  12153. return (next != NULL);
  12154. }
  12155. bool promote(unsigned p)
  12156. {
  12157. activeInputs--;
  12158. if(activeInputs == p)
  12159. return false;
  12160. mergeheap[p] = mergeheap[activeInputs];
  12161. return true;
  12162. }
  12163. bool siftDown(unsigned p)
  12164. {
  12165. // assuming that all descendants of p form a heap, sift p down to its correct position, and so include it in the heap
  12166. bool nochange = true;
  12167. while(1)
  12168. {
  12169. unsigned c = p*2 + 1;
  12170. if(c >= activeInputs)
  12171. return nochange;
  12172. if(c+1 < activeInputs)
  12173. {
  12174. int childcmp = BuffCompare(c+1, c);
  12175. if((childcmp < 0) || ((childcmp == 0) && (mergeheap[c+1] < mergeheap[c])))
  12176. ++c;
  12177. }
  12178. int cmp = BuffCompare(c, p);
  12179. if((cmp > 0) || ((cmp == 0) && (mergeheap[c] > mergeheap[p])))
  12180. return nochange;
  12181. nochange = false;
  12182. unsigned r = mergeheap[c];
  12183. mergeheap[c] = mergeheap[p];
  12184. mergeheap[p] = r;
  12185. p = c;
  12186. }
  12187. }
  12188. void siftDownDedupTop()
  12189. {
  12190. // same as siftDown(0), except that it also ensures that the top of the heap is not equal to either of its children
  12191. if(activeInputs < 2)
  12192. return;
  12193. unsigned c = 1;
  12194. int childcmp = 1;
  12195. if(activeInputs >= 3)
  12196. {
  12197. childcmp = BuffCompare(2, 1);
  12198. if(childcmp < 0)
  12199. c = 2;
  12200. }
  12201. int cmp = BuffCompare(c, 0);
  12202. if(cmp > 0)
  12203. return;
  12204. // the following loop ensures the correct property holds on the smaller branch, and that childcmp==0 iff the top matches the other branch
  12205. while(cmp <= 0)
  12206. {
  12207. if(cmp == 0)
  12208. {
  12209. if(mergeheap[c] < mergeheap[0])
  12210. {
  12211. unsigned r = mergeheap[c];
  12212. mergeheap[c] = mergeheap[0];
  12213. mergeheap[0] = r;
  12214. }
  12215. ReleaseClearRoxieRow(pending[mergeheap[c]]);
  12216. if(!pullInput(mergeheap[c]))
  12217. if(!promote(c))
  12218. break;
  12219. siftDown(c);
  12220. }
  12221. else
  12222. {
  12223. unsigned r = mergeheap[c];
  12224. mergeheap[c] = mergeheap[0];
  12225. mergeheap[0] = r;
  12226. if(siftDown(c))
  12227. break;
  12228. }
  12229. cmp = BuffCompare(c, 0);
  12230. }
  12231. // the following loop ensures the uniqueness property holds on the other branch too
  12232. c = 3-c;
  12233. if(activeInputs <= c)
  12234. return;
  12235. while(childcmp == 0)
  12236. {
  12237. if(mergeheap[c] < mergeheap[0])
  12238. {
  12239. unsigned r = mergeheap[c];
  12240. mergeheap[c] = mergeheap[0];
  12241. mergeheap[0] = r;
  12242. }
  12243. ReleaseClearRoxieRow(pending[mergeheap[c]]);
  12244. if(!pullInput(mergeheap[c]))
  12245. if(!promote(c))
  12246. break;
  12247. siftDown(c);
  12248. childcmp = BuffCompare(c, 0);
  12249. }
  12250. }
  12251. inline int BuffCompare(unsigned a, unsigned b)
  12252. {
  12253. return compare->docompare(pending[mergeheap[a]], pending[mergeheap[b]]);
  12254. }
  12255. public:
  12256. CRoxieServerMergeActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  12257. : CRoxieServerMultiInputActivity(_ctx, _factory, _probeManager, _numInputs), helper((IHThorMergeArg &)basehelper)
  12258. {
  12259. activeInputs = 0;
  12260. first = true;
  12261. mergeheap = new unsigned[numInputs];
  12262. pending = new const void *[numStreams];
  12263. compare = helper.queryCompare();
  12264. dedup = helper.dedup();
  12265. for (unsigned i = 0; i < numStreams; i++)
  12266. pending[i] = NULL;
  12267. }
  12268. ~CRoxieServerMergeActivity()
  12269. {
  12270. delete [] mergeheap;
  12271. delete [] pending;
  12272. }
  12273. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12274. {
  12275. activeInputs = 0;
  12276. first = true;
  12277. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  12278. }
  12279. virtual void reset()
  12280. {
  12281. for (unsigned i = 0; i < numStreams; i++)
  12282. ReleaseClearRoxieRow(pending[i]);
  12283. CRoxieServerMultiInputActivity::reset();
  12284. }
  12285. virtual const void * nextRow()
  12286. {
  12287. ActivityTimer t(totalCycles, timeActivities);
  12288. if (first)
  12289. {
  12290. permute();
  12291. first = false;
  12292. }
  12293. if (activeInputs)
  12294. {
  12295. const void *next = pending[mergeheap[0]];
  12296. readNext();
  12297. if (next)
  12298. processed++;
  12299. return next;
  12300. }
  12301. else
  12302. return NULL;
  12303. }
  12304. };
  12305. class CRoxieServerMergeActivityFactory : public CRoxieServerMultiInputFactory
  12306. {
  12307. public:
  12308. CRoxieServerMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12309. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12310. {
  12311. }
  12312. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12313. {
  12314. return new CRoxieServerMergeActivity(_ctx, this, _probeManager, numInputs());
  12315. }
  12316. };
  12317. IRoxieServerActivityFactory *createRoxieServerMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12318. {
  12319. return new CRoxieServerMergeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12320. }
  12321. //=================================================================================
  12322. class CRoxieServerRegroupActivity : public CRoxieServerMultiInputActivity
  12323. {
  12324. IHThorRegroupArg &helper;
  12325. unsigned streamIndex;
  12326. bool eof;
  12327. unsigned __int64 numProcessedLastGroup;
  12328. public:
  12329. CRoxieServerRegroupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  12330. : CRoxieServerMultiInputActivity(_ctx, _factory, _probeManager, _numInputs), helper((IHThorRegroupArg &)basehelper)
  12331. {
  12332. streamIndex = 0;
  12333. eof = false;
  12334. numProcessedLastGroup = 0;
  12335. }
  12336. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12337. {
  12338. streamIndex = 0;
  12339. eof = false;
  12340. numProcessedLastGroup = processed;
  12341. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  12342. }
  12343. const void * nextFromInputs()
  12344. {
  12345. unsigned initialStream = streamIndex;
  12346. while (streamIndex < numStreams)
  12347. {
  12348. const void * next = streamArray[streamIndex]->nextRow();
  12349. if (next)
  12350. {
  12351. if ((streamIndex != initialStream) && (streamIndex != initialStream+1))
  12352. {
  12353. ReleaseRoxieRow(next);
  12354. throw MakeStringException(ROXIE_MISMATCH_GROUP_ERROR, "Mismatched groups supplied to Regroup (%d)", factory->queryId());
  12355. }
  12356. return next;
  12357. }
  12358. streamIndex++;
  12359. }
  12360. if ((initialStream != 0) && (initialStream+1 != numStreams))
  12361. throw MakeStringException(ROXIE_MISMATCH_GROUP_ERROR, "Mismatched groups supplied to Regroup (%d)", factory->queryId());
  12362. streamIndex = 0;
  12363. return NULL;
  12364. }
  12365. virtual const void * nextRow()
  12366. {
  12367. ActivityTimer t(totalCycles, timeActivities);
  12368. if (eof)
  12369. return NULL;
  12370. const void * ret = nextFromInputs();
  12371. if (ret)
  12372. {
  12373. processed++;
  12374. return ret;
  12375. }
  12376. if (numProcessedLastGroup != processed)
  12377. {
  12378. numProcessedLastGroup = processed;
  12379. return NULL;
  12380. }
  12381. eof = true;
  12382. return NULL;
  12383. }
  12384. };
  12385. class CRoxieServerRegroupActivityFactory : public CRoxieServerMultiInputFactory
  12386. {
  12387. public:
  12388. CRoxieServerRegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12389. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12390. {
  12391. }
  12392. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12393. {
  12394. return new CRoxieServerRegroupActivity(_ctx, this, _probeManager, numInputs());
  12395. }
  12396. };
  12397. IRoxieServerActivityFactory *createRoxieServerRegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12398. {
  12399. return new CRoxieServerRegroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12400. }
  12401. //=================================================================================
  12402. class CRoxieServerCombineActivity : public CRoxieServerMultiInputActivity
  12403. {
  12404. IHThorCombineArg &helper;
  12405. unsigned __int64 numProcessedLastGroup;
  12406. public:
  12407. CRoxieServerCombineActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  12408. : CRoxieServerMultiInputActivity(_ctx, _factory, _probeManager, _numInputs), helper((IHThorCombineArg &)basehelper)
  12409. {
  12410. numProcessedLastGroup = 0;
  12411. }
  12412. ~CRoxieServerCombineActivity()
  12413. {
  12414. }
  12415. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12416. {
  12417. numProcessedLastGroup = processed;
  12418. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  12419. }
  12420. void nextInputs(ConstPointerArray & out)
  12421. {
  12422. for (unsigned i=0; i < numStreams; i++)
  12423. {
  12424. const void * next = streamArray[i]->nextRow();
  12425. if (next)
  12426. out.append(next);
  12427. }
  12428. }
  12429. virtual bool needsAllocator() const { return true; }
  12430. virtual const void * nextRow()
  12431. {
  12432. ActivityTimer t(totalCycles, timeActivities);
  12433. for (;;)
  12434. {
  12435. ConstPointerArray group;
  12436. nextInputs(group);
  12437. if ((group.ordinality() == 0) && (numProcessedLastGroup == processed))
  12438. nextInputs(group);
  12439. if (group.ordinality() == 0)
  12440. {
  12441. numProcessedLastGroup = processed;
  12442. return NULL;
  12443. }
  12444. else if (group.ordinality() != numInputs)
  12445. {
  12446. ReleaseRoxieRows(group);
  12447. throw MakeStringException(ROXIE_MISMATCH_GROUP_ERROR, "Mismatched group input for Combine Activity(%d)", factory->queryId());
  12448. }
  12449. try
  12450. {
  12451. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12452. size32_t outSize = helper.transform(rowBuilder, group.ordinality(), group.getArray());
  12453. ReleaseRoxieRows(group);
  12454. if (outSize)
  12455. {
  12456. processed++;
  12457. return rowBuilder.finalizeRowClear(outSize);
  12458. }
  12459. }
  12460. catch (IException *E)
  12461. {
  12462. ReleaseRoxieRows(group);
  12463. throw makeWrappedException(E);
  12464. }
  12465. }
  12466. }
  12467. };
  12468. class CRoxieServerCombineActivityFactory : public CRoxieServerMultiInputFactory
  12469. {
  12470. public:
  12471. CRoxieServerCombineActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12472. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12473. {
  12474. }
  12475. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12476. {
  12477. return new CRoxieServerCombineActivity(_ctx, this, _probeManager, numInputs());
  12478. }
  12479. };
  12480. IRoxieServerActivityFactory *createRoxieServerCombineActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12481. {
  12482. return new CRoxieServerCombineActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12483. }
  12484. //=================================================================================
  12485. class CRoxieServerCombineGroupActivity : public CRoxieServerTwoInputActivity
  12486. {
  12487. IHThorCombineGroupArg &helper;
  12488. unsigned __int64 numProcessedLastGroup;
  12489. public:
  12490. CRoxieServerCombineGroupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  12491. : CRoxieServerTwoInputActivity(_ctx, _factory, _probeManager), helper((IHThorCombineGroupArg &)basehelper)
  12492. {
  12493. numProcessedLastGroup = 0;
  12494. }
  12495. ~CRoxieServerCombineGroupActivity()
  12496. {
  12497. }
  12498. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12499. {
  12500. numProcessedLastGroup = processed;
  12501. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  12502. }
  12503. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  12504. {
  12505. if (idx==(unsigned)-1)
  12506. idx = 0;
  12507. return idx ? NULL : this;
  12508. }
  12509. virtual bool needsAllocator() const { return true; }
  12510. virtual const void * nextRow()
  12511. {
  12512. ActivityTimer t(totalCycles, timeActivities);
  12513. for (;;)
  12514. {
  12515. const void * left = inputStream->nextRow();
  12516. if (!left && (numProcessedLastGroup == processed))
  12517. left = inputStream->nextRow();
  12518. if (!left)
  12519. {
  12520. if (numProcessedLastGroup == processed)
  12521. {
  12522. const void * nextRight = inputStream1->nextRow();
  12523. if (nextRight)
  12524. {
  12525. ReleaseRoxieRow(nextRight);
  12526. throw MakeStringException(ROXIE_MISSING_GROUP_ERROR, "Missing LEFT record for Combine Group (%d)", factory->queryId());
  12527. }
  12528. }
  12529. else
  12530. numProcessedLastGroup = processed;
  12531. return NULL;
  12532. }
  12533. ConstPointerArray group;
  12534. for (;;)
  12535. {
  12536. const void * in = inputStream1->nextRow();
  12537. if (!in)
  12538. break;
  12539. group.append(in);
  12540. }
  12541. if (group.ordinality() == 0)
  12542. {
  12543. ReleaseRoxieRow(left);
  12544. ReleaseRoxieRows(group);
  12545. throw MakeStringException(ROXIE_MISSING_GROUP_ERROR, "Missing RIGHT group for Combine Group (%d)", factory->queryId());
  12546. }
  12547. try
  12548. {
  12549. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12550. size32_t outSize = helper.transform(rowBuilder, left, group.ordinality(), (const void * *)group.getArray());
  12551. ReleaseRoxieRow(left);
  12552. ReleaseRoxieRows(group);
  12553. if (outSize)
  12554. {
  12555. processed++;
  12556. return rowBuilder.finalizeRowClear(outSize);
  12557. }
  12558. }
  12559. catch (IException *E)
  12560. {
  12561. ReleaseRoxieRow(left);
  12562. ReleaseRoxieRows(group);
  12563. throw makeWrappedException(E);
  12564. }
  12565. }
  12566. }
  12567. };
  12568. class CRoxieServerCombineGroupActivityFactory : public CRoxieServerActivityFactory
  12569. {
  12570. unsigned input2;
  12571. unsigned input2idx;
  12572. public:
  12573. CRoxieServerCombineGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12574. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12575. {
  12576. input2 = 0;
  12577. input2idx = 0;
  12578. }
  12579. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12580. {
  12581. return new CRoxieServerCombineGroupActivity(_ctx, this, _probeManager);
  12582. }
  12583. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  12584. {
  12585. if (idx==1)
  12586. {
  12587. input2 = source;
  12588. input2idx = sourceidx;
  12589. }
  12590. else
  12591. CRoxieServerActivityFactory::setInput(idx, source, sourceidx);
  12592. }
  12593. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  12594. {
  12595. switch (idx)
  12596. {
  12597. case 1:
  12598. sourceidx = input2idx;
  12599. return input2;
  12600. case 0:
  12601. return CRoxieServerActivityFactory::getInput(idx, sourceidx);
  12602. default:
  12603. return (unsigned) -1;
  12604. }
  12605. }
  12606. virtual unsigned numInputs() const { return 2; }
  12607. };
  12608. IRoxieServerActivityFactory *createRoxieServerCombineGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12609. {
  12610. return new CRoxieServerCombineGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12611. }
  12612. //=================================================================================
  12613. class CRoxieServerRollupGroupActivity : public CRoxieServerActivity
  12614. {
  12615. IHThorRollupGroupArg &helper;
  12616. bool eof;
  12617. public:
  12618. CRoxieServerRollupGroupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  12619. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  12620. helper((IHThorRollupGroupArg &)basehelper)
  12621. {
  12622. eof = false;
  12623. }
  12624. ~CRoxieServerRollupGroupActivity()
  12625. {
  12626. }
  12627. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12628. {
  12629. eof = false;
  12630. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  12631. }
  12632. virtual bool needsAllocator() const { return true; }
  12633. virtual const void * nextRow()
  12634. {
  12635. ActivityTimer t(totalCycles, timeActivities);
  12636. if (eof)
  12637. return NULL;
  12638. for (;;)
  12639. {
  12640. ConstPointerArray group;
  12641. for (;;)
  12642. {
  12643. const void * in = inputStream->nextRow();
  12644. if (!in)
  12645. break;
  12646. group.append(in);
  12647. }
  12648. if (group.ordinality() == 0)
  12649. {
  12650. eof = true;
  12651. return NULL;
  12652. }
  12653. try
  12654. {
  12655. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12656. size32_t outSize = helper.transform(rowBuilder, group.ordinality(), (const void * *)group.getArray());
  12657. ReleaseRoxieRows(group);
  12658. if (outSize)
  12659. {
  12660. processed++;
  12661. return rowBuilder.finalizeRowClear(outSize);
  12662. }
  12663. }
  12664. catch (IException * E)
  12665. {
  12666. ReleaseRoxieRows(group);
  12667. throw makeWrappedException(E);
  12668. }
  12669. }
  12670. }
  12671. };
  12672. class CRoxieServerRollupGroupActivityFactory : public CRoxieServerActivityFactory
  12673. {
  12674. public:
  12675. CRoxieServerRollupGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12676. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12677. {
  12678. }
  12679. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12680. {
  12681. return new CRoxieServerRollupGroupActivity(_ctx, this, _probeManager);
  12682. }
  12683. };
  12684. IRoxieServerActivityFactory *createRoxieServerRollupGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12685. {
  12686. return new CRoxieServerRollupGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12687. }
  12688. //=================================================================================
  12689. class CRoxieServerFilterProjectActivity : public CRoxieServerLateStartActivity
  12690. {
  12691. IHThorFilterProjectArg &helper;
  12692. unsigned numProcessedLastGroup;
  12693. unsigned __int64 recordCount;
  12694. public:
  12695. CRoxieServerFilterProjectActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  12696. : CRoxieServerLateStartActivity(_ctx, _factory, _probeManager), helper((IHThorFilterProjectArg &)basehelper)
  12697. {
  12698. numProcessedLastGroup = 0;
  12699. recordCount = 0;
  12700. }
  12701. ~CRoxieServerFilterProjectActivity()
  12702. {
  12703. }
  12704. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12705. {
  12706. numProcessedLastGroup = 0;
  12707. recordCount = 0;
  12708. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  12709. lateStart(parentExtractSize, parentExtract, helper.canMatchAny()); //sets eof
  12710. }
  12711. virtual bool needsAllocator() const { return true; }
  12712. virtual const void * nextRow()
  12713. {
  12714. ActivityTimer t(totalCycles, timeActivities);
  12715. if (eof)
  12716. return NULL;
  12717. for (;;)
  12718. {
  12719. const void * in = inputStream->nextRow();
  12720. if (!in)
  12721. {
  12722. recordCount = 0;
  12723. if (numProcessedLastGroup == processed)
  12724. in = inputStream->nextRow();
  12725. if (!in)
  12726. {
  12727. numProcessedLastGroup = processed;
  12728. return NULL;
  12729. }
  12730. }
  12731. try
  12732. {
  12733. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12734. size32_t outSize = helper.transform(rowBuilder, in, ++recordCount);
  12735. ReleaseRoxieRow(in);
  12736. if (outSize)
  12737. {
  12738. processed++;
  12739. return rowBuilder.finalizeRowClear(outSize);
  12740. }
  12741. }
  12742. catch (IException *E)
  12743. {
  12744. throw makeWrappedException(E);
  12745. }
  12746. }
  12747. }
  12748. };
  12749. class CRoxieServerFilterProjectActivityFactory : public CRoxieServerActivityFactory
  12750. {
  12751. public:
  12752. CRoxieServerFilterProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12753. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12754. {
  12755. //MORE: Code generator needs to indicate if the count is used.
  12756. //optStableInput = false;
  12757. }
  12758. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12759. {
  12760. return new CRoxieServerFilterProjectActivity(_ctx, this, _probeManager);
  12761. }
  12762. };
  12763. IRoxieServerActivityFactory *createRoxieServerFilterProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12764. {
  12765. return new CRoxieServerFilterProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12766. }
  12767. //=====================================================
  12768. class CRoxieServerStrandedProjectActivity : public CRoxieServerStrandedActivity
  12769. {
  12770. class ProjectProcessor : public StrandProcessor
  12771. {
  12772. protected:
  12773. IHThorProjectArg &helper;
  12774. public:
  12775. ProjectProcessor(CRoxieServerActivity &_parent, IEngineRowStream *_inputStream, IHThorProjectArg &_helper)
  12776. : StrandProcessor(_parent, _inputStream, true), helper(_helper)
  12777. {
  12778. }
  12779. virtual const void * nextRow()
  12780. {
  12781. ActivityTimer t(totalCycles, timeActivities);
  12782. for (;;)
  12783. {
  12784. OwnedConstRoxieRow in = inputStream->nextRow();
  12785. if (!in)
  12786. {
  12787. if (numProcessedLastGroup == processed)
  12788. in.setown(inputStream->nextRow());
  12789. if (!in)
  12790. {
  12791. numProcessedLastGroup = processed;
  12792. return NULL;
  12793. }
  12794. }
  12795. try
  12796. {
  12797. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12798. size32_t outSize;
  12799. outSize = helper.transform(rowBuilder, in);
  12800. if (outSize)
  12801. {
  12802. processed++;
  12803. return rowBuilder.finalizeRowClear(outSize);
  12804. }
  12805. }
  12806. catch (IException *E)
  12807. {
  12808. throw parent.makeWrappedException(E);
  12809. }
  12810. }
  12811. }
  12812. };
  12813. public:
  12814. CRoxieServerStrandedProjectActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const StrandOptions &_strandOptions)
  12815. : CRoxieServerStrandedActivity(_ctx, _factory, _probeManager, _strandOptions)
  12816. {
  12817. }
  12818. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12819. {
  12820. CRoxieServerStrandedActivity::start(parentExtractSize, parentExtract, paused);
  12821. onStartStrands();
  12822. }
  12823. virtual StrandProcessor *createStrandProcessor(IEngineRowStream *instream)
  12824. {
  12825. return new ProjectProcessor(*this, instream, (IHThorProjectArg &) basehelper);
  12826. }
  12827. virtual StrandProcessor *createStrandSourceProcessor(bool inputOrdered) { throwUnexpected(); }
  12828. };
  12829. class CRoxieServerProjectActivity : public CRoxieServerActivity
  12830. {
  12831. unsigned numProcessedLastGroup;
  12832. unsigned __int64 recordCount;
  12833. bool count;
  12834. public:
  12835. CRoxieServerProjectActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _count)
  12836. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  12837. count(_count)
  12838. {
  12839. numProcessedLastGroup = 0;
  12840. recordCount = 0;
  12841. }
  12842. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12843. {
  12844. numProcessedLastGroup = 0;
  12845. recordCount = 0;
  12846. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  12847. }
  12848. virtual bool needsAllocator() const { return true; }
  12849. virtual const void * nextRow()
  12850. {
  12851. ActivityTimer t(totalCycles, timeActivities);
  12852. for (;;)
  12853. {
  12854. OwnedConstRoxieRow in = inputStream->nextRow();
  12855. if (!in)
  12856. {
  12857. recordCount = 0;
  12858. if (numProcessedLastGroup == processed)
  12859. in.setown(inputStream->nextRow());
  12860. if (!in)
  12861. {
  12862. numProcessedLastGroup = processed;
  12863. return NULL;
  12864. }
  12865. }
  12866. try
  12867. {
  12868. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12869. size32_t outSize;
  12870. if (count)
  12871. outSize = ((IHThorCountProjectArg &) basehelper).transform(rowBuilder, in, ++recordCount);
  12872. else
  12873. outSize = ((IHThorProjectArg &) basehelper).transform(rowBuilder, in);
  12874. if (outSize)
  12875. {
  12876. processed++;
  12877. return rowBuilder.finalizeRowClear(outSize);
  12878. }
  12879. }
  12880. catch (IException *E)
  12881. {
  12882. throw makeWrappedException(E);
  12883. }
  12884. }
  12885. }
  12886. };
  12887. class CRoxieServerProjectActivityFactory : public CRoxieServerActivityFactory
  12888. {
  12889. protected:
  12890. StrandOptions strandOptions;
  12891. bool count;
  12892. public:
  12893. CRoxieServerProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12894. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), strandOptions(_graphNode)
  12895. {
  12896. count = (kind==TAKcountproject || kind==TAKprefetchcountproject);
  12897. optStableInput = count;
  12898. }
  12899. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12900. {
  12901. // NOTE - if they explicitly requested numStrands = 1 via hint, we could use either of the below. For now use the stranded version to ensure it is tested.
  12902. if (kind == TAKproject) // Not supported on prefetch or count projects
  12903. return new CRoxieServerStrandedProjectActivity(_ctx, this, _probeManager, strandOptions);
  12904. else
  12905. return new CRoxieServerProjectActivity(_ctx, this, _probeManager, count);
  12906. }
  12907. };
  12908. IRoxieServerActivityFactory *createRoxieServerProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12909. {
  12910. return new CRoxieServerProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12911. }
  12912. //=================================================================================
  12913. class CRoxieServerPrefetchProjectActivity : public CRoxieServerActivity, implements IRecordPullerCallback
  12914. {
  12915. unsigned numProcessedLastGroup;
  12916. bool count;
  12917. bool eof;
  12918. bool allPulled;
  12919. bool isThreaded;
  12920. unsigned preload;
  12921. unsigned __int64 recordCount;
  12922. IHThorPrefetchProjectArg &helper;
  12923. RecordPullerThread puller;
  12924. InterruptableSemaphore ready;
  12925. InterruptableSemaphore space;
  12926. class PrefetchInfo : public CInterface
  12927. {
  12928. public:
  12929. inline PrefetchInfo(IHThorPrefetchProjectArg &helper, const void *_in, unsigned __int64 _recordCount)
  12930. {
  12931. if (helper.preTransform(extract, _in, _recordCount))
  12932. {
  12933. in.setown(_in);
  12934. recordCount = _recordCount;
  12935. }
  12936. else
  12937. {
  12938. ReleaseRoxieRow(_in);
  12939. recordCount = 0;
  12940. }
  12941. }
  12942. OwnedConstRoxieRow in;
  12943. unsigned __int64 recordCount;
  12944. rtlRowBuilder extract;
  12945. };
  12946. QueueOf<PrefetchInfo, true> pulled;
  12947. CriticalSection pulledCrit;
  12948. public:
  12949. CRoxieServerPrefetchProjectActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _count)
  12950. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  12951. helper((IHThorPrefetchProjectArg &) basehelper),
  12952. puller(false),
  12953. count(_count)
  12954. {
  12955. numProcessedLastGroup = 0;
  12956. recordCount = 0;
  12957. eof = false;
  12958. allPulled = false;
  12959. isThreaded = (helper.getFlags() & PPFparallel) != 0;
  12960. preload = 0;
  12961. }
  12962. ~CRoxieServerPrefetchProjectActivity()
  12963. {
  12964. while (pulled.ordinality())
  12965. ::Release(pulled.dequeue());
  12966. }
  12967. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  12968. {
  12969. if (idx)
  12970. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
  12971. puller.setInput(this, _sourceIdx, _in);
  12972. }
  12973. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  12974. {
  12975. puller.connectInputStreams(ctx, consumerOrdered);
  12976. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
  12977. }
  12978. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  12979. {
  12980. if (idx==0)
  12981. return puller.queryInput();
  12982. else
  12983. return NULL;
  12984. }
  12985. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12986. {
  12987. numProcessedLastGroup = 0;
  12988. recordCount = 0;
  12989. eof = false;
  12990. allPulled = false;
  12991. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  12992. preload = helper.getLookahead();
  12993. if (!preload)
  12994. preload = ctx->queryOptions().prefetchProjectPreload;
  12995. space.reinit(preload);
  12996. ready.reinit();
  12997. puller.start(parentExtractSize, parentExtract, paused, preload, !isThreaded, ctx);
  12998. }
  12999. virtual void stop()
  13000. {
  13001. space.interrupt();
  13002. ready.interrupt();
  13003. CRoxieServerActivity::stop();
  13004. puller.stop();
  13005. }
  13006. virtual void reset()
  13007. {
  13008. CRoxieServerActivity::reset();
  13009. puller.reset();
  13010. allPulled = false;
  13011. while (pulled.ordinality())
  13012. ::Release(pulled.dequeue());
  13013. }
  13014. virtual PrefetchInfo *readNextRecord()
  13015. {
  13016. if (!isThreaded)
  13017. {
  13018. if (!allPulled) // This looks like it's thread unsafe but we are inside the if(!isThreaded) so should be ok
  13019. puller.pullRecords(1);
  13020. }
  13021. else
  13022. ready.wait();
  13023. CriticalBlock b(pulledCrit);
  13024. PrefetchInfo *ret = pulled.ordinality() ? pulled.dequeue() : NULL;
  13025. space.signal();
  13026. return ret;
  13027. }
  13028. virtual bool needsAllocator() const { return true; }
  13029. virtual const void * nextRow()
  13030. {
  13031. ActivityTimer t(totalCycles, timeActivities);
  13032. if (eof)
  13033. return NULL;
  13034. for (;;)
  13035. {
  13036. Owned<PrefetchInfo> in = readNextRecord();
  13037. if (!in)
  13038. {
  13039. recordCount = 0;
  13040. if (numProcessedLastGroup == processed)
  13041. in.setown(readNextRecord());
  13042. if (!in)
  13043. {
  13044. numProcessedLastGroup = processed;
  13045. eof = true;
  13046. return NULL;
  13047. }
  13048. }
  13049. try
  13050. {
  13051. if (in->in)
  13052. {
  13053. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  13054. size32_t outSize;
  13055. IThorChildGraph *child = helper.queryChild();
  13056. Owned<IEclGraphResults> results;
  13057. if (child)
  13058. results.setown(child->evaluate(in->extract.size(), in->extract.getbytes()));
  13059. outSize = helper.transform(rowBuilder, in->in, results, in->recordCount);
  13060. if (outSize)
  13061. {
  13062. processed++;
  13063. return rowBuilder.finalizeRowClear(outSize);
  13064. }
  13065. }
  13066. }
  13067. catch (IException *E)
  13068. {
  13069. throw makeWrappedException(E);
  13070. }
  13071. }
  13072. }
  13073. // interface IExceptionHandler
  13074. virtual bool fireException(IException *e)
  13075. {
  13076. // called from puller thread on failure
  13077. ready.interrupt(LINK(e));
  13078. space.interrupt(e);
  13079. return true;
  13080. }
  13081. // interface IRecordPullerCallback
  13082. virtual void processRow(const void *row)
  13083. {
  13084. {
  13085. CriticalBlock b(pulledCrit);
  13086. pulled.enqueue(new PrefetchInfo(helper, row, ++recordCount));
  13087. }
  13088. if (isThreaded)
  13089. {
  13090. ready.signal();
  13091. space.wait();
  13092. }
  13093. }
  13094. virtual void processEOG()
  13095. {
  13096. {
  13097. CriticalBlock b(pulledCrit);
  13098. pulled.enqueue(NULL);
  13099. }
  13100. if (isThreaded)
  13101. {
  13102. ready.signal();
  13103. space.wait();
  13104. }
  13105. }
  13106. virtual void processGroup(const ConstPointerArray &rows)
  13107. {
  13108. throwUnexpected();
  13109. }
  13110. virtual void processDone()
  13111. {
  13112. CriticalBlock b(pulledCrit);
  13113. allPulled = true;
  13114. if (isThreaded)
  13115. ready.signal();
  13116. }
  13117. };
  13118. class CRoxieServerPrefetchProjectActivityFactory : public CRoxieServerProjectActivityFactory
  13119. {
  13120. public:
  13121. CRoxieServerPrefetchProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  13122. : CRoxieServerProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  13123. {
  13124. }
  13125. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  13126. {
  13127. return new CRoxieServerPrefetchProjectActivity(_ctx, this, _probeManager, count);
  13128. }
  13129. };
  13130. extern IRoxieServerActivityFactory *createRoxieServerPrefetchProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  13131. {
  13132. return new CRoxieServerPrefetchProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  13133. }
  13134. //=================================================================================
  13135. class CPointerArrayRoxieInput : public CPseudoRoxieInput
  13136. {
  13137. public:
  13138. CPointerArrayRoxieInput()
  13139. {
  13140. rowset = NULL;
  13141. rowcount = 0;
  13142. curRow = 0;
  13143. }
  13144. void init(size32_t _rowcount, byte **_rowset)
  13145. {
  13146. rowset = _rowset;
  13147. rowcount = _rowcount;
  13148. curRow = 0;
  13149. }
  13150. virtual const void * nextRow()
  13151. {
  13152. if (curRow < rowcount)
  13153. {
  13154. const void * ret = rowset[curRow];
  13155. if (ret)
  13156. LinkRoxieRow(ret);
  13157. curRow++;
  13158. return ret;
  13159. }
  13160. return NULL;
  13161. }
  13162. protected:
  13163. byte **rowset;
  13164. size32_t rowcount;
  13165. size32_t curRow;
  13166. };
  13167. class CRoxieServerLoopActivity : public CRoxieServerActivity
  13168. {
  13169. protected:
  13170. IHThorLoopArg &helper;
  13171. ThorActivityKind activityKind;
  13172. unsigned maxIterations;
  13173. bool finishedLooping;
  13174. unsigned flags;
  13175. bool eof;
  13176. rtlRowBuilder loopExtractBuilder;
  13177. unsigned loopGraphId;
  13178. Linked<IOutputMetaData> counterMeta;
  13179. public:
  13180. CRoxieServerLoopActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _loopGraphId, IOutputMetaData * _counterMeta)
  13181. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  13182. helper((IHThorLoopArg &)basehelper), loopGraphId(_loopGraphId), counterMeta(_counterMeta)
  13183. {
  13184. eof = false;
  13185. finishedLooping = false;
  13186. activityKind = factory->getKind();
  13187. flags = helper.getFlags();
  13188. maxIterations = 0;
  13189. }
  13190. virtual bool needsAllocator() const { return true; }
  13191. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13192. {
  13193. eof = false;
  13194. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  13195. int iterations = (int) helper.numIterations();
  13196. maxIterations = (iterations >= 0) ? iterations : 0;
  13197. finishedLooping = ((activityKind == TAKloopcount) && (maxIterations == 0));
  13198. if ((flags & IHThorLoopArg::LFnewloopagain) && !helper.loopFirstTime())
  13199. finishedLooping = true;
  13200. loopExtractBuilder.clear();
  13201. helper.createParentExtract(loopExtractBuilder); // could possibly delay this until execution actually happens
  13202. }
  13203. virtual void stop()
  13204. {
  13205. CRoxieServerActivity::stop();
  13206. loopExtractBuilder.clear();
  13207. }
  13208. void createCounterResult(IRoxieServerChildGraph * graph, unsigned counter)
  13209. {
  13210. if (flags & IHThorLoopArg::LFcounter)
  13211. {
  13212. void * counterRow = ctx->queryRowManager().allocate(sizeof(thor_loop_counter_t), activityId);
  13213. *((thor_loop_counter_t *)counterRow) = counter;
  13214. RtlLinkedDatasetBuilder builder(rowAllocator);
  13215. builder.appendOwn(counterRow);
  13216. Owned<CGraphResult> counterResult = new CGraphResult(builder.getcount(), builder.linkrows());
  13217. graph->setInputResult(2, counterResult);
  13218. }
  13219. }
  13220. };
  13221. //=================================================================================
  13222. class CRoxieServerSequentialLoopActivity : public CRoxieServerLoopActivity
  13223. {
  13224. Owned<IActivityGraph> loopQuery;
  13225. Owned<IRoxieServerChildGraph> loopGraph;
  13226. IEngineRowStream * curStream;
  13227. RtlLinkedDatasetBuilder *loopInputBuilder;
  13228. CPointerArrayRoxieInput arrayInput;
  13229. Linked<IEngineRowStream> resultStream;
  13230. unsigned loopCounter;
  13231. public:
  13232. CRoxieServerSequentialLoopActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _loopGraphId, IOutputMetaData * _counterMeta)
  13233. : CRoxieServerLoopActivity(_ctx, _factory, _probeManager, _loopGraphId, _counterMeta)
  13234. {
  13235. curStream = NULL;
  13236. loopCounter = 0;
  13237. loopInputBuilder = NULL;
  13238. }
  13239. virtual bool needsAllocator() const { return true; }
  13240. virtual void onCreate(IHThorArg *_colocalParent)
  13241. {
  13242. CRoxieServerLoopActivity::onCreate(_colocalParent);
  13243. loopQuery.set(ctx->queryChildGraph(loopGraphId));
  13244. }
  13245. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13246. {
  13247. curStream = inputStream;
  13248. loopCounter = 1;
  13249. CRoxieServerLoopActivity::start(parentExtractSize, parentExtract, paused);
  13250. //MORE: Not sure about this, should IRoxieServerChildGraph be combined with IActivityGraph?
  13251. loopGraph.set(loopQuery->queryLoopGraph());
  13252. loopInputBuilder = new RtlLinkedDatasetBuilder(rowAllocator);
  13253. }
  13254. virtual void stop()
  13255. {
  13256. delete loopInputBuilder;
  13257. loopInputBuilder = NULL;
  13258. CRoxieServerLoopActivity::stop();
  13259. }
  13260. virtual const void * nextRow()
  13261. {
  13262. ActivityTimer t(totalCycles, timeActivities);
  13263. if (eof)
  13264. return NULL;
  13265. unsigned emptyIterations = 0;
  13266. for (;;)
  13267. {
  13268. for (;;)
  13269. {
  13270. const void * ret = curStream->nextRow();
  13271. if (!ret)
  13272. {
  13273. ret = curStream->nextRow(); // more cope with groups somehow....
  13274. if (!ret)
  13275. {
  13276. if (finishedLooping)
  13277. {
  13278. eof = true;
  13279. return NULL;
  13280. }
  13281. break;
  13282. }
  13283. }
  13284. if (finishedLooping ||
  13285. ((flags & IHThorLoopArg::LFfiltered) && !helper.sendToLoop(loopCounter, ret)))
  13286. {
  13287. processed++;
  13288. return ret;
  13289. }
  13290. loopInputBuilder->appendOwn(ret);
  13291. }
  13292. switch (activityKind)
  13293. {
  13294. case TAKloopdataset:
  13295. {
  13296. if (!(flags & IHThorLoopArg::LFnewloopagain))
  13297. {
  13298. if (!helper.loopAgain(loopCounter, loopInputBuilder->getcount(), (const void**) loopInputBuilder->queryrows()))
  13299. {
  13300. if (loopInputBuilder->getcount() == 0)
  13301. {
  13302. eof = true;
  13303. return NULL;
  13304. }
  13305. arrayInput.init(loopInputBuilder->getcount(), loopInputBuilder->linkrows());
  13306. // MORE - should builder be cleared here?
  13307. curStream = &arrayInput;
  13308. finishedLooping = true;
  13309. continue; // back to the input loop again
  13310. }
  13311. }
  13312. break;
  13313. }
  13314. case TAKlooprow:
  13315. if (!loopInputBuilder->getcount())
  13316. {
  13317. finishedLooping = true;
  13318. eof = true;
  13319. return NULL;
  13320. }
  13321. break;
  13322. }
  13323. if (loopInputBuilder->getcount())
  13324. emptyIterations = 0;
  13325. else
  13326. {
  13327. //note: any outputs which didn't go around the loop again, would return the record, reinitializing emptyIterations
  13328. emptyIterations++;
  13329. if (emptyIterations > maxEmptyLoopIterations)
  13330. throw MakeStringException(ROXIE_TOO_MANY_EMPTY_LOOP, "Executed LOOP with empty input and output %u times", emptyIterations);
  13331. if (emptyIterations % 32 == 0)
  13332. CTXLOG("Executing LOOP with empty input and output %u times", emptyIterations);
  13333. }
  13334. checkAbort();
  13335. try
  13336. {
  13337. Owned<IRoxieGraphResults> results = executeIteration(loopExtractBuilder.size(), loopExtractBuilder.getbytes(), loopCounter);
  13338. resultStream.setown(results->createIterator(0));
  13339. if (flags & IHThorLoopArg::LFnewloopagain)
  13340. {
  13341. Owned<IEngineRowStream> againResult = results->createIterator(helper.loopAgainResult());
  13342. OwnedConstRoxieRow row = againResult->nextRow();
  13343. assertex(row);
  13344. //Result is a row which contains a single boolean field.
  13345. if (!((const bool *)row.get())[0])
  13346. finishedLooping = true;
  13347. }
  13348. }
  13349. catch (IException *E)
  13350. {
  13351. throw makeWrappedException(E);
  13352. }
  13353. curStream = resultStream.get();
  13354. loopCounter++;
  13355. if ((activityKind == TAKloopcount) && (loopCounter > maxIterations))
  13356. finishedLooping = true;
  13357. }
  13358. }
  13359. IRoxieGraphResults * executeIteration(unsigned parentExtractSize, const byte *parentExtract, unsigned counter)
  13360. {
  13361. try
  13362. {
  13363. loopGraph->beforeExecute();
  13364. Owned<IGraphResult> inputRowsResult = new CGraphResult(loopInputBuilder->getcount(), loopInputBuilder->linkrows());
  13365. loopInputBuilder->clear();
  13366. loopGraph->setInputResult(1, inputRowsResult);
  13367. createCounterResult(loopGraph, counter);
  13368. Owned<IRoxieGraphResults> ret = loopGraph->execute(parentExtractSize, parentExtract);
  13369. loopGraph->afterExecute();
  13370. return ret.getClear();
  13371. }
  13372. catch (...)
  13373. {
  13374. CTXLOG("Exception thrown in loop body - cleaning up");
  13375. loopGraph->afterExecute();
  13376. throw;
  13377. }
  13378. }
  13379. };
  13380. //=================================================================================
  13381. typedef SafeQueueOf<const void, true> SafeRowQueue;
  13382. class CRowQueuePseudoInput : public CPseudoRoxieInput
  13383. {
  13384. public:
  13385. CRowQueuePseudoInput(SafeRowQueue & _input, IOutputMetaData * _meta)
  13386. : meta(_meta), input(_input)
  13387. {
  13388. eof = false;
  13389. }
  13390. virtual const void * nextRow()
  13391. {
  13392. if (eof)
  13393. return NULL;
  13394. const void * ret = input.dequeue();
  13395. if (!ret)
  13396. eof = true;
  13397. return ret;
  13398. }
  13399. virtual IOutputMetaData * queryOutputMeta() const { return meta; }
  13400. protected:
  13401. SafeRowQueue & input;
  13402. IOutputMetaData * meta;
  13403. bool eof;
  13404. };
  13405. class CRoxieServerParallelLoopActivity;
  13406. class LoopFilterPseudoInput : public CIndirectRoxieInput
  13407. {
  13408. public:
  13409. LoopFilterPseudoInput(CRoxieServerParallelLoopActivity * _activity, unsigned _counter) :
  13410. activity(_activity), counter(_counter)
  13411. {
  13412. }
  13413. virtual const void * nextRow();
  13414. protected:
  13415. CRoxieServerParallelLoopActivity * activity;
  13416. unsigned counter;
  13417. };
  13418. class LoopExecutorThread : public RestartableThread
  13419. {
  13420. protected:
  13421. Owned<CSafeRoxieInput> safeInput;
  13422. CRoxieServerParallelLoopActivity * activity;
  13423. bool eof;
  13424. CriticalSection crit;
  13425. unsigned flags;
  13426. SafeRowQueue tempResults[2];
  13427. unsigned savedParentExtractSize;
  13428. const byte * savedParentExtract;
  13429. IArrayOf<IActivityGraph> cachedGraphs;
  13430. IRoxieSlaveContext *ctx;
  13431. public:
  13432. LoopExecutorThread()
  13433. : RestartableThread("LoopExecutorThread")
  13434. {
  13435. activity = NULL;
  13436. eof = false;
  13437. flags = 0;
  13438. ctx = NULL;
  13439. savedParentExtract = NULL;
  13440. savedParentExtractSize = 0;
  13441. }
  13442. void setInput(CRoxieServerParallelLoopActivity * _activity, unsigned _sourceIdx, IFinalRoxieInput *_input, unsigned _flags)
  13443. {
  13444. activity = _activity;
  13445. flags = _flags;
  13446. // 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-nextRow etc etc.
  13447. safeInput.setown(new CSafeRoxieInput(_sourceIdx, _input));
  13448. }
  13449. void connectInputStreams(bool consumerOrdered)
  13450. {
  13451. safeInput->connectInputStreams(ctx, consumerOrdered);
  13452. }
  13453. IFinalRoxieInput *queryInput() const
  13454. {
  13455. return safeInput;
  13456. }
  13457. void onCreate(IRoxieSlaveContext * _ctx);
  13458. void start(unsigned parentExtractSize, const byte *parentExtract, bool paused);
  13459. void stop();
  13460. void reset();
  13461. virtual int run();
  13462. protected:
  13463. void executeLoop();
  13464. void executeLoopInstance(unsigned counter, unsigned numIterations, unsigned inputIdx, IFinalRoxieInput * input, SafeRowQueue * spillOutput);
  13465. IFinalRoxieInput * createLoopIterationGraph(unsigned i, unsigned inputIdx, IFinalRoxieInput * input, unsigned counter);
  13466. };
  13467. class CRoxieServerParallelLoopActivity : public CRoxieServerLoopActivity
  13468. {
  13469. friend class LoopFilterPseudoInput;
  13470. friend class LoopExecutorThread;
  13471. QueueOf<const void, true> ready;
  13472. CriticalSection helperCS;
  13473. CriticalSection cs;
  13474. unsigned defaultNumParallel;
  13475. LoopExecutorThread executor;
  13476. IProbeManager* probeManager;
  13477. CriticalSection canAccess;
  13478. CriticalSection scrit;
  13479. InterruptableSemaphore readySpace;
  13480. InterruptableSemaphore recordsReady;
  13481. protected:
  13482. bool includeInLoop(unsigned counter, const void * row)
  13483. {
  13484. CriticalBlock b(helperCS);
  13485. return helper.sendToLoop(counter, row);
  13486. }
  13487. public:
  13488. CRoxieServerParallelLoopActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _loopGraphId, IOutputMetaData * _counterMeta)
  13489. : CRoxieServerLoopActivity(_ctx, _factory, _probeManager, _loopGraphId, _counterMeta),
  13490. readySpace(parallelLoopFlowLimit)
  13491. {
  13492. probeManager = _probeManager;
  13493. defaultNumParallel = 0;
  13494. }
  13495. virtual void onCreate(IHThorArg *_colocalParent)
  13496. {
  13497. CRoxieServerActivity::onCreate(_colocalParent);
  13498. executor.onCreate(ctx);
  13499. }
  13500. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13501. {
  13502. CriticalBlock b(scrit); // can stop while still starting, if unlucky...
  13503. readySpace.reinit(parallelLoopFlowLimit);
  13504. recordsReady.reinit();
  13505. CRoxieServerLoopActivity::start(parentExtractSize, parentExtract, paused);
  13506. defaultNumParallel = helper.defaultParallelIterations();
  13507. if (!defaultNumParallel)
  13508. defaultNumParallel = DEFAULT_PARALLEL_LOOP_THREADS;
  13509. //MORE: If numIterations <= number of parallel iterations[1],
  13510. //then we don't need to create a separate thread to do the processing, and the results will also avoid
  13511. //being transferred via a queue
  13512. executor.start(parentExtractSize, parentExtract, paused);
  13513. }
  13514. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  13515. {
  13516. if (idx)
  13517. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
  13518. executor.setInput(this, _sourceIdx, _in, flags);
  13519. }
  13520. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  13521. {
  13522. executor.connectInputStreams(consumerOrdered);
  13523. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, nullptr, consumerOrdered, nullptr);
  13524. }
  13525. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  13526. {
  13527. if (idx==0)
  13528. return executor.queryInput();
  13529. else
  13530. return NULL;
  13531. }
  13532. virtual void stop()
  13533. {
  13534. CriticalBlock b(scrit); // can stop while still starting, if unlucky...
  13535. readySpace.interrupt();
  13536. recordsReady.interrupt();
  13537. executor.join(); // MORE - may not be needed given stop/reset split
  13538. CRoxieServerLoopActivity::stop();
  13539. }
  13540. virtual void reset()
  13541. {
  13542. while (ready.ordinality())
  13543. ReleaseRoxieRow(ready.dequeue());
  13544. executor.reset();
  13545. CRoxieServerActivity::reset();
  13546. }
  13547. virtual const void * nextRow()
  13548. {
  13549. ActivityTimer t(totalCycles, timeActivities);
  13550. for (;;)
  13551. {
  13552. if (eof)
  13553. return NULL;
  13554. recordsReady.wait();
  13555. CriticalBlock procedure(canAccess);
  13556. if (ready.ordinality())
  13557. {
  13558. const void *result = ready.dequeue();
  13559. readySpace.signal();
  13560. if (result)
  13561. processed++;
  13562. return result;
  13563. }
  13564. else
  13565. eof = true;
  13566. }
  13567. }
  13568. unsigned getNumParallel(unsigned iter)
  13569. {
  13570. return defaultNumParallel;
  13571. }
  13572. inline void enqueueResult(const void * row)
  13573. {
  13574. try
  13575. {
  13576. while(!readySpace.wait(1000))
  13577. {
  13578. CTXLOG("Blocked waiting for space in loop %p activity id: %d output queue: %d records in queue", this, queryId(), ready.ordinality());
  13579. }
  13580. }
  13581. catch (...)
  13582. {
  13583. ReleaseRoxieRow(row);
  13584. throw;
  13585. }
  13586. CriticalBlock b2(canAccess);
  13587. ready.enqueue(row);
  13588. recordsReady.signal();
  13589. }
  13590. inline void finishResults()
  13591. {
  13592. recordsReady.signal();
  13593. }
  13594. virtual bool fireException(IException *e)
  13595. {
  13596. readySpace.interrupt(LINK(e));
  13597. recordsReady.interrupt(e);
  13598. return true;
  13599. }
  13600. IActivityGraph * createChildGraphInstance()
  13601. {
  13602. return factory->createChildGraph(ctx, &helper, loopGraphId, this, probeManager, *this);
  13603. }
  13604. IActivityGraph * queryChildGraph()
  13605. {
  13606. return ctx->queryChildGraph(loopGraphId);
  13607. }
  13608. };
  13609. //=================================================================================
  13610. const void * LoopFilterPseudoInput::nextRow()
  13611. {
  13612. for (;;)
  13613. {
  13614. const void * next = stream->nextRow();
  13615. if (!next || activity->includeInLoop(counter, next))
  13616. return next;
  13617. activity->enqueueResult(next);
  13618. }
  13619. }
  13620. void LoopExecutorThread::onCreate(IRoxieSlaveContext * _ctx)
  13621. {
  13622. //Initialise the cached graph list with the child instance that will always be created. Other iterations will be created on demand.
  13623. ctx = _ctx;
  13624. cachedGraphs.append(*LINK(activity->queryChildGraph()));
  13625. }
  13626. void LoopExecutorThread::start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13627. {
  13628. savedParentExtractSize = parentExtractSize;
  13629. savedParentExtract = parentExtract;
  13630. eof = false;
  13631. StringBuffer logPrefix("[");
  13632. ctx->getLogPrefix(logPrefix).append("] ");
  13633. RestartableThread::start(logPrefix);
  13634. }
  13635. int LoopExecutorThread::run()
  13636. {
  13637. try
  13638. {
  13639. executeLoop();
  13640. }
  13641. catch (IException *e)
  13642. {
  13643. activity->fireException(e);
  13644. }
  13645. catch (...)
  13646. {
  13647. activity->fireException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unexpected exception caught in LoopExecutorThread::run"));
  13648. }
  13649. return 0;
  13650. }
  13651. void LoopExecutorThread::stop()
  13652. {
  13653. safeInput->stop();
  13654. RestartableThread::join();
  13655. }
  13656. void LoopExecutorThread::reset()
  13657. {
  13658. safeInput->reset();
  13659. }
  13660. void LoopExecutorThread::executeLoop()
  13661. {
  13662. unsigned iterations = 0;
  13663. unsigned counter = 0;
  13664. unsigned outputIndex = 0;
  13665. //Note, activities don't link inputs, so need to be careful that special inputs remain linked while the activity is executing.
  13666. for (;;)
  13667. {
  13668. if (activity->activityKind == TAKloopcount)
  13669. {
  13670. if (counter == activity->maxIterations)
  13671. break;
  13672. }
  13673. else
  13674. {
  13675. //This condition isn't quite right because it needs to be whether the filtered
  13676. //input is empty. May be ok if we include that in the semantics,
  13677. if (tempResults[1-outputIndex].ordinality() == 0)
  13678. break;
  13679. }
  13680. unsigned numParallel = activity->getNumParallel(iterations);
  13681. Linked<IFinalRoxieInput> curInput;
  13682. if (iterations == 0)
  13683. curInput.set(safeInput);
  13684. else
  13685. {
  13686. SafeRowQueue & inputQueue = tempResults[1-outputIndex];
  13687. inputQueue.enqueue(NULL);
  13688. curInput.setown(new CRowQueuePseudoInput(inputQueue, activity->queryOutputMeta()));
  13689. }
  13690. SafeRowQueue * curOutput = NULL;
  13691. if (counter+numParallel > activity->maxIterations)
  13692. numParallel = activity->maxIterations - counter;
  13693. else if (counter+numParallel < activity->maxIterations)
  13694. curOutput = &tempResults[outputIndex];
  13695. executeLoopInstance(counter, numParallel, 0, curInput, curOutput); // CurInput is always SOME sort of proxy so idx always 0
  13696. outputIndex = 1-outputIndex;
  13697. counter += numParallel;
  13698. iterations++;
  13699. }
  13700. //Check for TAKlooprow, where end of loop couldn't be determined ahead of time
  13701. SafeRowQueue & inputQueue = tempResults[1-outputIndex];
  13702. while (inputQueue.ordinality())
  13703. {
  13704. const void * next = inputQueue.dequeue();
  13705. activity->enqueueResult(next);
  13706. }
  13707. activity->finishResults();
  13708. }
  13709. void LoopExecutorThread::executeLoopInstance(unsigned counter, unsigned numIterations, unsigned inputIdx, IFinalRoxieInput * input, SafeRowQueue * spillOutput)
  13710. {
  13711. IArrayOf<IFinalRoxieInput> savedInputs; // activities don't link their inputs, so this list keeps filters alive.
  13712. Linked<IFinalRoxieInput> curInput = input;
  13713. unsigned i;
  13714. for (i= 0; i != numIterations; i++)
  13715. {
  13716. unsigned thisCounter = counter+i+1;
  13717. IFinalRoxieInput * filtered = curInput;
  13718. if (flags & IHThorLoopArg::LFfiltered)
  13719. {
  13720. LoopFilterPseudoInput *newFiltered = new LoopFilterPseudoInput(activity, thisCounter);
  13721. newFiltered->setInput(inputIdx, curInput);
  13722. filtered = newFiltered;
  13723. savedInputs.append(*filtered);
  13724. inputIdx = 0;
  13725. }
  13726. //graph is kept, so new curInput will be guaranteed to exist
  13727. curInput.setown(createLoopIterationGraph(i, inputIdx, filtered, thisCounter));
  13728. inputIdx = 0;
  13729. }
  13730. Owned<IStrandJunction> curJunction;
  13731. IEngineRowStream *curStream = connectSingleStream(ctx, curInput, inputIdx, curJunction, true);
  13732. Owned<IException> failure;
  13733. try
  13734. {
  13735. curInput->start(savedParentExtractSize, savedParentExtract, false);
  13736. if (spillOutput)
  13737. {
  13738. for (;;)
  13739. {
  13740. const void * next = curStream->nextRow();
  13741. if (!next)
  13742. break;
  13743. spillOutput->enqueue(next);
  13744. }
  13745. }
  13746. else
  13747. {
  13748. for (;;)
  13749. {
  13750. const void * next = curStream->nextRow();
  13751. if (!next)
  13752. break;
  13753. activity->enqueueResult(next);
  13754. }
  13755. }
  13756. }
  13757. catch (IException *E)
  13758. {
  13759. ctx->notifyAbort(E);
  13760. failure.setown(E);
  13761. }
  13762. for (i= 0; i != numIterations; i++)
  13763. {
  13764. IRoxieServerChildGraph * loopGraph = cachedGraphs.item(i).queryLoopGraph();
  13765. loopGraph->afterExecute();
  13766. //NOTE: inputIdx is always 0 - the code above could be cleaned up.
  13767. loopGraph->querySetInputResult(1, 0, nullptr);
  13768. }
  13769. curStream->stop();
  13770. curInput->reset();
  13771. if (failure)
  13772. throw failure.getClear();
  13773. }
  13774. IFinalRoxieInput * LoopExecutorThread::createLoopIterationGraph(unsigned i, unsigned inputIdx, IFinalRoxieInput * input, unsigned counter)
  13775. {
  13776. if (!cachedGraphs.isItem(i))
  13777. cachedGraphs.append(*activity->createChildGraphInstance());
  13778. Linked<IRoxieServerChildGraph> loopGraph = cachedGraphs.item(i).queryLoopGraph();
  13779. loopGraph->beforeExecute();
  13780. if (!loopGraph->querySetInputResult(1, inputIdx, input))
  13781. throwUnexpected(); // a loop which doesn't use the value from the previous iteration. Should probably handle even if daft.
  13782. activity->createCounterResult(loopGraph, counter);
  13783. return loopGraph->selectOutput(0);
  13784. }
  13785. //=================================================================================
  13786. class CCounterRowMetaData : implements IOutputMetaData, public CInterface
  13787. {
  13788. public:
  13789. IMPLEMENT_IINTERFACE
  13790. virtual size32_t getRecordSize(const void *) { return sizeof(thor_loop_counter_t); }
  13791. virtual size32_t getMinRecordSize() const { return sizeof(thor_loop_counter_t); }
  13792. virtual size32_t getFixedSize() const { return sizeof(thor_loop_counter_t); }
  13793. virtual void toXML(const byte * self, IXmlWriter & out) { }
  13794. virtual unsigned getVersion() const { return OUTPUTMETADATA_VERSION; }
  13795. virtual unsigned getMetaFlags() { return 0; }
  13796. virtual void destruct(byte * self) {}
  13797. virtual IOutputRowSerializer * createDiskSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  13798. virtual IOutputRowDeserializer * createDiskDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  13799. virtual ISourceRowPrefetcher * createDiskPrefetcher(ICodeContext * ctx, unsigned activityId) { return NULL; }
  13800. virtual IOutputMetaData * querySerializedDiskMeta() { return this; }
  13801. virtual IOutputRowSerializer * createInternalSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  13802. virtual IOutputRowDeserializer * createInternalDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  13803. virtual void walkIndirectMembers(const byte * self, IIndirectMemberVisitor & visitor) {}
  13804. virtual IOutputMetaData * queryChildMeta(unsigned i) { return NULL; }
  13805. };
  13806. class CRoxieServerLoopActivityFactory : public CRoxieServerActivityFactory
  13807. {
  13808. unsigned loopGraphId;
  13809. unsigned flags;
  13810. Linked<IOutputMetaData> counterMeta;
  13811. public:
  13812. CRoxieServerLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _loopGraphId)
  13813. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), loopGraphId(_loopGraphId)
  13814. {
  13815. Owned<IHThorLoopArg> helper = (IHThorLoopArg *) helperFactory();
  13816. flags = helper->getFlags();
  13817. counterMeta.setown(new CCounterRowMetaData);
  13818. }
  13819. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  13820. {
  13821. if (flags & IHThorLoopArg::LFparallel)
  13822. return new CRoxieServerParallelLoopActivity(_ctx, this, _probeManager, loopGraphId, counterMeta);
  13823. else
  13824. return new CRoxieServerSequentialLoopActivity(_ctx, this, _probeManager, loopGraphId, counterMeta);
  13825. }
  13826. };
  13827. IRoxieServerActivityFactory *createRoxieServerLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _loopGraphId)
  13828. {
  13829. return new CRoxieServerLoopActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _loopGraphId);
  13830. }
  13831. //=================================================================================
  13832. class CRoxieServerGraphLoopActivity : public CRoxieServerActivity
  13833. {
  13834. protected:
  13835. IHThorGraphLoopArg &helper;
  13836. unsigned maxIterations;
  13837. unsigned flags;
  13838. rtlRowBuilder GraphExtractBuilder;
  13839. unsigned loopGraphId;
  13840. Linked<IOutputMetaData> counterMeta;
  13841. public:
  13842. CRoxieServerGraphLoopActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _GraphGraphId, IOutputMetaData * _counterMeta)
  13843. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  13844. helper((IHThorGraphLoopArg &)basehelper), loopGraphId(_GraphGraphId), counterMeta(_counterMeta)
  13845. {
  13846. flags = helper.getFlags();
  13847. maxIterations = 0;
  13848. }
  13849. virtual bool needsAllocator() const { return true; }
  13850. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13851. {
  13852. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  13853. int iterations = (int) helper.numIterations();
  13854. maxIterations = (iterations >= 0) ? iterations : 0;
  13855. if (maxIterations > maxGraphLoopIterations)
  13856. throw MakeStringException(ROXIE_TOO_MANY_GRAPH_LOOP, "Attempt to execute graph %u times", maxIterations);
  13857. if (maxIterations != 0)
  13858. {
  13859. GraphExtractBuilder.clear();
  13860. helper.createParentExtract(GraphExtractBuilder);
  13861. }
  13862. }
  13863. virtual void stop()
  13864. {
  13865. CRoxieServerActivity::stop();
  13866. GraphExtractBuilder.clear();
  13867. }
  13868. void createCounterResult(IRoxieServerChildGraph * graph, unsigned counter)
  13869. {
  13870. if (flags & IHThorGraphLoopArg::GLFcounter)
  13871. {
  13872. void * counterRow = ctx->queryRowManager().allocate(sizeof(thor_loop_counter_t), activityId);
  13873. *((thor_loop_counter_t *)counterRow) = counter;
  13874. RtlLinkedDatasetBuilder builder(rowAllocator);
  13875. builder.appendOwn(counterRow);
  13876. Owned<CGraphResult> counterResult = new CGraphResult(builder.getcount(), builder.linkrows());
  13877. graph->setInputResult(0, counterResult);
  13878. }
  13879. }
  13880. };
  13881. //=================================================================================
  13882. class CRoxieServerSequentialGraphLoopActivity : public CRoxieServerGraphLoopActivity
  13883. {
  13884. Owned<IActivityGraph> GraphQuery;
  13885. Owned<IRoxieServerChildGraph> loopGraph;
  13886. Linked<IEngineRowStream> resultStream;
  13887. bool evaluated;
  13888. public:
  13889. CRoxieServerSequentialGraphLoopActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _GraphGraphId, IOutputMetaData * _counterMeta)
  13890. : CRoxieServerGraphLoopActivity(_ctx, _factory, _probeManager, _GraphGraphId, _counterMeta)
  13891. {
  13892. evaluated = false;
  13893. }
  13894. virtual void onCreate(IHThorArg *_colocalParent)
  13895. {
  13896. CRoxieServerGraphLoopActivity::onCreate(_colocalParent);
  13897. GraphQuery.set(ctx->queryChildGraph(loopGraphId));
  13898. }
  13899. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13900. {
  13901. CRoxieServerGraphLoopActivity::start(parentExtractSize, parentExtract, paused);
  13902. //MORE: Not sure about this, should IRoxieServerChildGraph be combined with IActivityGraph?
  13903. loopGraph.set(GraphQuery->queryLoopGraph());
  13904. evaluated = false;
  13905. }
  13906. virtual void stop()
  13907. {
  13908. if (loopGraph)
  13909. loopGraph->clearGraphLoopResults();
  13910. CRoxieServerGraphLoopActivity::stop();
  13911. }
  13912. virtual const void * nextRow()
  13913. {
  13914. ActivityTimer t(totalCycles, timeActivities);
  13915. if (!evaluated)
  13916. {
  13917. executeEntireGraph();
  13918. evaluated = true;
  13919. }
  13920. const void * ret = resultStream->nextRow();
  13921. if (ret)
  13922. processed++;
  13923. return ret;
  13924. }
  13925. void executeIteration(unsigned parentExtractSize, const byte *parentExtract, unsigned counter)
  13926. {
  13927. try
  13928. {
  13929. loopGraph->beforeExecute();
  13930. createCounterResult(loopGraph, counter);
  13931. loopGraph->executeGraphLoop(parentExtractSize, parentExtract);
  13932. loopGraph->afterExecute();
  13933. }
  13934. catch (...)
  13935. {
  13936. CTXLOG("Exception thrown in graph body - cleaning up");
  13937. loopGraph->afterExecute();
  13938. throw;
  13939. }
  13940. }
  13941. void createInitialGraphInput()
  13942. {
  13943. loopGraph->clearGraphLoopResults();
  13944. RtlLinkedDatasetBuilder builder(rowAllocator);
  13945. inputStream->readAll(builder);
  13946. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  13947. loopGraph->setGraphLoopResult(0, result);
  13948. }
  13949. void executeEntireGraph()
  13950. {
  13951. createInitialGraphInput();
  13952. for (unsigned loopCounter=1; loopCounter <= maxIterations; loopCounter++)
  13953. {
  13954. executeIteration(GraphExtractBuilder.size(), GraphExtractBuilder.getbytes(), loopCounter);
  13955. }
  13956. resultStream.setown(loopGraph->getGraphLoopResult(maxIterations));
  13957. }
  13958. };
  13959. //=================================================================================
  13960. struct GraphOutputSplitterArg : public ccdserver_hqlhelper::CThorSplitArg
  13961. {
  13962. public:
  13963. virtual unsigned numBranches()
  13964. {
  13965. return 0;
  13966. }
  13967. virtual IOutputMetaData * queryOutputMeta()
  13968. {
  13969. return NULL;// get it from the parent..
  13970. }
  13971. };
  13972. extern "C" IHThorArg * createGraphOutputSplitter() { return new GraphOutputSplitterArg; }
  13973. class CGraphIterationInfo : public CInterface
  13974. {
  13975. private:
  13976. Owned<IRoxieServerActivityFactory> factory; // Note - before sourceAct, so destroyed last
  13977. unsigned sourceIdx;
  13978. Linked<IRoxieServerActivity> sourceAct;
  13979. Linked<IFinalRoxieInput> sourceInput;
  13980. unsigned numUses;
  13981. unsigned iteration;
  13982. public:
  13983. CGraphIterationInfo(IRoxieServerActivity * _sourceAct, IFinalRoxieInput *_input, unsigned _sourceIdx, unsigned _iteration)
  13984. : sourceAct(_sourceAct), sourceInput(_input), sourceIdx(_sourceIdx), iteration(_iteration)
  13985. {
  13986. numUses = 0;
  13987. }
  13988. inline void noteUsed()
  13989. {
  13990. numUses++;
  13991. }
  13992. void createSplitter(IRoxieSlaveContext *ctx, IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes)
  13993. {
  13994. if (numUses > 1)
  13995. {
  13996. Owned<IPropertyTree> splitterNode = createPTree(ipt_fast);
  13997. factory.setown(createRoxieServerThroughSpillActivityFactory(sourceAct->queryFactory()->queryQueryFactory(), createGraphOutputSplitter, numUses, *splitterNode));
  13998. IRoxieServerActivity *splitter = factory->createActivity(ctx, NULL);
  13999. splitter->onCreate(NULL);
  14000. IFinalRoxieInput *input = sourceAct->queryOutput(sourceIdx);
  14001. if (probeManager)
  14002. {
  14003. IRoxieProbe * inputProbe = probeManager->createProbe(static_cast<IInputBase*>(input), sourceAct, splitter, sourceIdx, 0, iteration);
  14004. probes.append(*LINK(inputProbe));
  14005. input = &dynamic_cast<IFinalRoxieInput &>(inputProbe->queryInput());
  14006. sourceIdx = 0;
  14007. }
  14008. sourceAct.setown(splitter);
  14009. sourceAct->setInput(0, sourceIdx, input);
  14010. sourceIdx = 0;
  14011. sourceInput.clear();
  14012. }
  14013. }
  14014. IFinalRoxieInput *connectOutput(IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes, IRoxieServerActivity *targetAct, unsigned targetIdx)
  14015. {
  14016. // MORE - not really necessary to create splitters in separate pass, is it?
  14017. if (factory) // we created a splitter....
  14018. sourceInput.set(sourceAct->queryOutput(sourceIdx));
  14019. IFinalRoxieInput *ret = sourceInput;
  14020. if (probeManager)
  14021. {
  14022. IRoxieProbe * inputProbe = probeManager->createProbe(sourceInput, sourceAct, targetAct, sourceIdx, targetIdx, iteration);
  14023. probes.append(*LINK(inputProbe));
  14024. ret = &dynamic_cast<IFinalRoxieInput &>(inputProbe->queryInput());
  14025. // MORE - do we need to connect the stream in the probe?
  14026. }
  14027. if (factory) // we created a splitter....
  14028. sourceIdx++;
  14029. return ret;
  14030. }
  14031. };
  14032. class CRoxieServerParallelGraphLoopActivity : public CRoxieServerGraphLoopActivity, implements IRoxieServerLoopResultProcessor
  14033. {
  14034. Owned<IActivityGraph> childGraph;
  14035. IFinalRoxieInput * resultInput;
  14036. IEngineRowStream * resultStream;
  14037. Owned<IStrandJunction> resultJunction;
  14038. CIArrayOf<CGraphIterationInfo> outputs;
  14039. IArrayOf<IRoxieServerChildGraph> iterationGraphs;
  14040. Owned<CExtractMapperInput> inputExtractMapper;
  14041. IProbeManager *probeManager;
  14042. unsigned createLoopCounter;
  14043. IArrayOf<IRoxieProbe> probes;
  14044. public:
  14045. CRoxieServerParallelGraphLoopActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _GraphGraphId, IOutputMetaData * _counterMeta)
  14046. : CRoxieServerGraphLoopActivity(_ctx, _factory, _probeManager, _GraphGraphId, _counterMeta), probeManager(_probeManager)
  14047. {
  14048. inputExtractMapper.setown(new CExtractMapperInput);
  14049. resultInput = NULL;
  14050. resultStream = NULL;
  14051. createLoopCounter = 0;
  14052. }
  14053. virtual void onCreate(IHThorArg *_colocalParent)
  14054. {
  14055. CRoxieServerGraphLoopActivity::onCreate(_colocalParent);
  14056. childGraph.set(ctx->queryChildGraph(loopGraphId));
  14057. }
  14058. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  14059. {
  14060. //Input needs to be handled very carefully.....
  14061. //We don't want to call onStart on the input unless it is actually used, so don't use the base CRoxieServerActivity implementation.
  14062. //This activity's input needs to be started with (parentExtractSize, parentExtract), but the elements in the graph need to be started with the
  14063. //GraphExtractBuilder parent extract. So we need to wrap the input in a pseudo-input (inputExtractMapper) that passes through a different
  14064. //parentExtract. Something very similar will be needed for query library calls with streaming inputs when they are implemented.
  14065. assertex(idx == 0);
  14066. inputExtractMapper->setInput(_sourceIdx, _in);
  14067. }
  14068. virtual void connectInputStreams(bool consumerOrdered)
  14069. {
  14070. //NB: inputExtractMapper is not connected at this point - only if/when it is used from within the graph
  14071. CRoxieServerActivity::connectInputStreams(consumerOrdered);
  14072. }
  14073. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  14074. {
  14075. if (idx==0)
  14076. return inputExtractMapper->queryInput();
  14077. else
  14078. return NULL;
  14079. }
  14080. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14081. {
  14082. CRoxieServerGraphLoopActivity::start(parentExtractSize, parentExtract, paused); // initialises GraphExtractBuilder
  14083. inputExtractMapper->setParentExtract(parentExtractSize, parentExtract);
  14084. createExpandedGraph(GraphExtractBuilder.size(), GraphExtractBuilder.getbytes(), probeManager);
  14085. resultInput->start(GraphExtractBuilder.size(), GraphExtractBuilder.getbytes(), paused);
  14086. startJunction(resultJunction);
  14087. }
  14088. virtual void stop()
  14089. {
  14090. if (resultStream)
  14091. resultStream->stop();
  14092. CRoxieServerGraphLoopActivity::stop();
  14093. }
  14094. virtual void reset()
  14095. {
  14096. if (resultInput)
  14097. resultInput->reset();
  14098. resetJunction(resultJunction);
  14099. resultInput = NULL;
  14100. resultStream = NULL;
  14101. resultJunction.clear();
  14102. outputs.kill();
  14103. iterationGraphs.kill(); // must be done after all activities killed
  14104. if (probeManager)
  14105. {
  14106. probeManager->deleteGraph(NULL, (IArrayOf<IInputBase>*)&probes);
  14107. probes.kill();
  14108. }
  14109. CRoxieServerGraphLoopActivity::reset();
  14110. }
  14111. virtual const void * nextRow()
  14112. {
  14113. ActivityTimer t(totalCycles, timeActivities);
  14114. const void * ret = resultStream->nextRow();
  14115. if (ret)
  14116. processed++;
  14117. return ret;
  14118. }
  14119. void createExpandedGraph(unsigned parentExtractSize, const byte *parentExtract, IProbeManager *probeManager)
  14120. {
  14121. //result(0) is the input to the graph.
  14122. resultInput = inputExtractMapper;
  14123. outputs.append(* new CGraphIterationInfo(resultInput->queryActivity(), resultInput, 0, 1));
  14124. for (createLoopCounter=1; createLoopCounter <= maxIterations; createLoopCounter++)
  14125. {
  14126. IRoxieServerChildGraph * graph = childGraph->createGraphLoopInstance(ctx, createLoopCounter, parentExtractSize, parentExtract, *this);
  14127. graph->beforeExecute();
  14128. iterationGraphs.append(*graph);
  14129. graph->gatherIterationUsage(*this);
  14130. CGraphIterationInfo *iteration = graph->selectGraphLoopOutput();
  14131. outputs.append(*iteration);
  14132. }
  14133. createLoopCounter = 0;
  14134. createSplitters(probeManager, probes);
  14135. ForEachItemIn(i2, iterationGraphs)
  14136. iterationGraphs.item(i2).associateIterationOutputs(*this);
  14137. resultInput = outputs.tos().connectOutput(probeManager, probes, this, 0);
  14138. resultStream = connectSingleStream(ctx, resultInput, 0, resultJunction, true);
  14139. }
  14140. void createSplitters(IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes)
  14141. {
  14142. ForEachItemIn(i, outputs)
  14143. {
  14144. CGraphIterationInfo & next = outputs.item(i);
  14145. next.createSplitter(ctx, probeManager, probes);
  14146. }
  14147. }
  14148. //IRoxieServerLoopResultProcessor
  14149. virtual void noteUseIteration(unsigned _whichIteration)
  14150. {
  14151. int whichIteration = (int) _whichIteration; // May go negative - API is unsigned for historical reasons
  14152. if (whichIteration >= 0)
  14153. {
  14154. if (!outputs.isItem(whichIteration))
  14155. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Error reading graph result %d from iteration %d", whichIteration, createLoopCounter);
  14156. outputs.item(whichIteration).noteUsed();
  14157. }
  14158. }
  14159. virtual IFinalRoxieInput* connectIterationOutput(unsigned whichIteration, IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes, IRoxieServerActivity *targetAct, unsigned targetIdx)
  14160. {
  14161. if (outputs.isItem(whichIteration))
  14162. {
  14163. CGraphIterationInfo & next = outputs.item(whichIteration);
  14164. return next.connectOutput(probeManager, probes, targetAct, targetIdx);
  14165. }
  14166. return NULL;
  14167. }
  14168. };
  14169. //=================================================================================
  14170. class CRoxieServerGraphLoopActivityFactory : public CRoxieServerActivityFactory
  14171. {
  14172. unsigned loopGraphId;
  14173. unsigned flags;
  14174. Linked<IOutputMetaData> counterMeta;
  14175. public:
  14176. CRoxieServerGraphLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _loopGraphId)
  14177. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), loopGraphId(_loopGraphId)
  14178. {
  14179. Owned<IHThorGraphLoopArg> helper = (IHThorGraphLoopArg *) helperFactory();
  14180. flags = helper->getFlags();
  14181. counterMeta.setown(new CCounterRowMetaData);
  14182. }
  14183. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  14184. {
  14185. if (kind == TAKparallelgraphloop)
  14186. return new CRoxieServerParallelGraphLoopActivity(_ctx, this, _probeManager, loopGraphId, counterMeta);
  14187. else
  14188. return new CRoxieServerSequentialGraphLoopActivity(_ctx, this, _probeManager, loopGraphId, counterMeta);
  14189. }
  14190. };
  14191. IRoxieServerActivityFactory *createRoxieServerGraphLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _loopGraphId)
  14192. {
  14193. return new CRoxieServerGraphLoopActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _loopGraphId);
  14194. }
  14195. //=====================================================================================================
  14196. class CRoxieServerLibraryCallActivity : public CRoxieServerActivity
  14197. {
  14198. class OutputAdaptor : public CExtractMapperInput
  14199. {
  14200. bool stopped;
  14201. public:
  14202. CRoxieServerLibraryCallActivity *parent;
  14203. IOutputMetaData * meta = nullptr;
  14204. unsigned oid;
  14205. unsigned processed;
  14206. public:
  14207. OutputAdaptor()
  14208. {
  14209. parent = NULL;
  14210. oid = 0;
  14211. init();
  14212. }
  14213. ~OutputAdaptor()
  14214. {
  14215. if (traceStartStop)
  14216. DBGLOG("%p ~OutputAdaptor %d", this, oid);
  14217. if (processed && parent && parent->factory)
  14218. {
  14219. parent->factory->noteProcessed(oid, processed);
  14220. if (parent->ctx)
  14221. parent->ctx->noteProcessed(parent->querySubgraphId(), parent->activityId, oid, processed, 0);
  14222. }
  14223. }
  14224. void setParent(CRoxieServerLibraryCallActivity * _parent, IOutputMetaData * _meta, unsigned _oid)
  14225. {
  14226. parent = _parent;
  14227. meta = _meta;
  14228. oid = _oid;
  14229. }
  14230. void init()
  14231. {
  14232. processed = 0;
  14233. stopped = false;
  14234. }
  14235. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14236. {
  14237. parent->start(oid, parentExtractSize, parentExtract, paused);
  14238. CExtractMapperInput::start(parentExtractSize, parentExtract, paused);
  14239. }
  14240. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  14241. {
  14242. //MORE value of consumerOrdered depends on whether this activity is marked as ordered.
  14243. if (!oid) // Only need to set up once
  14244. {
  14245. parent->connectInputStreams(true); // To handle dependencies etc
  14246. }
  14247. return CExtractMapperInput::getOutputStreams(ctx, 0, streams, nullptr, true, nullptr);
  14248. }
  14249. //This override should not really be needed, but input is set up too late for the call to connect strands
  14250. virtual IOutputMetaData * queryOutputMeta() const
  14251. {
  14252. return meta;
  14253. }
  14254. virtual void stop()
  14255. {
  14256. if (!stopped)
  14257. {
  14258. stopped = true;
  14259. parent->stop(oid); // parent code relies on stop being called exactly once per adaptor, so make sure it is!
  14260. CExtractMapperInput::stop();
  14261. }
  14262. };
  14263. virtual void reset()
  14264. {
  14265. parent->reset(oid);
  14266. CExtractMapperInput::reset();
  14267. init();
  14268. };
  14269. virtual void checkAbort()
  14270. {
  14271. parent->checkAbort();
  14272. }
  14273. };
  14274. IHThorLibraryCallArg &helper;
  14275. unsigned numInputs;
  14276. unsigned numOutputs;
  14277. unsigned numActiveOutputs;
  14278. bool started;
  14279. OutputAdaptor* outputAdaptors;
  14280. CExtractMapperInput * * inputAdaptors;
  14281. bool * inputUsed;
  14282. bool * outputUsed;
  14283. Owned<IException> error;
  14284. CriticalSection crit;
  14285. rtlRowBuilder libraryExtractBuilder;
  14286. Owned<IActivityGraph> libraryGraph;
  14287. const LibraryCallFactoryExtra & extra;
  14288. public:
  14289. CRoxieServerLibraryCallActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs, unsigned _numOutputs, const LibraryCallFactoryExtra & _extra)
  14290. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  14291. helper((IHThorLibraryCallArg &)basehelper), extra(_extra)
  14292. {
  14293. numInputs = _numInputs;
  14294. numOutputs = _numOutputs;
  14295. numActiveOutputs = numOutputs;
  14296. inputAdaptors = new CExtractMapperInput*[numInputs];
  14297. inputUsed = new bool[numInputs];
  14298. for (unsigned i1 = 0; i1 < numInputs; i1++)
  14299. {
  14300. inputAdaptors[i1] = new CExtractMapperInput;
  14301. inputUsed[i1] = false;
  14302. }
  14303. outputAdaptors = new OutputAdaptor[numOutputs];
  14304. outputUsed = new bool[numOutputs];
  14305. for (unsigned i2 = 0; i2 < numOutputs; i2++)
  14306. {
  14307. outputAdaptors[i2].setParent(this, helper.queryOutputMeta(i2), i2);
  14308. outputUsed[i2] = false;
  14309. }
  14310. started = false;
  14311. }
  14312. ~CRoxieServerLibraryCallActivity()
  14313. {
  14314. for (unsigned i1 = 0; i1 < numInputs; i1++)
  14315. ::Release(inputAdaptors[i1]);
  14316. delete [] inputAdaptors;
  14317. delete [] inputUsed;
  14318. delete [] outputAdaptors;
  14319. delete [] outputUsed;
  14320. }
  14321. virtual void onCreate(IHThorArg *_colocalParent)
  14322. {
  14323. CRoxieServerActivity::onCreate(_colocalParent);
  14324. libraryGraph.setown(ctx->getLibraryGraph(extra, this));
  14325. libraryGraph->onCreate(_colocalParent);
  14326. //Now map the inputs and outputs to the adapters
  14327. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  14328. for (unsigned i1=0; i1<numInputs; i1++)
  14329. inputUsed[i1] = graph->querySetInputResult(i1, 0, inputAdaptors[i1]);
  14330. for (unsigned i2=0; i2<numOutputs; i2++)
  14331. {
  14332. unsigned outputIndex = extra.outputs.item(i2);
  14333. Owned<IFinalRoxieInput> output = graph->selectOutput(numInputs+outputIndex);
  14334. outputAdaptors[i2].setInput(0, output); // MORE - no idea if this 0 is right??
  14335. outputAdaptors[i2].connectInputStreams(ctx, true);
  14336. }
  14337. }
  14338. virtual void start(unsigned oid, unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14339. {
  14340. CriticalBlock b(crit);
  14341. if (error)
  14342. throw error.getLink();
  14343. if (factory)
  14344. factory->noteStarted(oid);
  14345. if (!started)
  14346. {
  14347. // even though it is not complete, we don't want to run this again if it fails.
  14348. started = true;
  14349. //see notes on splitter above
  14350. try
  14351. {
  14352. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14353. }
  14354. catch (IException *E)
  14355. {
  14356. #ifdef TRACE_SPLIT
  14357. CTXLOG("spill %d caught exception in start", activityId);
  14358. #endif
  14359. error.set(E);
  14360. throw;
  14361. }
  14362. catch (...)
  14363. {
  14364. IException *E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught in CRoxieServerLibraryCallActivity::start");
  14365. error.set(E);
  14366. throw E;
  14367. }
  14368. //recreate the parent extract, and use it to reinitialize the graphs...
  14369. libraryExtractBuilder.clear();
  14370. helper.createParentExtract(libraryExtractBuilder);
  14371. // 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
  14372. // some inputs before we see start on others.
  14373. for (unsigned i1 = 0; i1 < numInputs; i1++)
  14374. {
  14375. if (inputUsed[i1])
  14376. inputAdaptors[i1]->setParentExtract(parentExtractSize, parentExtract);
  14377. else
  14378. inputAdaptors[i1]->queryInput()->stopall();
  14379. }
  14380. for (unsigned i2 = 0; i2 < numOutputs; i2++)
  14381. outputAdaptors[i2].setParentExtract(libraryExtractBuilder.size(), libraryExtractBuilder.getbytes());
  14382. //call stop on all the unused inputs.
  14383. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  14384. graph->beforeExecute();
  14385. ForEachItemIn(i3, extra.unusedOutputs)
  14386. {
  14387. Owned<IFinalRoxieInput> output = graph->selectOutput(numInputs+extra.unusedOutputs.item(i3));
  14388. output->stopall();
  14389. }
  14390. }
  14391. }
  14392. virtual void stop(unsigned oid)
  14393. {
  14394. CriticalBlock b(crit);
  14395. if (--numActiveOutputs == 0)
  14396. {
  14397. //call stop on all the unused inputs.
  14398. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  14399. graph->beforeExecute();
  14400. ForEachItemIn(i3, extra.unusedOutputs)
  14401. {
  14402. Owned<IFinalRoxieInput> output = graph->selectOutput(numInputs+extra.unusedOutputs.item(i3));
  14403. output->stopall();
  14404. }
  14405. CRoxieServerActivity::stop();
  14406. }
  14407. }
  14408. void reset(unsigned oid)
  14409. {
  14410. started = false;
  14411. error.clear();
  14412. numActiveOutputs = numOutputs;
  14413. if (state != STATEreset) // make sure input is only reset once
  14414. {
  14415. CRoxieServerActivity::reset();
  14416. libraryGraph->reset();
  14417. //Call reset on all unused inputs/outputs from the graph - no one else will.
  14418. for (unsigned i1 = 0; i1 < numInputs; i1++)
  14419. {
  14420. if (!inputUsed[i1])
  14421. inputAdaptors[i1]->reset();
  14422. }
  14423. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  14424. ForEachItemIn(i3, extra.unusedOutputs)
  14425. {
  14426. Owned<IFinalRoxieInput> output = graph->selectOutput(numInputs+extra.unusedOutputs.item(i3));
  14427. output->reset();
  14428. }
  14429. }
  14430. };
  14431. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  14432. {
  14433. inputAdaptors[idx]->setInput(_sourceIdx, _in);
  14434. }
  14435. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  14436. {
  14437. if (idx < numInputs && inputAdaptors[idx])
  14438. return inputAdaptors[idx]->queryInput();
  14439. else
  14440. return NULL;
  14441. }
  14442. public:
  14443. virtual const void *nextRow()
  14444. {
  14445. throwUnexpected(); // Internal logic error - we are not anybody's input
  14446. }
  14447. virtual IOutputMetaData * queryOutputMeta() const
  14448. {
  14449. throwUnexpected(); // should be called on outputs instead
  14450. }
  14451. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  14452. {
  14453. assertex(idx!=(unsigned)-1);
  14454. assertex(!outputUsed[idx]);
  14455. outputUsed[idx] = true;
  14456. return &outputAdaptors[idx];
  14457. }
  14458. };
  14459. void LibraryCallFactoryExtra::set(const LibraryCallFactoryExtra & _other)
  14460. {
  14461. ForEachItemIn(i1, _other.outputs)
  14462. outputs.append(_other.outputs.item(i1));
  14463. ForEachItemIn(i2, _other.unusedOutputs)
  14464. unusedOutputs.append(_other.unusedOutputs.item(i2));
  14465. maxOutputs = _other.maxOutputs;
  14466. graphid = _other.graphid;
  14467. libraryName.set(_other.libraryName);
  14468. embeddedGraphName.set(_other.embeddedGraphName);
  14469. interfaceHash = _other.interfaceHash;
  14470. embedded = _other.embedded;
  14471. }
  14472. void LibraryCallFactoryExtra::calcUnused()
  14473. {
  14474. for (unsigned i=0; i < maxOutputs; i++)
  14475. if (!outputs.contains(i))
  14476. unusedOutputs.append(i);
  14477. }
  14478. class CRoxieServerLibraryCallActivityFactory : public CRoxieServerMultiOutputFactory
  14479. {
  14480. private:
  14481. CRoxieServerMultiInputInfo inputs;
  14482. LibraryCallFactoryExtra extra;
  14483. public:
  14484. CRoxieServerLibraryCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, LibraryCallFactoryExtra & _extra)
  14485. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  14486. {
  14487. extra.set(_extra);
  14488. extra.calcUnused();
  14489. setNumOutputs(extra.outputs.ordinality());
  14490. }
  14491. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  14492. {
  14493. return new CRoxieServerLibraryCallActivity(_ctx, this, _probeManager, numInputs(), numOutputs, extra);
  14494. }
  14495. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  14496. {
  14497. inputs.set(idx, source, sourceidx);
  14498. }
  14499. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  14500. {
  14501. return inputs.get(idx, sourceidx);
  14502. }
  14503. virtual unsigned numInputs() const { return inputs.ordinality(); }
  14504. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  14505. {
  14506. addXrefLibraryInfo(reply, extra.libraryName);
  14507. }
  14508. };
  14509. IRoxieServerActivityFactory *createRoxieServerLibraryCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, LibraryCallFactoryExtra & _extra)
  14510. {
  14511. return new CRoxieServerLibraryCallActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _extra);
  14512. }
  14513. //=====================================================================================================
  14514. // CRoxieServerNWayInputActivity is a multi-input, multi-output activity, where the outputs are a subset of the inputs
  14515. // Used to implement RANGE(<rowset-expression>, [set-of-indices])
  14516. class CRoxieServerNWayInputBaseActivity : public CRoxieServerMultiInputBaseActivity
  14517. {
  14518. protected:
  14519. PointerArrayOf<IFinalRoxieInput> selectedInputs;
  14520. PointerArrayOf<IEngineRowStream> selectedStreams;
  14521. PointerArrayOf<IStrandJunction> selectedJunctions;
  14522. public:
  14523. CRoxieServerNWayInputBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14524. : CRoxieServerMultiInputBaseActivity(_ctx, _factory, _probeManager, _numInputs)
  14525. {
  14526. }
  14527. virtual unsigned __int64 queryLocalCycles() const
  14528. {
  14529. __int64 localCycles = totalCycles.totalCycles;
  14530. ForEachItemIn(i, selectedInputs)
  14531. {
  14532. localCycles -= selectedInputs.item(i)->queryTotalCycles();
  14533. }
  14534. if (localCycles < 0)
  14535. localCycles = 0;
  14536. return localCycles;
  14537. }
  14538. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  14539. {
  14540. if (selectedInputs.isItem(idx))
  14541. return selectedInputs.item(idx);
  14542. else
  14543. return NULL;
  14544. }
  14545. virtual void reset()
  14546. {
  14547. ForEachItemIn(i, selectedInputs)
  14548. selectedInputs.item(i)->reset();
  14549. selectedInputs.kill();
  14550. selectedStreams.kill();
  14551. selectedJunctions.kill();
  14552. CRoxieServerMultiInputBaseActivity::reset();
  14553. }
  14554. virtual const void * nextRow()
  14555. {
  14556. throwUnexpected();
  14557. }
  14558. virtual unsigned numConcreteOutputs() const
  14559. {
  14560. return selectedInputs.ordinality();
  14561. }
  14562. virtual IFinalRoxieInput * queryConcreteInput(unsigned idx)
  14563. {
  14564. return queryInput(idx);
  14565. }
  14566. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput)
  14567. {
  14568. if (selectedStreams.isItem(whichInput))
  14569. return selectedStreams.item(whichInput);
  14570. return NULL;
  14571. }
  14572. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const
  14573. {
  14574. if (selectedJunctions.isItem(idx))
  14575. return selectedJunctions.item(idx);
  14576. return NULL;
  14577. }
  14578. };
  14579. class CRoxieServerNWayInputActivity : public CRoxieServerNWayInputBaseActivity
  14580. {
  14581. IHThorNWayInputArg & helper;
  14582. public:
  14583. CRoxieServerNWayInputActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14584. : CRoxieServerNWayInputBaseActivity(_ctx, _factory, _probeManager, _numInputs), helper((IHThorNWayInputArg &)basehelper)
  14585. {
  14586. }
  14587. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14588. {
  14589. CRoxieServerNWayInputBaseActivity::start(parentExtractSize, parentExtract, paused);
  14590. bool selectionIsAll;
  14591. size32_t selectionLen;
  14592. rtlDataAttr selection;
  14593. helper.getInputSelection(selectionIsAll, selectionLen, selection.refdata());
  14594. selectedInputs.kill();
  14595. selectedStreams.kill();
  14596. selectedJunctions.kill();
  14597. assertex(numInputs==numStreams); // Will need refactoring when that ceases to be true
  14598. if (selectionIsAll)
  14599. {
  14600. for (unsigned i=0; i < numInputs; i++)
  14601. {
  14602. selectedInputs.append(inputArray[i]);
  14603. selectedStreams.append(streamArray[i]); // Assumes 1:1 relationship - is that good?
  14604. selectedJunctions.append(junctionArray[i]);
  14605. }
  14606. }
  14607. else
  14608. {
  14609. const size32_t * selections = (const size32_t *)selection.getdata();
  14610. unsigned max = selectionLen/sizeof(size32_t);
  14611. for (unsigned i = 0; i < max; i++)
  14612. {
  14613. unsigned nextIndex = selections[i];
  14614. //Check there are no duplicates..... Assumes there are a fairly small number of inputs, so n^2 search is ok.
  14615. for (unsigned j=i+1; j < max; j++)
  14616. {
  14617. if (nextIndex == selections[j])
  14618. throw MakeStringException(ROXIE_NWAY_INPUT_ERROR, "Selection list for nway input can not contain duplicates");
  14619. }
  14620. if (nextIndex > numInputs || nextIndex > numStreams)
  14621. throw MakeStringException(ROXIE_NWAY_INPUT_ERROR, "Index %d in RANGE selection list is out of range", nextIndex);
  14622. selectedInputs.append(inputArray[nextIndex-1]);
  14623. selectedStreams.append(streamArray[nextIndex-1]); // Assumes 1:1 relationship - is that good?
  14624. selectedJunctions.append(junctionArray[nextIndex-1]);
  14625. }
  14626. }
  14627. // NB: Whatever pulls this nwayinput activity, starts and stops the selectedInputs and selectedJunctions
  14628. // But the N-Way input itself is now done with processing, and can stop itself/dependencies.
  14629. stop();
  14630. }
  14631. };
  14632. class CRoxieServerNWayInputActivityFactory : public CRoxieServerMultiInputFactory
  14633. {
  14634. public:
  14635. CRoxieServerNWayInputActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  14636. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  14637. {
  14638. }
  14639. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  14640. {
  14641. return new CRoxieServerNWayInputActivity(_ctx, this, _probeManager, numInputs());
  14642. }
  14643. };
  14644. IRoxieServerActivityFactory *createRoxieServerNWayInputActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  14645. {
  14646. return new CRoxieServerNWayInputActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  14647. }
  14648. //=====================================================================================================
  14649. class CRoxieServerNWayGraphLoopResultReadActivity : public CRoxieServerNWayInputBaseActivity
  14650. {
  14651. IHThorNWayGraphLoopResultReadArg & helper;
  14652. IArrayOf<IRoxieServerActivity> resultReaders;
  14653. Owned<IStrandJunction> *resultJunctions;
  14654. unsigned graphId;
  14655. bool grouped;
  14656. bool selectionIsAll;
  14657. size32_t selectionLen;
  14658. rtlDataAttr selection;
  14659. public:
  14660. CRoxieServerNWayGraphLoopResultReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId)
  14661. : CRoxieServerNWayInputBaseActivity(_ctx, _factory, _probeManager, 0), helper((IHThorNWayGraphLoopResultReadArg &)basehelper)
  14662. {
  14663. grouped = helper.isGrouped();
  14664. graphId = _graphId;
  14665. selectionIsAll = false;
  14666. selectionLen = 0;
  14667. resultJunctions = NULL;
  14668. }
  14669. ~CRoxieServerNWayGraphLoopResultReadActivity()
  14670. {
  14671. delete [] resultJunctions;
  14672. }
  14673. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14674. {
  14675. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14676. if (selectedInputs.ordinality() == 0)
  14677. {
  14678. initInputSelection();
  14679. unsigned max = selectionLen / sizeof(size32_t);
  14680. const size32_t * selections = (const size32_t *)selection.getdata();
  14681. IProbeManager * probeManager = NULL; // MORE!!
  14682. for (unsigned i = 0; i < max; i++)
  14683. {
  14684. CRoxieServerActivity * resultInput = new CRoxieServerInternalGraphLoopResultReadActivity(ctx, factory, probeManager, graphId, selections[i]);
  14685. resultReaders.append(*resultInput);
  14686. selectedInputs.append(resultInput);
  14687. resultInput->onCreate(colocalParent);
  14688. resultInput->start(parentExtractSize, parentExtract, paused);
  14689. selectedStreams.append(connectSingleStream(ctx, resultInput, 0, resultJunctions[i], true));
  14690. selectedJunctions.append(resultJunctions[i]);
  14691. }
  14692. }
  14693. // I have done with my processing - note that this won't stop my inputs
  14694. stop();
  14695. }
  14696. virtual void reset()
  14697. {
  14698. resultReaders.kill();
  14699. CRoxieServerNWayInputBaseActivity::reset();
  14700. ForEachItemIn(i, selectedStreams)
  14701. resetJunction(resultJunctions[i]);
  14702. }
  14703. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract)
  14704. {
  14705. ensureCreated();
  14706. basehelper.onStart(parentExtract, NULL);
  14707. initInputSelection();
  14708. unsigned max = selectionLen / sizeof(size32_t);
  14709. const size32_t * selections = (const size32_t *)selection.getdata();
  14710. for (unsigned i = 0; i < max; i++)
  14711. processor.noteUseIteration(selections[i]);
  14712. }
  14713. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract, IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes)
  14714. {
  14715. //selection etc. already initialised from the gatherIterationUsage() call.
  14716. unsigned max = selectionLen / sizeof(size32_t);
  14717. const size32_t * selections = (const size32_t *)selection.getdata();
  14718. resultJunctions = new Owned<IStrandJunction> [max];
  14719. for (unsigned i = 0; i < max; i++)
  14720. {
  14721. IFinalRoxieInput *in = processor.connectIterationOutput(selections[i], probeManager, probes, this, i);
  14722. selectedInputs.append(in);
  14723. selectedStreams.append(connectSingleStream(ctx, in, 0, resultJunctions[i], true));
  14724. selectedJunctions.append(resultJunctions[i]);
  14725. }
  14726. }
  14727. protected:
  14728. void initInputSelection()
  14729. {
  14730. helper.getInputSelection(selectionIsAll, selectionLen, selection.refdata());
  14731. if (selectionIsAll)
  14732. throw MakeStringException(ROXIE_NWAY_INPUT_ERROR, "ALL not yet supported for NWay graph inputs");
  14733. }
  14734. };
  14735. class CRoxieServerNWayGraphLoopResultReadActivityFactory : public CRoxieServerActivityFactory
  14736. {
  14737. unsigned graphId;
  14738. public:
  14739. CRoxieServerNWayGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _graphId)
  14740. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), graphId(_graphId)
  14741. {
  14742. }
  14743. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  14744. {
  14745. return new CRoxieServerNWayGraphLoopResultReadActivity(_ctx, this, _probeManager, graphId);
  14746. }
  14747. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  14748. {
  14749. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for NWay GraphLoopResultRead activity");
  14750. }
  14751. };
  14752. IRoxieServerActivityFactory *createRoxieServerNWayGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned graphId)
  14753. {
  14754. return new CRoxieServerNWayGraphLoopResultReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, graphId);
  14755. }
  14756. //=================================================================================
  14757. class RoxieSteppedInput : implements ISteppedInput, public CInterface
  14758. {
  14759. public:
  14760. RoxieSteppedInput(IFinalRoxieInput * _input, IEngineRowStream *_stream) { input = _input; inputStream = _stream; }
  14761. IMPLEMENT_IINTERFACE
  14762. protected:
  14763. virtual const void * nextInputRow()
  14764. {
  14765. #ifdef TRACE_SEEK_REQUESTS
  14766. IRoxieContextLogger * logger = input->queryActivity();
  14767. const void * ret = doNextInputRow();
  14768. {
  14769. CommonXmlWriter xmlwrite(XWFtrim|XWFopt|XWFnoindent);
  14770. if (!ret)
  14771. xmlwrite.outputBool(true,"eof");
  14772. else if (input->queryOutputMeta()->hasXML())
  14773. input->queryOutputMeta()->toXML((byte *) ret, xmlwrite);
  14774. logger->CTXLOG("next() returns (%s)", xmlwrite.str());
  14775. }
  14776. return ret;
  14777. #else
  14778. return inputStream->ungroupedNextRow();
  14779. #endif
  14780. }
  14781. virtual const void * nextInputRowGE(const void * seek, unsigned numFields, bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  14782. {
  14783. #ifdef TRACE_SEEK_REQUESTS
  14784. IRoxieContextLogger * logger = input->queryActivity();
  14785. {
  14786. CommonXmlWriter xmlwrite(XWFtrim|XWFopt|XWFnoindent);
  14787. if (input->queryOutputMeta()->hasXML())
  14788. input->queryOutputMeta()->toXML((byte *) seek, xmlwrite);
  14789. logger->CTXLOG("nextInputRowGE(%d, %s%s%s, %s) seek(%s)",
  14790. numFields,
  14791. stepExtra.readAheadManyResults() ? "readahead " : "",
  14792. stepExtra.returnMismatches() ? "mismatch" : "exact",
  14793. stepExtra.onlyReturnFirstSeekMatch() ? " single-match" : "",
  14794. stepExtra.queryExtraSeeks() ? "multi-seek":"",
  14795. xmlwrite.str());
  14796. }
  14797. const void * ret = doNextInputRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  14798. {
  14799. CommonXmlWriter xmlwrite(XWFtrim|XWFopt|XWFnoindent);
  14800. if (!ret)
  14801. xmlwrite.outputBool(true,"eof");
  14802. else if (input->queryOutputMeta()->hasXML())
  14803. input->queryOutputMeta()->toXML((byte *) ret, xmlwrite);
  14804. logger->CTXLOG("nextInputRowGE(%d, %s%s%s, %s) result(%s)",
  14805. numFields,
  14806. stepExtra.readAheadManyResults() ? "readahead " : "",
  14807. stepExtra.returnMismatches() ? "mismatch" : "exact",
  14808. stepExtra.onlyReturnFirstSeekMatch() ? " single-match" : "",
  14809. stepExtra.queryExtraSeeks() ? "multi-seek":"",
  14810. xmlwrite.str());
  14811. }
  14812. return ret;
  14813. #else
  14814. return doNextInputRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  14815. #endif
  14816. }
  14817. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  14818. {
  14819. return input->gatherConjunctions(collector);
  14820. }
  14821. virtual void resetEOF()
  14822. {
  14823. inputStream->resetEOF();
  14824. }
  14825. virtual IInputSteppingMeta * queryInputSteppingMeta()
  14826. {
  14827. return input->querySteppingMeta();
  14828. }
  14829. inline const void * doNextInputRowGE(const void * seek, unsigned numFields, bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  14830. {
  14831. assertex(wasCompleteMatch);
  14832. return inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  14833. }
  14834. protected:
  14835. IFinalRoxieInput * input;
  14836. IEngineRowStream * inputStream;
  14837. };
  14838. //=================================================================================
  14839. class CRoxieServerNWayBaseActivity : public CRoxieServerMultiInputBaseActivity
  14840. {
  14841. public:
  14842. CRoxieServerNWayBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14843. : CRoxieServerMultiInputBaseActivity(_ctx, _factory, _probeManager, _numInputs)
  14844. {
  14845. }
  14846. void startExpandedInputs(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14847. {
  14848. ForEachItemIn(ei, expandedInputs)
  14849. expandedInputs.item(ei)->start(parentExtractSize, parentExtract, paused);
  14850. ForEachItemIn(idx, expandedInputs)
  14851. startJunction(expandedJunctions.item(idx));
  14852. }
  14853. virtual void stop()
  14854. {
  14855. ForEachItemIn(i, expandedStreams)
  14856. expandedStreams.item(i)->stop();
  14857. CRoxieServerMultiInputBaseActivity::stop();
  14858. }
  14859. virtual void reset()
  14860. {
  14861. ForEachItemIn(idx, expandedInputs)
  14862. resetJunction(expandedJunctions.item(idx));
  14863. expandedInputs.kill();
  14864. expandedStreams.kill();
  14865. expandedJunctions.kill();
  14866. CRoxieServerMultiInputBaseActivity::reset();
  14867. }
  14868. protected:
  14869. PointerArrayOf<IFinalRoxieInput> expandedInputs;
  14870. PointerArrayOf<IEngineRowStream> expandedStreams;
  14871. PointerArrayOf<IStrandJunction> expandedJunctions;
  14872. };
  14873. //=================================================================================
  14874. class CRoxieServerNaryActivity : public CRoxieServerNWayBaseActivity
  14875. {
  14876. public:
  14877. CRoxieServerNaryActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14878. : CRoxieServerNWayBaseActivity(_ctx, _factory, _probeManager, _numInputs)
  14879. {
  14880. }
  14881. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14882. {
  14883. CRoxieServerNWayBaseActivity::start(parentExtractSize, parentExtract, paused);
  14884. for (unsigned i=0; i < numInputs; i++)
  14885. {
  14886. IFinalRoxieInput * cur = inputArray[i];
  14887. CRoxieServerNWayInputBaseActivity *nWayInput = dynamic_cast<CRoxieServerNWayInputBaseActivity *>(cur);
  14888. if (nWayInput)
  14889. {
  14890. nWayInput->start(parentExtractSize, parentExtract, paused);
  14891. unsigned numRealInputs = cur->numConcreteOutputs();
  14892. for (unsigned j = 0; j < numRealInputs; j++)
  14893. {
  14894. expandedInputs.append(cur->queryConcreteInput(j));
  14895. expandedStreams.append(cur->queryConcreteOutputStream(j));
  14896. expandedJunctions.append(cur->queryConcreteOutputJunction(j));
  14897. }
  14898. }
  14899. else
  14900. {
  14901. expandedInputs.append(cur);
  14902. // NB: this activities input streams + junction have been setup and held in CRoxieServerMultiInputActivity base
  14903. expandedStreams.append(queryConcreteOutputStream(i));
  14904. expandedJunctions.append(queryConcreteOutputJunction(i));
  14905. }
  14906. }
  14907. startExpandedInputs(parentExtractSize, parentExtract, paused);
  14908. }
  14909. };
  14910. //=================================================================================
  14911. class CRoxieStreamMerger : public CStreamMerger
  14912. {
  14913. public:
  14914. CRoxieStreamMerger() : CStreamMerger(true)
  14915. {
  14916. streamArray = NULL;
  14917. }
  14918. void initInputs(unsigned _numInputs, IEngineRowStream ** _streamArray)
  14919. {
  14920. CStreamMerger::initInputs(_numInputs);
  14921. streamArray = _streamArray;
  14922. }
  14923. virtual bool pullInput(unsigned i, const void * seek, unsigned numFields, const SmartStepExtra * stepExtra)
  14924. {
  14925. const void * next;
  14926. bool matches = true;
  14927. if (seek)
  14928. next = streamArray[i]->nextRowGE(seek, numFields, matches, *stepExtra);
  14929. else
  14930. next = streamArray[i]->ungroupedNextRow();
  14931. pending[i] = next;
  14932. pendingMatches[i] = matches;
  14933. return (next != NULL);
  14934. }
  14935. virtual void releaseRow(const void * row)
  14936. {
  14937. ReleaseRoxieRow(row);
  14938. }
  14939. protected:
  14940. IEngineRowStream **streamArray;
  14941. };
  14942. class CRoxieServerNWayMergeActivity : public CRoxieServerNaryActivity
  14943. {
  14944. public:
  14945. CRoxieServerNWayMergeActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14946. : CRoxieServerNaryActivity(_ctx, _factory, _probeManager, _numInputs),
  14947. helper((IHThorNWayMergeArg &)basehelper)
  14948. {
  14949. initializedMeta = false;
  14950. }
  14951. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14952. {
  14953. CRoxieServerNaryActivity::start(parentExtractSize, parentExtract, paused);
  14954. merger.init(helper.queryCompare(), helper.dedup(), helper.querySteppingMeta()->queryCompare());
  14955. merger.initInputs(expandedStreams.length(), expandedStreams.getArray());
  14956. }
  14957. virtual void stop()
  14958. {
  14959. merger.done();
  14960. CRoxieServerNaryActivity::stop();
  14961. }
  14962. virtual void reset()
  14963. {
  14964. merger.cleanup();
  14965. CRoxieServerNaryActivity::reset();
  14966. initializedMeta = false;
  14967. }
  14968. virtual const void * nextRow()
  14969. {
  14970. ActivityTimer t(totalCycles, timeActivities);
  14971. const void * next = merger.nextRow();
  14972. if (next)
  14973. processed++;
  14974. return next;
  14975. }
  14976. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  14977. {
  14978. ActivityTimer t(totalCycles, timeActivities);
  14979. const void * next = merger.nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  14980. if (next)
  14981. processed++;
  14982. return next;
  14983. }
  14984. virtual IInputSteppingMeta * querySteppingMeta()
  14985. {
  14986. if (expandedStreams.ordinality() == 0)
  14987. return NULL;
  14988. if (!initializedMeta)
  14989. {
  14990. meta.init(helper.querySteppingMeta(), false);
  14991. ForEachItemIn(i, expandedStreams)
  14992. {
  14993. if (meta.getNumFields() == 0)
  14994. break;
  14995. IInputSteppingMeta * inputMeta = expandedInputs.item(i)->querySteppingMeta();
  14996. meta.intersect(inputMeta);
  14997. }
  14998. initializedMeta = true;
  14999. }
  15000. if (meta.getNumFields() == 0)
  15001. return NULL;
  15002. return &meta;
  15003. }
  15004. protected:
  15005. IHThorNWayMergeArg &helper;
  15006. CRoxieStreamMerger merger;
  15007. CSteppingMeta meta;
  15008. bool initializedMeta;
  15009. };
  15010. class CRoxieServerNWayMergeActivityFactory : public CRoxieServerMultiInputFactory
  15011. {
  15012. public:
  15013. CRoxieServerNWayMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15014. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15015. {
  15016. }
  15017. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15018. {
  15019. return new CRoxieServerNWayMergeActivity(_ctx, this, _probeManager, numInputs());
  15020. }
  15021. };
  15022. IRoxieServerActivityFactory *createRoxieServerNWayMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15023. {
  15024. return new CRoxieServerNWayMergeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15025. }
  15026. //=================================================================================
  15027. class CRoxieServerNWayMergeJoinActivity : public CRoxieServerNaryActivity
  15028. {
  15029. public:
  15030. CRoxieServerNWayMergeJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs, CMergeJoinProcessor & _processor)
  15031. : CRoxieServerNaryActivity(_ctx, _factory, _probeManager, _numInputs),processor(_processor),
  15032. helper((IHThorNWayMergeJoinArg &)basehelper)
  15033. {
  15034. }
  15035. virtual void onCreate(IHThorArg *_colocalParent)
  15036. {
  15037. CRoxieServerNaryActivity::onCreate(_colocalParent);
  15038. ICodeContext * codectx = ctx->queryCodeContext();
  15039. inputAllocator.setown(createRowAllocator(helper.queryInputMeta()));
  15040. outputAllocator.setown(createRowAllocator(helper.queryOutputMeta()));
  15041. }
  15042. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15043. {
  15044. CRoxieServerNaryActivity::start(parentExtractSize, parentExtract, paused);
  15045. ForEachItemIn(i1, expandedInputs)
  15046. {
  15047. Owned<RoxieSteppedInput> stepInput = new RoxieSteppedInput(expandedInputs.item(i1), expandedStreams.item(i1));
  15048. processor.addInput(stepInput);
  15049. }
  15050. processor.beforeProcessing(inputAllocator, outputAllocator);
  15051. }
  15052. virtual void stop()
  15053. {
  15054. processor.afterProcessing();
  15055. CRoxieServerNaryActivity::stop();
  15056. }
  15057. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  15058. {
  15059. return processor.gatherConjunctions(collector);
  15060. }
  15061. virtual void resetEOF()
  15062. {
  15063. processor.queryResetEOF();
  15064. }
  15065. virtual const void * nextRow()
  15066. {
  15067. ActivityTimer t(totalCycles, timeActivities);
  15068. const void * next = processor.nextRow();
  15069. if (next)
  15070. processed++;
  15071. return next;
  15072. }
  15073. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  15074. {
  15075. ActivityTimer t(totalCycles, timeActivities);
  15076. const void * next = processor.nextGE(seek, numFields, wasCompleteMatch, stepExtra);
  15077. if (next)
  15078. processed++;
  15079. return next;
  15080. }
  15081. virtual IInputSteppingMeta * querySteppingMeta()
  15082. {
  15083. return processor.queryInputSteppingMeta();
  15084. }
  15085. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  15086. {
  15087. CRoxieServerNaryActivity::gatherStats(merged);
  15088. if (inputAllocator)
  15089. inputAllocator->gatherStats(merged);
  15090. if (outputAllocator)
  15091. outputAllocator->gatherStats(merged);
  15092. }
  15093. protected:
  15094. IHThorNWayMergeJoinArg & helper;
  15095. CMergeJoinProcessor & processor;
  15096. Owned<IEngineRowAllocator> inputAllocator;
  15097. Owned<IEngineRowAllocator> outputAllocator;
  15098. };
  15099. class CRoxieServerAndMergeJoinActivity : public CRoxieServerNWayMergeJoinActivity
  15100. {
  15101. public:
  15102. CRoxieServerAndMergeJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  15103. : CRoxieServerNWayMergeJoinActivity(_ctx, _factory, _probeManager, _numInputs, andProcessor), andProcessor(helper)
  15104. {
  15105. }
  15106. protected:
  15107. CAndMergeJoinProcessor andProcessor;
  15108. };
  15109. class CRoxieServerAndLeftMergeJoinActivity : public CRoxieServerNWayMergeJoinActivity
  15110. {
  15111. public:
  15112. CRoxieServerAndLeftMergeJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  15113. : CRoxieServerNWayMergeJoinActivity(_ctx, _factory, _probeManager, _numInputs, andLeftProcessor), andLeftProcessor(helper)
  15114. {
  15115. }
  15116. protected:
  15117. CAndLeftMergeJoinProcessor andLeftProcessor;
  15118. };
  15119. class CRoxieServerMofNMergeJoinActivity : public CRoxieServerNWayMergeJoinActivity
  15120. {
  15121. public:
  15122. CRoxieServerMofNMergeJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  15123. : CRoxieServerNWayMergeJoinActivity(_ctx, _factory, _probeManager, _numInputs, mofnProcessor), mofnProcessor(helper)
  15124. {
  15125. }
  15126. protected:
  15127. CMofNMergeJoinProcessor mofnProcessor;
  15128. };
  15129. class CRoxieServerProximityJoinActivity : public CRoxieServerNWayMergeJoinActivity
  15130. {
  15131. public:
  15132. CRoxieServerProximityJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  15133. : CRoxieServerNWayMergeJoinActivity(_ctx, _factory, _probeManager, _numInputs, proximityProcessor), proximityProcessor(helper)
  15134. {
  15135. }
  15136. protected:
  15137. CProximityJoinProcessor proximityProcessor;
  15138. };
  15139. class CRoxieServerNWayMergeJoinActivityFactory : public CRoxieServerMultiInputFactory
  15140. {
  15141. unsigned flags;
  15142. public:
  15143. CRoxieServerNWayMergeJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15144. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15145. {
  15146. Owned<IHThorNWayMergeJoinArg> helper = (IHThorNWayMergeJoinArg *) helperFactory();
  15147. flags = helper->getJoinFlags();
  15148. }
  15149. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15150. {
  15151. if (flags & IHThorNWayMergeJoinArg::MJFhasrange)
  15152. return new CRoxieServerProximityJoinActivity(_ctx, this, _probeManager, numInputs());
  15153. switch (flags & IHThorNWayMergeJoinArg::MJFkindmask)
  15154. {
  15155. case IHThorNWayMergeJoinArg::MJFinner:
  15156. return new CRoxieServerAndMergeJoinActivity(_ctx, this, _probeManager, numInputs());
  15157. case IHThorNWayMergeJoinArg::MJFleftonly:
  15158. case IHThorNWayMergeJoinArg::MJFleftouter:
  15159. return new CRoxieServerAndLeftMergeJoinActivity(_ctx, this, _probeManager, numInputs());
  15160. case IHThorNWayMergeJoinArg::MJFmofn:
  15161. return new CRoxieServerMofNMergeJoinActivity(_ctx, this, _probeManager, numInputs());
  15162. default:
  15163. throwUnexpected();
  15164. }
  15165. }
  15166. };
  15167. IRoxieServerActivityFactory *createRoxieServerNWayMergeJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15168. {
  15169. return new CRoxieServerNWayMergeJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15170. }
  15171. //=================================================================================
  15172. class CRoxieServerNWaySelectActivity : public CRoxieServerNWayBaseActivity
  15173. {
  15174. IHThorNWaySelectArg &helper;
  15175. public:
  15176. CRoxieServerNWaySelectActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  15177. : CRoxieServerNWayBaseActivity(_ctx, _factory, _probeManager, _numInputs),
  15178. helper((IHThorNWaySelectArg &)basehelper)
  15179. {
  15180. }
  15181. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15182. {
  15183. CRoxieServerNWayBaseActivity::start(parentExtractSize, parentExtract, paused);
  15184. unsigned whichInput = helper.getInputIndex();
  15185. selectedInput = nullptr;
  15186. selectedStream = nullptr;
  15187. if (whichInput--)
  15188. {
  15189. for (unsigned i=0; i < numInputs; i++)
  15190. {
  15191. IFinalRoxieInput * cur = inputArray[i];
  15192. CRoxieServerNWayInputBaseActivity *nWayInput = dynamic_cast<CRoxieServerNWayInputBaseActivity *>(cur);
  15193. if (nWayInput)
  15194. {
  15195. nWayInput->start(parentExtractSize, parentExtract, paused);
  15196. unsigned numRealInputs = cur->numConcreteOutputs();
  15197. if (whichInput < numRealInputs)
  15198. {
  15199. expandedInputs.append(cur->queryConcreteInput(whichInput));
  15200. expandedStreams.append(cur->queryConcreteOutputStream(whichInput));
  15201. expandedJunctions.append(cur->queryConcreteOutputJunction(whichInput));
  15202. break;
  15203. }
  15204. whichInput -= numRealInputs;
  15205. }
  15206. else
  15207. {
  15208. if (whichInput == 0)
  15209. {
  15210. expandedInputs.append(cur);
  15211. // NB: this activities input streams + junction have been setup and held in CRoxieServerMultiInputActivity base
  15212. expandedStreams.append(queryConcreteOutputStream(i));
  15213. expandedJunctions.append(queryConcreteOutputJunction(i));
  15214. break;
  15215. }
  15216. whichInput -= 1;
  15217. }
  15218. }
  15219. }
  15220. if (expandedInputs.ordinality())
  15221. {
  15222. startExpandedInputs(parentExtractSize, parentExtract, paused);
  15223. selectedInput = expandedInputs.item(0);
  15224. selectedStream = expandedStreams.item(0);
  15225. }
  15226. }
  15227. const void * nextRow()
  15228. {
  15229. ActivityTimer t(totalCycles, timeActivities);
  15230. if (!selectedStream)
  15231. return NULL;
  15232. return selectedStream->nextRow();
  15233. }
  15234. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  15235. {
  15236. if (!selectedInput)
  15237. return false;
  15238. return selectedInput->gatherConjunctions(collector);
  15239. }
  15240. virtual void resetEOF()
  15241. {
  15242. if (selectedStream)
  15243. selectedStream->resetEOF();
  15244. }
  15245. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  15246. {
  15247. ActivityTimer t(totalCycles, timeActivities);
  15248. if (!selectedStream)
  15249. return NULL;
  15250. return selectedStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  15251. }
  15252. IInputSteppingMeta * querySteppingMeta()
  15253. {
  15254. if (selectedInput)
  15255. return selectedInput->querySteppingMeta();
  15256. return NULL;
  15257. }
  15258. protected:
  15259. IFinalRoxieInput * selectedInput = nullptr;
  15260. IEngineRowStream * selectedStream = nullptr;
  15261. Owned<IStrandJunction> selectedJunction;
  15262. };
  15263. class CRoxieServerNWaySelectActivityFactory : public CRoxieServerMultiInputFactory
  15264. {
  15265. public:
  15266. CRoxieServerNWaySelectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15267. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15268. {
  15269. }
  15270. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15271. {
  15272. return new CRoxieServerNWaySelectActivity(_ctx, this, _probeManager, numInputs());
  15273. }
  15274. };
  15275. IRoxieServerActivityFactory *createRoxieServerNWaySelectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15276. {
  15277. return new CRoxieServerNWaySelectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15278. }
  15279. //=================================================================================
  15280. class CRoxieServerRemoteActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler
  15281. {
  15282. protected:
  15283. IHThorRemoteArg &helper;
  15284. CRemoteResultAdaptor remote;
  15285. public:
  15286. CRoxieServerRemoteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteID)
  15287. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  15288. helper((IHThorRemoteArg &)basehelper),
  15289. remote(_ctx, this, _remoteID, meta.queryOriginal(), helper, *this, false, false) // MORE - if they need it stable we'll have to think!
  15290. {
  15291. }
  15292. virtual const IResolvedFile *queryVarFileInfo() const
  15293. {
  15294. return NULL;
  15295. }
  15296. virtual void onCreate(IHThorArg *_colocalParent)
  15297. {
  15298. CRoxieServerActivity::onCreate(_colocalParent);
  15299. remote.onCreate(_colocalParent);
  15300. }
  15301. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15302. {
  15303. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  15304. remote.onStart(parentExtractSize, parentExtract);
  15305. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  15306. unsigned fileNo = 0; // MORE - superfiles require us to do this per file part... maybe (needs thought)
  15307. remote.getMem(0, fileNo, 0); // the cached context is all we need to send
  15308. remote.flush();
  15309. remote.senddone();
  15310. }
  15311. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  15312. {
  15313. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  15314. }
  15315. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  15316. {
  15317. if (idx==(unsigned)-1)
  15318. idx = 0;
  15319. return idx ? NULL: &remote;
  15320. }
  15321. virtual void reset()
  15322. {
  15323. processed = remote.processed;
  15324. remote.processed = 0;
  15325. CRoxieServerActivity::reset();
  15326. }
  15327. virtual void onLimitExceeded(bool isKeyed)
  15328. {
  15329. if (traceLevel > 4)
  15330. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  15331. helper.onLimitExceeded();
  15332. }
  15333. virtual const void *createLimitFailRow(bool isKeyed)
  15334. {
  15335. UNIMPLEMENTED; // MORE - is there an ONFAIL for a limit folded into a remote?
  15336. }
  15337. virtual const void *nextRow()
  15338. {
  15339. throwUnexpected(); // I am nobody's input
  15340. }
  15341. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  15342. {
  15343. CRoxieServerActivity::gatherStats(merged);
  15344. remote.gatherStats(merged);
  15345. }
  15346. };
  15347. class CRoxieServerRemoteActivityFactory : public CRoxieServerActivityFactory
  15348. {
  15349. public:
  15350. RemoteActivityId remoteId;
  15351. bool isRoot;
  15352. CRoxieServerRemoteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId, bool _isRoot)
  15353. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), remoteId(_remoteId), isRoot(_isRoot)
  15354. {
  15355. }
  15356. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15357. {
  15358. return new CRoxieServerRemoteActivity(_ctx, this, _probeManager, remoteId);
  15359. }
  15360. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  15361. {
  15362. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  15363. }
  15364. virtual bool isSink() const
  15365. {
  15366. //I don't think the action version of this is implemented - but this would be the code
  15367. return isRoot && !meta.queryOriginal();
  15368. }
  15369. virtual const StatisticsMapping &queryStatsMapping() const
  15370. {
  15371. return allStatistics; // Child queries...
  15372. }
  15373. };
  15374. IRoxieServerActivityFactory *createRoxieServerRemoteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId, bool _isRoot)
  15375. {
  15376. return new CRoxieServerRemoteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId, _isRoot);
  15377. }
  15378. //=================================================================================
  15379. class CRoxieServerIterateActivity : public CRoxieServerActivity
  15380. {
  15381. IHThorIterateArg &helper;
  15382. OwnedConstRoxieRow defaultRecord;
  15383. OwnedConstRoxieRow left;
  15384. OwnedConstRoxieRow right;
  15385. unsigned counter;
  15386. public:
  15387. CRoxieServerIterateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  15388. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  15389. helper((IHThorIterateArg &)basehelper)
  15390. {
  15391. counter = 0;
  15392. }
  15393. virtual bool needsAllocator() const { return true; }
  15394. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15395. {
  15396. counter = 0;
  15397. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  15398. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15399. size32_t thisSize = helper.createDefault(rowBuilder);
  15400. defaultRecord.setown(rowBuilder.finalizeRowClear(thisSize));
  15401. }
  15402. virtual void reset()
  15403. {
  15404. defaultRecord.clear();
  15405. right.clear();
  15406. left.clear();
  15407. CRoxieServerActivity::reset();
  15408. }
  15409. virtual const void * nextRow()
  15410. {
  15411. ActivityTimer t(totalCycles, timeActivities);
  15412. for (;;)
  15413. {
  15414. right.setown(inputStream->nextRow());
  15415. if (!right)
  15416. {
  15417. bool skippedGroup = (left == NULL) && (counter > 0); //we have just skipped entire group, but shouldn't output a double null
  15418. left.clear();
  15419. counter = 0;
  15420. if (skippedGroup) continue;
  15421. return NULL;
  15422. }
  15423. try
  15424. {
  15425. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15426. unsigned outSize = helper.transform(rowBuilder, left ? left : defaultRecord, right, ++counter);
  15427. if (outSize)
  15428. {
  15429. left.setown(rowBuilder.finalizeRowClear(outSize));
  15430. processed++;
  15431. return left.getLink();
  15432. }
  15433. }
  15434. catch (IException *E)
  15435. {
  15436. throw makeWrappedException(E);
  15437. }
  15438. }
  15439. }
  15440. };
  15441. class CRoxieServerIterateActivityFactory : public CRoxieServerActivityFactory
  15442. {
  15443. public:
  15444. CRoxieServerIterateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15445. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15446. {
  15447. }
  15448. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15449. {
  15450. return new CRoxieServerIterateActivity(_ctx, this, _probeManager);
  15451. }
  15452. };
  15453. IRoxieServerActivityFactory *createRoxieServerIterateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15454. {
  15455. return new CRoxieServerIterateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15456. }
  15457. //=================================================================================
  15458. class CRoxieServerProcessActivity : public CRoxieServerActivity
  15459. {
  15460. IHThorProcessArg &helper;
  15461. OwnedConstRoxieRow curRight;
  15462. OwnedConstRoxieRow initialRight;
  15463. unsigned counter;
  15464. Owned<IEngineRowAllocator> rightRowAllocator;
  15465. public:
  15466. CRoxieServerProcessActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  15467. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorProcessArg &)basehelper)
  15468. {
  15469. counter = 0;
  15470. }
  15471. virtual bool needsAllocator() const { return true; }
  15472. virtual void onCreate(IHThorArg *_colocalParent)
  15473. {
  15474. CRoxieServerActivity::onCreate(_colocalParent);
  15475. rightRowAllocator.setown(createRowAllocator(helper.queryRightRecordSize()));
  15476. }
  15477. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15478. {
  15479. counter = 0;
  15480. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  15481. RtlDynamicRowBuilder rowBuilder(rightRowAllocator);
  15482. size32_t thisSize = helper.createInitialRight(rowBuilder);
  15483. initialRight.setown(rowBuilder.finalizeRowClear(thisSize));
  15484. curRight.set(initialRight);
  15485. }
  15486. virtual const void * nextRow()
  15487. {
  15488. ActivityTimer t(totalCycles, timeActivities);
  15489. try
  15490. {
  15491. for (;;)
  15492. {
  15493. const void * in = inputStream->nextRow();
  15494. if (!in)
  15495. {
  15496. bool eog = (curRight != initialRight); // processed any records?
  15497. counter = 0;
  15498. curRight.set(initialRight);
  15499. if (eog)
  15500. return NULL;
  15501. in = inputStream->nextRow();
  15502. if (!in)
  15503. return NULL;
  15504. }
  15505. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15506. RtlDynamicRowBuilder rightRowBuilder(rightRowAllocator);
  15507. size32_t outSize = helper.transform(rowBuilder, rightRowBuilder, in, curRight, ++counter);
  15508. ReleaseRoxieRow(in);
  15509. if (outSize)
  15510. {
  15511. //MORE: This should be returned...
  15512. size32_t rightSize = rightRowAllocator->queryOutputMeta()->getRecordSize(rightRowBuilder.getSelf());
  15513. curRight.setown(rightRowBuilder.finalizeRowClear(rightSize));
  15514. processed++;
  15515. return rowBuilder.finalizeRowClear(outSize);
  15516. }
  15517. }
  15518. }
  15519. catch (IException *E)
  15520. {
  15521. throw makeWrappedException(E);
  15522. }
  15523. }
  15524. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  15525. {
  15526. CRoxieServerActivity::gatherStats(merged);
  15527. if (rightRowAllocator)
  15528. rightRowAllocator->gatherStats(merged);
  15529. }
  15530. };
  15531. class CRoxieServerProcessActivityFactory : public CRoxieServerActivityFactory
  15532. {
  15533. public:
  15534. CRoxieServerProcessActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15535. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15536. {
  15537. }
  15538. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15539. {
  15540. return new CRoxieServerProcessActivity(_ctx, this, _probeManager);
  15541. }
  15542. };
  15543. IRoxieServerActivityFactory *createRoxieServerProcessActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15544. {
  15545. return new CRoxieServerProcessActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15546. }
  15547. //=================================================================================
  15548. class CRoxieServerGroupActivity : public CRoxieServerActivity
  15549. {
  15550. IHThorGroupArg &helper;
  15551. bool endPending;
  15552. bool eof;
  15553. bool first;
  15554. unsigned numGroups;
  15555. unsigned numGroupMax;
  15556. unsigned numProcessedLastGroup;
  15557. const void *next;
  15558. public:
  15559. CRoxieServerGroupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  15560. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorGroupArg &)basehelper)
  15561. {
  15562. next = NULL;
  15563. endPending = false;
  15564. eof = false;
  15565. first = true;
  15566. numGroups = 0;
  15567. numGroupMax = 0;
  15568. numProcessedLastGroup = 0;
  15569. }
  15570. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15571. {
  15572. endPending = false;
  15573. eof = false;
  15574. first = true;
  15575. numGroups = 0;
  15576. numGroupMax = 0;
  15577. numProcessedLastGroup = processed;
  15578. assertex(next == NULL);
  15579. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  15580. }
  15581. virtual void reset()
  15582. {
  15583. noteStatistic(StNumGroups, numGroups);
  15584. noteStatistic(StNumGroupMax, numGroupMax);
  15585. ReleaseClearRoxieRow(next);
  15586. CRoxieServerActivity::reset();
  15587. }
  15588. virtual const void * nextRow()
  15589. {
  15590. ActivityTimer t(totalCycles, timeActivities);
  15591. if (first)
  15592. {
  15593. next = inputStream->nextRow();
  15594. first = false;
  15595. }
  15596. if (eof || endPending)
  15597. {
  15598. endPending = false;
  15599. return NULL;
  15600. }
  15601. const void * prev = next;
  15602. next = inputStream->ungroupedNextRow();
  15603. if (next)
  15604. {
  15605. assertex(prev);
  15606. if (!helper.isSameGroup(prev, next))
  15607. {
  15608. noteEndOfGroup();
  15609. endPending = true;
  15610. }
  15611. }
  15612. else
  15613. {
  15614. noteEndOfGroup();
  15615. eof = true;
  15616. }
  15617. if (prev)
  15618. processed++;
  15619. return prev;
  15620. }
  15621. inline void noteEndOfGroup()
  15622. {
  15623. unsigned numThisGroup = processed - numProcessedLastGroup;
  15624. if (numThisGroup == 0)
  15625. return;
  15626. numProcessedLastGroup = processed;
  15627. if (numThisGroup > numGroupMax)
  15628. numGroupMax = numThisGroup;
  15629. numGroups++;
  15630. }
  15631. };
  15632. class CRoxieServerGroupActivityFactory : public CRoxieServerActivityFactory
  15633. {
  15634. public:
  15635. CRoxieServerGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15636. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15637. {
  15638. }
  15639. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15640. {
  15641. return new CRoxieServerGroupActivity(_ctx, this, _probeManager);
  15642. }
  15643. virtual const StatisticsMapping &queryStatsMapping() const
  15644. {
  15645. return groupStatistics;
  15646. }
  15647. };
  15648. IRoxieServerActivityFactory *createRoxieServerGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15649. {
  15650. return new CRoxieServerGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15651. }
  15652. //=================================================================================
  15653. class CRoxieServerFirstNActivity : public CRoxieServerLateStartActivity
  15654. {
  15655. unsigned __int64 limit;
  15656. unsigned __int64 skip;
  15657. unsigned doneThisGroup;
  15658. IHThorFirstNArg &helper;
  15659. public:
  15660. CRoxieServerFirstNActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  15661. : CRoxieServerLateStartActivity(_ctx, _factory, _probeManager), helper((IHThorFirstNArg &)basehelper)
  15662. {
  15663. doneThisGroup = 0;
  15664. limit = 0;
  15665. skip = 0;
  15666. }
  15667. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15668. {
  15669. doneThisGroup = 0;
  15670. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  15671. limit = helper.getLimit();
  15672. skip = helper.numToSkip();
  15673. lateStart(parentExtractSize, parentExtract, limit > 0);
  15674. if (limit + skip >= limit)
  15675. limit += skip;
  15676. }
  15677. const void * nextRow()
  15678. {
  15679. ActivityTimer t(totalCycles, timeActivities);
  15680. if (eof)
  15681. return NULL;
  15682. const void *ret;
  15683. for (;;)
  15684. {
  15685. ret = inputStream->nextRow();
  15686. if (!ret)
  15687. {
  15688. if (meta.isGrouped())
  15689. {
  15690. if (doneThisGroup > skip)
  15691. {
  15692. doneThisGroup = 0;
  15693. return NULL;
  15694. }
  15695. doneThisGroup = 0;
  15696. }
  15697. ret = inputStream->nextRow();
  15698. if (!ret)
  15699. {
  15700. eof = true;
  15701. return NULL;
  15702. }
  15703. }
  15704. doneThisGroup++;
  15705. if (doneThisGroup > skip)
  15706. break;
  15707. ReleaseRoxieRow(ret);
  15708. }
  15709. if (doneThisGroup <= limit)
  15710. {
  15711. processed++;
  15712. return ret;
  15713. }
  15714. ReleaseRoxieRow(ret);
  15715. if (meta.isGrouped())
  15716. {
  15717. while ((ret = inputStream->nextRow()) != NULL)
  15718. ReleaseRoxieRow(ret);
  15719. doneThisGroup = 0;
  15720. }
  15721. else
  15722. eof = true;
  15723. return NULL;
  15724. }
  15725. };
  15726. class CRoxieServerFirstNActivityFactory : public CRoxieServerActivityFactory
  15727. {
  15728. public:
  15729. CRoxieServerFirstNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15730. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15731. {
  15732. }
  15733. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15734. {
  15735. return new CRoxieServerFirstNActivity(_ctx, this, _probeManager);
  15736. }
  15737. };
  15738. IRoxieServerActivityFactory *createRoxieServerFirstNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15739. {
  15740. return new CRoxieServerFirstNActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15741. }
  15742. //=================================================================================
  15743. class CRoxieServerSelectNActivity : public CRoxieServerActivity
  15744. {
  15745. bool done;
  15746. IHThorSelectNArg &helper;
  15747. public:
  15748. CRoxieServerSelectNActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  15749. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorSelectNArg &)basehelper)
  15750. {
  15751. done = false;
  15752. }
  15753. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15754. {
  15755. done = false;
  15756. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  15757. }
  15758. const void *defaultRow()
  15759. {
  15760. if (!rowAllocator)
  15761. ensureRowAllocator(); // We delay as often not needed...
  15762. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15763. size32_t thisSize = helper.createDefault(rowBuilder);
  15764. return rowBuilder.finalizeRowClear(thisSize);
  15765. }
  15766. virtual const void * nextRow()
  15767. {
  15768. ActivityTimer t(totalCycles, timeActivities);
  15769. if (done)
  15770. return NULL;
  15771. done = true;
  15772. processed++; // always going to return a row!
  15773. unsigned __int64 index = helper.getRowToSelect();
  15774. while (--index)
  15775. {
  15776. const void * next = inputStream->ungroupedNextRow();
  15777. if (!next)
  15778. return defaultRow();
  15779. ReleaseRoxieRow(next);
  15780. }
  15781. const void * next = inputStream->ungroupedNextRow();
  15782. if (!next)
  15783. next = defaultRow();
  15784. return next;
  15785. }
  15786. };
  15787. class CRoxieServerSelectNActivityFactory : public CRoxieServerActivityFactory
  15788. {
  15789. public:
  15790. CRoxieServerSelectNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15791. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15792. {
  15793. }
  15794. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15795. {
  15796. return new CRoxieServerSelectNActivity(_ctx, this, _probeManager);
  15797. }
  15798. };
  15799. IRoxieServerActivityFactory *createRoxieServerSelectNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15800. {
  15801. return new CRoxieServerSelectNActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15802. }
  15803. //=================================================================================
  15804. class CRoxieServerSelfJoinActivity : public CRoxieServerActivity
  15805. {
  15806. IHThorJoinArg &helper;
  15807. ICompare *collate;
  15808. OwnedRowArray group;
  15809. bool matchedLeft;
  15810. BoolArray matchedRight;
  15811. bool eof;
  15812. bool first;
  15813. unsigned leftIndex;
  15814. unsigned rightIndex;
  15815. unsigned rightOuterIndex;
  15816. unsigned joinLimit;
  15817. unsigned atmostLimit;
  15818. unsigned atmostsTriggered;
  15819. unsigned abortLimit;
  15820. unsigned keepLimit;
  15821. unsigned joinCounter;
  15822. bool leftOuterJoin;
  15823. bool rightOuterJoin;
  15824. bool exclude;
  15825. bool limitFail;
  15826. bool limitOnFail;
  15827. bool cloneLeft;
  15828. bool forceSpill;
  15829. OwnedConstRoxieRow defaultLeft;
  15830. OwnedConstRoxieRow defaultRight;
  15831. OwnedConstRoxieRow lhs;
  15832. Owned<IException> failingLimit;
  15833. bool failingOuterAtmost;
  15834. Owned<IEngineRowAllocator> defaultAllocator;
  15835. Owned<IRHLimitedCompareHelper> limitedhelper;
  15836. Owned<CRHDualCache> dualcache;
  15837. Owned<IGroupedInput> groupedInput;
  15838. IRowStream *dualCacheInput;
  15839. bool fillGroup()
  15840. {
  15841. group.clear();
  15842. matchedLeft = false;
  15843. matchedRight.kill();
  15844. failingOuterAtmost = false;
  15845. const void * next;
  15846. unsigned groupCount = 0;
  15847. while((next = groupedInput->nextRow()) != NULL)
  15848. {
  15849. if(groupCount==abortLimit)
  15850. {
  15851. if(limitFail)
  15852. failLimit(next);
  15853. if (ctx->queryDebugContext())
  15854. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  15855. if(limitOnFail)
  15856. {
  15857. assertex(!failingLimit);
  15858. try
  15859. {
  15860. failLimit(next);
  15861. }
  15862. catch(IException * except)
  15863. {
  15864. failingLimit.setown(except);
  15865. }
  15866. assertex(failingLimit != NULL);
  15867. group.append(next);
  15868. groupCount++;
  15869. break;
  15870. }
  15871. group.clear();
  15872. groupCount = 0;
  15873. while(next)
  15874. {
  15875. ReleaseRoxieRow(next);
  15876. next = groupedInput->nextRow();
  15877. }
  15878. }
  15879. else if(groupCount==atmostLimit)
  15880. {
  15881. atmostsTriggered++;
  15882. if(leftOuterJoin)
  15883. {
  15884. group.append(next);
  15885. groupCount++;
  15886. failingOuterAtmost = true;
  15887. break;
  15888. }
  15889. else
  15890. {
  15891. group.clear();
  15892. groupCount = 0;
  15893. while (next)
  15894. {
  15895. ReleaseRoxieRow(next);
  15896. next = groupedInput->nextRow();
  15897. }
  15898. }
  15899. }
  15900. else
  15901. {
  15902. group.append(next);
  15903. groupCount++;
  15904. }
  15905. }
  15906. if(group.ordinality()==0)
  15907. {
  15908. eof = true;
  15909. return false;
  15910. }
  15911. leftIndex = 0;
  15912. rightIndex = 0;
  15913. rightOuterIndex = 0;
  15914. joinCounter = 0;
  15915. joinLimit = keepLimit;
  15916. ForEachItemIn(idx, group)
  15917. matchedRight.append(false);
  15918. return true;
  15919. }
  15920. void failLimit(const void * next)
  15921. {
  15922. helper.onMatchAbortLimitExceeded();
  15923. CommonXmlWriter xmlwrite(XWFtrim|XWFopt );
  15924. if (!ctx->isBlind() && input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  15925. {
  15926. input->queryOutputMeta()->toXML((byte *) next, xmlwrite);
  15927. }
  15928. throw MakeStringException(ROXIE_TOO_MANY_RESULTS, "More than %d match candidates in self-join %d for row %s", abortLimit, queryId(), xmlwrite.str());
  15929. }
  15930. virtual bool needsAllocator() const { return true; }
  15931. const void *joinRecords(const void * curLeft, const void * curRight, unsigned counter, IException * except)
  15932. {
  15933. try
  15934. {
  15935. if (cloneLeft && !except)
  15936. {
  15937. LinkRoxieRow(curLeft);
  15938. return curLeft;
  15939. }
  15940. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15941. size32_t outsize = except ? helper.onFailTransform(rowBuilder, curLeft, curRight, except) : helper.transform(rowBuilder, curLeft, curRight, counter);
  15942. if (outsize)
  15943. return rowBuilder.finalizeRowClear(outsize);
  15944. else
  15945. return NULL;
  15946. }
  15947. catch (IException *E)
  15948. {
  15949. throw makeWrappedException(E);
  15950. }
  15951. }
  15952. void createDefaultLeft()
  15953. {
  15954. if (!defaultLeft)
  15955. {
  15956. if (!defaultAllocator)
  15957. defaultAllocator.setown(createRowAllocator(input->queryOutputMeta()));
  15958. RtlDynamicRowBuilder rowBuilder(defaultAllocator);
  15959. size32_t thisSize = helper.createDefaultLeft(rowBuilder);
  15960. defaultLeft.setown(rowBuilder.finalizeRowClear(thisSize));
  15961. }
  15962. }
  15963. void createDefaultRight()
  15964. {
  15965. if (!defaultRight)
  15966. {
  15967. if (!defaultAllocator)
  15968. defaultAllocator.setown(createRowAllocator(input->queryOutputMeta()));
  15969. RtlDynamicRowBuilder rowBuilder(defaultAllocator);
  15970. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  15971. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  15972. }
  15973. }
  15974. public:
  15975. CRoxieServerSelfJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _forceSpill)
  15976. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorJoinArg &)basehelper), forceSpill(_forceSpill)
  15977. {
  15978. collate = helper.queryCompareLeftRight();
  15979. eof = false;
  15980. first = true;
  15981. keepLimit = 0;
  15982. atmostLimit = 0;
  15983. atmostsTriggered = 0;
  15984. unsigned joinFlags = helper.getJoinFlags();
  15985. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  15986. rightOuterJoin = (joinFlags & JFrightouter) != 0;
  15987. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  15988. exclude = (joinFlags & JFexclude) != 0;
  15989. abortLimit = 0;
  15990. joinLimit = 0;
  15991. assertex((joinFlags & (JFfirst | JFfirstleft | JFfirstright)) == 0); // no longer supported
  15992. getLimitType(joinFlags, limitFail, limitOnFail);
  15993. if((joinFlags & JFslidingmatch) != 0)
  15994. throw MakeStringException(ROXIE_UNIMPLEMENTED_ERROR, "Internal Error: Sliding self join not supported");
  15995. failingOuterAtmost = false;
  15996. matchedLeft = false;
  15997. leftIndex = 0;
  15998. rightIndex = 0;
  15999. rightOuterIndex = 0;
  16000. joinCounter = 0;
  16001. dualCacheInput = NULL;
  16002. }
  16003. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16004. {
  16005. eof = false;
  16006. first = true;
  16007. failingLimit.clear();
  16008. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  16009. keepLimit = helper.getKeepLimit();
  16010. if(keepLimit == 0)
  16011. keepLimit = (unsigned)-1;
  16012. atmostsTriggered = 0;
  16013. atmostLimit = helper.getJoinLimit();
  16014. if(atmostLimit == 0)
  16015. atmostLimit = (unsigned)-1;
  16016. else
  16017. assertex(!rightOuterJoin);
  16018. abortLimit = helper.getMatchAbortLimit();
  16019. if (abortLimit == 0)
  16020. abortLimit = (unsigned)-1;
  16021. if (rightOuterJoin)
  16022. createDefaultLeft();
  16023. if (leftOuterJoin || limitOnFail)
  16024. createDefaultRight();
  16025. ICompare *compareLeft = helper.queryCompareLeft();
  16026. if (helper.isLeftAlreadySorted())
  16027. groupedInput.setown(createGroupedInputReader(inputStream, compareLeft));
  16028. else
  16029. {
  16030. bool isStable = (helper.getJoinFlags() & JFunstable) == 0;
  16031. RoxieSortAlgorithm sortAlgorithm;
  16032. if (forceSpill)
  16033. sortAlgorithm = isStable ? stableSpillingQuickSortAlgorithm : spillingQuickSortAlgorithm;
  16034. else
  16035. sortAlgorithm = isStable ? stableQuickSortAlgorithm : quickSortAlgorithm;
  16036. groupedInput.setown(createSortedGroupedInputReader(inputStream, compareLeft, createSortAlgorithm(sortAlgorithm, compareLeft, ctx->queryRowManager(), input->queryOutputMeta(), ctx->queryCodeContext(), tempDirectory, activityId)));
  16037. }
  16038. if ((helper.getJoinFlags() & JFlimitedprefixjoin) && helper.getJoinLimit())
  16039. { //limited match join (s[1..n])
  16040. dualcache.setown(new CRHDualCache());
  16041. dualcache->init(groupedInput);
  16042. dualCacheInput = dualcache->queryOut1();
  16043. failingOuterAtmost = false;
  16044. matchedLeft = false;
  16045. leftIndex = 0;
  16046. rightOuterIndex = 0;
  16047. joinCounter = 0;
  16048. limitedhelper.setown(createRHLimitedCompareHelper());
  16049. limitedhelper->init( helper.getJoinLimit(), dualcache->queryOut2(), collate, helper.queryPrefixCompare() );
  16050. }
  16051. }
  16052. virtual void reset()
  16053. {
  16054. if (atmostsTriggered)
  16055. noteStatistic(StNumAtmostTriggered, atmostsTriggered);
  16056. group.clear();
  16057. groupedInput.clear();
  16058. CRoxieServerActivity::reset();
  16059. defaultLeft.clear();
  16060. defaultRight.clear();
  16061. }
  16062. virtual const void * nextRow()
  16063. {
  16064. ActivityTimer t(totalCycles, timeActivities);
  16065. if (limitedhelper)
  16066. {
  16067. while(!eof) //limited match join
  16068. {
  16069. if (!group.isItem(rightIndex))
  16070. {
  16071. lhs.setown(dualCacheInput->nextRow());
  16072. if (lhs)
  16073. {
  16074. rightIndex = 0;
  16075. joinCounter = 0;
  16076. group.clear();
  16077. limitedhelper->getGroup(group,lhs);
  16078. }
  16079. else
  16080. {
  16081. eof = true;
  16082. }
  16083. }
  16084. if (group.isItem(rightIndex))
  16085. {
  16086. const void * rhs = group.item(rightIndex++);
  16087. if(helper.match(lhs, rhs))
  16088. {
  16089. const void * ret = joinRecords(lhs, rhs, ++joinCounter, NULL);
  16090. if(ret)
  16091. {
  16092. processed++;
  16093. return ret;
  16094. }
  16095. }
  16096. }
  16097. }
  16098. return NULL;
  16099. }
  16100. else
  16101. {
  16102. if (first)
  16103. {
  16104. first = false;
  16105. fillGroup();
  16106. }
  16107. while(!eof)
  16108. {
  16109. if(failingOuterAtmost)
  16110. while(group.isItem(leftIndex))
  16111. {
  16112. const void * ret = joinRecords(group.item(leftIndex++), defaultRight, 0, NULL);
  16113. if(ret)
  16114. {
  16115. processed++;
  16116. return ret;
  16117. }
  16118. }
  16119. if((joinLimit == 0) || !group.isItem(rightIndex))
  16120. {
  16121. if(leftOuterJoin && !matchedLeft && !failingLimit)
  16122. {
  16123. const void * ret = joinRecords(group.item(leftIndex), defaultRight, 0, NULL);
  16124. if(ret)
  16125. {
  16126. matchedLeft = true;
  16127. processed++;
  16128. return ret;
  16129. }
  16130. }
  16131. leftIndex++;
  16132. matchedLeft = false;
  16133. rightIndex = 0;
  16134. joinCounter = 0;
  16135. joinLimit = keepLimit;
  16136. }
  16137. if(!group.isItem(leftIndex))
  16138. {
  16139. if(failingLimit || failingOuterAtmost)
  16140. {
  16141. const void * lhs;
  16142. while((lhs = groupedInput->nextRow()) != NULL) // dualCache never active here
  16143. {
  16144. const void * ret = joinRecords(lhs, defaultRight, 0, failingLimit);
  16145. ReleaseRoxieRow(lhs);
  16146. if(ret)
  16147. {
  16148. processed++;
  16149. return ret;
  16150. }
  16151. }
  16152. failingLimit.clear();
  16153. }
  16154. if(rightOuterJoin && !failingLimit)
  16155. while(group.isItem(rightOuterIndex))
  16156. if(!matchedRight.item(rightOuterIndex++))
  16157. {
  16158. const void * ret = joinRecords(defaultLeft, group.item(rightOuterIndex-1), 0, NULL);
  16159. if(ret)
  16160. {
  16161. processed++;
  16162. return ret;
  16163. }
  16164. }
  16165. if(!fillGroup())
  16166. return NULL;
  16167. continue;
  16168. }
  16169. const void * lhs = group.item(leftIndex);
  16170. if(failingLimit)
  16171. {
  16172. leftIndex++;
  16173. const void * ret = joinRecords(lhs, defaultRight, 0, failingLimit);
  16174. if(ret)
  16175. {
  16176. processed++;
  16177. return ret;
  16178. }
  16179. }
  16180. else
  16181. {
  16182. const void * rhs = group.item(rightIndex++);
  16183. if(helper.match(lhs, rhs))
  16184. {
  16185. matchedLeft = true;
  16186. matchedRight.replace(true, rightIndex-1);
  16187. if(!exclude)
  16188. {
  16189. const void * ret = joinRecords(lhs, rhs, ++joinCounter, NULL);
  16190. if(ret)
  16191. {
  16192. processed++;
  16193. joinLimit--;
  16194. return ret;
  16195. }
  16196. }
  16197. }
  16198. }
  16199. }
  16200. return NULL;
  16201. }
  16202. }
  16203. };
  16204. class CRoxieServerSelfJoinActivityFactory : public CRoxieServerActivityFactory
  16205. {
  16206. bool forceSpill;
  16207. public:
  16208. CRoxieServerSelfJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  16209. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  16210. {
  16211. forceSpill = queryFactory.queryOptions().allSortsMaySpill || _graphNode.getPropBool("hint[@name='spill']/@value", false);;
  16212. }
  16213. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  16214. {
  16215. return new CRoxieServerSelfJoinActivity(_ctx, this, _probeManager, forceSpill);
  16216. }
  16217. virtual const StatisticsMapping &queryStatsMapping() const
  16218. {
  16219. return joinStatistics;
  16220. }
  16221. };
  16222. IRoxieServerActivityFactory *createRoxieServerSelfJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  16223. {
  16224. return new CRoxieServerSelfJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  16225. }
  16226. //=====================================================================================================
  16227. class CRoxieServerLookupJoinActivity : public CRoxieServerTwoInputActivity
  16228. {
  16229. private:
  16230. class LookupTable : public CInterface
  16231. {
  16232. public:
  16233. LookupTable(IHThorHashJoinArg &helper)
  16234. : leftRightCompare(helper.queryCompareLeftRight()), rightCompare(helper.queryCompareRight()),
  16235. leftHash(helper.queryHashLeft()), rightHash(helper.queryHashRight())
  16236. {
  16237. size = 0;
  16238. }
  16239. virtual const void *find(const void * left) const = 0;
  16240. virtual const void *findNext(const void * left) const = 0;
  16241. protected:
  16242. ICompare * leftRightCompare;
  16243. ICompare * rightCompare;
  16244. IHash * leftHash;
  16245. IHash * rightHash;
  16246. unsigned size;
  16247. };
  16248. class DedupLookupTable : public LookupTable
  16249. {
  16250. public:
  16251. DedupLookupTable(ConstPointerArray &rightRows, IHThorHashJoinArg &helper)
  16252. : LookupTable(helper)
  16253. {
  16254. size = (4*rightRows.length())/3 + 1;
  16255. table = (const void * *)calloc(size, sizeof(void *)); // This should probably be allocated from roxiemem (and size rounded up to actual available size)
  16256. ForEachItemIn(idx, rightRows)
  16257. add(rightRows.item(idx));
  16258. }
  16259. ~DedupLookupTable()
  16260. {
  16261. roxiemem::ReleaseRoxieRowArray(size, table);
  16262. free(table);
  16263. }
  16264. virtual const void *find(const void * left) const
  16265. {
  16266. unsigned index = leftHash->hash(left) % size;
  16267. unsigned start = index;
  16268. while (table[index])
  16269. {
  16270. if(leftRightCompare->docompare(left, table[index]) == 0)
  16271. return table[index];
  16272. index++;
  16273. if (index==size)
  16274. index = 0;
  16275. if (index==start)
  16276. throw MakeStringException(ROXIE_JOIN_ERROR, "Internal error in lookup join activity (hash table full on lookup)");
  16277. }
  16278. return NULL;
  16279. }
  16280. virtual const void *findNext(const void * left) const
  16281. {
  16282. return NULL;
  16283. }
  16284. protected:
  16285. void add(const void * right)
  16286. {
  16287. unsigned index = rightHash->hash(right) % size;
  16288. unsigned start = index;
  16289. while (table[index])
  16290. {
  16291. if (rightCompare->docompare(table[index], right) == 0)
  16292. {
  16293. ReleaseRoxieRow(right);
  16294. return;
  16295. }
  16296. index++;
  16297. if (index==size)
  16298. index = 0;
  16299. if (index==start)
  16300. throw MakeStringException(ROXIE_JOIN_ERROR, "Internal error in lookup join activity (hash table full on add)");
  16301. }
  16302. table[index] = right;
  16303. }
  16304. const void * * table;
  16305. };
  16306. class FewLookupTable : public LookupTable
  16307. {
  16308. public:
  16309. FewLookupTable(ConstPointerArray &rightRows, IHThorHashJoinArg &helper)
  16310. : LookupTable(helper)
  16311. {
  16312. size = (4*rightRows.length())/3 + 1;
  16313. table = (const void * *)calloc(size, sizeof(void *)); // This should probably be allocated from roxiemem
  16314. findex = fstart = BadIndex;
  16315. ForEachItemIn(idx, rightRows)
  16316. add(rightRows.item(idx));
  16317. }
  16318. ~FewLookupTable()
  16319. {
  16320. roxiemem::ReleaseRoxieRowArray(size, table);
  16321. free(table);
  16322. }
  16323. virtual const void *find(const void * left) const
  16324. {
  16325. fstart = leftHash->hash(left) % size;
  16326. findex = fstart;
  16327. return doFind(left);
  16328. }
  16329. virtual const void *findNext(const void * left) const
  16330. {
  16331. if (findex == BadIndex)
  16332. return NULL;
  16333. advance();
  16334. return doFind(left);
  16335. }
  16336. protected:
  16337. void add(const void * right)
  16338. {
  16339. unsigned start = rightHash->hash(right) % size;
  16340. unsigned index = start;
  16341. while (table[index])
  16342. {
  16343. index++;
  16344. if (index==size)
  16345. index = 0;
  16346. if (index==start)
  16347. throwUnexpected(); //table is full, should never happen
  16348. }
  16349. table[index] = right;
  16350. }
  16351. void advance() const
  16352. {
  16353. findex++;
  16354. if(findex==size)
  16355. findex = 0;
  16356. if(findex==fstart)
  16357. throw MakeStringException(ROXIE_JOIN_ERROR, "Internal error in lookup join activity (hash table full on lookup)");
  16358. }
  16359. const void *doFind(const void * left) const
  16360. {
  16361. while(table[findex])
  16362. {
  16363. if (leftRightCompare->docompare(left, table[findex]) == 0)
  16364. return table[findex];
  16365. advance();
  16366. }
  16367. findex = BadIndex;
  16368. return NULL;
  16369. }
  16370. const void * * table;
  16371. unsigned mutable fstart;
  16372. unsigned mutable findex;
  16373. static unsigned const BadIndex;
  16374. };
  16375. class ManyLookupTable : public LookupTable
  16376. {
  16377. public:
  16378. ManyLookupTable(ConstPointerArray &rightRows, IHThorHashJoinArg &helper)
  16379. : LookupTable(helper)
  16380. {
  16381. rightRows.swapWith(rowtable);
  16382. UInt64Array groups;
  16383. unsigned numRows = rowtable.length();
  16384. if (numRows)
  16385. {
  16386. unsigned groupStart = 0;
  16387. const void *groupStartRow = rowtable.item(0);
  16388. for (unsigned i=1; i < numRows; i++)
  16389. {
  16390. const void *thisRow = rowtable.item(i);
  16391. if (rightCompare->docompare(groupStartRow, thisRow))
  16392. {
  16393. groups.append(makeint64(groupStart, i-groupStart));
  16394. groupStart = i;
  16395. groupStartRow = thisRow;
  16396. }
  16397. }
  16398. groups.append(makeint64(groupStart, numRows-groupStart));
  16399. }
  16400. size = (4*groups.length())/3 + 1;
  16401. table = (__uint64 *) calloc(size, sizeof(__uint64)); // This should probably be allocated from roxiemem
  16402. ForEachItemIn(idx, groups)
  16403. {
  16404. unsigned __int64 group = groups.item(idx);
  16405. unsigned groupstart = high(group);
  16406. const void *row = rowtable.item(groupstart);
  16407. add(row, group);
  16408. }
  16409. }
  16410. ~ManyLookupTable()
  16411. {
  16412. roxiemem::ReleaseRoxieRows(rowtable);
  16413. free(table);
  16414. }
  16415. void add(const void *row, unsigned __int64 group)
  16416. {
  16417. unsigned start = rightHash->hash(row) % size;
  16418. unsigned index = start;
  16419. while (table[index])
  16420. {
  16421. index++;
  16422. if (index==size)
  16423. index = 0;
  16424. if (index==start)
  16425. throwUnexpected(); //table is full, should never happen
  16426. }
  16427. table[index] = group;
  16428. }
  16429. virtual const void *find(const void * left) const
  16430. {
  16431. unsigned index = leftHash->hash(left) % size;
  16432. unsigned start = index;
  16433. while (table[index])
  16434. {
  16435. __uint64 group = table[index];
  16436. currentMatch = high(group);
  16437. const void *right = rowtable.item(currentMatch);
  16438. if (leftRightCompare->docompare(left, right) == 0)
  16439. {
  16440. currentMatch++;
  16441. matchCount = low(group) - 1;
  16442. return right;
  16443. }
  16444. index++;
  16445. if (index==size)
  16446. index = 0;
  16447. if (index==start)
  16448. throw MakeStringException(ROXIE_JOIN_ERROR, "Internal error in lookup join activity (hash table full on lookup)");
  16449. }
  16450. matchCount = 0;
  16451. return NULL;
  16452. }
  16453. virtual const void *findNext(const void * left) const
  16454. {
  16455. if (!matchCount)
  16456. return NULL;
  16457. matchCount--;
  16458. return rowtable.item(currentMatch++);
  16459. }
  16460. protected:
  16461. __uint64 *table;
  16462. ConstPointerArray rowtable;
  16463. mutable unsigned currentMatch = 0;
  16464. mutable unsigned matchCount = 0;
  16465. };
  16466. IHThorHashJoinArg &helper;
  16467. bool leftOuterJoin;
  16468. bool exclude;
  16469. bool eog;
  16470. bool many;
  16471. bool dedupRHS;
  16472. bool useFewTable;
  16473. bool matchedGroup;
  16474. const void *left;
  16475. OwnedConstRoxieRow defaultRight;
  16476. Owned<LookupTable> table;
  16477. unsigned keepLimit;
  16478. unsigned atmostLimit;
  16479. unsigned atmostsTriggered;
  16480. unsigned limitLimit;
  16481. unsigned joinCounter;
  16482. bool limitFail;
  16483. bool limitOnFail;
  16484. bool hasGroupLimit;
  16485. bool isSmartJoin;
  16486. unsigned keepCount;
  16487. bool gotMatch;
  16488. bool cloneLeft;
  16489. ConstPointerArray rightGroup;
  16490. aindex_t rightGroupIndex;
  16491. Owned<IException> failingLimit;
  16492. ConstPointerArray filteredRight;
  16493. ThorActivityKind activityKind;
  16494. Owned<IEngineRowAllocator> defaultRightAllocator;
  16495. void createDefaultRight()
  16496. {
  16497. if (!defaultRight)
  16498. {
  16499. if (!defaultRightAllocator)
  16500. defaultRightAllocator.setown(createRowAllocator(input1->queryOutputMeta()));
  16501. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  16502. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  16503. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  16504. }
  16505. }
  16506. public:
  16507. CRoxieServerLookupJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _useFewTable)
  16508. : CRoxieServerTwoInputActivity(_ctx, _factory, _probeManager), helper((IHThorHashJoinArg &)basehelper), useFewTable(_useFewTable)
  16509. {
  16510. unsigned joinFlags = helper.getJoinFlags();
  16511. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  16512. assertex((joinFlags & JFrightouter) == 0);
  16513. exclude = (joinFlags & JFexclude) != 0;
  16514. many = (joinFlags & JFmanylookup) != 0;
  16515. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  16516. dedupRHS = (joinFlags & (JFmanylookup | JFmatchrequired | JFtransformMaySkip)) == 0; // optimisation: can implicitly dedup RHS unless is many lookup, or match required, or transform may skip
  16517. left = NULL;
  16518. activityKind = factory->getKind();
  16519. eog = false;
  16520. matchedGroup = false;
  16521. gotMatch = false;
  16522. keepLimit = 0;
  16523. keepCount = 0;
  16524. joinCounter = 0;
  16525. atmostLimit = 0;
  16526. atmostsTriggered = 0;
  16527. limitLimit = 0;
  16528. rightGroupIndex = 0;
  16529. hasGroupLimit = false;
  16530. isSmartJoin = (joinFlags & JFsmart) != 0;
  16531. getLimitType(joinFlags, limitFail, limitOnFail);
  16532. }
  16533. void loadRight()
  16534. {
  16535. ConstPointerArray rightset;
  16536. try
  16537. {
  16538. const void * next;
  16539. while(true)
  16540. {
  16541. next = inputStream1->ungroupedNextRow();
  16542. if(!next)
  16543. break;
  16544. rightset.append(next);
  16545. }
  16546. if (!dedupRHS)
  16547. {
  16548. if (useFewTable)
  16549. {
  16550. table.setown(new FewLookupTable(rightset, helper)); // NOTE - takes ownership of rightset
  16551. }
  16552. else
  16553. {
  16554. if (!helper.isRightAlreadySorted())
  16555. {
  16556. if (helper.getJoinFlags() & JFunstable)
  16557. {
  16558. qsortvec(const_cast<void * *>(rightset.getArray()), rightset.ordinality(), *helper.queryCompareRight());
  16559. }
  16560. else
  16561. {
  16562. unsigned rightord = rightset.ordinality();
  16563. MemoryAttr tempAttr(rightord*sizeof(void **)); // Temp storage for stable sort. This should probably be allocated from roxiemem
  16564. void **temp = (void **) tempAttr.bufferBase();
  16565. void **_rows = const_cast<void * *>(rightset.getArray());
  16566. msortvecstableinplace(_rows, rightord, *helper.queryCompareRight(), temp);
  16567. }
  16568. }
  16569. table.setown(new ManyLookupTable(rightset, helper)); // NOTE - takes ownership of rightset
  16570. }
  16571. }
  16572. else
  16573. {
  16574. table.setown(new DedupLookupTable(rightset, helper)); // NOTE - takes ownership of rightset
  16575. }
  16576. }
  16577. catch (...)
  16578. {
  16579. roxiemem::ReleaseRoxieRows(rightset);
  16580. throw;
  16581. }
  16582. };
  16583. virtual void reset()
  16584. {
  16585. if (atmostsTriggered)
  16586. noteStatistic(StNumAtmostTriggered, atmostsTriggered);
  16587. CRoxieServerTwoInputActivity::reset();
  16588. ReleaseClearRoxieRow(left);
  16589. defaultRight.clear();
  16590. table.clear();
  16591. }
  16592. virtual bool needsAllocator() const { return true; }
  16593. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16594. {
  16595. eog = false;
  16596. matchedGroup = false;
  16597. left = NULL;
  16598. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  16599. keepLimit = helper.getKeepLimit();
  16600. if(keepLimit==0) keepLimit = static_cast<unsigned>(-1);
  16601. atmostsTriggered = 0;
  16602. atmostLimit = helper.getJoinLimit();
  16603. limitLimit = helper.getMatchAbortLimit();
  16604. hasGroupLimit = ((atmostLimit > 0) || (limitLimit > 0));
  16605. if(atmostLimit==0) atmostLimit = static_cast<unsigned>(-1);
  16606. if(limitLimit==0) limitLimit = static_cast<unsigned>(-1);
  16607. getLimitType(helper.getJoinFlags(), limitFail, limitOnFail);
  16608. switch (activityKind)
  16609. {
  16610. case TAKlookupjoin:
  16611. case TAKlookupdenormalizegroup:
  16612. case TAKsmartjoin:
  16613. case TAKsmartdenormalizegroup:
  16614. if (leftOuterJoin)
  16615. createDefaultRight();
  16616. break;
  16617. }
  16618. if (limitOnFail)
  16619. createDefaultRight();
  16620. }
  16621. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  16622. {
  16623. if (!idx && (helper.getJoinFlags() & JFparallel) != 0)
  16624. {
  16625. puller.setown(new CRoxieServerReadAheadInput(ctx, ctx->queryOptions().parallelJoinPreload));
  16626. puller->setInput(0, _sourceIdx, _in);
  16627. _in = puller;
  16628. _sourceIdx = 0;
  16629. }
  16630. CRoxieServerTwoInputActivity::setInput(idx, _sourceIdx, _in);
  16631. }
  16632. virtual const void * nextRow()
  16633. {
  16634. ActivityTimer t(totalCycles, timeActivities);
  16635. if(!table)
  16636. loadRight();
  16637. switch (activityKind)
  16638. {
  16639. case TAKlookupjoin:
  16640. case TAKsmartjoin:
  16641. return nextRowJoin();
  16642. case TAKlookupdenormalize:
  16643. case TAKlookupdenormalizegroup:
  16644. case TAKsmartdenormalize:
  16645. case TAKsmartdenormalizegroup:
  16646. return nextRowDenormalize();
  16647. }
  16648. throwUnexpected();
  16649. }
  16650. private:
  16651. const void * nextRowJoin()
  16652. {
  16653. if(!table)
  16654. loadRight();
  16655. while(true)
  16656. {
  16657. const void * right = NULL;
  16658. if(!left)
  16659. {
  16660. left = inputStream->nextRow();
  16661. keepCount = keepLimit;
  16662. joinCounter = 0;
  16663. if(!left)
  16664. {
  16665. if (isSmartJoin)
  16666. left = inputStream->nextRow();
  16667. if (!left)
  16668. {
  16669. if(matchedGroup || eog)
  16670. {
  16671. matchedGroup = false;
  16672. eog = true;
  16673. return NULL;
  16674. }
  16675. eog = true;
  16676. continue;
  16677. }
  16678. }
  16679. eog = false;
  16680. gotMatch = false;
  16681. right = getRightFirst();
  16682. }
  16683. else
  16684. right = getRightNext();
  16685. const void * ret = NULL;
  16686. if(failingLimit)
  16687. {
  16688. ret = joinException(left, failingLimit);
  16689. }
  16690. else
  16691. {
  16692. while(right)
  16693. {
  16694. if(helper.match(left, right))
  16695. {
  16696. gotMatch = true;
  16697. if(exclude)
  16698. break;
  16699. ret = joinRecords(left, right, ++joinCounter);
  16700. if(ret)
  16701. {
  16702. processed++;
  16703. break;
  16704. }
  16705. }
  16706. right = getRightNext();
  16707. ret = NULL;
  16708. }
  16709. if(leftOuterJoin && !gotMatch)
  16710. {
  16711. ret = joinRecords(left, defaultRight, 0);
  16712. gotMatch = true;
  16713. }
  16714. }
  16715. if(ret)
  16716. {
  16717. matchedGroup = true;
  16718. processed++;
  16719. if(!many || (--keepCount == 0) || failingLimit)
  16720. {
  16721. ReleaseClearRoxieRow(left);
  16722. failingLimit.clear();
  16723. }
  16724. return ret;
  16725. }
  16726. ReleaseClearRoxieRow(left);
  16727. }
  16728. }
  16729. const void * nextRowDenormalize()
  16730. {
  16731. while(true)
  16732. {
  16733. left = inputStream->nextRow();
  16734. if(!left)
  16735. {
  16736. if (!matchedGroup || isSmartJoin)
  16737. left = inputStream->nextRow();
  16738. if (!left)
  16739. {
  16740. matchedGroup = false;
  16741. return NULL;
  16742. }
  16743. }
  16744. gotMatch = false;
  16745. const void * right = getRightFirst();
  16746. const void * ret = NULL;
  16747. if (failingLimit)
  16748. ret = joinException(left, failingLimit);
  16749. else if (activityKind == TAKlookupdenormalize || activityKind == TAKsmartdenormalize)
  16750. {
  16751. OwnedConstRoxieRow newLeft;
  16752. newLeft.set(left);
  16753. unsigned rowSize = 0;
  16754. unsigned leftCount = 0;
  16755. keepCount = keepLimit;
  16756. while (right)
  16757. {
  16758. try
  16759. {
  16760. if (helper.match(left, right))
  16761. {
  16762. gotMatch = true;
  16763. if (exclude)
  16764. break;
  16765. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16766. unsigned thisSize = helper.transform(rowBuilder, newLeft, right, ++leftCount);
  16767. if (thisSize)
  16768. {
  16769. rowSize = thisSize;
  16770. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  16771. }
  16772. if(!many || (--keepCount == 0))
  16773. break;
  16774. }
  16775. right = getRightNext();
  16776. }
  16777. catch (IException *E)
  16778. {
  16779. throw makeWrappedException(E);
  16780. }
  16781. }
  16782. if (rowSize)
  16783. ret = newLeft.getClear();
  16784. else if (leftOuterJoin && !gotMatch)
  16785. {
  16786. ret = left;
  16787. left = NULL;
  16788. }
  16789. }
  16790. else
  16791. {
  16792. filteredRight.kill();
  16793. keepCount = keepLimit;
  16794. while (right)
  16795. {
  16796. if (helper.match(left, right))
  16797. {
  16798. gotMatch = true;
  16799. if(exclude)
  16800. break;
  16801. filteredRight.append(right);
  16802. if(!many || (--keepCount == 0))
  16803. break;
  16804. }
  16805. right = getRightNext();
  16806. }
  16807. if((filteredRight.ordinality() > 0) || (leftOuterJoin && !gotMatch))
  16808. ret = denormalizeRecords(left, filteredRight);
  16809. filteredRight.kill();
  16810. }
  16811. ReleaseRoxieRow(left);
  16812. left = NULL;
  16813. failingLimit.clear();
  16814. if(ret)
  16815. {
  16816. matchedGroup = true;
  16817. processed++;
  16818. return ret;
  16819. }
  16820. }
  16821. }
  16822. const void * joinRecords(const void * left, const void * right, unsigned counter)
  16823. {
  16824. if (cloneLeft)
  16825. {
  16826. LinkRoxieRow(left);
  16827. return left;
  16828. }
  16829. try
  16830. {
  16831. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16832. unsigned outSize = helper.transform(rowBuilder, left, right, counter);
  16833. if (outSize)
  16834. return rowBuilder.finalizeRowClear(outSize);
  16835. else
  16836. return NULL;
  16837. }
  16838. catch (IException *E)
  16839. {
  16840. throw makeWrappedException(E);
  16841. }
  16842. }
  16843. const void * joinException(const void * left, IException * except)
  16844. {
  16845. try
  16846. {
  16847. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16848. unsigned outSize = helper.onFailTransform(rowBuilder, left, defaultRight, except);
  16849. if (outSize)
  16850. return rowBuilder.finalizeRowClear(outSize);
  16851. else
  16852. return NULL;
  16853. }
  16854. catch (IException *E)
  16855. {
  16856. throw makeWrappedException(E);
  16857. }
  16858. }
  16859. const void * denormalizeRecords(const void * left, ConstPointerArray & rows)
  16860. {
  16861. try
  16862. {
  16863. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16864. unsigned numRows = rows.ordinality();
  16865. const void * right = numRows ? rows.item(0) : defaultRight.get();
  16866. unsigned outSize = helper.transform(rowBuilder, left, right, numRows, (const void * *)rows.getArray());
  16867. if (outSize)
  16868. return rowBuilder.finalizeRowClear(outSize);
  16869. else
  16870. return NULL;
  16871. }
  16872. catch (IException *E)
  16873. {
  16874. throw makeWrappedException(E);
  16875. }
  16876. }
  16877. const void * getRightFirst() { if(hasGroupLimit) return fillRightGroup(); else return table->find(left); }
  16878. const void * getRightNext() { if(hasGroupLimit) return readRightGroup(); else return table->findNext(left); }
  16879. const void * readRightGroup() { if(rightGroup.isItem(rightGroupIndex)) return rightGroup.item(rightGroupIndex++); else return NULL; }
  16880. const void *fillRightGroup()
  16881. {
  16882. rightGroup.kill();
  16883. for(const void * right = table->find(left); right; right = table->findNext(left))
  16884. {
  16885. rightGroup.append(right);
  16886. if(rightGroup.ordinality() > limitLimit)
  16887. {
  16888. if(limitFail)
  16889. failLimit();
  16890. gotMatch = true;
  16891. if (ctx->queryDebugContext())
  16892. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  16893. if(limitOnFail)
  16894. {
  16895. assertex(!failingLimit);
  16896. try
  16897. {
  16898. failLimit();
  16899. }
  16900. catch(IException * e)
  16901. {
  16902. failingLimit.setown(e);
  16903. }
  16904. assertex(failingLimit != NULL);
  16905. }
  16906. else
  16907. {
  16908. rightGroup.kill();
  16909. }
  16910. break;
  16911. }
  16912. if(rightGroup.ordinality() > atmostLimit)
  16913. {
  16914. atmostsTriggered++;
  16915. rightGroup.kill();
  16916. break;
  16917. }
  16918. }
  16919. rightGroupIndex = 0;
  16920. return readRightGroup();
  16921. }
  16922. void failLimit()
  16923. {
  16924. helper.onMatchAbortLimitExceeded();
  16925. CommonXmlWriter xmlwrite(XWFtrim|XWFopt );
  16926. if(!ctx->isBlind() && input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  16927. {
  16928. input->queryOutputMeta()->toXML(static_cast<const unsigned char *>(left), xmlwrite);
  16929. }
  16930. throw MakeStringException(ROXIE_TOO_MANY_RESULTS, "More than %u match candidates in join %d for row %s", limitLimit, queryId(), xmlwrite.str());
  16931. }
  16932. };
  16933. unsigned const CRoxieServerLookupJoinActivity::FewLookupTable::BadIndex(static_cast<unsigned>(-1));
  16934. class CRoxieServerLookupJoinActivityFactory : public CRoxieServerJoinActivityFactory
  16935. {
  16936. public:
  16937. CRoxieServerLookupJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  16938. : CRoxieServerJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  16939. {
  16940. Owned<IHThorHashJoinArg> helper = (IHThorHashJoinArg *) helperFactory();
  16941. useFewTable = _graphNode.getPropBool("hint[@name='usefewtable']/@value", false);
  16942. if((helper->getJoinFlags() & (JFfirst | JFfirstleft | JFfirstright | JFslidingmatch)) != 0)
  16943. throw MakeStringException(ROXIE_INVALID_FLAGS, "Invalid flags for lookup join activity"); // code generator should never create such an activity
  16944. }
  16945. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  16946. {
  16947. return new CRoxieServerLookupJoinActivity(_ctx, this, _probeManager, useFewTable);
  16948. }
  16949. virtual const StatisticsMapping &queryStatsMapping() const
  16950. {
  16951. return joinStatistics;
  16952. }
  16953. protected:
  16954. bool useFewTable;
  16955. };
  16956. IRoxieServerActivityFactory *createRoxieServerLookupJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  16957. {
  16958. return new CRoxieServerLookupJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  16959. }
  16960. //=====================================================================================================
  16961. class CRoxieServerAllJoinActivity : public CRoxieServerTwoInputActivity
  16962. {
  16963. private:
  16964. IHThorAllJoinArg &helper;
  16965. bool leftOuterJoin;
  16966. bool rightOuterJoin;
  16967. bool exclude;
  16968. OwnedConstRoxieRow defaultRight;
  16969. OwnedConstRoxieRow defaultLeft;
  16970. Owned<IEngineRowAllocator> defaultRightAllocator;
  16971. Owned<IEngineRowAllocator> defaultLeftAllocator;
  16972. const void *left;
  16973. unsigned countForLeft;
  16974. ConstPointerArray rightset;
  16975. BoolArray matchedRight; // MORE - could use a bitset...
  16976. unsigned keepLimit;
  16977. bool started;
  16978. bool eog;
  16979. bool eos;
  16980. bool matchedLeft;
  16981. bool matchedGroup;
  16982. bool leftIsGrouped;
  16983. bool cloneLeft;
  16984. unsigned rightIndex;
  16985. unsigned joinCounter;
  16986. unsigned rightOrdinality;
  16987. ThorActivityKind activityKind;
  16988. ConstPointerArray filteredRight;
  16989. void createDefaultLeft()
  16990. {
  16991. if (!defaultLeft)
  16992. {
  16993. if (!defaultLeftAllocator)
  16994. defaultLeftAllocator.setown(createRowAllocator(input->queryOutputMeta()));
  16995. RtlDynamicRowBuilder rowBuilder(defaultLeftAllocator);
  16996. size32_t thisSize = helper.createDefaultLeft(rowBuilder);
  16997. defaultLeft.setown(rowBuilder.finalizeRowClear(thisSize));
  16998. }
  16999. }
  17000. void createDefaultRight()
  17001. {
  17002. if (!defaultRight)
  17003. {
  17004. if (!defaultRightAllocator)
  17005. defaultRightAllocator.setown(createRowAllocator(input1->queryOutputMeta()));
  17006. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  17007. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  17008. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  17009. }
  17010. }
  17011. public:
  17012. CRoxieServerAllJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17013. : CRoxieServerTwoInputActivity(_ctx, _factory, _probeManager), helper((IHThorAllJoinArg &)basehelper)
  17014. {
  17015. unsigned joinFlags = helper.getJoinFlags();
  17016. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  17017. rightOuterJoin = (joinFlags & JFrightouter) != 0;
  17018. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  17019. keepLimit = (unsigned) -1;
  17020. exclude = (joinFlags & JFexclude) != 0;
  17021. left = NULL;
  17022. started = true;
  17023. eog = false;
  17024. eos = false;
  17025. matchedLeft = false;
  17026. matchedGroup = false;
  17027. activityKind = factory->getKind();
  17028. rightIndex = 0;
  17029. rightOrdinality = 0;
  17030. leftIsGrouped = false;
  17031. countForLeft = 0;
  17032. joinCounter = 0;
  17033. }
  17034. virtual void reset()
  17035. {
  17036. defaultRight.clear();
  17037. defaultLeft.clear();
  17038. ReleaseRoxieRows(rightset);
  17039. matchedRight.kill();
  17040. CRoxieServerTwoInputActivity::reset();
  17041. }
  17042. virtual bool needsAllocator() const { return true; }
  17043. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17044. {
  17045. eog = false;
  17046. eos = false;
  17047. matchedLeft = false;
  17048. matchedGroup = false;
  17049. started = false;
  17050. left = NULL;
  17051. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  17052. keepLimit = helper.getKeepLimit();
  17053. if(keepLimit==0)
  17054. keepLimit = (unsigned) -1;
  17055. countForLeft = keepLimit;
  17056. joinCounter = 0;
  17057. leftIsGrouped = input->queryOutputMeta()->isGrouped();
  17058. if((activityKind==TAKalljoin || activityKind==TAKalldenormalizegroup) && leftOuterJoin)
  17059. createDefaultRight();
  17060. if(rightOuterJoin)
  17061. createDefaultLeft();
  17062. }
  17063. void loadRight()
  17064. {
  17065. const void * next;
  17066. while(true)
  17067. {
  17068. next = inputStream1->ungroupedNextRow();
  17069. if(!next)
  17070. break;
  17071. rightset.append(next);
  17072. matchedRight.append(false);
  17073. }
  17074. rightIndex = 0;
  17075. joinCounter = 0;
  17076. rightOrdinality = rightset.ordinality();
  17077. }
  17078. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  17079. {
  17080. if (!idx && (helper.getJoinFlags() & JFparallel) != 0)
  17081. {
  17082. puller.setown(new CRoxieServerReadAheadInput(ctx, ctx->queryOptions().parallelJoinPreload));
  17083. puller->setInput(0, _sourceIdx, _in);
  17084. _in = puller;
  17085. _sourceIdx = 0;
  17086. }
  17087. CRoxieServerTwoInputActivity::setInput(idx, _sourceIdx, _in);
  17088. }
  17089. const void * joinRecords(const void * left, const void * right, unsigned counter)
  17090. {
  17091. // MORE - could share some code with lookup join
  17092. if (cloneLeft)
  17093. {
  17094. LinkRoxieRow(left);
  17095. return left;
  17096. }
  17097. try
  17098. {
  17099. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17100. unsigned outSize = helper.transform(rowBuilder, left, right, counter);
  17101. if (outSize)
  17102. return rowBuilder.finalizeRowClear(outSize);
  17103. else
  17104. return NULL;
  17105. }
  17106. catch (IException *E)
  17107. {
  17108. throw makeWrappedException(E);
  17109. }
  17110. }
  17111. const void * denormalizeRecords(const void * curLeft, ConstPointerArray & rows)
  17112. {
  17113. try
  17114. {
  17115. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17116. unsigned numRows = rows.ordinality();
  17117. const void * right = numRows ? rows.item(0) : defaultRight.get();
  17118. unsigned outSize = helper.transform(rowBuilder, curLeft, right, numRows, rows.getArray());
  17119. if (outSize)
  17120. return rowBuilder.finalizeRowClear(outSize);
  17121. else
  17122. return NULL;
  17123. }
  17124. catch (IException *E)
  17125. {
  17126. throw makeWrappedException(E);
  17127. }
  17128. }
  17129. virtual const void *nextRow()
  17130. {
  17131. ActivityTimer t(totalCycles, timeActivities);
  17132. if(!started)
  17133. {
  17134. started = true;
  17135. left = inputStream->nextRow();
  17136. matchedLeft = false;
  17137. countForLeft = keepLimit;
  17138. joinCounter = 0;
  17139. if(left == NULL)
  17140. {
  17141. eos = true;
  17142. return NULL;
  17143. }
  17144. loadRight();
  17145. }
  17146. const void * ret;
  17147. const void * right;
  17148. if(eos)
  17149. return NULL;
  17150. while(true)
  17151. {
  17152. ret = NULL;
  17153. if((rightIndex == rightOrdinality) || (countForLeft==0))
  17154. {
  17155. if(leftOuterJoin && left && !matchedLeft)
  17156. {
  17157. switch(activityKind)
  17158. {
  17159. case TAKalljoin:
  17160. ret = joinRecords(left, defaultRight, 0);
  17161. break;
  17162. case TAKalldenormalize:
  17163. ret = left;
  17164. left = NULL;
  17165. break;
  17166. case TAKalldenormalizegroup:
  17167. filteredRight.kill();
  17168. ret = denormalizeRecords(left, filteredRight);
  17169. break;
  17170. default:
  17171. throwUnexpected();
  17172. }
  17173. }
  17174. rightIndex = 0;
  17175. joinCounter = 0;
  17176. ReleaseRoxieRow(left);
  17177. left = NULL;
  17178. if(ret)
  17179. {
  17180. matchedGroup = true;
  17181. processed++;
  17182. return ret;
  17183. }
  17184. }
  17185. if(!left)
  17186. {
  17187. left = inputStream->nextRow();
  17188. matchedLeft = false;
  17189. countForLeft = keepLimit;
  17190. joinCounter = 0;
  17191. }
  17192. if(!left)
  17193. {
  17194. if(eog)
  17195. {
  17196. eos = true;
  17197. matchedGroup = false;
  17198. return NULL;
  17199. }
  17200. eog = true;
  17201. if (matchedGroup && leftIsGrouped)
  17202. {
  17203. matchedGroup = false;
  17204. return NULL;
  17205. }
  17206. matchedGroup = false;
  17207. continue;
  17208. }
  17209. eog = false;
  17210. switch(activityKind)
  17211. {
  17212. case TAKalljoin:
  17213. while(rightIndex < rightOrdinality)
  17214. {
  17215. right = rightset.item(rightIndex);
  17216. if(helper.match(left, right))
  17217. {
  17218. matchedLeft = true;
  17219. matchedRight.replace(true, rightIndex);
  17220. if(!exclude)
  17221. ret = joinRecords(left, right, ++joinCounter);
  17222. }
  17223. rightIndex++;
  17224. if(ret)
  17225. {
  17226. countForLeft--;
  17227. matchedGroup = true;
  17228. processed++;
  17229. return ret;
  17230. }
  17231. }
  17232. break;
  17233. case TAKalldenormalize:
  17234. {
  17235. OwnedConstRoxieRow newLeft;
  17236. newLeft.set(left);
  17237. unsigned rowSize = 0;
  17238. unsigned leftCount = 0;
  17239. while((rightIndex < rightOrdinality) && countForLeft)
  17240. {
  17241. right = rightset.item(rightIndex);
  17242. if(helper.match(left, right))
  17243. {
  17244. matchedLeft = true;
  17245. matchedRight.replace(true, rightIndex);
  17246. if(!exclude)
  17247. {
  17248. try
  17249. {
  17250. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17251. unsigned thisSize = helper.transform(rowBuilder, newLeft, right, ++leftCount);
  17252. if(thisSize)
  17253. {
  17254. rowSize = thisSize;
  17255. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  17256. --countForLeft;
  17257. }
  17258. }
  17259. catch (IException *e)
  17260. {
  17261. throw makeWrappedException(e);
  17262. }
  17263. }
  17264. }
  17265. rightIndex++;
  17266. }
  17267. if(rowSize)
  17268. {
  17269. processed++;
  17270. return newLeft.getClear();
  17271. }
  17272. }
  17273. break;
  17274. case TAKalldenormalizegroup:
  17275. filteredRight.kill();
  17276. while((rightIndex < rightOrdinality) && countForLeft)
  17277. {
  17278. right = rightset.item(rightIndex);
  17279. if(helper.match(left, right))
  17280. {
  17281. matchedLeft = true;
  17282. matchedRight.replace(true, rightIndex);
  17283. filteredRight.append(right);
  17284. --countForLeft;
  17285. }
  17286. ++rightIndex;
  17287. }
  17288. if(!exclude && filteredRight.ordinality())
  17289. {
  17290. ret = denormalizeRecords(left, filteredRight);
  17291. filteredRight.kill();
  17292. if(ret)
  17293. {
  17294. processed++;
  17295. return ret;
  17296. }
  17297. }
  17298. break;
  17299. default:
  17300. throwUnexpected();
  17301. }
  17302. }
  17303. }
  17304. };
  17305. class CRoxieServerAllJoinActivityFactory : public CRoxieServerJoinActivityFactory
  17306. {
  17307. public:
  17308. CRoxieServerAllJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17309. : CRoxieServerJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  17310. {
  17311. Owned<IHThorAllJoinArg> helper = (IHThorAllJoinArg *) helperFactory();
  17312. if((helper->getJoinFlags() & (JFfirst | JFfirstleft | JFfirstright)) != 0)
  17313. throw MakeStringException(ROXIE_INVALID_FLAGS, "Invalid flags for join all activity"); // code generator should never create such an activity
  17314. }
  17315. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  17316. {
  17317. return new CRoxieServerAllJoinActivity(_ctx, this, _probeManager);
  17318. }
  17319. virtual const StatisticsMapping &queryStatsMapping() const
  17320. {
  17321. return joinStatistics;
  17322. }
  17323. };
  17324. IRoxieServerActivityFactory *createRoxieServerAllJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17325. {
  17326. return new CRoxieServerAllJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  17327. }
  17328. //=====================================================================================================
  17329. class CRoxieServerTopNActivity : public CRoxieServerLateStartActivity
  17330. {
  17331. unsigned limit;
  17332. bool hasBest;
  17333. bool eoi;
  17334. const void **sorted;
  17335. unsigned sortedCount;
  17336. unsigned curIndex;
  17337. IHThorTopNArg &helper;
  17338. ICompare &compare;
  17339. public:
  17340. CRoxieServerTopNActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17341. : CRoxieServerLateStartActivity(_ctx, _factory, _probeManager), helper((IHThorTopNArg &)basehelper), compare(*helper.queryCompare())
  17342. {
  17343. sorted = NULL;
  17344. sortedCount = 0;
  17345. curIndex = 0;
  17346. limit = 0;
  17347. eoi = false;
  17348. hasBest = false;
  17349. }
  17350. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17351. {
  17352. assertex(sorted == NULL);
  17353. sortedCount = 0;
  17354. curIndex = 0;
  17355. eoi = false;
  17356. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  17357. limit = (unsigned) helper.getLimit();
  17358. hasBest = helper.hasBest();
  17359. lateStart(parentExtractSize, parentExtract, limit > 0);
  17360. // MORE - should we use an expanding array instead?
  17361. if (limit > 0)
  17362. sorted = (const void **) ctx->queryRowManager().allocate((limit+1) * sizeof(const void *), activityId);
  17363. }
  17364. virtual void reset()
  17365. {
  17366. if (sorted)
  17367. {
  17368. roxiemem::ReleaseRoxieRowRange(sorted, curIndex, sortedCount);
  17369. curIndex = 0;
  17370. sortedCount = 0;
  17371. ReleaseRoxieRow(sorted);
  17372. sorted = NULL;
  17373. }
  17374. CRoxieServerLateStartActivity::reset();
  17375. }
  17376. bool abortEarly()
  17377. {
  17378. if (hasBest && (sortedCount == limit))
  17379. {
  17380. int compare = helper.compareBest(sorted[sortedCount-1]);
  17381. if (compare == 0)
  17382. {
  17383. if (meta.isGrouped())
  17384. {
  17385. //MORE: This would be more efficient if we had a away of skipping to the end of the incoming group.
  17386. const void * next;
  17387. while ((next = inputStream->nextRow()) != NULL)
  17388. ReleaseRoxieRow(next);
  17389. }
  17390. else
  17391. eoi = true;
  17392. return true;
  17393. }
  17394. //This only checks the lowest element - we could check all elements inserted, but it would increase the number of compares
  17395. if (compare < 0)
  17396. throw MakeStringException(ROXIE_TOPN_ROW_ERROR, "TOPN: row found that exceeds the best value");
  17397. }
  17398. return false;
  17399. }
  17400. void getSorted()
  17401. {
  17402. curIndex = 0;
  17403. sortedCount = 0;
  17404. if(eoi)
  17405. return;
  17406. const void * next;
  17407. while ((next = inputStream->nextRow()) != NULL)
  17408. {
  17409. if (sortedCount < limit)
  17410. {
  17411. binary_vec_insert_stable(next, sorted, sortedCount, compare);
  17412. sortedCount++;
  17413. if(abortEarly())
  17414. return;
  17415. }
  17416. else
  17417. {
  17418. if(limit && compare.docompare(sorted[sortedCount-1], next) > 0) // MORE - if stability is an issue, need to consider whether this should be > or >=
  17419. {
  17420. binary_vec_insert_stable(next, sorted, sortedCount, compare); // MORE - not sure this is stable!
  17421. ReleaseRoxieRow(sorted[sortedCount]);
  17422. if(abortEarly())
  17423. return;
  17424. }
  17425. else
  17426. {
  17427. ReleaseRoxieRow(next); // do not bother with insertion sort if we know next will fall off the end
  17428. }
  17429. }
  17430. }
  17431. }
  17432. virtual const void * nextRow()
  17433. {
  17434. ActivityTimer t(totalCycles, timeActivities);
  17435. if (eof)
  17436. return NULL;
  17437. if (curIndex >= sortedCount)
  17438. {
  17439. bool eog = sortedCount != 0;
  17440. getSorted();
  17441. if(sortedCount == 0)
  17442. {
  17443. eof = true;
  17444. return NULL;
  17445. }
  17446. if (eog)
  17447. return NULL;
  17448. }
  17449. processed++;
  17450. return sorted[curIndex++];
  17451. }
  17452. };
  17453. class CRoxieServerTopNActivityFactory : public CRoxieServerActivityFactory
  17454. {
  17455. public:
  17456. CRoxieServerTopNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17457. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  17458. {
  17459. }
  17460. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  17461. {
  17462. return new CRoxieServerTopNActivity(_ctx, this, _probeManager);
  17463. }
  17464. };
  17465. IRoxieServerActivityFactory *createRoxieServerTopNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17466. {
  17467. return new CRoxieServerTopNActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  17468. }
  17469. //=================================================================================
  17470. class CRoxieServerLimitActivity : public CRoxieServerActivity
  17471. {
  17472. protected:
  17473. unsigned __int64 rowLimit;
  17474. IHThorLimitArg &helper;
  17475. public:
  17476. CRoxieServerLimitActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17477. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorLimitArg &)basehelper)
  17478. {
  17479. rowLimit = 0;
  17480. }
  17481. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17482. {
  17483. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  17484. rowLimit = helper.getRowLimit(); // could conceivably depend on context so should not compute any earlier than this
  17485. }
  17486. virtual const void *nextRow()
  17487. {
  17488. ActivityTimer t(totalCycles, timeActivities);
  17489. const void * ret = inputStream->nextRow();
  17490. if (ret)
  17491. {
  17492. processed++;
  17493. if (processed > rowLimit)
  17494. {
  17495. ReleaseRoxieRow(ret);
  17496. if (traceLevel > 4)
  17497. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  17498. helper.onLimitExceeded();
  17499. }
  17500. }
  17501. return ret;
  17502. }
  17503. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  17504. {
  17505. ActivityTimer t(totalCycles, timeActivities);
  17506. const void * ret = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  17507. if (ret)
  17508. {
  17509. if (wasCompleteMatch)
  17510. processed++;
  17511. if (processed > rowLimit)
  17512. {
  17513. ReleaseRoxieRow(ret);
  17514. if (traceLevel > 4)
  17515. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  17516. helper.onLimitExceeded();
  17517. }
  17518. }
  17519. return ret;
  17520. }
  17521. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  17522. {
  17523. return input->gatherConjunctions(collector);
  17524. }
  17525. virtual void resetEOF()
  17526. {
  17527. //Do not reset the rowLimit
  17528. inputStream->resetEOF();
  17529. }
  17530. IInputSteppingMeta * querySteppingMeta()
  17531. {
  17532. return input->querySteppingMeta();
  17533. }
  17534. };
  17535. class CRoxieServerLimitActivityFactory : public CRoxieServerActivityFactory
  17536. {
  17537. public:
  17538. CRoxieServerLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17539. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  17540. {
  17541. }
  17542. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  17543. {
  17544. return new CRoxieServerLimitActivity(_ctx, this, _probeManager);
  17545. }
  17546. };
  17547. IRoxieServerActivityFactory *createRoxieServerLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17548. {
  17549. return new CRoxieServerLimitActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  17550. }
  17551. //=====================================================================================================
  17552. class CRoxieServerSkipLimitActivity : public CRoxieServerLimitActivity
  17553. {
  17554. ConstPointerArray buff;
  17555. bool started;
  17556. unsigned index;
  17557. IHThorLimitTransformExtra * transformExtra;
  17558. public:
  17559. CRoxieServerSkipLimitActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _onFail)
  17560. : CRoxieServerLimitActivity(_ctx, _factory, _probeManager)
  17561. {
  17562. transformExtra = NULL;
  17563. started = false;
  17564. index = 0;
  17565. if (_onFail)
  17566. transformExtra = static_cast<IHThorLimitTransformExtra *>(helper.selectInterface(TAIlimittransformextra_1));
  17567. }
  17568. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17569. {
  17570. started = false;
  17571. index = 0;
  17572. CRoxieServerLimitActivity::start(parentExtractSize, parentExtract, paused);
  17573. }
  17574. virtual void reset()
  17575. {
  17576. roxiemem::ReleaseRoxieRowRange(buff.getArray(), index, buff.ordinality());
  17577. buff.kill();
  17578. index = 0;
  17579. started = false;
  17580. CRoxieServerLimitActivity::reset();
  17581. }
  17582. virtual const void *nextRow()
  17583. {
  17584. ActivityTimer t(totalCycles, timeActivities);
  17585. if (!started)
  17586. pullInput();
  17587. if (buff.isItem(index))
  17588. {
  17589. const void * next = buff.item(index++);
  17590. if(next)
  17591. processed++;
  17592. return next;
  17593. }
  17594. return NULL;
  17595. }
  17596. protected:
  17597. void pullInput()
  17598. {
  17599. unsigned count = 0;
  17600. for (;;)
  17601. {
  17602. const void * next = inputStream->nextRow();
  17603. if (next == NULL)
  17604. {
  17605. next = inputStream->nextRow();
  17606. if(next == NULL)
  17607. break;
  17608. buff.append(NULL);
  17609. }
  17610. count++;
  17611. if (count > rowLimit)
  17612. {
  17613. ReleaseRoxieRow(next);
  17614. ReleaseRoxieRows(buff);
  17615. if (ctx->queryDebugContext())
  17616. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  17617. if (transformExtra)
  17618. {
  17619. ensureRowAllocator();
  17620. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17621. size32_t outSize = transformExtra->transformOnLimitExceeded(rowBuilder);
  17622. if (outSize)
  17623. buff.append(rowBuilder.finalizeRowClear(outSize));
  17624. }
  17625. break;
  17626. }
  17627. buff.append(next);
  17628. }
  17629. started = true;
  17630. }
  17631. };
  17632. class CRoxieServerSkipLimitActivityFactory : public CRoxieServerActivityFactory
  17633. {
  17634. public:
  17635. CRoxieServerSkipLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17636. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  17637. {
  17638. }
  17639. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  17640. {
  17641. return new CRoxieServerSkipLimitActivity(_ctx, this, _probeManager, kind==TAKcreaterowlimit);
  17642. }
  17643. };
  17644. IRoxieServerActivityFactory *createRoxieServerSkipLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17645. {
  17646. return new CRoxieServerSkipLimitActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  17647. }
  17648. //=================================================================================
  17649. class CRoxieServerCatchActivity : public CRoxieServerActivity
  17650. {
  17651. IHThorCatchArg &helper;
  17652. public:
  17653. CRoxieServerCatchActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17654. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorCatchArg &)basehelper)
  17655. {
  17656. }
  17657. virtual const void *nextRow()
  17658. {
  17659. ActivityTimer t(totalCycles, timeActivities);
  17660. try
  17661. {
  17662. const void *ret = inputStream->nextRow();
  17663. if (ret)
  17664. processed++;
  17665. return ret;
  17666. }
  17667. catch (IException *E)
  17668. {
  17669. E->Release();
  17670. helper.onExceptionCaught();
  17671. }
  17672. catch (...)
  17673. {
  17674. helper.onExceptionCaught();
  17675. }
  17676. throwUnexpected(); // onExceptionCaught should have thrown something
  17677. }
  17678. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  17679. {
  17680. try
  17681. {
  17682. ActivityTimer t(totalCycles, timeActivities);
  17683. const void * ret = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  17684. if (ret && wasCompleteMatch)
  17685. processed++;
  17686. return ret;
  17687. }
  17688. catch (IException *E)
  17689. {
  17690. E->Release();
  17691. helper.onExceptionCaught();
  17692. }
  17693. catch (...)
  17694. {
  17695. helper.onExceptionCaught();
  17696. }
  17697. throwUnexpected(); // onExceptionCaught should have thrown something
  17698. }
  17699. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  17700. {
  17701. return input->gatherConjunctions(collector);
  17702. }
  17703. virtual void resetEOF()
  17704. {
  17705. inputStream->resetEOF(); // MORE - why not in base class?
  17706. }
  17707. IInputSteppingMeta * querySteppingMeta()
  17708. {
  17709. return input->querySteppingMeta();
  17710. }
  17711. };
  17712. class CRoxieServerSkipCatchActivity : public CRoxieServerActivity
  17713. {
  17714. ConstPointerArray buff;
  17715. bool started;
  17716. unsigned index;
  17717. IHThorCatchArg &helper;
  17718. bool createRow;
  17719. public:
  17720. CRoxieServerSkipCatchActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _createRow)
  17721. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorCatchArg &)basehelper), createRow(_createRow)
  17722. {
  17723. started = false;
  17724. index = 0;
  17725. }
  17726. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17727. {
  17728. started = false;
  17729. index = 0;
  17730. try
  17731. {
  17732. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  17733. }
  17734. catch (IException *E)
  17735. {
  17736. onException(E);
  17737. started = true;
  17738. }
  17739. catch (...)
  17740. {
  17741. onException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught"));
  17742. started = true;
  17743. }
  17744. }
  17745. virtual void reset()
  17746. {
  17747. roxiemem::ReleaseRoxieRowRange(buff.getArray(), index, buff.ordinality());
  17748. buff.kill();
  17749. index = 0;
  17750. started = false;
  17751. CRoxieServerActivity::reset();
  17752. }
  17753. virtual const void *nextRow()
  17754. {
  17755. ActivityTimer t(totalCycles, timeActivities);
  17756. if (!started)
  17757. pullInput();
  17758. if (buff.isItem(index))
  17759. {
  17760. const void * next = buff.item(index++);
  17761. if(next)
  17762. processed++;
  17763. return next;
  17764. }
  17765. return NULL;
  17766. }
  17767. protected:
  17768. void onException(IException *E)
  17769. {
  17770. inputStream->stop();
  17771. ReleaseRoxieRows(buff);
  17772. if (createRow)
  17773. {
  17774. ensureRowAllocator();
  17775. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17776. size32_t outSize = helper.transformOnExceptionCaught(rowBuilder, E);
  17777. if (outSize)
  17778. buff.append(rowBuilder.finalizeRowClear(outSize));
  17779. }
  17780. E->Release();
  17781. }
  17782. void pullInput()
  17783. {
  17784. try
  17785. {
  17786. bool EOGseen = false;
  17787. for (;;)
  17788. {
  17789. const void * next = inputStream->nextRow();
  17790. buff.append(next);
  17791. if (next == NULL)
  17792. {
  17793. if (EOGseen)
  17794. break;
  17795. EOGseen = true;
  17796. }
  17797. else
  17798. EOGseen = false;
  17799. }
  17800. }
  17801. catch (IException *E)
  17802. {
  17803. onException(E);
  17804. }
  17805. catch (...)
  17806. {
  17807. onException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught"));
  17808. }
  17809. started = true;
  17810. }
  17811. };
  17812. class CRoxieServerCatchActivityFactory : public CRoxieServerActivityFactory
  17813. {
  17814. public:
  17815. CRoxieServerCatchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17816. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  17817. {
  17818. }
  17819. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  17820. {
  17821. switch (kind)
  17822. {
  17823. case TAKcatch:
  17824. return new CRoxieServerCatchActivity(_ctx, this, _probeManager);
  17825. case TAKskipcatch:
  17826. return new CRoxieServerSkipCatchActivity(_ctx, this, _probeManager, false);
  17827. case TAKcreaterowcatch:
  17828. return new CRoxieServerSkipCatchActivity(_ctx, this, _probeManager, true);
  17829. default:
  17830. throwUnexpected();
  17831. }
  17832. }
  17833. };
  17834. IRoxieServerActivityFactory *createRoxieServerCatchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17835. {
  17836. return new CRoxieServerCatchActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  17837. }
  17838. //=================================================================================
  17839. class CRoxieServerPullActivity : public CRoxieServerActivity
  17840. {
  17841. ConstPointerArray buff;
  17842. bool started;
  17843. unsigned index;
  17844. public:
  17845. CRoxieServerPullActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17846. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  17847. {
  17848. started = false;
  17849. index = 0;
  17850. }
  17851. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17852. {
  17853. started = false;
  17854. index = 0;
  17855. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  17856. }
  17857. virtual void reset()
  17858. {
  17859. while (buff.isItem(index))
  17860. ReleaseRoxieRow(buff.item(index++));
  17861. buff.kill();
  17862. started = false;
  17863. index = 0;
  17864. CRoxieServerActivity::reset();
  17865. }
  17866. virtual const void *nextRow()
  17867. {
  17868. ActivityTimer t(totalCycles, timeActivities);
  17869. if (!started)
  17870. pullInput();
  17871. if (buff.isItem(index))
  17872. {
  17873. const void * next = buff.item(index++);
  17874. if (next)
  17875. processed++;
  17876. return next;
  17877. }
  17878. return NULL;
  17879. }
  17880. protected:
  17881. void pullInput()
  17882. {
  17883. bool EOGseen = false;
  17884. for (;;)
  17885. {
  17886. const void * next = inputStream->nextRow();
  17887. buff.append(next);
  17888. if (next == NULL)
  17889. {
  17890. if (EOGseen)
  17891. break;
  17892. EOGseen = true;
  17893. }
  17894. else
  17895. EOGseen = false;
  17896. }
  17897. started = true;
  17898. }
  17899. };
  17900. class CRoxieServerPullActivityFactory : public CRoxieServerActivityFactory
  17901. {
  17902. public:
  17903. CRoxieServerPullActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17904. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  17905. {
  17906. }
  17907. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  17908. {
  17909. return new CRoxieServerPullActivity(_ctx, this, _probeManager);
  17910. }
  17911. };
  17912. IRoxieServerActivityFactory *createRoxieServerPullActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17913. {
  17914. return new CRoxieServerPullActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  17915. }
  17916. //=================================================================================
  17917. class CRoxieServerTraceActivity : public CRoxieServerActivity
  17918. {
  17919. public:
  17920. CRoxieServerTraceActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17921. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorTraceArg &) basehelper),
  17922. keepLimit(0), skip(0), sample(0)
  17923. {
  17924. assertex(meta.hasXML());
  17925. traceEnabled = defaultTraceEnabled && !isBlind();
  17926. }
  17927. virtual void onCreate(IHThorArg *_colocalParent)
  17928. {
  17929. CRoxieServerActivity::onCreate(_colocalParent);
  17930. if (ctx)
  17931. traceEnabled = ctx->queryOptions().traceEnabled && !isBlind();
  17932. }
  17933. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17934. {
  17935. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  17936. if (traceEnabled && helper.canMatchAny())
  17937. {
  17938. keepLimit = helper.getKeepLimit();
  17939. if (keepLimit==(unsigned) -1)
  17940. keepLimit = ctx->queryOptions().traceLimit;
  17941. skip = helper.getSkip();
  17942. sample = helper.getSample();
  17943. if (sample)
  17944. sample--;
  17945. name.setown(helper.getName());
  17946. if (!name)
  17947. name.set("Row");
  17948. }
  17949. else
  17950. keepLimit = 0;
  17951. }
  17952. virtual void stop()
  17953. {
  17954. name.clear();
  17955. CRoxieServerActivity::stop();
  17956. }
  17957. virtual bool isPassThrough()
  17958. {
  17959. return true;
  17960. }
  17961. virtual const void *nextRow()
  17962. {
  17963. ActivityTimer t(totalCycles, timeActivities);
  17964. const void *row = inputStream->nextRow();
  17965. if (row)
  17966. {
  17967. onTrace(row);
  17968. processed++;
  17969. }
  17970. return row;
  17971. }
  17972. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  17973. {
  17974. // MORE - will need rethinking once we rethink the nextRowGE interface for global smart-stepping.
  17975. ActivityTimer t(totalCycles, timeActivities);
  17976. const void * row = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  17977. if (row)
  17978. {
  17979. onTrace(row);
  17980. processed++;
  17981. }
  17982. return row;
  17983. }
  17984. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  17985. {
  17986. return input->gatherConjunctions(collector);
  17987. }
  17988. virtual void resetEOF()
  17989. {
  17990. inputStream->resetEOF();
  17991. }
  17992. IInputSteppingMeta * querySteppingMeta()
  17993. {
  17994. return input->querySteppingMeta();
  17995. }
  17996. protected:
  17997. void onTrace(const void *row)
  17998. {
  17999. if (keepLimit && helper.isValid(row))
  18000. {
  18001. if (skip)
  18002. skip--;
  18003. else if (sample)
  18004. sample--;
  18005. else
  18006. {
  18007. CommonXmlWriter xmlwrite(XWFnoindent);
  18008. meta.toXML((const byte *) row, xmlwrite);
  18009. CTXLOG("TRACE: <%s>%s<%s>", name.get(), xmlwrite.str(), name.get());
  18010. keepLimit--;
  18011. sample = helper.getSample();
  18012. if (sample)
  18013. sample--;
  18014. }
  18015. }
  18016. }
  18017. OwnedRoxieString name;
  18018. IHThorTraceArg &helper;
  18019. unsigned keepLimit;
  18020. unsigned skip;
  18021. unsigned sample;
  18022. bool traceEnabled;
  18023. };
  18024. class CRoxieServerTraceActivityFactory : public CRoxieServerActivityFactory
  18025. {
  18026. public:
  18027. CRoxieServerTraceActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  18028. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  18029. {
  18030. }
  18031. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18032. {
  18033. return new CRoxieServerTraceActivity(_ctx, this, _probeManager);
  18034. }
  18035. };
  18036. IRoxieServerActivityFactory *createRoxieServerTraceActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  18037. {
  18038. return new CRoxieServerTraceActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  18039. }
  18040. //=================================================================================
  18041. class CRoxieServerCaseActivity : public CRoxieServerMultiInputBaseActivity
  18042. {
  18043. IHThorCaseArg &helper;
  18044. unsigned cond;
  18045. bool unusedStopped;
  18046. IEngineRowStream *active;
  18047. public:
  18048. CRoxieServerCaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  18049. : CRoxieServerMultiInputBaseActivity(_ctx, _factory, _probeManager, _numInputs), helper((IHThorCaseArg &)basehelper)
  18050. {
  18051. unusedStopped = false;
  18052. cond = 0;
  18053. active = NULL;
  18054. }
  18055. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18056. {
  18057. CRoxieServerMultiInputBaseActivity::start(parentExtractSize, parentExtract, paused);
  18058. cond = helper.getBranch();
  18059. //CHOOSE defaults to the last argument if out of range.
  18060. if (cond >= numInputs)
  18061. cond = numInputs - 1;
  18062. inputArray[cond]->start(parentExtractSize, parentExtract, paused);
  18063. startJunction(junctionArray[cond]);
  18064. assertex(numInputs==numStreams);
  18065. for (unsigned idx = 0; idx < numStreams; idx++)
  18066. {
  18067. if (idx!=cond)
  18068. streamArray[idx]->stop(); // Note: stopping unused branches early helps us avoid buffering splits too long.
  18069. }
  18070. active = streamArray[cond];
  18071. unusedStopped = true;
  18072. }
  18073. virtual void stop()
  18074. {
  18075. for (unsigned idx = 0; idx < numStreams; idx++)
  18076. {
  18077. if (idx==cond || !unusedStopped)
  18078. streamArray[idx]->stop();
  18079. }
  18080. CRoxieServerMultiInputBaseActivity::stop();
  18081. }
  18082. virtual void reset()
  18083. {
  18084. unusedStopped = false;
  18085. active = NULL;
  18086. CRoxieServerMultiInputBaseActivity::reset();
  18087. }
  18088. virtual const void *nextRow()
  18089. {
  18090. ActivityTimer t(totalCycles, timeActivities);
  18091. if (active)
  18092. {
  18093. const void *ret = active->nextRow();
  18094. if (ret)
  18095. processed++;
  18096. return ret;
  18097. }
  18098. return NULL;
  18099. }
  18100. };
  18101. class CRoxieServerCaseActivityFactory : public CRoxieServerMultiInputFactory
  18102. {
  18103. bool graphInvariant;
  18104. public:
  18105. CRoxieServerCaseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _graphInvariant)
  18106. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  18107. {
  18108. graphInvariant = _graphInvariant;
  18109. }
  18110. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18111. {
  18112. return new CRoxieServerCaseActivity(_ctx, this, _probeManager, numInputs());
  18113. }
  18114. virtual bool isGraphInvariant() const
  18115. {
  18116. return graphInvariant;
  18117. }
  18118. };
  18119. IRoxieServerActivityFactory *createRoxieServerCaseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _graphInvariant)
  18120. {
  18121. return new CRoxieServerCaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _graphInvariant);
  18122. }
  18123. //=================================================================================
  18124. class CRoxieServerIfActivity : public CRoxieServerActivity
  18125. {
  18126. IHThorIfArg &helper;
  18127. IFinalRoxieInput *inputTrue;
  18128. IFinalRoxieInput *inputFalse;
  18129. IEngineRowStream *streamTrue;
  18130. IEngineRowStream *streamFalse;
  18131. unsigned sourceIdxFalse = 0;
  18132. unsigned sourceIdxTrue = 0;
  18133. Owned<IStrandJunction> junctionTrue;
  18134. Owned<IStrandJunction> junctionFalse;
  18135. bool cond;
  18136. bool unusedStopped;
  18137. public:
  18138. CRoxieServerIfActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18139. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorIfArg &)basehelper)
  18140. {
  18141. inputFalse = NULL;
  18142. inputTrue = NULL;
  18143. streamTrue = NULL;
  18144. streamFalse = NULL;
  18145. unusedStopped = false;
  18146. cond = false;
  18147. }
  18148. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18149. {
  18150. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  18151. cond = helper.getCondition();
  18152. if (cond)
  18153. {
  18154. inputTrue->start(parentExtractSize, parentExtract, paused);
  18155. startJunction(junctionTrue);
  18156. if (streamFalse)
  18157. streamFalse->stop(); // Note: stopping unused branches early helps us avoid buffering splits too long.
  18158. }
  18159. else
  18160. {
  18161. if (inputFalse)
  18162. {
  18163. inputFalse->start(parentExtractSize, parentExtract, paused);
  18164. startJunction(junctionFalse);
  18165. }
  18166. streamTrue->stop();
  18167. }
  18168. unusedStopped = true;
  18169. }
  18170. virtual void stop()
  18171. {
  18172. if (!unusedStopped || cond)
  18173. streamTrue->stop();
  18174. if (streamFalse && (!unusedStopped || !cond))
  18175. streamFalse->stop();
  18176. CRoxieServerActivity::stop();
  18177. }
  18178. virtual unsigned __int64 queryLocalCycles() const
  18179. {
  18180. __int64 localCycles = totalCycles.totalCycles;
  18181. localCycles -= inputTrue->queryTotalCycles();
  18182. if (inputFalse)
  18183. localCycles -= inputFalse->queryTotalCycles();
  18184. if (localCycles < 0)
  18185. localCycles = 0;
  18186. return localCycles;
  18187. }
  18188. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  18189. {
  18190. switch (idx)
  18191. {
  18192. case 0:
  18193. return inputTrue;
  18194. case 1:
  18195. return inputFalse;
  18196. default:
  18197. return NULL;
  18198. }
  18199. }
  18200. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { return this; }
  18201. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { return nullptr; }
  18202. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  18203. {
  18204. IFinalRoxieInput *in = cond ? inputTrue : inputFalse;
  18205. if (in)
  18206. return in->queryIndexReadActivity();
  18207. return NULL;
  18208. }
  18209. virtual void reset()
  18210. {
  18211. CRoxieServerActivity::reset();
  18212. inputTrue->reset();
  18213. if (inputFalse)
  18214. inputFalse->reset();
  18215. resetJunction(junctionTrue);
  18216. resetJunction(junctionFalse);
  18217. unusedStopped = false;
  18218. }
  18219. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  18220. {
  18221. if (idx==1)
  18222. {
  18223. inputFalse = _in;
  18224. sourceIdxFalse = _sourceIdx;
  18225. }
  18226. else
  18227. {
  18228. assertex(!idx);
  18229. inputTrue = _in;
  18230. sourceIdxTrue = _sourceIdx;
  18231. }
  18232. }
  18233. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  18234. {
  18235. //It should be possible to stream IF(), but the number of strands would need to match on the two branches.
  18236. streamTrue = connectSingleStream(ctx, inputTrue, sourceIdxTrue, junctionTrue, consumerOrdered);
  18237. streamFalse = connectSingleStream(ctx, inputFalse, sourceIdxFalse, junctionFalse, consumerOrdered);
  18238. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, nullptr, consumerOrdered, nullptr);
  18239. }
  18240. virtual const void *nextRow()
  18241. {
  18242. ActivityTimer t(totalCycles, timeActivities);
  18243. IEngineRowStream *in = cond ? streamTrue : streamFalse;
  18244. if (in)
  18245. {
  18246. const void * ret;
  18247. if ((ret = in->nextRow()) != NULL)
  18248. processed++;
  18249. return ret;
  18250. }
  18251. return NULL;
  18252. }
  18253. };
  18254. class CRoxieServerIfActivityFactory : public CRoxieServerActivityFactory
  18255. {
  18256. unsigned input2;
  18257. unsigned input2idx;
  18258. bool graphInvariant;
  18259. public:
  18260. CRoxieServerIfActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _graphInvariant)
  18261. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  18262. {
  18263. graphInvariant = _graphInvariant;
  18264. input2 = (unsigned)-1;
  18265. input2idx = (unsigned)-1;
  18266. }
  18267. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18268. {
  18269. return new CRoxieServerIfActivity(_ctx, this, _probeManager);
  18270. }
  18271. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  18272. {
  18273. if (idx==1)
  18274. {
  18275. input2 = source;
  18276. input2idx = sourceidx;
  18277. }
  18278. else
  18279. CRoxieServerActivityFactory::setInput(idx, source, sourceidx);
  18280. }
  18281. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  18282. {
  18283. switch (idx)
  18284. {
  18285. case 1:
  18286. sourceidx = input2idx;
  18287. return input2;
  18288. case 0:
  18289. return CRoxieServerActivityFactory::getInput(idx, sourceidx);
  18290. default:
  18291. return (unsigned) -1;
  18292. }
  18293. }
  18294. virtual unsigned numInputs() const { return (input2 == (unsigned)-1) ? 1 : 2; }
  18295. virtual bool isGraphInvariant() const
  18296. {
  18297. return graphInvariant;
  18298. }
  18299. };
  18300. IRoxieServerActivityFactory *createRoxieServerIfActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _graphInvariant)
  18301. {
  18302. return new CRoxieServerIfActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _graphInvariant);
  18303. }
  18304. //=================================================================================
  18305. class CRoxieServerActionBaseActivity : public CRoxieServerActivity
  18306. {
  18307. CriticalSection ecrit;
  18308. Owned<IException> exception;
  18309. bool executed;
  18310. public:
  18311. CRoxieServerActionBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18312. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  18313. {
  18314. executed = false;
  18315. }
  18316. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract) = 0;
  18317. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  18318. {
  18319. CriticalBlock b(ecrit);
  18320. if (exception)
  18321. throw(exception.getLink());
  18322. if (!executed)
  18323. {
  18324. try
  18325. {
  18326. executed = true;
  18327. start(parentExtractSize, parentExtract, false);
  18328. doExecuteAction(parentExtractSize, parentExtract);
  18329. stop();
  18330. }
  18331. catch (IException * E)
  18332. {
  18333. ctx->notifyAbort(E);
  18334. abort();
  18335. exception.set(E);
  18336. throw;
  18337. }
  18338. }
  18339. }
  18340. virtual void reset()
  18341. {
  18342. executed = false;
  18343. exception.clear();
  18344. CRoxieServerActivity::reset();
  18345. }
  18346. virtual const void *nextRow()
  18347. {
  18348. throwUnexpected(); // I am nobody's input
  18349. }
  18350. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  18351. {
  18352. return NULL;
  18353. }
  18354. };
  18355. class CRoxieServerIfActionActivity : public CRoxieServerActionBaseActivity
  18356. {
  18357. IHThorIfArg &helper;
  18358. public:
  18359. CRoxieServerIfActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18360. : CRoxieServerActionBaseActivity(_ctx, _factory, _probeManager), helper((IHThorIfArg &)basehelper)
  18361. {
  18362. }
  18363. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  18364. {
  18365. bool cond;
  18366. {
  18367. ActivityTimer t(totalCycles, timeActivities);
  18368. cond = helper.getCondition();
  18369. }
  18370. stopDependencies(parentExtractSize, parentExtract, cond ? 2 : 1);
  18371. executeDependencies(parentExtractSize, parentExtract, cond ? 1 : 2);
  18372. }
  18373. };
  18374. class CRoxieServerIfActionActivityFactory : public CRoxieServerActivityFactory
  18375. {
  18376. bool isRoot;
  18377. public:
  18378. CRoxieServerIfActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18379. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  18380. {
  18381. }
  18382. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18383. {
  18384. return new CRoxieServerIfActionActivity(_ctx, this, _probeManager);
  18385. }
  18386. virtual bool isSink() const
  18387. {
  18388. return isRoot;
  18389. }
  18390. };
  18391. IRoxieServerActivityFactory *createRoxieServerIfActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18392. {
  18393. return new CRoxieServerIfActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  18394. }
  18395. //=================================================================================
  18396. class CRoxieServerParallelActionActivity : public CRoxieServerActionBaseActivity
  18397. {
  18398. public:
  18399. CRoxieServerParallelActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18400. : CRoxieServerActionBaseActivity(_ctx, _factory, _probeManager)
  18401. {
  18402. }
  18403. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  18404. {
  18405. #ifdef PARALLEL_EXECUTE
  18406. CParallelActivityExecutor afor(dependencies, parentExtractSize, parentExtract);
  18407. afor.For(dependencies.ordinality(), dependencies.ordinality(), true);
  18408. #else
  18409. ForEachItemIn(idx, dependencies)
  18410. {
  18411. dependencies.item(idx).execute(parentExtractSize, parentExtract);
  18412. }
  18413. #endif
  18414. }
  18415. };
  18416. class CRoxieServerParallelActionActivityFactory : public CRoxieServerActivityFactory
  18417. {
  18418. bool isRoot;
  18419. public:
  18420. CRoxieServerParallelActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18421. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  18422. {
  18423. assertex(!isRoot); // non-internal should be expanded out..
  18424. }
  18425. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18426. {
  18427. return new CRoxieServerParallelActionActivity(_ctx, this, _probeManager);
  18428. }
  18429. virtual bool isSink() const
  18430. {
  18431. return isRoot;
  18432. }
  18433. };
  18434. IRoxieServerActivityFactory *createRoxieServerParallelActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18435. {
  18436. return new CRoxieServerParallelActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  18437. }
  18438. //=================================================================================
  18439. class CRoxieServerSequentialActionActivity : public CRoxieServerActionBaseActivity
  18440. {
  18441. IHThorSequentialArg &helper;
  18442. public:
  18443. CRoxieServerSequentialActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18444. : CRoxieServerActionBaseActivity(_ctx, _factory, _probeManager), helper((IHThorSequentialArg &)basehelper)
  18445. {
  18446. }
  18447. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  18448. {
  18449. unsigned numBranches = helper.numBranches();
  18450. for (unsigned branch=1; branch <= numBranches; branch++)
  18451. executeDependencies(parentExtractSize, parentExtract, branch);
  18452. }
  18453. };
  18454. class CRoxieServerSequentialActionActivityFactory : public CRoxieServerActivityFactory
  18455. {
  18456. bool isRoot;
  18457. public:
  18458. CRoxieServerSequentialActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18459. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  18460. {
  18461. }
  18462. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18463. {
  18464. return new CRoxieServerSequentialActionActivity(_ctx, this, _probeManager);
  18465. }
  18466. virtual bool isSink() const
  18467. {
  18468. return isRoot;
  18469. }
  18470. };
  18471. IRoxieServerActivityFactory *createRoxieServerSequentialActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18472. {
  18473. return new CRoxieServerSequentialActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  18474. }
  18475. //=================================================================================
  18476. class CRoxieServerWhenActivity : public CRoxieServerActivity
  18477. {
  18478. public:
  18479. CRoxieServerWhenActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18480. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  18481. {
  18482. savedExtractSize = 0;
  18483. savedExtract = NULL;
  18484. eofseen = false;
  18485. eogseen = false;
  18486. }
  18487. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18488. {
  18489. savedExtractSize = parentExtractSize;
  18490. savedExtract = parentExtract;
  18491. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  18492. executeDependencies(parentExtractSize, parentExtract, WhenBeforeId);
  18493. executeDependencies(parentExtractSize, parentExtract, WhenParallelId); // MORE: This should probably be done in parallel!
  18494. eofseen = false;
  18495. eogseen = false;
  18496. }
  18497. virtual void stop()
  18498. {
  18499. if (state == STATEreset || (!aborted && !eofseen)) // If someone else aborted, then WHEN clauses don't trigger, whatever
  18500. {
  18501. stopDependencies(savedExtractSize, savedExtract, WhenSuccessId);
  18502. stopDependencies(savedExtractSize, savedExtract, WhenFailureId);
  18503. }
  18504. else if (state != STATEstopped)
  18505. {
  18506. stopDependencies(savedExtractSize, savedExtract, aborted ? WhenSuccessId : WhenFailureId); // These ones don't get executed
  18507. executeDependencies(savedExtractSize, savedExtract, aborted ? WhenFailureId : WhenSuccessId); // These ones do
  18508. }
  18509. CRoxieServerActivity::stop();
  18510. }
  18511. virtual const void *nextRow()
  18512. {
  18513. try
  18514. {
  18515. ActivityTimer t(totalCycles, timeActivities); // bit of a waste of time....
  18516. const void *ret = inputStream->nextRow();
  18517. if (!ret)
  18518. {
  18519. if (eogseen)
  18520. eofseen = true;
  18521. else
  18522. eogseen = true;
  18523. }
  18524. else
  18525. eogseen = false;
  18526. return ret;
  18527. }
  18528. catch (...)
  18529. {
  18530. aborted = true;
  18531. throw;
  18532. }
  18533. }
  18534. protected:
  18535. const byte *savedExtract;
  18536. unsigned savedExtractSize;
  18537. bool eofseen;
  18538. bool eogseen;
  18539. };
  18540. class CRoxieServerWhenActivityFactory : public CRoxieServerActivityFactory
  18541. {
  18542. public:
  18543. CRoxieServerWhenActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  18544. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  18545. {
  18546. }
  18547. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18548. {
  18549. return new CRoxieServerWhenActivity(_ctx, this, _probeManager);
  18550. }
  18551. };
  18552. extern IRoxieServerActivityFactory *createRoxieServerWhenActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  18553. {
  18554. return new CRoxieServerWhenActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  18555. }
  18556. //=================================================================================
  18557. class CRoxieServerWhenActionActivity : public CRoxieServerActionBaseActivity
  18558. {
  18559. public:
  18560. CRoxieServerWhenActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18561. : CRoxieServerActionBaseActivity(_ctx, _factory, _probeManager)
  18562. {
  18563. savedExtractSize = 0;
  18564. savedExtract = NULL;
  18565. }
  18566. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18567. {
  18568. savedExtractSize = parentExtractSize;
  18569. savedExtract = parentExtract;
  18570. CRoxieServerActionBaseActivity::start(parentExtractSize, parentExtract, paused);
  18571. executeDependencies(parentExtractSize, parentExtract, WhenBeforeId);
  18572. executeDependencies(parentExtractSize, parentExtract, WhenParallelId); // MORE: This should probably be done in parallel!
  18573. }
  18574. virtual void stop()
  18575. {
  18576. if (state != STATEstopped)
  18577. {
  18578. stopDependencies(savedExtractSize, savedExtract, aborted ? WhenSuccessId : WhenFailureId); // these are NOT going to execute
  18579. executeDependencies(savedExtractSize, savedExtract, aborted ? WhenFailureId : WhenSuccessId);
  18580. }
  18581. CRoxieServerActionBaseActivity::stop();
  18582. }
  18583. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  18584. {
  18585. executeDependencies(parentExtractSize, parentExtract, 1);
  18586. }
  18587. protected:
  18588. unsigned savedExtractSize;
  18589. const byte *savedExtract;
  18590. };
  18591. class CRoxieServerWhenActionActivityFactory : public CRoxieServerActivityFactory
  18592. {
  18593. public:
  18594. CRoxieServerWhenActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18595. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  18596. {
  18597. }
  18598. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18599. {
  18600. return new CRoxieServerWhenActionActivity(_ctx, this, _probeManager);
  18601. }
  18602. virtual bool isSink() const
  18603. {
  18604. return isRoot;
  18605. }
  18606. private:
  18607. bool isRoot;
  18608. };
  18609. extern IRoxieServerActivityFactory *createRoxieServerWhenActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18610. {
  18611. return new CRoxieServerWhenActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  18612. }
  18613. //=================================================================================
  18614. class CRoxieServerStrandedParseActivity : public CRoxieServerStrandedActivity
  18615. {
  18616. INlpParseAlgorithm * algorithm;
  18617. class ParseProcessor : public StrandProcessor, implements IMatchedAction
  18618. {
  18619. protected:
  18620. IHThorParseArg &helper;
  18621. INlpParser * parser;
  18622. INlpResultIterator * rowIter;
  18623. const void * in;
  18624. char * curSearchText;
  18625. size32_t curSearchTextLen;
  18626. bool processRecord(const void * inRec)
  18627. {
  18628. if (helper.searchTextNeedsFree())
  18629. rtlFree(curSearchText);
  18630. curSearchTextLen = 0;
  18631. curSearchText = NULL;
  18632. helper.getSearchText(curSearchTextLen, curSearchText, inRec);
  18633. return parser->performMatch(*this, in, curSearchTextLen, curSearchText);
  18634. }
  18635. public:
  18636. ParseProcessor(CRoxieServerActivity &_parent, IEngineRowStream *_inputStream, IHThorParseArg &_helper, INlpParseAlgorithm * _algorithm)
  18637. : StrandProcessor(_parent, _inputStream, false), helper(_helper)
  18638. {
  18639. parser = _algorithm->createParser(parent.queryCodeContext(), parent.queryId(), helper.queryHelper(), &helper);
  18640. rowIter = parser->queryResultIter();
  18641. in = NULL;
  18642. curSearchText = NULL;
  18643. curSearchTextLen = 0;
  18644. }
  18645. ~ParseProcessor()
  18646. {
  18647. ::Release(parser);
  18648. }
  18649. virtual void start()
  18650. {
  18651. StrandProcessor::start();
  18652. numProcessedLastGroup = 0;
  18653. curSearchTextLen = 0;
  18654. curSearchText = NULL;
  18655. in = NULL;
  18656. parser->reset();
  18657. }
  18658. virtual void reset()
  18659. {
  18660. if (helper.searchTextNeedsFree())
  18661. rtlFree(curSearchText);
  18662. curSearchText = NULL;
  18663. ReleaseClearRoxieRow(in);
  18664. StrandProcessor::reset();
  18665. }
  18666. virtual const void * nextRow()
  18667. {
  18668. ActivityTimer t(totalCycles, timeActivities);
  18669. for (;;)
  18670. {
  18671. if (rowIter->isValid())
  18672. {
  18673. OwnedConstRoxieRow out = rowIter->getRow();
  18674. rowIter->next();
  18675. processed++;
  18676. return out.getClear();
  18677. }
  18678. ReleaseClearRoxieRow(in);
  18679. in = inputStream->nextRow();
  18680. if (!in)
  18681. {
  18682. if (processed == numProcessedLastGroup)
  18683. in = inputStream->nextRow();
  18684. if (!in)
  18685. {
  18686. processed = numProcessedLastGroup;
  18687. return NULL;
  18688. }
  18689. in = inputStream->nextRow();
  18690. if (!in)
  18691. return NULL;
  18692. }
  18693. processRecord(in);
  18694. rowIter->first();
  18695. }
  18696. }
  18697. virtual unsigned onMatch(ARowBuilder & self, const void * curRecord, IMatchedResults * results, IMatchWalker * walker)
  18698. {
  18699. try
  18700. {
  18701. return helper.transform(self, curRecord, results, walker);
  18702. }
  18703. catch (IException *E)
  18704. {
  18705. throw parent.makeWrappedException(E);
  18706. }
  18707. }
  18708. };
  18709. public:
  18710. CRoxieServerStrandedParseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, INlpParseAlgorithm * _algorithm, const StrandOptions &_strandOptions)
  18711. : CRoxieServerStrandedActivity(_ctx, _factory, _probeManager, _strandOptions), algorithm(_algorithm)
  18712. {
  18713. }
  18714. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18715. {
  18716. CRoxieServerStrandedActivity::start(parentExtractSize, parentExtract, paused);
  18717. onStartStrands();
  18718. }
  18719. virtual StrandProcessor *createStrandProcessor(IEngineRowStream *instream)
  18720. {
  18721. return new ParseProcessor(*this, instream, (IHThorParseArg &) basehelper, algorithm);
  18722. }
  18723. virtual StrandProcessor *createStrandSourceProcessor(bool inputOrdered) { throwUnexpected(); }
  18724. };
  18725. class CRoxieServerParseActivityFactory : public CRoxieServerActivityFactory
  18726. {
  18727. Owned<INlpParseAlgorithm> algorithm;
  18728. Owned<IHThorParseArg> helper;
  18729. StrandOptions strandOptions;
  18730. public:
  18731. CRoxieServerParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, IResourceContext *rc)
  18732. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), strandOptions(_graphNode)
  18733. {
  18734. helper.setown((IHThorParseArg *) helperFactory());
  18735. algorithm.setown(createThorParser(rc, *helper));
  18736. optStableInput = false;
  18737. }
  18738. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18739. {
  18740. return new CRoxieServerStrandedParseActivity(_ctx, this, _probeManager, algorithm, strandOptions);
  18741. }
  18742. };
  18743. IRoxieServerActivityFactory *createRoxieServerParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, IResourceContext *rc)
  18744. {
  18745. return new CRoxieServerParseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, rc);
  18746. }
  18747. //=====================================================================================================
  18748. class CRoxieServerWorkUnitWriteActivity : public CRoxieServerInternalSinkActivity
  18749. {
  18750. IHThorWorkUnitWriteArg &helper;
  18751. bool isReread;
  18752. bool grouped;
  18753. IRoxieServerContext *serverContext;
  18754. public:
  18755. CRoxieServerWorkUnitWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _isReread, unsigned _numOutputs)
  18756. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _numOutputs), helper((IHThorWorkUnitWriteArg &)basehelper), isReread(_isReread)
  18757. {
  18758. grouped = (helper.getFlags() & POFgrouped) != 0;
  18759. serverContext = NULL;
  18760. }
  18761. virtual void onCreate(IHThorArg *_colocalParent)
  18762. {
  18763. CRoxieServerInternalSinkActivity::onCreate(_colocalParent);
  18764. serverContext = ctx->queryServerContext();
  18765. if (!serverContext)
  18766. {
  18767. throw MakeStringException(ROXIE_PIPE_ERROR, "Pipe output activity cannot be executed in slave context");
  18768. }
  18769. }
  18770. virtual bool needsAllocator() const { return true; }
  18771. virtual void onExecute()
  18772. {
  18773. int sequence = helper.getSequence();
  18774. const char *storedName = helper.queryName();
  18775. if (!storedName)
  18776. storedName = "Dataset";
  18777. MemoryBuffer result;
  18778. bool saveInContext = (int) sequence < 0 || isReread;
  18779. if (!meta.queryOriginal()) // this is a bit of a hack - don't know why no meta on an output....
  18780. meta.set(input->queryOutputMeta());
  18781. Owned<IOutputRowSerializer> rowSerializer;
  18782. Owned<IXmlWriter> xmlwriter;
  18783. bool appendRaw = false;
  18784. IHpccProtocolResultsWriter *results = NULL;
  18785. IHpccNativeProtocolResultsWriter *nativeResults = NULL;
  18786. IHpccProtocolResponse *protocol = serverContext->queryProtocol();
  18787. unsigned protocolFlags = (protocol) ? protocol->getFlags() : 0;
  18788. if ((int) sequence >= 0)
  18789. {
  18790. results = (protocol) ? protocol->queryHpccResultsSection() : NULL;
  18791. if (results)
  18792. {
  18793. nativeResults = dynamic_cast<IHpccNativeProtocolResultsWriter*>(results);
  18794. xmlwriter.setown(results->addDataset(helper.queryName(), sequence, "Dataset", appendRaw, serverContext->getXmlFlags(), (helper.getFlags() & POFextend) != 0, serverContext->queryXmlns(sequence))); //xmlwriter only returned if needed
  18795. }
  18796. }
  18797. size32_t outputLimitBytes = 0;
  18798. IConstWorkUnit *workunit = serverContext->queryWorkUnit();
  18799. if (workunit)
  18800. {
  18801. size32_t outputLimit;
  18802. if (helper.getFlags() & POFmaxsize)
  18803. outputLimit = helper.getMaxSize();
  18804. else
  18805. {
  18806. // In absense of OPT_OUTPUTLIMIT check pre 5.2 legacy name OPT_OUTPUTLIMIT_LEGACY
  18807. outputLimit = workunit->getDebugValueInt(OPT_OUTPUTLIMIT, workunit->getDebugValueInt(OPT_OUTPUTLIMIT_LEGACY, defaultDaliResultLimit));
  18808. }
  18809. if (outputLimit>defaultDaliResultOutputMax)
  18810. throw MakeStringException(0, "Dali result outputs are restricted to a maximum of %d MB, the current limit is %d MB. A huge dali result usually indicates the ECL needs altering.", defaultDaliResultOutputMax, defaultDaliResultLimit);
  18811. assertex(outputLimit<=0x1000); // 32bit limit because MemoryBuffer/CMessageBuffers involved etc.
  18812. outputLimitBytes = outputLimit * 0x100000;
  18813. }
  18814. if (workunit != NULL || (results && protocol->getFlags() & HPCC_PROTOCOL_NATIVE_RAW))
  18815. {
  18816. ensureRowAllocator();
  18817. rowSerializer.setown(rowAllocator->createDiskSerializer(ctx->queryCodeContext()));
  18818. }
  18819. __int64 initialProcessed = processed;
  18820. RtlLinkedDatasetBuilder builder(rowAllocator);
  18821. for (;;)
  18822. {
  18823. const void *row = inputStream->nextRow();
  18824. if (saveInContext)
  18825. {
  18826. if (row || grouped)
  18827. builder.append(row);
  18828. }
  18829. if (grouped && (processed != initialProcessed))
  18830. {
  18831. if (workunit)
  18832. result.append(row == NULL);
  18833. if (results)
  18834. {
  18835. if (protocolFlags & HPCC_PROTOCOL_NATIVE_RAW && nativeResults)
  18836. {
  18837. char val = (char)(row == NULL);
  18838. nativeResults->appendRaw(sequence, 1, &val);
  18839. }
  18840. else if (xmlwriter)
  18841. {
  18842. xmlwriter->outputBeginNested("Row", false);
  18843. xmlwriter->outputCString("1", "@__GroupBreak__");
  18844. xmlwriter->outputEndNested("Row");
  18845. }
  18846. }
  18847. }
  18848. if (!row)
  18849. {
  18850. row = inputStream->nextRow();
  18851. if (!row)
  18852. break;
  18853. if (saveInContext)
  18854. builder.append(row);
  18855. }
  18856. processed++;
  18857. if (workunit)
  18858. {
  18859. CThorDemoRowSerializer serializerTarget(result);
  18860. rowSerializer->serialize(serializerTarget, (const byte *) row);
  18861. }
  18862. if ((int) sequence >= 0)
  18863. {
  18864. if (appendRaw && nativeResults)
  18865. {
  18866. // MORE - should be able to serialize straight to the response...
  18867. MemoryBuffer rowbuff;
  18868. CThorDemoRowSerializer serializerTarget(rowbuff);
  18869. rowSerializer->serialize(serializerTarget, (const byte *) row);
  18870. nativeResults->appendRawRow(sequence, rowbuff.length(), rowbuff.toByteArray());
  18871. }
  18872. else if (xmlwriter)
  18873. {
  18874. xmlwriter->outputBeginNested(DEFAULTXMLROWTAG, false);
  18875. helper.serializeXml((byte *) row, *xmlwriter);
  18876. xmlwriter->outputEndNested(DEFAULTXMLROWTAG);
  18877. results->finalizeXmlRow(sequence);
  18878. }
  18879. else if (nativeResults)
  18880. {
  18881. SimpleOutputWriter x;
  18882. helper.serializeXml((byte *) row, x);
  18883. x.newline();
  18884. nativeResults->appendSimpleRow(sequence, x.str());
  18885. }
  18886. }
  18887. ReleaseRoxieRow(row);
  18888. if (outputLimitBytes && result.length() > outputLimitBytes)
  18889. {
  18890. StringBuffer errMsg("Dataset too large to output to workunit (limit ");
  18891. errMsg.append(outputLimitBytes/0x100000).append(" megabytes), in result (");
  18892. const char *name = helper.queryName();
  18893. if (name)
  18894. errMsg.append("name=").append(name);
  18895. else
  18896. errMsg.append("sequence=").append(helper.getSequence());
  18897. errMsg.append(")");
  18898. throw MakeStringExceptionDirect(0, errMsg.str());
  18899. }
  18900. }
  18901. if (xmlwriter)
  18902. xmlwriter->outputEndArray(DEFAULTXMLROWTAG);
  18903. if (saveInContext)
  18904. serverContext->appendResultDeserialized(storedName, sequence, builder.getcount(), builder.linkrows(), (helper.getFlags() & POFextend) != 0, LINK(meta.queryOriginal()));
  18905. if (workunit)
  18906. serverContext->appendResultRawContext(storedName, sequence, result.length(), result.toByteArray(), processed, (helper.getFlags() & POFextend) != 0, false); // MORE - shame to do extra copy...
  18907. }
  18908. };
  18909. class CRoxieServerWorkUnitWriteActivityFactory : public CRoxieServerInternalSinkFactory
  18910. {
  18911. bool isReread;
  18912. public:
  18913. CRoxieServerWorkUnitWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  18914. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot)
  18915. {
  18916. isReread = usageCount > 0;
  18917. Owned<IHThorWorkUnitWriteArg> helper = (IHThorWorkUnitWriteArg *) helperFactory();
  18918. isInternal = (helper->getSequence()==ResultSequenceInternal);
  18919. }
  18920. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18921. {
  18922. return new CRoxieServerWorkUnitWriteActivity(_ctx, this, _probeManager, isReread, usageCount);
  18923. }
  18924. };
  18925. IRoxieServerActivityFactory *createRoxieServerWorkUnitWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  18926. {
  18927. return new CRoxieServerWorkUnitWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot);
  18928. }
  18929. //=====================================================================================================
  18930. class CRoxieServerWorkUnitWriteDictActivity : public CRoxieServerInternalSinkActivity
  18931. {
  18932. IHThorDictionaryWorkUnitWriteArg &helper;
  18933. IRoxieServerContext *serverContext;
  18934. public:
  18935. CRoxieServerWorkUnitWriteDictActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _usageCount)
  18936. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _usageCount), helper((IHThorDictionaryWorkUnitWriteArg &)basehelper)
  18937. {
  18938. serverContext = NULL;
  18939. }
  18940. virtual void onCreate(IHThorArg *_colocalParent)
  18941. {
  18942. CRoxieServerInternalSinkActivity::onCreate(_colocalParent);
  18943. serverContext = ctx->queryServerContext();
  18944. if (!serverContext)
  18945. {
  18946. throw MakeStringException(ROXIE_PIPE_ERROR, "Write Dictionary activity cannot be executed in slave context");
  18947. }
  18948. }
  18949. virtual bool needsAllocator() const { return true; }
  18950. virtual void onExecute()
  18951. {
  18952. int sequence = helper.getSequence();
  18953. const char *storedName = helper.queryName();
  18954. assertex(storedName && *storedName);
  18955. assertex(sequence < 0);
  18956. RtlLinkedDictionaryBuilder builder(rowAllocator, helper.queryHashLookupInfo());
  18957. for (;;)
  18958. {
  18959. const void *row = inputStream->ungroupedNextRow();
  18960. if (!row)
  18961. break;
  18962. builder.appendOwn(row);
  18963. processed++;
  18964. }
  18965. serverContext->appendResultDeserialized(storedName, sequence, builder.getcount(), builder.linkrows(), (helper.getFlags() & POFextend) != 0, LINK(meta.queryOriginal()));
  18966. }
  18967. };
  18968. class CRoxieServerWorkUnitWriteDictActivityFactory : public CRoxieServerInternalSinkFactory
  18969. {
  18970. public:
  18971. CRoxieServerWorkUnitWriteDictActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  18972. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot)
  18973. {
  18974. Owned<IHThorDictionaryWorkUnitWriteArg> helper = (IHThorDictionaryWorkUnitWriteArg *) helperFactory();
  18975. isInternal = (helper->getSequence()==ResultSequenceInternal);
  18976. }
  18977. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18978. {
  18979. return new CRoxieServerWorkUnitWriteDictActivity(_ctx, this, _probeManager, usageCount);
  18980. }
  18981. };
  18982. IRoxieServerActivityFactory *createRoxieServerWorkUnitWriteDictActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  18983. {
  18984. return new CRoxieServerWorkUnitWriteDictActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot);
  18985. }
  18986. //=================================================================================
  18987. class CRoxieServerRemoteResultActivity : public CRoxieServerInternalSinkActivity
  18988. {
  18989. IHThorRemoteResultArg &helper;
  18990. public:
  18991. CRoxieServerRemoteResultActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  18992. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _numOutputs), helper((IHThorRemoteResultArg &)basehelper)
  18993. {
  18994. }
  18995. virtual void onExecute()
  18996. {
  18997. OwnedConstRoxieRow row = inputStream->nextRow();
  18998. helper.sendResult(row); // should be only one row or something has gone wrong!
  18999. }
  19000. };
  19001. class CRoxieServerRemoteResultActivityFactory : public CRoxieServerInternalSinkFactory
  19002. {
  19003. public:
  19004. CRoxieServerRemoteResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  19005. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot)
  19006. {
  19007. Owned<IHThorRemoteResultArg> helper = (IHThorRemoteResultArg *) helperFactory();
  19008. isInternal = (helper->getSequence()==ResultSequenceInternal);
  19009. }
  19010. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  19011. {
  19012. return new CRoxieServerRemoteResultActivity(_ctx, this, _probeManager, usageCount);
  19013. }
  19014. };
  19015. IRoxieServerActivityFactory *createRoxieServerRemoteResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  19016. {
  19017. return new CRoxieServerRemoteResultActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot);
  19018. }
  19019. //=================================================================================
  19020. class CRoxieServerXmlParseActivity : public CRoxieServerActivity, implements IXMLSelect
  19021. {
  19022. IHThorXmlParseArg &helper;
  19023. Owned<IXMLParse> xmlParser;
  19024. const void * in;
  19025. char * srchStr;
  19026. unsigned numProcessedLastGroup;
  19027. bool srchStrNeedsFree;
  19028. Owned<IColumnProvider> lastMatch;
  19029. public:
  19030. IMPLEMENT_IINTERFACE_USING(CRoxieServerActivity)
  19031. CRoxieServerXmlParseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  19032. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  19033. helper((IHThorXmlParseArg &)basehelper)
  19034. {
  19035. srchStrNeedsFree = helper.searchTextNeedsFree();
  19036. numProcessedLastGroup = 0;
  19037. srchStr = NULL;
  19038. in = NULL;
  19039. }
  19040. ~CRoxieServerXmlParseActivity()
  19041. {
  19042. }
  19043. virtual bool needsAllocator() const { return true; }
  19044. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19045. {
  19046. numProcessedLastGroup = 0;
  19047. srchStr = NULL;
  19048. in = NULL;
  19049. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  19050. }
  19051. virtual void reset()
  19052. {
  19053. if (helper.searchTextNeedsFree())
  19054. rtlFree(srchStr);
  19055. srchStr = NULL;
  19056. ReleaseClearRoxieRow(in);
  19057. xmlParser.clear();
  19058. CRoxieServerActivity::reset();
  19059. }
  19060. virtual void match(IColumnProvider &entry, offset_t startOffset, offset_t endOffset)
  19061. {
  19062. lastMatch.set(&entry);
  19063. }
  19064. virtual const void *nextRow()
  19065. {
  19066. ActivityTimer t(totalCycles, timeActivities);
  19067. for (;;)
  19068. {
  19069. if(xmlParser)
  19070. {
  19071. for (;;)
  19072. {
  19073. if(!xmlParser->next())
  19074. {
  19075. if (srchStrNeedsFree)
  19076. {
  19077. rtlFree(srchStr);
  19078. srchStr = NULL;
  19079. }
  19080. xmlParser.clear();
  19081. break;
  19082. }
  19083. if(lastMatch)
  19084. {
  19085. try
  19086. {
  19087. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  19088. size32_t outSize = helper.transform(rowBuilder, in, lastMatch);
  19089. lastMatch.clear();
  19090. if (outSize)
  19091. {
  19092. processed++;
  19093. return rowBuilder.finalizeRowClear(outSize);
  19094. }
  19095. }
  19096. catch (IException *E)
  19097. {
  19098. throw makeWrappedException(E);
  19099. }
  19100. }
  19101. }
  19102. }
  19103. ReleaseClearRoxieRow(in);
  19104. in = inputStream->nextRow();
  19105. if(!in)
  19106. {
  19107. if(numProcessedLastGroup == processed)
  19108. in = inputStream->nextRow();
  19109. if(!in)
  19110. {
  19111. numProcessedLastGroup = processed;
  19112. return NULL;
  19113. }
  19114. }
  19115. size32_t srchLen;
  19116. helper.getSearchText(srchLen, srchStr, in);
  19117. OwnedRoxieString xmlIteratorPath(helper.getXmlIteratorPath());
  19118. xmlParser.setown(createXMLParse(srchStr, srchLen, xmlIteratorPath, *this));
  19119. }
  19120. }
  19121. };
  19122. class CRoxieServerXmlParseActivityFactory : public CRoxieServerActivityFactory
  19123. {
  19124. public:
  19125. CRoxieServerXmlParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  19126. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  19127. {
  19128. }
  19129. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  19130. {
  19131. return new CRoxieServerXmlParseActivity(_ctx, this, _probeManager);
  19132. }
  19133. };
  19134. IRoxieServerActivityFactory *createRoxieServerXmlParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  19135. {
  19136. return new CRoxieServerXmlParseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  19137. }
  19138. //=====================================================================================================
  19139. class CRoxieServerDiskReadBaseActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler, implements IIndexReadContext
  19140. {
  19141. protected:
  19142. IHThorDiskReadBaseArg &helper;
  19143. IHThorCompoundExtra * compoundHelper;
  19144. RemoteActivityId remoteId; // Note we copy it rather than reference
  19145. Owned<CSkippableRemoteResultAdaptor> remote;
  19146. unsigned numParts;
  19147. unsigned __int64 rowLimit;
  19148. unsigned __int64 stopAfter;
  19149. Linked<IInMemoryIndexManager> manager;
  19150. Owned<IInMemoryIndexCursor> cursor;
  19151. Owned<IDirectReader> reader;
  19152. CThorContiguousRowBuffer deserializeSource;
  19153. Owned<ISourceRowPrefetcher> prefetcher;
  19154. bool eof;
  19155. bool isKeyed;
  19156. bool variableFileName;
  19157. bool isOpt;
  19158. bool sorted;
  19159. bool maySkip;
  19160. bool isLocal;
  19161. bool forceRemote;
  19162. bool isGrouped = false;
  19163. CachedOutputMetaData diskSize;
  19164. Owned<const IResolvedFile> varFileInfo;
  19165. Owned<IFileIOArray> varFiles;
  19166. inline bool useRemote()
  19167. {
  19168. return remote != NULL && (forceRemote || numParts > 1);
  19169. }
  19170. public:
  19171. IMPLEMENT_IINTERFACE_USING(CRoxieServerActivity)
  19172. CRoxieServerDiskReadBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager)
  19173. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  19174. helper((IHThorDiskReadBaseArg &)basehelper),
  19175. numParts(_numParts),
  19176. remoteId(_remoteId),
  19177. manager(_manager),
  19178. isLocal(_isLocal),
  19179. sorted(_sorted),
  19180. maySkip(_maySkip),
  19181. deserializeSource(NULL)
  19182. {
  19183. forceRemote = factory->queryQueryFactory().queryOptions().disableLocalOptimizations;
  19184. if ((forceRemote || numParts != 1) && !isLocal) // NOTE : when numParts == 0 (variable case) we create, even though we may not use
  19185. remote.setown(new CSkippableRemoteResultAdaptor(_ctx, this, remoteId, meta.queryOriginal(), helper, *this, sorted, false, _maySkip));
  19186. compoundHelper = NULL;
  19187. eof = false;
  19188. rowLimit = (unsigned __int64) -1;
  19189. isKeyed = false;
  19190. stopAfter = I64C(0x7FFFFFFFFFFFFFFF);
  19191. Linked<IOutputMetaData> diskMeta(helper.queryDiskRecordSize()->querySerializedDiskMeta());
  19192. if (diskMeta->isGrouped())
  19193. {
  19194. diskMeta.setown(new CSuffixedOutputMeta(+1, diskMeta.getClear()));
  19195. isGrouped = true;
  19196. }
  19197. diskSize.set(diskMeta);
  19198. variableFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getFlags() & (TDXvarfilename|TDXdynamicfilename)) != 0);
  19199. isOpt = (helper.getFlags() & TDRoptional) != 0;
  19200. }
  19201. virtual const IResolvedFile *queryVarFileInfo() const
  19202. {
  19203. return varFileInfo;
  19204. }
  19205. virtual void onCreate(IHThorArg *_colocalParent)
  19206. {
  19207. CRoxieServerActivity::onCreate(_colocalParent);
  19208. if (remote)
  19209. remote->onCreate(_colocalParent);
  19210. }
  19211. virtual bool needsAllocator() const { return true; }
  19212. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19213. {
  19214. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  19215. if (compoundHelper)
  19216. {
  19217. rowLimit = compoundHelper->getRowLimit();
  19218. stopAfter = compoundHelper->getChooseNLimit();
  19219. }
  19220. if (!helper.canMatchAny())
  19221. eof = true;
  19222. else
  19223. {
  19224. if (variableFileName)
  19225. {
  19226. OwnedRoxieString fileName(helper.getFileName());
  19227. varFileInfo.setown(resolveLFN(fileName, isOpt));
  19228. numParts = 0;
  19229. if (varFileInfo)
  19230. {
  19231. numParts = varFileInfo->getNumParts();
  19232. const IPropertyTree *options = varFileInfo->queryProperties();
  19233. if (options)
  19234. {
  19235. isGrouped = options->getPropBool("@grouped");
  19236. if (isGrouped && !diskSize.isGrouped())
  19237. {
  19238. // We are prepared to read contents of a grouped persist ungrouped... But not vice versa
  19239. VStringBuffer msg("Published group information for file %s does not match coded information - assuming grouped", fileName.get());
  19240. WARNLOG("%s", msg.str());
  19241. ctx->queryCodeContext()->addWuException(msg.str(), ROXIE_LAYOUT_MISMATCH, SeverityError, "roxie");
  19242. Owned<IOutputMetaData> diskMeta(new CSuffixedOutputMeta(+1, LINK(diskSize.queryOriginal())));
  19243. diskSize.set(diskMeta);
  19244. }
  19245. size32_t dfsSize = options->getPropInt("@recordSize");
  19246. if (dfsSize && diskSize.isFixedSize() && dfsSize != diskSize.getFixedSize())
  19247. throw MakeStringException(ROXIE_LAYOUT_MISMATCH, "Published record size %d for file %s (%s) does not match coded record size %d", dfsSize, fileName.get(), isGrouped ? "grouped" : "ungrouped", diskSize.getFixedSize());
  19248. }
  19249. }
  19250. }
  19251. if (!numParts)
  19252. {
  19253. eof = true;
  19254. }
  19255. else if (useRemote())
  19256. {
  19257. remote->onStart(parentExtractSize, parentExtract);
  19258. remote->setLimits(rowLimit, (unsigned __int64) -1, stopAfter);
  19259. unsigned fileNo = 0;
  19260. // Translation into a message per channel done elsewhere....
  19261. remote->getMem(0, fileNo, 0);
  19262. remote->flush();
  19263. remote->senddone();
  19264. }
  19265. else
  19266. {
  19267. if (variableFileName)
  19268. {
  19269. unsigned channel = isLocal ? factory->queryQueryFactory().queryChannel() : 0;
  19270. varFiles.setown(varFileInfo->getIFileIOArray(isOpt, channel));
  19271. manager.setown(varFileInfo->getIndexManager(isOpt, channel, varFiles, diskSize, false, 0));
  19272. }
  19273. assertex(manager != NULL);
  19274. helper.createSegmentMonitors(this);
  19275. if (cursor)
  19276. {
  19277. isKeyed = cursor->selectKey();
  19278. cursor->reset();
  19279. }
  19280. if (!isKeyed)
  19281. {
  19282. reader.setown(manager->createReader(0, 0, 1));
  19283. deserializeSource.setStream(reader);
  19284. prefetcher.setown(diskSize.queryOriginal()->createDiskPrefetcher(ctx->queryCodeContext(), activityId));
  19285. }
  19286. helper.setCallback(reader ? reader->queryThorDiskCallback() : cursor);
  19287. }
  19288. }
  19289. }
  19290. virtual void append(IKeySegmentMonitor *segment)
  19291. {
  19292. if (!segment->isWild())
  19293. {
  19294. if (!cursor)
  19295. cursor.setown(manager->createCursor());
  19296. cursor->append(segment);
  19297. }
  19298. }
  19299. virtual unsigned ordinality() const
  19300. {
  19301. return cursor ? cursor->ordinality() : 0;
  19302. }
  19303. virtual IKeySegmentMonitor *item(unsigned idx) const
  19304. {
  19305. return cursor ? cursor->item(idx) : 0;
  19306. }
  19307. virtual void setMergeBarrier(unsigned barrierOffset)
  19308. {
  19309. // no merging so no issue...
  19310. }
  19311. virtual void stop()
  19312. {
  19313. if (useRemote())
  19314. remote->onStop();
  19315. CRoxieServerActivity::stop();
  19316. }
  19317. virtual void reset()
  19318. {
  19319. if (useRemote())
  19320. {
  19321. processed = remote->processed;
  19322. remote->processed = 0;
  19323. remote->onReset();
  19324. }
  19325. varFileInfo.clear();
  19326. eof = false;
  19327. if (cursor)
  19328. cursor->reset();
  19329. deserializeSource.clearStream();
  19330. CRoxieServerActivity::reset();
  19331. }
  19332. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  19333. {
  19334. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  19335. }
  19336. virtual void onLimitExceeded(bool isKeyed)
  19337. {
  19338. if (traceLevel > 4)
  19339. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  19340. assertex(compoundHelper);
  19341. if (isKeyed) // MORE does this exist for diskread? should it?
  19342. {
  19343. if (helper.getFlags() & (TDRkeyedlimitskips|TDRkeyedlimitcreates))
  19344. {
  19345. if (ctx->queryDebugContext())
  19346. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  19347. throw makeLimitSkipException(true);
  19348. }
  19349. else
  19350. {
  19351. UNIMPLEMENTED;
  19352. //compoundHelper->onKeyedLimitExceeded(); Doesn't exist - though the flags do... interesting...
  19353. }
  19354. }
  19355. else
  19356. {
  19357. if (helper.getFlags() & (TDRlimitskips|TDRlimitcreates))
  19358. {
  19359. if (ctx->queryDebugContext())
  19360. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  19361. throw makeLimitSkipException(false);
  19362. }
  19363. else
  19364. compoundHelper->onLimitExceeded();
  19365. }
  19366. }
  19367. virtual const void * createLimitFailRow(bool isKeyed)
  19368. {
  19369. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  19370. IHThorSourceLimitTransformExtra *limitTransformExtra = static_cast<IHThorSourceLimitTransformExtra *>(helper.selectInterface(TAIsourcelimittransformextra_1));
  19371. assertex(limitTransformExtra);
  19372. size32_t outSize = isKeyed ? limitTransformExtra->transformOnKeyedLimitExceeded(rowBuilder) : limitTransformExtra->transformOnLimitExceeded(rowBuilder);
  19373. if (outSize)
  19374. return rowBuilder.finalizeRowClear(outSize);
  19375. return NULL;
  19376. }
  19377. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  19378. {
  19379. CRoxieServerActivity::gatherStats(merged);
  19380. if (remote)
  19381. remote->gatherStats(merged);
  19382. }
  19383. };
  19384. class CRoxieServerDiskReadActivity : public CRoxieServerDiskReadBaseActivity
  19385. {
  19386. IHThorCompoundReadExtra * readHelper;
  19387. ConstPointerArray readrows;
  19388. bool readAheadDone;
  19389. bool eogPending;
  19390. unsigned readIndex;
  19391. unsigned lastGroupProcessed;
  19392. public:
  19393. CRoxieServerDiskReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager)
  19394. : CRoxieServerDiskReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, _maySkip, _manager)
  19395. {
  19396. compoundHelper = (IHThorDiskReadArg *)&helper;
  19397. readHelper = (IHThorDiskReadArg *)&helper;
  19398. readAheadDone = false;
  19399. readIndex = 0;
  19400. eogPending = false;
  19401. lastGroupProcessed = processed;
  19402. }
  19403. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19404. {
  19405. rowLimit = compoundHelper->getRowLimit();
  19406. stopAfter = compoundHelper->getChooseNLimit();
  19407. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  19408. readAheadDone = false;
  19409. readIndex = 0;
  19410. eogPending = false;
  19411. lastGroupProcessed = processed;
  19412. }
  19413. virtual void reset()
  19414. {
  19415. roxiemem::ReleaseRoxieRowRange(readrows.getArray(), readIndex, readrows.ordinality());
  19416. readrows.kill();
  19417. readAheadDone = false;
  19418. readIndex = 0;
  19419. eogPending = false;
  19420. lastGroupProcessed = processed;
  19421. CRoxieServerDiskReadBaseActivity::reset();
  19422. }
  19423. virtual const void *nextRow()
  19424. {
  19425. ActivityTimer t(totalCycles, timeActivities);
  19426. if (eof)
  19427. return NULL;
  19428. else if (useRemote())
  19429. return remote->nextRow();
  19430. else if (maySkip)
  19431. {
  19432. if (!readAheadDone)
  19433. {
  19434. unsigned preprocessed = 0;
  19435. while (!eof)
  19436. {
  19437. const void *row = _nextRow();
  19438. if (row)
  19439. preprocessed++;
  19440. if (preprocessed > rowLimit)
  19441. {
  19442. ReleaseRoxieRow(row);
  19443. roxiemem::ReleaseRoxieRowRange(readrows.getArray(), readIndex, readrows.ordinality());
  19444. readrows.kill();
  19445. readIndex = 0;
  19446. eof = true;
  19447. if (ctx->queryDebugContext())
  19448. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  19449. if (helper.getFlags() & TDRlimitskips)
  19450. return NULL;
  19451. else if (helper.getFlags() & TDRlimitcreates)
  19452. return createLimitFailRow(false);
  19453. else
  19454. throwUnexpected();
  19455. }
  19456. if (preprocessed > stopAfter) // MORE - bit of a strange place to check
  19457. {
  19458. eof = true;
  19459. ReleaseRoxieRow(row);
  19460. break;
  19461. }
  19462. readrows.append(row);
  19463. }
  19464. readAheadDone = true;
  19465. }
  19466. if (readrows.isItem(readIndex))
  19467. {
  19468. const void *ret = readrows.item(readIndex++);
  19469. if (ret)
  19470. processed++;
  19471. return ret;
  19472. }
  19473. else
  19474. {
  19475. eof = true;
  19476. return NULL;
  19477. }
  19478. }
  19479. else
  19480. {
  19481. const void *ret = _nextRow();
  19482. if (ret)
  19483. {
  19484. processed++;
  19485. if (processed > rowLimit)
  19486. {
  19487. if (traceLevel > 4)
  19488. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  19489. ReleaseRoxieRow(ret);
  19490. compoundHelper->onLimitExceeded();
  19491. throwUnexpected(); // onLimitExceeded is not supposed to return
  19492. }
  19493. if (processed > stopAfter) // MORE - bit of a strange place to check
  19494. {
  19495. eof = true;
  19496. ReleaseRoxieRow(ret);
  19497. return NULL;
  19498. }
  19499. }
  19500. return ret;
  19501. }
  19502. }
  19503. const void *_nextRow()
  19504. {
  19505. if (eogPending && (lastGroupProcessed != processed))
  19506. {
  19507. eogPending = false;
  19508. lastGroupProcessed = processed;
  19509. return NULL;
  19510. }
  19511. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  19512. unsigned transformedSize = 0;
  19513. if (isKeyed)
  19514. {
  19515. for (;;)
  19516. {
  19517. const void *nextCandidate = cursor->nextMatch();
  19518. if (!nextCandidate)
  19519. {
  19520. eof = true;
  19521. return NULL;
  19522. }
  19523. transformedSize = readHelper->transform(rowBuilder, nextCandidate);
  19524. if (transformedSize)
  19525. break;
  19526. }
  19527. }
  19528. else // use reader...
  19529. {
  19530. assertex(reader != NULL);
  19531. for (;;)
  19532. {
  19533. if (deserializeSource.eos())
  19534. {
  19535. eof = true;
  19536. return NULL;
  19537. }
  19538. prefetcher->readAhead(deserializeSource);
  19539. const byte *nextRec = deserializeSource.queryRow();
  19540. if (cursor && cursor->isFiltered(nextRec))
  19541. transformedSize = 0;
  19542. else
  19543. transformedSize = readHelper->transform(rowBuilder, nextRec);
  19544. bool eog;
  19545. if (isGrouped)
  19546. {
  19547. size32_t sizeRead = diskSize.getRecordSize(nextRec);
  19548. eog = nextRec[sizeRead-1];
  19549. }
  19550. else
  19551. eog = false;
  19552. deserializeSource.finishedRow();
  19553. if (transformedSize)
  19554. {
  19555. if (isGrouped)
  19556. eogPending = eog;
  19557. break;
  19558. }
  19559. else
  19560. {
  19561. if (eog && (lastGroupProcessed != processed))
  19562. {
  19563. lastGroupProcessed = processed;
  19564. return NULL;
  19565. }
  19566. }
  19567. }
  19568. }
  19569. return rowBuilder.finalizeRowClear(transformedSize);
  19570. }
  19571. };
  19572. class CRoxieServerXmlReadActivity : public CRoxieServerDiskReadBaseActivity, implements IXMLSelect, implements IThorDiskCallback
  19573. {
  19574. IHThorXmlReadArg * readHelper;
  19575. Owned<IXmlToRowTransformer> rowTransformer;
  19576. Owned<IXMLParse> xmlParser;
  19577. Owned<IColumnProvider> lastMatch;
  19578. unsigned __int64 fileoffset;
  19579. public:
  19580. IMPLEMENT_IINTERFACE_USING(CRoxieServerDiskReadBaseActivity)
  19581. CRoxieServerXmlReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager)
  19582. : CRoxieServerDiskReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, _maySkip, _manager)
  19583. {
  19584. compoundHelper = NULL;
  19585. readHelper = (IHThorXmlReadArg *)&helper;
  19586. fileoffset = 0;
  19587. }
  19588. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19589. {
  19590. rowLimit = readHelper->getRowLimit();
  19591. stopAfter = readHelper->getChooseNLimit();
  19592. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  19593. if (!useRemote())
  19594. {
  19595. rowTransformer.set(readHelper->queryTransformer());
  19596. assertex(reader != NULL);
  19597. OwnedRoxieString xmlIterator(readHelper->getXmlIteratorPath());
  19598. if (factory->getKind()==TAKjsonread)
  19599. xmlParser.setown(createJSONParse(*reader->querySimpleStream(), xmlIterator, *this, (0 != (TDRxmlnoroot & readHelper->getFlags()))?ptr_noRoot:ptr_none, (readHelper->getFlags() & TDRusexmlcontents) != 0));
  19600. else
  19601. xmlParser.setown(createXMLParse(*reader->querySimpleStream(), xmlIterator, *this, (0 != (TDRxmlnoroot & readHelper->getFlags()))?ptr_noRoot:ptr_none, (readHelper->getFlags() & TDRusexmlcontents) != 0));
  19602. }
  19603. }
  19604. virtual void reset()
  19605. {
  19606. CRoxieServerDiskReadBaseActivity::reset();
  19607. rowTransformer.clear();
  19608. xmlParser.clear();
  19609. }
  19610. virtual void match(IColumnProvider &entry, offset_t startOffset, offset_t endOffset)
  19611. {
  19612. fileoffset = startOffset;
  19613. lastMatch.set(&entry);
  19614. }
  19615. //interface IThorDiskCallback
  19616. virtual unsigned __int64 getFilePosition(const void * row)
  19617. {
  19618. return fileoffset;
  19619. }
  19620. virtual unsigned __int64 getLocalFilePosition(const void * row)
  19621. {
  19622. return reader->makeFilePositionLocal(fileoffset);
  19623. }
  19624. virtual const char * queryLogicalFilename(const void * row)
  19625. {
  19626. return reader->queryThorDiskCallback()->queryLogicalFilename(row);
  19627. }
  19628. virtual const void *nextRow()
  19629. {
  19630. ActivityTimer t(totalCycles, timeActivities);
  19631. if (eof)
  19632. return NULL;
  19633. else if (useRemote())
  19634. return remote->nextRow();
  19635. assertex(xmlParser != NULL);
  19636. try
  19637. {
  19638. while (!eof)
  19639. {
  19640. //call to next() will callback on the IXmlSelect interface
  19641. bool gotNext = false;
  19642. gotNext = xmlParser->next();
  19643. if(!gotNext)
  19644. eof = true;
  19645. else if (lastMatch)
  19646. {
  19647. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  19648. unsigned sizeGot = rowTransformer->transform(rowBuilder, lastMatch, this);
  19649. lastMatch.clear();
  19650. fileoffset = 0;
  19651. if (sizeGot)
  19652. {
  19653. OwnedConstRoxieRow ret = rowBuilder.finalizeRowClear(sizeGot);
  19654. if (processed > rowLimit)
  19655. {
  19656. if (traceLevel > 4)
  19657. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  19658. readHelper->onLimitExceeded();
  19659. throwUnexpected(); // onLimitExceeded is not supposed to return
  19660. }
  19661. processed++;
  19662. if (processed > stopAfter) // MORE - bit of a strange place to check
  19663. {
  19664. eof = true;
  19665. return NULL;
  19666. }
  19667. return ret.getClear();
  19668. }
  19669. }
  19670. }
  19671. return NULL;
  19672. }
  19673. catch(IException *E)
  19674. {
  19675. throw makeWrappedException(E);
  19676. }
  19677. }
  19678. };
  19679. class CRoxieServerCsvReadActivity : public CRoxieServerDiskReadBaseActivity
  19680. {
  19681. IHThorCsvReadArg *readHelper;
  19682. ICsvParameters * csvInfo;
  19683. unsigned headerLines;
  19684. unsigned maxDiskSize;
  19685. CSVSplitter csvSplitter;
  19686. unsigned __int64 localOffset;
  19687. const char *quotes;
  19688. const char *separators;
  19689. const char *terminators;
  19690. const char *escapes;
  19691. size32_t maxRowSize;
  19692. public:
  19693. CRoxieServerCsvReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  19694. unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager,
  19695. const char *_quotes, const char *_separators, const char *_terminators, const char *_escapes, size32_t _maxRowSize)
  19696. : CRoxieServerDiskReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, _maySkip, _manager),
  19697. quotes(_quotes), separators(_separators), terminators(_terminators), escapes(_escapes), maxRowSize(_maxRowSize)
  19698. {
  19699. compoundHelper = NULL;
  19700. readHelper = (IHThorCsvReadArg *)&helper;
  19701. rowLimit = readHelper->getRowLimit();
  19702. stopAfter = readHelper->getChooseNLimit();
  19703. csvInfo = readHelper->queryCsvParameters();
  19704. maxDiskSize = csvInfo->queryMaxSize();
  19705. localOffset = 0;
  19706. headerLines = 0;
  19707. }
  19708. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19709. {
  19710. rowLimit = readHelper->getRowLimit();
  19711. stopAfter = readHelper->getChooseNLimit();
  19712. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  19713. if (!useRemote())
  19714. {
  19715. headerLines = csvInfo->queryHeaderLen();
  19716. if (headerLines && isLocal && reader->queryFilePart() != 1)
  19717. 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...
  19718. if (!eof)
  19719. {
  19720. if (varFileInfo)
  19721. {
  19722. const IPropertyTree *options = varFileInfo->queryProperties();
  19723. if (options)
  19724. {
  19725. quotes = options->queryProp("@csvQuote");
  19726. separators = options->queryProp("@csvSeparate");
  19727. terminators = options->queryProp("@csvTerminate");
  19728. escapes = options->queryProp("@csvEscape");
  19729. }
  19730. }
  19731. csvSplitter.init(readHelper->getMaxColumns(), csvInfo, quotes, separators, terminators, escapes);
  19732. }
  19733. }
  19734. }
  19735. virtual const void *nextRow()
  19736. {
  19737. ActivityTimer t(totalCycles, timeActivities);
  19738. if (eof)
  19739. return NULL;
  19740. else if (useRemote())
  19741. return remote->nextRow();
  19742. try
  19743. {
  19744. while (!eof)
  19745. {
  19746. if (reader->eos())
  19747. {
  19748. eof = true;
  19749. break;
  19750. }
  19751. // MORE - there are rumours of a csvSplitter that operates on a stream... if/when it exists, this should use it
  19752. size32_t rowSize = 4096; // MORE - make configurable
  19753. size32_t thisLineLength;
  19754. for (;;)
  19755. {
  19756. size32_t avail;
  19757. const void *peek = reader->peek(rowSize, avail);
  19758. thisLineLength = csvSplitter.splitLine(avail, (const byte *)peek);
  19759. if (thisLineLength < rowSize || avail < rowSize)
  19760. break;
  19761. if (rowSize == maxRowSize)
  19762. throw MakeStringException(0, "File contained a line of length greater than %d bytes.", maxRowSize);
  19763. if (rowSize >= maxRowSize/2)
  19764. rowSize = maxRowSize;
  19765. else
  19766. rowSize += rowSize;
  19767. }
  19768. if (headerLines)
  19769. {
  19770. headerLines--;
  19771. reader->skip(thisLineLength);
  19772. }
  19773. else
  19774. {
  19775. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  19776. unsigned transformedSize = readHelper->transform(rowBuilder, csvSplitter.queryLengths(), (const char * *)csvSplitter.queryData());
  19777. reader->skip(thisLineLength);
  19778. if (transformedSize)
  19779. {
  19780. OwnedConstRoxieRow ret = rowBuilder.finalizeRowClear(transformedSize);
  19781. if (processed > rowLimit)
  19782. {
  19783. readHelper->onLimitExceeded();
  19784. throwUnexpected(); // onLimitExceeded is not supposed to return
  19785. }
  19786. processed++;
  19787. if (processed > stopAfter) // MORE - bit of a strange place to check
  19788. {
  19789. eof = true;
  19790. return NULL;
  19791. }
  19792. return ret.getClear();
  19793. }
  19794. }
  19795. }
  19796. return NULL;
  19797. }
  19798. catch(IException *E)
  19799. {
  19800. throw makeWrappedException(E);
  19801. }
  19802. }
  19803. virtual void reset()
  19804. {
  19805. CRoxieServerDiskReadBaseActivity::reset();
  19806. csvSplitter.reset();
  19807. localOffset = 0;
  19808. }
  19809. virtual unsigned __int64 getFilePosition(const void * row)
  19810. {
  19811. UNIMPLEMENTED; // we know offset in the reader but not sure it helps us much
  19812. }
  19813. virtual unsigned __int64 getLocalFilePosition(const void * row)
  19814. {
  19815. UNIMPLEMENTED;
  19816. }
  19817. };
  19818. class CRoxieServerDiskNormalizeActivity : public CRoxieServerDiskReadBaseActivity
  19819. {
  19820. IHThorDiskNormalizeArg *normalizeHelper;
  19821. bool firstPending;
  19822. public:
  19823. CRoxieServerDiskNormalizeActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, IInMemoryIndexManager *_manager)
  19824. : CRoxieServerDiskReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, false, _manager)
  19825. {
  19826. compoundHelper = (IHThorDiskNormalizeArg *)&helper;
  19827. normalizeHelper = (IHThorDiskNormalizeArg *)&helper;
  19828. firstPending = true;
  19829. }
  19830. virtual void reset()
  19831. {
  19832. firstPending = true;
  19833. CRoxieServerDiskReadBaseActivity::reset();
  19834. }
  19835. virtual const void *nextRow()
  19836. {
  19837. ActivityTimer t(totalCycles, timeActivities);
  19838. if (eof)
  19839. return NULL;
  19840. else if (useRemote())
  19841. return remote->nextRow();
  19842. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  19843. unsigned transformedSize = 0;
  19844. if (isKeyed)
  19845. {
  19846. for (;;)
  19847. {
  19848. while (firstPending)
  19849. {
  19850. const void *nextCandidate = cursor->nextMatch();
  19851. if (!nextCandidate)
  19852. {
  19853. eof = true;
  19854. return NULL;
  19855. }
  19856. if (normalizeHelper->first(nextCandidate))
  19857. {
  19858. firstPending = false;
  19859. break;
  19860. }
  19861. }
  19862. transformedSize = normalizeHelper->transform(rowBuilder);
  19863. firstPending = !normalizeHelper->next();
  19864. if (transformedSize)
  19865. break;
  19866. }
  19867. }
  19868. else
  19869. {
  19870. assertex(reader != NULL);
  19871. for (;;)
  19872. {
  19873. while (firstPending)
  19874. {
  19875. if (deserializeSource.eos())
  19876. {
  19877. eof = true;
  19878. return NULL;
  19879. }
  19880. prefetcher->readAhead(deserializeSource);
  19881. const byte *nextRec = deserializeSource.queryRow();
  19882. if (!cursor || !cursor->isFiltered(nextRec))
  19883. {
  19884. if (normalizeHelper->first(nextRec))
  19885. firstPending = false;
  19886. }
  19887. deserializeSource.finishedRow();
  19888. }
  19889. transformedSize = normalizeHelper->transform(rowBuilder);
  19890. firstPending = !normalizeHelper->next();
  19891. if (transformedSize)
  19892. break;
  19893. }
  19894. }
  19895. OwnedConstRoxieRow recBuffer = rowBuilder.finalizeRowClear(transformedSize);
  19896. processed++;
  19897. if (processed > rowLimit)
  19898. {
  19899. compoundHelper->onLimitExceeded();
  19900. throwUnexpected(); // onLimitExceeded is not supposed to return
  19901. }
  19902. if (processed > stopAfter) // MORE - bit of a strange place to check
  19903. {
  19904. eof = true;
  19905. return NULL;
  19906. }
  19907. return recBuffer.getClear();
  19908. }
  19909. };
  19910. class CRoxieServerDiskAggregateBaseActivity : public CRoxieServerDiskReadBaseActivity
  19911. {
  19912. protected:
  19913. bool done;
  19914. public:
  19915. CRoxieServerDiskAggregateBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager)
  19916. : CRoxieServerDiskReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, false, false, _manager),
  19917. done(false)
  19918. {
  19919. }
  19920. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19921. {
  19922. done = false;
  19923. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  19924. }
  19925. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  19926. {
  19927. if (idx==(unsigned)-1)
  19928. idx = 0;
  19929. return idx ? NULL: this;
  19930. }
  19931. };
  19932. class CRoxieServerDiskCountActivity : public CRoxieServerDiskAggregateBaseActivity
  19933. {
  19934. IHThorDiskCountArg & countHelper;
  19935. unsigned __int64 choosenLimit;
  19936. IHThorSourceCountLimit *limitHelper;
  19937. unsigned __int64 getSkippedCount()
  19938. {
  19939. unsigned flags = countHelper.getFlags();
  19940. if (flags & TDRlimitskips)
  19941. return 0;
  19942. else if (flags & TDRlimitcreates)
  19943. return 1;
  19944. else
  19945. {
  19946. assertex(limitHelper);
  19947. if (traceLevel > 4)
  19948. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  19949. limitHelper->onLimitExceeded();
  19950. throwUnexpected(); // onLimitExceeded should always throw exception
  19951. }
  19952. }
  19953. public:
  19954. CRoxieServerDiskCountActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager)
  19955. : CRoxieServerDiskAggregateBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _manager),
  19956. countHelper((IHThorDiskCountArg &)basehelper)
  19957. {
  19958. limitHelper = static_cast<IHThorSourceCountLimit *>(basehelper.selectInterface(TAIsourcecountlimit_1));
  19959. choosenLimit = 0;
  19960. }
  19961. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19962. {
  19963. choosenLimit = countHelper.getChooseNLimit();
  19964. if (limitHelper)
  19965. {
  19966. rowLimit = limitHelper->getRowLimit();
  19967. // keyedLimit = limitHelper->getKeyedLimit(); // more - should there be one?
  19968. }
  19969. CRoxieServerDiskAggregateBaseActivity::start(parentExtractSize, parentExtract, paused);
  19970. }
  19971. virtual const void *nextRow()
  19972. {
  19973. ActivityTimer t(totalCycles, timeActivities);
  19974. if (done) return NULL;
  19975. done = true;
  19976. unsigned __int64 totalCount = 0;
  19977. if (helper.canMatchAny() && !eof)
  19978. {
  19979. if (useRemote())
  19980. {
  19981. for (;;)
  19982. {
  19983. const void * next = remote->nextRow();
  19984. if (!next)
  19985. break;
  19986. if (meta.getFixedSize() == 1)
  19987. totalCount += *(byte *)next;
  19988. else
  19989. totalCount += *(unsigned __int64 *)next;
  19990. ReleaseRoxieRow(next);
  19991. if (totalCount > rowLimit)
  19992. {
  19993. totalCount = getSkippedCount();
  19994. break;
  19995. }
  19996. else if (totalCount >= choosenLimit)
  19997. {
  19998. totalCount = choosenLimit;
  19999. break;
  20000. }
  20001. }
  20002. }
  20003. else
  20004. {
  20005. if (isKeyed)
  20006. {
  20007. for (;;)
  20008. {
  20009. const void *nextCandidate = cursor->nextMatch();
  20010. if (!nextCandidate)
  20011. break;
  20012. totalCount += countHelper.numValid(nextCandidate);
  20013. if (totalCount > rowLimit)
  20014. {
  20015. totalCount = getSkippedCount();
  20016. break;
  20017. }
  20018. else if (totalCount >= choosenLimit)
  20019. {
  20020. totalCount = choosenLimit;
  20021. break;
  20022. }
  20023. }
  20024. }
  20025. else
  20026. {
  20027. assertex(reader != NULL);
  20028. while (!deserializeSource.eos())
  20029. {
  20030. prefetcher->readAhead(deserializeSource);
  20031. const byte *nextRec = deserializeSource.queryRow();
  20032. if (!cursor || !cursor->isFiltered(nextRec))
  20033. {
  20034. totalCount += countHelper.numValid(nextRec);
  20035. }
  20036. deserializeSource.finishedRow();
  20037. if (totalCount > rowLimit)
  20038. {
  20039. totalCount = getSkippedCount();
  20040. break;
  20041. }
  20042. else if (totalCount >= choosenLimit)
  20043. {
  20044. totalCount = choosenLimit;
  20045. break;
  20046. }
  20047. }
  20048. }
  20049. }
  20050. }
  20051. size32_t rowSize = meta.getFixedSize();
  20052. void * result = rowAllocator->createRow();
  20053. if (rowSize == 1)
  20054. *(byte *)result = (byte)totalCount;
  20055. else
  20056. {
  20057. assertex(rowSize == sizeof(unsigned __int64));
  20058. *(unsigned __int64 *)result = totalCount;
  20059. }
  20060. return rowAllocator->finalizeRow(rowSize, result, rowSize);
  20061. }
  20062. };
  20063. class CRoxieServerDiskAggregateActivity : public CRoxieServerDiskAggregateBaseActivity
  20064. {
  20065. IHThorCompoundAggregateExtra & aggregateHelper;
  20066. public:
  20067. CRoxieServerDiskAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  20068. unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager)
  20069. : CRoxieServerDiskAggregateBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _manager),
  20070. aggregateHelper((IHThorDiskAggregateArg &)basehelper)
  20071. {
  20072. }
  20073. const void * gatherMerged()
  20074. {
  20075. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  20076. size32_t finalSize = 0;
  20077. if (useRemote())
  20078. {
  20079. const void * firstRow = remote->nextRow();
  20080. if (!firstRow)
  20081. {
  20082. rowBuilder.ensureRow();
  20083. finalSize = aggregateHelper.clearAggregate(rowBuilder);
  20084. }
  20085. else
  20086. {
  20087. // NOTE need to clone this because going to modify below, could special case 1 row only
  20088. finalSize = cloneRow(rowBuilder, firstRow, meta);
  20089. ReleaseRoxieRow(firstRow);
  20090. }
  20091. for (;;)
  20092. {
  20093. const void * next = remote->nextRow();
  20094. if (!next)
  20095. break;
  20096. finalSize = aggregateHelper.mergeAggregate(rowBuilder, next);
  20097. ReleaseRoxieRow(next);
  20098. }
  20099. }
  20100. else
  20101. {
  20102. aggregateHelper.clearAggregate(rowBuilder);
  20103. if (helper.canMatchAny() && !eof)
  20104. {
  20105. if (isKeyed)
  20106. {
  20107. for (;;)
  20108. {
  20109. const void *next = cursor->nextMatch();
  20110. if (!next)
  20111. break;
  20112. aggregateHelper.processRow(rowBuilder, next);
  20113. }
  20114. }
  20115. else
  20116. {
  20117. assertex(reader != NULL);
  20118. while (!deserializeSource.eos())
  20119. {
  20120. prefetcher->readAhead(deserializeSource);
  20121. const byte *nextRec = deserializeSource.queryRow();
  20122. if (!cursor || !cursor->isFiltered(nextRec))
  20123. {
  20124. aggregateHelper.processRow(rowBuilder, nextRec);
  20125. }
  20126. deserializeSource.finishedRow();
  20127. }
  20128. }
  20129. }
  20130. finalSize = meta.getRecordSize(rowBuilder.getSelf());
  20131. }
  20132. return rowBuilder.finalizeRowClear(finalSize);
  20133. }
  20134. virtual const void *nextRow()
  20135. {
  20136. ActivityTimer t(totalCycles, timeActivities);
  20137. if (done) return NULL;
  20138. const void * ret = gatherMerged();
  20139. done = true;
  20140. return ret;
  20141. }
  20142. };
  20143. class CRoxieServerDiskGroupAggregateActivity : public CRoxieServerDiskAggregateBaseActivity
  20144. {
  20145. IHThorDiskGroupAggregateArg & aggregateHelper;
  20146. RowAggregator resultAggregator;
  20147. bool gathered;
  20148. public:
  20149. CRoxieServerDiskGroupAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager)
  20150. : CRoxieServerDiskAggregateBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _manager),
  20151. aggregateHelper((IHThorDiskGroupAggregateArg &)basehelper),
  20152. resultAggregator(aggregateHelper, aggregateHelper),
  20153. gathered(false)
  20154. {
  20155. }
  20156. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20157. {
  20158. gathered= false;
  20159. CRoxieServerDiskAggregateBaseActivity::start(parentExtractSize, parentExtract, paused);
  20160. resultAggregator.start(rowAllocator);
  20161. }
  20162. virtual void reset()
  20163. {
  20164. resultAggregator.reset();
  20165. CRoxieServerDiskAggregateBaseActivity::reset();
  20166. }
  20167. void gatherMerged()
  20168. {
  20169. if (useRemote())
  20170. {
  20171. for (;;)
  20172. {
  20173. const void * next = remote->nextRow();
  20174. if (!next)
  20175. break;
  20176. resultAggregator.mergeElement(next);
  20177. ReleaseRoxieRow(next);
  20178. }
  20179. }
  20180. else
  20181. {
  20182. if (helper.canMatchAny() && !eof)
  20183. {
  20184. Owned<IInMemoryFileProcessor> processor = isKeyed ?
  20185. createKeyedGroupAggregateRecordProcessor(cursor, resultAggregator, aggregateHelper) :
  20186. createUnkeyedGroupAggregateRecordProcessor(cursor, resultAggregator, aggregateHelper, manager->createReader(0, 0, 1),
  20187. ctx->queryCodeContext(), activityId);
  20188. processor->doQuery(NULL, 0, 0, 0);
  20189. }
  20190. }
  20191. gathered = true;
  20192. }
  20193. virtual const void *nextRow()
  20194. {
  20195. ActivityTimer t(totalCycles, timeActivities);
  20196. if (done)
  20197. return NULL;
  20198. if (!gathered)
  20199. gatherMerged();
  20200. Owned<AggregateRowBuilder> next = resultAggregator.nextResult();
  20201. if (next)
  20202. {
  20203. processed++;
  20204. return next->finalizeRowClear();
  20205. }
  20206. done = true;
  20207. return NULL;
  20208. }
  20209. };
  20210. class CRoxieServerDiskReadActivityFactory : public CRoxieServerActivityFactory
  20211. {
  20212. public:
  20213. RemoteActivityId remoteId;
  20214. bool isLocal;
  20215. bool sorted;
  20216. bool maySkip;
  20217. bool variableFileName;
  20218. Owned<IFileIOArray> files;
  20219. Owned<IInMemoryIndexManager> manager;
  20220. Owned<const IResolvedFile> datafile;
  20221. const char *quotes;
  20222. const char *separators;
  20223. const char *terminators;
  20224. const char *escapes;
  20225. size32_t maxCsvRowSize;
  20226. CRoxieServerDiskReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  20227. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), remoteId(_remoteId)
  20228. {
  20229. isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  20230. Owned<IHThorDiskReadBaseArg> helper = (IHThorDiskReadBaseArg *) helperFactory();
  20231. sorted = (helper->getFlags() & TDRunsorted) == 0;
  20232. variableFileName = allFilesDynamic || _queryFactory.isDynamic() || ((helper->getFlags() & (TDXvarfilename|TDXdynamicfilename)) != 0);
  20233. maySkip = (helper->getFlags() & (TDRkeyedlimitskips|TDRkeyedlimitcreates|TDRlimitskips|TDRlimitcreates)) != 0;
  20234. quotes = separators = terminators = escapes = NULL;
  20235. if (!variableFileName)
  20236. {
  20237. bool isOpt = (helper->getFlags() & TDRoptional) != 0;
  20238. OwnedRoxieString fileName(helper->getFileName());
  20239. datafile.setown(_queryFactory.queryPackage().lookupFileName(fileName, isOpt, true, true, _queryFactory.queryWorkUnit(), true));
  20240. Linked<IOutputMetaData> diskMeta(helper->queryDiskRecordSize()->querySerializedDiskMeta());
  20241. if (diskMeta->isGrouped())
  20242. diskMeta.setown(new CSuffixedOutputMeta(+1, diskMeta.getClear()));
  20243. if (datafile)
  20244. {
  20245. const IPropertyTree *options = datafile->queryProperties();
  20246. if (options)
  20247. {
  20248. bool isGrouped = options->getPropBool("@grouped");
  20249. if (isGrouped && !diskMeta->isGrouped())
  20250. {
  20251. // We are prepared to read contents of a grouped persist ungrouped... But not vice versa
  20252. WARNLOG("Published group information for file %s does not match coded information - assuming grouped", fileName.get());
  20253. diskMeta.setown(new CSuffixedOutputMeta(+1, diskMeta.getClear()));
  20254. }
  20255. size32_t dfsSize = options->getPropInt("@recordSize");
  20256. if (dfsSize && diskMeta->isFixedSize() && dfsSize != diskMeta->getFixedSize())
  20257. throw MakeStringException(ROXIE_LAYOUT_MISMATCH, "Published record size %d for file %s (%s) does not match coded record size %d", dfsSize, fileName.get(), isGrouped ? "grouped" : "ungrouped", diskMeta->getFixedSize());
  20258. }
  20259. }
  20260. bool isSimple = (datafile && datafile->getNumParts()==1 && !_queryFactory.queryOptions().disableLocalOptimizations);
  20261. if (isLocal || isSimple)
  20262. {
  20263. if (datafile)
  20264. {
  20265. unsigned channel = isLocal ? queryFactory.queryChannel() : 0;
  20266. files.setown(datafile->getIFileIOArray(isOpt, channel));
  20267. manager.setown(datafile->getIndexManager(isOpt, channel, files, diskMeta, _graphNode.getPropBool("att[@name=\"preload\"]/@value", false), _graphNode.getPropInt("att[@name=\"_preloadSize\"]/@value", 0)));
  20268. const IPropertyTree *options = datafile->queryProperties();
  20269. if (options)
  20270. {
  20271. quotes = options->queryProp("@csvQuote");
  20272. separators = options->queryProp("@csvSeparate");
  20273. terminators = options->queryProp("@csvTerminate");
  20274. escapes = options->queryProp("@csvEscape");
  20275. }
  20276. }
  20277. else
  20278. manager.setown(getEmptyIndexManager());
  20279. }
  20280. }
  20281. switch (kind)
  20282. {
  20283. case TAKcsvread:
  20284. {
  20285. maxCsvRowSize = defaultMaxCsvRowSize * 1024 * 1024;
  20286. IConstWorkUnit *workunit = _queryFactory.queryWorkUnit();
  20287. if (workunit)
  20288. maxCsvRowSize = workunit->getDebugValueInt(OPT_MAXCSVROWSIZE, defaultMaxCsvRowSize) * 1024 * 1024;
  20289. break;
  20290. }
  20291. default:
  20292. maxCsvRowSize = 0; // unused
  20293. }
  20294. }
  20295. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  20296. {
  20297. unsigned numParts = datafile ? datafile->getNumParts() : 0;
  20298. switch (kind)
  20299. {
  20300. case TAKcsvread:
  20301. return new CRoxieServerCsvReadActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, sorted, maySkip, manager,
  20302. quotes, separators, terminators, escapes, maxCsvRowSize);
  20303. case TAKxmlread:
  20304. case TAKjsonread:
  20305. return new CRoxieServerXmlReadActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, sorted, maySkip, manager);
  20306. case TAKdiskread:
  20307. return new CRoxieServerDiskReadActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, sorted, maySkip, manager);
  20308. case TAKdisknormalize:
  20309. return new CRoxieServerDiskNormalizeActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, sorted, manager);
  20310. case TAKdiskcount:
  20311. return new CRoxieServerDiskCountActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, manager);
  20312. case TAKdiskaggregate:
  20313. return new CRoxieServerDiskAggregateActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, manager);
  20314. case TAKdiskgroupaggregate:
  20315. return new CRoxieServerDiskGroupAggregateActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, manager);
  20316. }
  20317. throwUnexpected();
  20318. }
  20319. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  20320. {
  20321. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  20322. }
  20323. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  20324. {
  20325. if (datafile)
  20326. addXrefFileInfo(reply, datafile);
  20327. else
  20328. {
  20329. // Temporarily resolve the file
  20330. Owned<IHThorDiskReadBaseArg> helper = (IHThorDiskReadBaseArg *) helperFactory();
  20331. if ((helper->getFlags() & (TDXvarfilename|TDXdynamicfilename)) == 0)
  20332. {
  20333. OwnedRoxieString fileName(helper->getFileName());
  20334. Owned<const IResolvedFile> temp = queryFactory.queryPackage().lookupFileName(fileName, true, true, false, queryFactory.queryWorkUnit(), true);
  20335. if (temp)
  20336. addXrefFileInfo(reply, temp);
  20337. }
  20338. }
  20339. }
  20340. virtual const StatisticsMapping &queryStatsMapping() const
  20341. {
  20342. return diskStatistics;
  20343. }
  20344. };
  20345. IRoxieServerActivityFactory *createRoxieServerDiskReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  20346. {
  20347. return new CRoxieServerDiskReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  20348. }
  20349. //=================================================================================
  20350. class CRoxieServerIndexActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler
  20351. {
  20352. protected:
  20353. IHThorIndexReadBaseArg &indexHelper;
  20354. IHThorSteppedSourceExtra * steppedExtra;
  20355. Linked<IKeyArray> keySet;
  20356. Linked<TranslatorArray> translators;
  20357. CSkippableRemoteResultAdaptor remote;
  20358. CIndexTransformCallback callback;
  20359. bool sorted;
  20360. bool variableFileName;
  20361. bool variableInfoPending;
  20362. bool isOpt;
  20363. bool isLocal;
  20364. unsigned __int64 rowLimit;
  20365. unsigned __int64 keyedLimit;
  20366. unsigned __int64 choosenLimit;
  20367. unsigned accepted;
  20368. unsigned rejected;
  20369. unsigned seekGEOffset;
  20370. Owned<IKeyManager> tlk;
  20371. Owned<const IResolvedFile> varFileInfo;
  20372. const RemoteActivityId &remoteId;
  20373. void setVariableFileInfo()
  20374. {
  20375. OwnedRoxieString indexName(indexHelper.getFileName());
  20376. varFileInfo.setown(resolveLFN(indexName, isOpt));
  20377. if (varFileInfo)
  20378. {
  20379. translators.setown(new TranslatorArray) ;
  20380. keySet.setown(varFileInfo->getKeyArray(factory->queryActivityMeta(), translators, isOpt, isLocal ? factory->queryQueryFactory().queryChannel() : 0, factory->queryQueryFactory().queryOptions().enableFieldTranslation));
  20381. }
  20382. variableInfoPending = false;
  20383. }
  20384. public:
  20385. CRoxieServerIndexActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  20386. IKeyArray * _keySet, TranslatorArray *_translators, bool _sorted, bool _isLocal, bool _maySkip)
  20387. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  20388. keySet(_keySet),
  20389. translators(_translators),
  20390. indexHelper((IHThorIndexReadBaseArg &)basehelper),
  20391. remote(_ctx, this, _remoteId, meta.queryOriginal(), indexHelper, *this, _sorted, false, _maySkip),
  20392. remoteId(_remoteId),
  20393. sorted(_sorted),
  20394. isLocal(_isLocal)
  20395. {
  20396. indexHelper.setCallback(&callback);
  20397. steppedExtra = static_cast<IHThorSteppedSourceExtra *>(indexHelper.selectInterface(TAIsteppedsourceextra_1));
  20398. variableFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((indexHelper.getFlags() & (TIRvarfilename|TIRdynamicfilename)) != 0);
  20399. variableInfoPending = false;
  20400. isOpt = (indexHelper.getFlags() & TIRoptional) != 0;
  20401. seekGEOffset = 0;
  20402. // started = false;
  20403. rejected = accepted = 0;
  20404. rowLimit = choosenLimit = keyedLimit = 0;
  20405. }
  20406. virtual const IResolvedFile *queryVarFileInfo() const
  20407. {
  20408. return varFileInfo;
  20409. }
  20410. virtual void onCreate(IHThorArg *_colocalParent)
  20411. {
  20412. CRoxieServerActivity::onCreate(_colocalParent);
  20413. remote.onCreate(_colocalParent);
  20414. }
  20415. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20416. {
  20417. accepted = 0;
  20418. rejected = 0;
  20419. rowLimit = (unsigned __int64) -1;
  20420. keyedLimit = (unsigned __int64 ) -1;
  20421. choosenLimit = I64C(0x7fffffffffffffff);
  20422. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  20423. remote.onStart(parentExtractSize, parentExtract);
  20424. variableInfoPending = variableFileName;
  20425. }
  20426. void processAllKeys()
  20427. {
  20428. try
  20429. {
  20430. if (indexHelper.canMatchAny())
  20431. {
  20432. if (variableInfoPending)
  20433. setVariableFileInfo();
  20434. remote.setLimits(rowLimit, keyedLimit, choosenLimit);
  20435. if (keySet)
  20436. {
  20437. // MORE - this recreates the segmonitors per part but not per fileno (which is a little backwards).
  20438. // 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
  20439. // However order is probably better to iterate fileno's inside partnos
  20440. // MORE - also not properly supporting STEPPED I fear.
  20441. // A superkey that mixes single and multipart or tlk and roroot keys might be hard
  20442. for (unsigned partNo = 0; partNo < keySet->length(); partNo++)
  20443. {
  20444. IKeyIndexBase *thisBase = keySet->queryKeyPart(partNo);
  20445. if (thisBase)
  20446. {
  20447. unsigned fileNo = 0;
  20448. IKeyIndex *thisKey = thisBase->queryPart(fileNo);
  20449. if (!thisKey->isTopLevelKey())
  20450. {
  20451. if (keyedLimit != (unsigned __int64) -1)
  20452. {
  20453. if ((indexHelper.getFlags() & TIRcountkeyedlimit) != 0)
  20454. {
  20455. Owned<IKeyManager> countKey;
  20456. countKey.setown(createKeyManager(thisKey, 0, this));
  20457. countKey->setLayoutTranslator(translators->item(fileNo));
  20458. createSegmentMonitors(countKey);
  20459. unsigned __int64 count = countKey->checkCount(keyedLimit);
  20460. if (count > keyedLimit)
  20461. {
  20462. if (traceLevel > 4)
  20463. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  20464. onLimitExceeded(true);
  20465. }
  20466. }
  20467. }
  20468. }
  20469. if (seekGEOffset && !thisKey->isTopLevelKey())
  20470. {
  20471. tlk.setown(createSingleKeyMerger(thisKey, 0, seekGEOffset, this));
  20472. }
  20473. else
  20474. {
  20475. tlk.setown(createKeyManager(thisKey, 0, this));
  20476. tlk->setLayoutTranslator(translators->item(fileNo));
  20477. }
  20478. createSegmentMonitors(tlk);
  20479. if (queryTraceLevel() > 3 || ctx->queryProbeManager())
  20480. {
  20481. StringBuffer out;
  20482. printKeyedValues(out, tlk, indexHelper.queryDiskRecordSize());
  20483. CTXLOG("Using filter %s", out.str());
  20484. if (ctx->queryProbeManager())
  20485. ctx->queryProbeManager()->setNodeProperty(this, "filter", out.str());
  20486. }
  20487. tlk->reset();
  20488. for (;;) // for each file part
  20489. {
  20490. //block for TransformCallbackAssociation
  20491. {
  20492. TransformCallbackAssociation associate(callback, tlk);
  20493. if (thisKey->isTopLevelKey())
  20494. {
  20495. if (thisKey->isFullySorted())
  20496. {
  20497. while (tlk->lookup(false))
  20498. {
  20499. unsigned slavePart = (unsigned) tlk->queryFpos();
  20500. if (slavePart)
  20501. {
  20502. accepted++;
  20503. remote.getMem(slavePart, fileNo, 0); // the cached context is all we need to send
  20504. if (sorted && numChannels>1)
  20505. remote.flush(); // don't combine parts if we need result sorted, except on a 1-way
  20506. }
  20507. }
  20508. }
  20509. else
  20510. {
  20511. // MORE - we could check whether there are any matching parts if we wanted.
  20512. // If people are in the habit of sending null values that would be worthwhile
  20513. remote.getMem(0, fileNo, 0);
  20514. }
  20515. }
  20516. else
  20517. {
  20518. if (processSingleKey(thisKey, translators->item(fileNo)))
  20519. break;
  20520. }
  20521. }
  20522. if (++fileNo < thisBase->numParts())
  20523. {
  20524. thisKey = thisBase->queryPart(fileNo);
  20525. tlk->setKey(thisKey);
  20526. tlk->setLayoutTranslator(translators->item(fileNo));
  20527. tlk->reset();
  20528. }
  20529. else
  20530. break;
  20531. }
  20532. tlk->releaseSegmentMonitors();
  20533. tlk->setKey(NULL);
  20534. }
  20535. }
  20536. }
  20537. }
  20538. remote.flush();
  20539. remote.senddone();
  20540. }
  20541. catch (IException *E)
  20542. {
  20543. remote.setException(E);
  20544. }
  20545. }
  20546. virtual void createSegmentMonitors(IKeyManager *key)
  20547. {
  20548. indexHelper.createSegmentMonitors(key);
  20549. key->finishSegmentMonitors();
  20550. }
  20551. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans) = 0;
  20552. virtual void reset()
  20553. {
  20554. if (accepted)
  20555. noteStatistic(StNumIndexAccepted, accepted);
  20556. if (rejected)
  20557. noteStatistic(StNumIndexRejected, rejected);
  20558. remote.onReset();
  20559. CRoxieServerActivity::reset();
  20560. if (varFileInfo)
  20561. {
  20562. keySet.clear();
  20563. varFileInfo.clear();
  20564. }
  20565. variableInfoPending = false;
  20566. }
  20567. virtual void stop()
  20568. {
  20569. remote.onStop();
  20570. CRoxieServerActivity::stop();
  20571. }
  20572. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  20573. {
  20574. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  20575. }
  20576. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  20577. {
  20578. CRoxieServerActivity::gatherStats(merged);
  20579. remote.gatherStats(merged);
  20580. }
  20581. };
  20582. class CRoxieServerIndexReadBaseActivity : public CRoxieServerIndexActivity
  20583. {
  20584. IHThorSourceLimitTransformExtra * limitTransformExtra;
  20585. public:
  20586. CRoxieServerIndexReadBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  20587. IKeyArray * _keySet, TranslatorArray *_translators, bool _sorted, bool _isLocal, bool _maySkip)
  20588. : CRoxieServerIndexActivity(_ctx, _factory, _probeManager, _remoteId, _keySet, _translators, _sorted, _isLocal, _maySkip)
  20589. {
  20590. limitTransformExtra = static_cast<IHThorSourceLimitTransformExtra *>(indexHelper.selectInterface(TAIsourcelimittransformextra_1));
  20591. }
  20592. virtual void reset()
  20593. {
  20594. remote.onReset();
  20595. CRoxieServerIndexActivity::reset();
  20596. }
  20597. virtual const void *nextRow()
  20598. {
  20599. ActivityTimer t(totalCycles, timeActivities);
  20600. try
  20601. {
  20602. const void *ret = remote.nextRow();
  20603. if (ret)
  20604. processed++;
  20605. return ret;
  20606. }
  20607. catch (IException *E)
  20608. {
  20609. throw makeWrappedException(E);
  20610. }
  20611. }
  20612. protected:
  20613. virtual const void * createLimitFailRow(bool isKeyed)
  20614. {
  20615. ensureRowAllocator();
  20616. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  20617. size32_t outSize = isKeyed ? limitTransformExtra->transformOnKeyedLimitExceeded(rowBuilder) : limitTransformExtra->transformOnLimitExceeded(rowBuilder);
  20618. if (outSize)
  20619. return rowBuilder.finalizeRowClear(outSize);
  20620. return NULL;
  20621. }
  20622. };
  20623. class CRoxieServerIndexReadActivity : public CRoxieServerIndexReadBaseActivity, implements IIndexReadActivityInfo
  20624. {
  20625. protected:
  20626. IHThorCompoundReadExtra & readHelper;
  20627. ISteppingMeta *rawMeta = nullptr;
  20628. CSteppingMeta steppingMeta;
  20629. unsigned * seekSizes = nullptr;
  20630. bool optimizeSteppedPostFilter;
  20631. ISteppingMeta * projectedMeta = nullptr;
  20632. unsigned maxSeekLookahead;
  20633. public:
  20634. CRoxieServerIndexReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  20635. IKeyArray * _keySet, TranslatorArray *_translators, bool _sorted, bool _isLocal, bool _maySkip, unsigned _maxSeekLookahead)
  20636. : CRoxieServerIndexReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _keySet, _translators, _sorted, _isLocal, _maySkip),
  20637. readHelper((IHThorIndexReadArg &)basehelper)
  20638. {
  20639. rawMeta = readHelper.queryRawSteppingMeta();
  20640. unsigned flags = indexHelper.getFlags();
  20641. optimizeSteppedPostFilter = (flags & TIRunfilteredtransform) != 0;
  20642. seekSizes = NULL;
  20643. maxSeekLookahead = _maxSeekLookahead;
  20644. if (rawMeta)
  20645. {
  20646. const CFieldOffsetSize * fields = rawMeta->queryFields();
  20647. unsigned maxFields = rawMeta->getNumFields();
  20648. seekGEOffset = fields[0].offset;
  20649. seekSizes = new unsigned[maxFields];
  20650. seekSizes[0] = fields[0].size;
  20651. for (unsigned i=1; i < maxFields; i++)
  20652. seekSizes[i] = seekSizes[i-1] + fields[i].size;
  20653. projectedMeta = readHelper.queryProjectedSteppingMeta();
  20654. ISteppingMeta *useMeta = projectedMeta ? projectedMeta : rawMeta;
  20655. remote.setMergeInfo(useMeta); // also need to consider superfile case where there is a mix of multiway and singleparts.. ?
  20656. bool hasPostFilter = readHelper.transformMayFilter() && optimizeSteppedPostFilter;
  20657. steppingMeta.init(useMeta, hasPostFilter);
  20658. }
  20659. }
  20660. ~CRoxieServerIndexReadActivity()
  20661. {
  20662. delete [] seekSizes;
  20663. }
  20664. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20665. {
  20666. CRoxieServerIndexReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  20667. steppingMeta.setDistributed();
  20668. if (steppedExtra)
  20669. steppingMeta.setExtra(steppedExtra);
  20670. rowLimit = readHelper.getRowLimit();
  20671. keyedLimit = readHelper.getKeyedLimit();
  20672. choosenLimit = readHelper.getChooseNLimit();
  20673. if (!paused)
  20674. processAllKeys();
  20675. }
  20676. class LazyLocalKeyReader : implements IMessageUnpackCursor, implements IMessageResult, public CInterface
  20677. {
  20678. public:
  20679. IMPLEMENT_IINTERFACE;
  20680. virtual IMessageUnpackCursor *getCursor(roxiemem::IRowManager *rowMgr) const
  20681. {
  20682. Link();
  20683. return const_cast<LazyLocalKeyReader*> (this);
  20684. }
  20685. virtual const void *getMessageHeader(unsigned &length) const
  20686. {
  20687. length = 0;
  20688. return NULL;
  20689. }
  20690. virtual const void *getMessageMetadata(unsigned &length) const
  20691. {
  20692. length = 0;
  20693. return NULL;
  20694. }
  20695. virtual void discard() const
  20696. {
  20697. // nothing to do.
  20698. }
  20699. unsigned keyedCount;
  20700. unsigned matched;
  20701. bool EOFseen;
  20702. Owned<IKeyIndexSet> keySet;
  20703. Owned<IKeyManager> tlk;
  20704. CRoxieServerIndexReadActivity &owner;
  20705. LazyLocalKeyReader(CRoxieServerIndexReadActivity &_owner, IKeyIndex *key, IRecordLayoutTranslator * trans)
  20706. : owner(_owner)
  20707. {
  20708. keyedCount = 0;
  20709. matched = 0;
  20710. EOFseen = false;
  20711. keySet.setown(createKeyIndexSet());
  20712. keySet->addIndex(LINK(key));
  20713. if (owner.seekGEOffset)
  20714. tlk.setown(createKeyMerger(keySet, 0, owner.seekGEOffset, &owner));
  20715. else
  20716. tlk.setown(createKeyManager(keySet->queryPart(0), 0, &owner));
  20717. tlk->setLayoutTranslator(trans);
  20718. owner.indexHelper.createSegmentMonitors(tlk);
  20719. tlk->finishSegmentMonitors();
  20720. tlk->reset();
  20721. }
  20722. virtual const void *getNext(int length)
  20723. {
  20724. TransformCallbackAssociation associate(owner.callback, tlk);
  20725. while (tlk->lookup(true))
  20726. {
  20727. keyedCount++;
  20728. if (keyedCount > owner.keyedLimit)
  20729. {
  20730. owner.onLimitExceeded(true); // Should throw exception
  20731. throwUnexpected();
  20732. }
  20733. size32_t transformedSize;
  20734. RtlDynamicRowBuilder rowBuilder(owner.rowAllocator);
  20735. byte const * keyRow = tlk->queryKeyBuffer(owner.callback.getFPosRef());
  20736. try
  20737. {
  20738. transformedSize = owner.readHelper.transform(rowBuilder, keyRow);
  20739. owner.callback.finishedRow();
  20740. }
  20741. catch (IException *E)
  20742. {
  20743. throw owner.makeWrappedException(E);
  20744. }
  20745. if (transformedSize)
  20746. {
  20747. OwnedConstRoxieRow result = rowBuilder.finalizeRowClear(transformedSize);
  20748. matched++;
  20749. if (matched > owner.rowLimit)
  20750. {
  20751. owner.onLimitExceeded(false); // Should throw exception
  20752. throwUnexpected();
  20753. }
  20754. if (matched > owner.choosenLimit) // MORE - bit of a strange place to check
  20755. {
  20756. break;
  20757. }
  20758. owner.accepted++;
  20759. return result.getClear();
  20760. }
  20761. else
  20762. owner.rejected++;
  20763. }
  20764. EOFseen = true;
  20765. return NULL;
  20766. }
  20767. virtual bool atEOF() const
  20768. {
  20769. return EOFseen;
  20770. }
  20771. virtual bool isSerialized() const
  20772. {
  20773. return false;
  20774. }
  20775. };
  20776. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
  20777. {
  20778. ensureRowAllocator();
  20779. remote.injectResult(new LazyLocalKeyReader(*this, key, trans));
  20780. return false;
  20781. }
  20782. virtual void onLimitExceeded(bool isKeyed)
  20783. {
  20784. if (traceLevel > 4)
  20785. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  20786. if (isKeyed)
  20787. {
  20788. if (indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates))
  20789. {
  20790. if (ctx->queryDebugContext())
  20791. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  20792. throw makeLimitSkipException(true);
  20793. }
  20794. else
  20795. readHelper.onKeyedLimitExceeded();
  20796. }
  20797. else
  20798. {
  20799. if (indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates))
  20800. {
  20801. if (ctx->queryDebugContext())
  20802. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  20803. throw makeLimitSkipException(false);
  20804. }
  20805. else
  20806. readHelper.onLimitExceeded();
  20807. }
  20808. }
  20809. virtual void serializeSkipInfo(MemoryBuffer &out, unsigned seekLen, const void *rawSeek, unsigned numFields, const void * seek, const SmartStepExtra &stepExtra) const
  20810. {
  20811. out.append((unsigned short) numFields);
  20812. out.append((unsigned short) seekLen);
  20813. out.append((unsigned short) stepExtra.queryFlags());
  20814. IMultipleStepSeekInfo *seeks = stepExtra.queryExtraSeeks();
  20815. if (seeks)
  20816. {
  20817. unsigned lookahead = 40000/seekLen;
  20818. if (maxSeekLookahead && (lookahead > maxSeekLookahead))
  20819. lookahead = maxSeekLookahead;
  20820. seeks->ensureFilled(seek, numFields, lookahead);
  20821. out.append(lookahead != seeks->ordinality()); // seeksAreEof flag
  20822. unsigned serialized = 1; // rawseek is always serialized...
  20823. unsigned patchLength = out.length();
  20824. out.append(serialized); // NOTE - we come back and patch with the actual value...
  20825. out.append(seekLen, rawSeek);
  20826. if (seeks->ordinality())
  20827. {
  20828. const void *lastSeek = rawSeek;
  20829. byte *nextSeek = NULL;
  20830. if (projectedMeta)
  20831. nextSeek = (byte *) alloca(seekLen);
  20832. for (unsigned i = 0; i < seeks->ordinality(); i++)
  20833. {
  20834. if (projectedMeta)
  20835. {
  20836. RtlStaticRowBuilder rowBuilder(nextSeek-seekGEOffset, seekGEOffset+seekLen);
  20837. readHelper.mapOutputToInput(rowBuilder, seeks->querySeek(i), numFields); // NOTE - weird interface to mapOutputToInput means that it STARTS writing at seekGEOffset...
  20838. }
  20839. else
  20840. nextSeek = (byte *) seeks->querySeek(i)+seekGEOffset;
  20841. int diff = memcmp(nextSeek, lastSeek, seekLen);
  20842. if (diff > 0)
  20843. {
  20844. serialized++;
  20845. out.append(seekLen, nextSeek);
  20846. lastSeek = (const byte *) out.reserve(0) - seekLen;
  20847. }
  20848. }
  20849. unsigned length = out.length();
  20850. out.setWritePos(patchLength);
  20851. out.append(serialized);
  20852. out.setWritePos(length);
  20853. }
  20854. }
  20855. else
  20856. {
  20857. out.append(false);
  20858. out.append(1);
  20859. out.append(seekLen, rawSeek);
  20860. }
  20861. }
  20862. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  20863. {
  20864. ActivityTimer t(totalCycles, timeActivities);
  20865. try
  20866. {
  20867. unsigned seeklen = 0;
  20868. const void *rawSeek = NULL;
  20869. if (seek && numFields)
  20870. {
  20871. seeklen = seekSizes[numFields-1];
  20872. rawSeek = (const byte *)seek + seekGEOffset;
  20873. if (projectedMeta)
  20874. {
  20875. byte * temp = (byte *) alloca(seeklen);
  20876. RtlStaticRowBuilder rawBuilder(temp-seekGEOffset, seekGEOffset+seeklen);
  20877. readHelper.mapOutputToInput(rawBuilder, seek, numFields); // NOTE - weird interface to mapOutputToInput means that it STARTS writing at seekGEOffset...
  20878. rawSeek = (byte *)temp;
  20879. }
  20880. }
  20881. const void *ret = remote.nextRowGE(seek, rawSeek, numFields, seeklen, wasCompleteMatch, stepExtra);
  20882. if (ret && wasCompleteMatch) // GH pleas confirm the wasCompleteMatch I just added here is right
  20883. processed++;
  20884. return ret;
  20885. }
  20886. catch (IException *E)
  20887. {
  20888. throw makeWrappedException(E);
  20889. }
  20890. }
  20891. virtual IInputSteppingMeta * querySteppingMeta()
  20892. {
  20893. if (rawMeta && steppingEnabled && ((indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates|TIRkeyedlimitskips|TIRkeyedlimitcreates)) == 0))
  20894. return &steppingMeta;
  20895. return NULL;
  20896. }
  20897. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  20898. {
  20899. if (variableInfoPending)
  20900. setVariableFileInfo();
  20901. return this;
  20902. }
  20903. virtual IKeyArray *getKeySet() const
  20904. {
  20905. return keySet.getLink();
  20906. }
  20907. virtual const IResolvedFile *getVarFileInfo() const
  20908. {
  20909. return varFileInfo.getLink();
  20910. }
  20911. virtual TranslatorArray *getTranslators() const
  20912. {
  20913. return translators.getLink();
  20914. }
  20915. virtual void mergeSegmentMonitors(IIndexReadContext *irc) const
  20916. {
  20917. indexHelper.createSegmentMonitors(irc); // NOTE: they will merge
  20918. }
  20919. virtual IRoxieServerActivity *queryActivity() { return this; }
  20920. virtual const RemoteActivityId& queryRemoteId() const
  20921. {
  20922. return remoteId;
  20923. }
  20924. };
  20925. class CRoxieServerSimpleIndexReadActivity : public CRoxieServerActivity, implements IIndexReadActivityInfo
  20926. {
  20927. IHThorCompoundReadExtra & readHelper;
  20928. IHThorIndexReadBaseArg & indexHelper;
  20929. IHThorSourceLimitTransformExtra * limitTransformExtra;
  20930. IHThorSteppedSourceExtra * steppedExtra;
  20931. bool eof;
  20932. Linked<IKeyArray>keySet;
  20933. Owned<IKeyIndexSet>keyIndexSet;
  20934. Owned<IKeyManager> tlk;
  20935. Linked<TranslatorArray> translators;
  20936. CIndexTransformCallback callback;
  20937. unsigned __int64 keyedLimit;
  20938. unsigned rowLimit;
  20939. unsigned chooseNLimit;
  20940. unsigned accepted;
  20941. unsigned rejected;
  20942. unsigned keyedCount;
  20943. ISteppingMeta * rawMeta;
  20944. ISteppingMeta * projectedMeta;
  20945. size32_t seekGEOffset;
  20946. unsigned * seekSizes;
  20947. CSteppingMeta steppingMeta;
  20948. Owned<const IResolvedFile> varFileInfo;
  20949. const RemoteActivityId &remoteId;
  20950. bool firstRead;
  20951. bool variableFileName;
  20952. bool variableInfoPending;
  20953. bool isOpt;
  20954. bool isLocal;
  20955. bool optimizeSteppedPostFilter;
  20956. // MORE there may be enough in common between this and CRoxieServerIndexActivity to warrant some refactoring
  20957. void initKeySet()
  20958. {
  20959. if ((keySet->length() > 1 || rawMeta != NULL) && translators->needsTranslation())
  20960. {
  20961. throw MakeStringException(ROXIE_UNIMPLEMENTED_ERROR, "Layout translation is not available when merging key parts or smart-stepping, as it may change record order");
  20962. }
  20963. keyIndexSet.setown(createKeyIndexSet());
  20964. for (unsigned part = 0; part < keySet->length(); part++)
  20965. {
  20966. IKeyIndexBase *kib = keySet->queryKeyPart(part);
  20967. if (kib)
  20968. {
  20969. for (unsigned subpart = 0; subpart < kib->numParts(); subpart++)
  20970. {
  20971. IKeyIndex *k = kib->queryPart(subpart);
  20972. if (k)
  20973. {
  20974. assertex(!k->isTopLevelKey());
  20975. keyIndexSet->addIndex(LINK(k));
  20976. }
  20977. }
  20978. }
  20979. }
  20980. }
  20981. void setVariableFileInfo()
  20982. {
  20983. OwnedRoxieString indexName(indexHelper.getFileName());
  20984. varFileInfo.setown(resolveLFN(indexName, isOpt));
  20985. translators.setown(new TranslatorArray) ;
  20986. keySet.setown(varFileInfo->getKeyArray(factory->queryActivityMeta(), translators, isOpt, isLocal ? factory->queryQueryFactory().queryChannel() : 0, factory->queryQueryFactory().queryOptions().enableFieldTranslation));
  20987. initKeySet();
  20988. variableInfoPending = false;
  20989. }
  20990. void onEOF()
  20991. {
  20992. callback.setManager(NULL);
  20993. eof = true;
  20994. tlk.clear();
  20995. }
  20996. public:
  20997. CRoxieServerSimpleIndexReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  20998. IKeyArray *_keyArray, TranslatorArray *_translatorArray, bool _isLocal)
  20999. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  21000. readHelper((IHThorIndexReadArg &)basehelper),
  21001. indexHelper((IHThorIndexReadArg &)basehelper),
  21002. translators(_translatorArray),
  21003. keySet(_keyArray),
  21004. isLocal(_isLocal),
  21005. remoteId(_remoteId)
  21006. {
  21007. rowLimit = 0;
  21008. keyedLimit = 0;
  21009. chooseNLimit = 0;
  21010. indexHelper.setCallback(&callback);
  21011. steppedExtra = static_cast<IHThorSteppedSourceExtra *>(indexHelper.selectInterface(TAIsteppedsourceextra_1));
  21012. limitTransformExtra = static_cast<IHThorSourceLimitTransformExtra *>(indexHelper.selectInterface(TAIsourcelimittransformextra_1));
  21013. unsigned flags = indexHelper.getFlags();
  21014. variableFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((flags & (TIRvarfilename|TIRdynamicfilename)) != 0);
  21015. variableInfoPending = false;
  21016. isOpt = (flags & TIRoptional) != 0;
  21017. optimizeSteppedPostFilter = (flags & TIRunfilteredtransform) != 0;
  21018. firstRead = true;
  21019. accepted = 0;
  21020. rejected = 0;
  21021. keyedCount = 0;
  21022. eof = false;
  21023. rawMeta = readHelper.queryRawSteppingMeta();
  21024. projectedMeta = readHelper.queryProjectedSteppingMeta();
  21025. seekGEOffset = 0;
  21026. seekSizes = NULL;
  21027. if (rawMeta)
  21028. {
  21029. // MORE - should check all keys in maxFields list can actually be keyed.
  21030. const CFieldOffsetSize * fields = rawMeta->queryFields();
  21031. unsigned maxFields = rawMeta->getNumFields();
  21032. seekGEOffset = fields[0].offset;
  21033. seekSizes = new unsigned[maxFields];
  21034. seekSizes[0] = fields[0].size;
  21035. for (unsigned i=1; i < maxFields; i++)
  21036. seekSizes[i] = seekSizes[i-1] + fields[i].size;
  21037. bool hasPostFilter = readHelper.transformMayFilter() && optimizeSteppedPostFilter;
  21038. if (projectedMeta)
  21039. steppingMeta.init(projectedMeta, hasPostFilter);
  21040. else
  21041. steppingMeta.init(rawMeta, hasPostFilter);
  21042. }
  21043. }
  21044. virtual const IResolvedFile *queryVarFileInfo() const
  21045. {
  21046. return varFileInfo;
  21047. }
  21048. ~CRoxieServerSimpleIndexReadActivity()
  21049. {
  21050. delete [] seekSizes;
  21051. }
  21052. virtual bool needsAllocator() const { return true; }
  21053. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21054. {
  21055. firstRead = true;
  21056. accepted = 0;
  21057. rejected = 0;
  21058. keyedCount = 0;
  21059. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  21060. if (steppedExtra)
  21061. steppingMeta.setExtra(steppedExtra);
  21062. eof = !indexHelper.canMatchAny();
  21063. if (variableFileName)
  21064. variableInfoPending = true;
  21065. else
  21066. {
  21067. variableInfoPending = false;
  21068. if (!keyIndexSet)
  21069. initKeySet();
  21070. }
  21071. }
  21072. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  21073. {
  21074. if (variableInfoPending)
  21075. setVariableFileInfo();
  21076. return this;
  21077. }
  21078. virtual IKeyArray *getKeySet() const
  21079. {
  21080. return keySet.getLink();
  21081. }
  21082. virtual const IResolvedFile *getVarFileInfo() const
  21083. {
  21084. return varFileInfo.getLink();
  21085. }
  21086. virtual TranslatorArray *getTranslators() const
  21087. {
  21088. return translators.getLink();
  21089. }
  21090. virtual void mergeSegmentMonitors(IIndexReadContext *irc) const
  21091. {
  21092. indexHelper.createSegmentMonitors(irc); // NOTE: they will merge
  21093. }
  21094. virtual IRoxieServerActivity *queryActivity() { return this; }
  21095. virtual const RemoteActivityId& queryRemoteId() const
  21096. {
  21097. return remoteId;
  21098. }
  21099. const void *nextRow()
  21100. {
  21101. bool matched = true;
  21102. return nextRowGE(NULL, 0, matched, dummySmartStepExtra);
  21103. }
  21104. unsigned __int64 checkCount(unsigned __int64 limit)
  21105. {
  21106. unsigned numParts = keyIndexSet->numParts();
  21107. unsigned __int64 result = 0;
  21108. for (unsigned i = 0; i < numParts; i++)
  21109. {
  21110. Owned<IKeyManager> countTlk = createKeyManager(keyIndexSet->queryPart(i), 0, this);
  21111. countTlk->setLayoutTranslator(translators->item(i));
  21112. indexHelper.createSegmentMonitors(countTlk);
  21113. countTlk->finishSegmentMonitors();
  21114. result += countTlk->checkCount(limit-result);
  21115. if (result > limit)
  21116. break;
  21117. }
  21118. return result;
  21119. }
  21120. virtual const void *nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  21121. {
  21122. ActivityTimer t(totalCycles, timeActivities);
  21123. if (eof)
  21124. return NULL;
  21125. if (firstRead)
  21126. {
  21127. if (variableInfoPending)
  21128. setVariableFileInfo();
  21129. rowLimit = (unsigned) readHelper.getRowLimit();
  21130. chooseNLimit = (unsigned) readHelper.getChooseNLimit();
  21131. unsigned numParts = keyIndexSet->numParts();
  21132. if (!numParts)
  21133. {
  21134. onEOF();
  21135. return NULL;
  21136. }
  21137. if (numParts > 1 || seekGEOffset)
  21138. {
  21139. tlk.setown(createKeyMerger(keyIndexSet, 0, seekGEOffset, this));
  21140. // note that we don't set up translator because we don't support it. If that ever changes...
  21141. }
  21142. else
  21143. {
  21144. tlk.setown(createKeyManager(keyIndexSet->queryPart(0), 0, this));
  21145. tlk->setLayoutTranslator(translators->item(0));
  21146. }
  21147. indexHelper.createSegmentMonitors(tlk);
  21148. tlk->finishSegmentMonitors();
  21149. if (queryTraceLevel() > 3 || ctx->queryProbeManager())
  21150. {
  21151. StringBuffer out;
  21152. printKeyedValues(out, tlk, indexHelper.queryDiskRecordSize());
  21153. CTXLOG("Using filter %s", out.str());
  21154. if (ctx->queryProbeManager())
  21155. ctx->queryProbeManager()->setNodeProperty(this, "filter", out.str());
  21156. }
  21157. tlk->reset();
  21158. callback.setManager(tlk);
  21159. keyedLimit = readHelper.getKeyedLimit();
  21160. if (keyedLimit != (unsigned __int64) -1)
  21161. {
  21162. if ((indexHelper.getFlags() & TIRcountkeyedlimit) != 0)
  21163. {
  21164. unsigned __int64 count = checkCount(keyedLimit);
  21165. if (count > keyedLimit)
  21166. {
  21167. if ((indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates)) == 0)
  21168. readHelper.onKeyedLimitExceeded();
  21169. const void * ret = NULL;
  21170. if (indexHelper.getFlags() & TIRkeyedlimitcreates)
  21171. ret = createKeyedLimitOnFailRow();
  21172. onEOF();
  21173. return ret;
  21174. }
  21175. keyedLimit = (unsigned __int64) -1;
  21176. }
  21177. }
  21178. firstRead = false;
  21179. }
  21180. if (accepted == chooseNLimit)
  21181. {
  21182. onEOF();
  21183. return NULL;
  21184. }
  21185. const byte * rawSeek = NULL;
  21186. unsigned seekSize = 0;
  21187. if (seek)
  21188. {
  21189. seekSize = seekSizes[numFields-1];
  21190. rawSeek = (const byte *)seek + seekGEOffset;
  21191. if (projectedMeta)
  21192. {
  21193. byte *temp = (byte *) alloca(seekSize);
  21194. RtlStaticRowBuilder rawBuilder(temp-seekGEOffset, seekGEOffset+seekSize);
  21195. readHelper.mapOutputToInput(rawBuilder, seek, numFields);// NOTE - weird interface to mapOutputToInput means that it STARTS writing at seekGEOffset...
  21196. rawSeek = (byte *)temp;
  21197. }
  21198. #ifdef _DEBUG
  21199. // StringBuffer seekStr;
  21200. // for (unsigned i = 0; i < seekSize; i++)
  21201. // {
  21202. // seekStr.appendf("%02x ", ((unsigned char *) rawSeek)[i]);
  21203. // }
  21204. // DBGLOG("nextRowGE can skip offset %d size %d value %s", seekGEOffset, seekSize, seekStr.str());
  21205. #endif
  21206. }
  21207. const byte * originalRawSeek = rawSeek;
  21208. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  21209. while (rawSeek ? tlk->lookupSkip(rawSeek, seekGEOffset, seekSize) : tlk->lookup(true))
  21210. {
  21211. checkAbort();
  21212. keyedCount++;
  21213. if (keyedCount > keyedLimit)
  21214. {
  21215. readHelper.onKeyedLimitExceeded();
  21216. break;
  21217. }
  21218. byte const * keyRow = tlk->queryKeyBuffer(callback.getFPosRef());
  21219. #ifdef _DEBUG
  21220. // StringBuffer recstr;
  21221. // unsigned size = (tlk->queryRecordSize()<80) ? tlk->queryRecordSize() : 80;
  21222. // for (unsigned i = 0; i < size; i++)
  21223. // {
  21224. // recstr.appendf("%02x ", ((unsigned char *) keyRow)[i]);
  21225. // }
  21226. // DBGLOG("nextRowGE Got %s", recstr.str());
  21227. if (originalRawSeek && memcmp(keyRow + seekGEOffset, originalRawSeek, seekSize) < 0)
  21228. assertex(!"smart seek failure");
  21229. #endif
  21230. size32_t transformedSize;
  21231. rowBuilder.ensureRow();
  21232. try
  21233. {
  21234. transformedSize = readHelper.transform(rowBuilder, keyRow);
  21235. //if the post filter causes a mismatch, and the stepping condition no longer matches
  21236. //then return a mismatch record - so the join code can start seeking on the other input.
  21237. if (transformedSize == 0 && optimizeSteppedPostFilter && stepExtra.returnMismatches())
  21238. {
  21239. if (memcmp(keyRow + seekGEOffset, originalRawSeek, seekSize) != 0)
  21240. {
  21241. transformedSize = readHelper.unfilteredTransform(rowBuilder, keyRow);
  21242. if (transformedSize != 0)
  21243. wasCompleteMatch = false;
  21244. }
  21245. }
  21246. callback.finishedRow();
  21247. }
  21248. catch (IException *E)
  21249. {
  21250. throw makeWrappedException(E);
  21251. }
  21252. if (transformedSize)
  21253. {
  21254. accepted++;
  21255. if (accepted > rowLimit)
  21256. {
  21257. if ((indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates)) != 0)
  21258. {
  21259. throwUnexpected(); // should not have used simple variant if maySkip set...
  21260. }
  21261. if (traceLevel > 4)
  21262. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  21263. readHelper.onLimitExceeded();
  21264. break;
  21265. }
  21266. processed++;
  21267. #ifdef _DEBUG
  21268. // const byte *ret = (const byte *) out.get();
  21269. // CommonXmlWriter xmlwrite(XWFnoindent|XWFtrim|XWFopt);
  21270. // queryOutputMeta()->toXML(ret, xmlwrite);
  21271. // DBGLOG("ROW: {%p} %s", ret, xmlwrite.str());
  21272. #endif
  21273. return rowBuilder.finalizeRowClear(transformedSize);
  21274. }
  21275. else
  21276. rejected++;
  21277. rawSeek = NULL;
  21278. }
  21279. onEOF();
  21280. return NULL;
  21281. }
  21282. virtual void reset()
  21283. {
  21284. onEOF();
  21285. if (accepted)
  21286. noteStatistic(StNumIndexAccepted, accepted);
  21287. if (rejected)
  21288. noteStatistic(StNumIndexRejected, rejected);
  21289. if (variableFileName)
  21290. {
  21291. varFileInfo.clear();
  21292. translators.clear();
  21293. }
  21294. variableInfoPending = false;
  21295. CRoxieServerActivity::reset();
  21296. }
  21297. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  21298. {
  21299. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  21300. }
  21301. virtual IInputSteppingMeta * querySteppingMeta()
  21302. {
  21303. if (rawMeta && steppingEnabled && ((indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates|TIRkeyedlimitskips|TIRkeyedlimitcreates)) == 0))
  21304. return &steppingMeta;
  21305. return NULL;
  21306. }
  21307. protected:
  21308. const void * createKeyedLimitOnFailRow()
  21309. {
  21310. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  21311. size32_t outSize = limitTransformExtra->transformOnKeyedLimitExceeded(rowBuilder);
  21312. if (outSize)
  21313. return rowBuilder.finalizeRowClear(outSize);
  21314. return NULL;
  21315. }
  21316. };
  21317. class CRoxieServerBaseIndexActivityFactory : public CRoxieServerActivityFactory
  21318. {
  21319. public:
  21320. Owned<IKeyArray> keySet;
  21321. Owned<TranslatorArray> translatorArray;
  21322. Owned<IDefRecordMeta> activityMeta;
  21323. RemoteActivityId remoteId;
  21324. bool isSimple;
  21325. bool isLocal;
  21326. bool maySkip;
  21327. bool sorted;
  21328. bool variableFileName;
  21329. IRecordLayoutTranslator::Mode enableFieldTranslation;
  21330. unsigned maxSeekLookahead;
  21331. Owned<const IResolvedFile> indexfile;
  21332. CRoxieServerSideCache *cache;
  21333. CRoxieServerBaseIndexActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21334. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), remoteId(_remoteId)
  21335. {
  21336. Owned<IHThorIndexReadBaseArg> indexHelper = (IHThorIndexReadBaseArg *) helperFactory();
  21337. unsigned flags = indexHelper->getFlags();
  21338. sorted = (flags & TIRunordered) == 0;
  21339. isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  21340. rtlDataAttr indexLayoutMeta;
  21341. size32_t indexLayoutSize;
  21342. if(!indexHelper->getIndexLayout(indexLayoutSize, indexLayoutMeta.refdata()))
  21343. assertex(indexLayoutSize==0);
  21344. MemoryBuffer m;
  21345. m.setBuffer(indexLayoutSize, indexLayoutMeta.getdata());
  21346. activityMeta.setown(deserializeRecordMeta(m, true));
  21347. enableFieldTranslation = queryFactory.queryOptions().enableFieldTranslation;
  21348. translatorArray.setown(new TranslatorArray);
  21349. variableFileName = allFilesDynamic || _queryFactory.isDynamic() || ((flags & (TIRvarfilename|TIRdynamicfilename)) != 0);
  21350. if (!variableFileName)
  21351. {
  21352. bool isOpt = (flags & TIRoptional) != 0;
  21353. OwnedRoxieString indexName(indexHelper->getFileName());
  21354. indexfile.setown(queryFactory.queryPackage().lookupFileName(indexName, isOpt, true, true, queryFactory.queryWorkUnit(), true));
  21355. if (indexfile)
  21356. keySet.setown(indexfile->getKeyArray(activityMeta, translatorArray, isOpt, isLocal ? queryFactory.queryChannel() : 0, enableFieldTranslation));
  21357. }
  21358. isSimple = isLocal;
  21359. maySkip = (flags & (TIRkeyedlimitskips|TIRlimitskips|TIRlimitcreates|TIRkeyedlimitcreates)) != 0;
  21360. if (keySet && keySet->length()==1 && !isLocal && (flags & (TIRlimitskips|TIRlimitcreates|TIRkeyedlimitskips|TIRkeyedlimitcreates))==0)
  21361. {
  21362. IKeyIndexBase *thisBase = keySet->queryKeyPart(0);
  21363. if (thisBase->numParts()==1 && !thisBase->queryPart(0)->isTopLevelKey() && !_queryFactory.queryOptions().disableLocalOptimizations)
  21364. isSimple = true;
  21365. }
  21366. int cacheSize = _graphNode.getPropInt("hint[@name='cachehits']/@value", serverSideCacheSize);
  21367. cache = cacheSize ? new CRoxieServerSideCache(cacheSize) : NULL;
  21368. maxSeekLookahead = _graphNode.getPropInt("hint[@name='maxseeklookahead']/@value", 0);
  21369. }
  21370. ~CRoxieServerBaseIndexActivityFactory()
  21371. {
  21372. delete cache;
  21373. }
  21374. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  21375. {
  21376. if (indexfile)
  21377. addXrefFileInfo(reply, indexfile);
  21378. else
  21379. {
  21380. Owned<IHThorIndexReadBaseArg> indexHelper = (IHThorIndexReadBaseArg *) helperFactory();
  21381. if ((indexHelper->getFlags() & (TIRvarfilename|TIRdynamicfilename)) == 0)
  21382. {
  21383. OwnedRoxieString indexName(indexHelper->getFileName());
  21384. Owned<const IResolvedFile> temp = queryFactory.queryPackage().lookupFileName(indexName, true, true, false, queryFactory.queryWorkUnit(), true);
  21385. if (temp)
  21386. addXrefFileInfo(reply, temp);
  21387. }
  21388. }
  21389. }
  21390. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  21391. {
  21392. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for indexread activity");
  21393. }
  21394. virtual IRoxieServerSideCache *queryServerSideCache() const
  21395. {
  21396. return cache;
  21397. }
  21398. virtual bool getEnableFieldTranslation() const
  21399. {
  21400. return enableFieldTranslation;
  21401. }
  21402. virtual IDefRecordMeta *queryActivityMeta() const
  21403. {
  21404. return activityMeta;
  21405. }
  21406. virtual const StatisticsMapping &queryStatsMapping() const
  21407. {
  21408. return indexStatistics;
  21409. }
  21410. };
  21411. class CRoxieServerIndexReadActivityFactory : public CRoxieServerBaseIndexActivityFactory
  21412. {
  21413. public:
  21414. CRoxieServerIndexReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21415. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId)
  21416. {
  21417. }
  21418. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  21419. {
  21420. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  21421. return new CRoxieServerNullActivity(_ctx, this, _probeManager);
  21422. else if (isSimple && !maySkip)
  21423. return new CRoxieServerSimpleIndexReadActivity(_ctx, this, _probeManager, remoteId, keySet, translatorArray, isLocal);
  21424. else
  21425. return new CRoxieServerIndexReadActivity(_ctx, this, _probeManager, remoteId, keySet, translatorArray, sorted, isLocal, maySkip, maxSeekLookahead);
  21426. }
  21427. };
  21428. IRoxieServerActivityFactory *createRoxieServerIndexReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21429. {
  21430. return new CRoxieServerIndexReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  21431. }
  21432. //--------------------------------------------------------------------------------------------------------------------------
  21433. class CRoxieServerNullCountActivity : public CRoxieServerActivity
  21434. {
  21435. bool done;
  21436. public:
  21437. CRoxieServerNullCountActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  21438. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  21439. {
  21440. done = false;
  21441. }
  21442. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21443. {
  21444. done = false;
  21445. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  21446. }
  21447. virtual bool needsAllocator() const { return true; }
  21448. virtual const void *nextRow()
  21449. {
  21450. ActivityTimer t(totalCycles, timeActivities);
  21451. if (done) return NULL;
  21452. done = true;
  21453. size32_t rowSize = meta.getFixedSize();
  21454. void * nullRow = rowAllocator->createRow();
  21455. if (rowSize == 1)
  21456. *(byte *)nullRow = 0;
  21457. else
  21458. {
  21459. assertex(rowSize == sizeof(unsigned __int64));
  21460. *(unsigned __int64 *)nullRow = 0;
  21461. }
  21462. return rowAllocator->finalizeRow(rowSize, nullRow, rowSize);
  21463. }
  21464. };
  21465. class CRoxieServerIndexCountActivity : public CRoxieServerIndexActivity
  21466. {
  21467. IHThorCompoundCountExtra & countHelper;
  21468. IHThorSourceCountLimit * limitHelper;
  21469. bool done;
  21470. public:
  21471. CRoxieServerIndexCountActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IKeyArray * _keySet, TranslatorArray *_translators, bool _isLocal)
  21472. : CRoxieServerIndexActivity(_ctx, _factory, _probeManager, _remoteId, _keySet, _translators, false, _isLocal, false),
  21473. countHelper((IHThorIndexCountArg &)basehelper),
  21474. done(false)
  21475. {
  21476. limitHelper = static_cast<IHThorSourceCountLimit *>(basehelper.selectInterface(TAIsourcecountlimit_1));
  21477. }
  21478. virtual bool needsAllocator() const { return true; }
  21479. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21480. {
  21481. done = false;
  21482. CRoxieServerIndexActivity::start(parentExtractSize, parentExtract, paused);
  21483. choosenLimit = countHelper.getChooseNLimit();
  21484. if (limitHelper)
  21485. {
  21486. rowLimit = limitHelper->getRowLimit();
  21487. keyedLimit = limitHelper->getKeyedLimit();
  21488. }
  21489. if (!paused)
  21490. processAllKeys();
  21491. }
  21492. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
  21493. {
  21494. unsigned __int64 count = 0;
  21495. if (countHelper.hasFilter())
  21496. {
  21497. while (tlk->lookup(true))
  21498. {
  21499. try
  21500. {
  21501. count += countHelper.numValid(tlk->queryKeyBuffer(callback.getFPosRef()));
  21502. callback.finishedRow();
  21503. }
  21504. catch (IException *E)
  21505. {
  21506. throw makeWrappedException(E);
  21507. }
  21508. accepted++;
  21509. if (count >= choosenLimit) // MORE - what about limit?
  21510. break;
  21511. }
  21512. }
  21513. else
  21514. count = tlk->getCount(); //MORE: GH->RKC There should be value in providing a max limit to getCount()
  21515. if (count)
  21516. {
  21517. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), false);
  21518. if (count > choosenLimit)
  21519. count = choosenLimit;
  21520. void * recBuffer = rowAllocator->createRow();
  21521. if (meta.getFixedSize() == 1)
  21522. *(byte *)recBuffer = (byte)count;
  21523. else
  21524. {
  21525. assertex(meta.getFixedSize() == sizeof(unsigned __int64));
  21526. *(unsigned __int64 *)recBuffer = count;
  21527. }
  21528. recBuffer = rowAllocator->finalizeRow(meta.getFixedSize(), recBuffer, meta.getFixedSize());
  21529. result->append(recBuffer);
  21530. remote.injectResult(result.getClear());
  21531. //GH->RKC for count(,choosen)/exists passing in the previous count would short-circuit this much earlier
  21532. if (count >= choosenLimit)
  21533. return true;
  21534. }
  21535. return false;
  21536. }
  21537. virtual void onLimitExceeded(bool isKeyed)
  21538. {
  21539. if (traceLevel > 4)
  21540. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  21541. if (isKeyed)
  21542. {
  21543. if (indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates))
  21544. {
  21545. if (ctx->queryDebugContext())
  21546. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  21547. throw makeLimitSkipException(true);
  21548. }
  21549. else
  21550. {
  21551. assertex(limitHelper); // Should not be able to generate exception if there was not one...
  21552. limitHelper->onKeyedLimitExceeded();
  21553. }
  21554. }
  21555. else
  21556. {
  21557. if (indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates))
  21558. {
  21559. if (ctx->queryDebugContext())
  21560. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  21561. throw makeLimitSkipException(false);
  21562. }
  21563. else
  21564. {
  21565. assertex(limitHelper);
  21566. limitHelper->onLimitExceeded();
  21567. }
  21568. }
  21569. }
  21570. virtual const void *createLimitFailRow(bool isKeyed)
  21571. {
  21572. throwUnexpected();
  21573. }
  21574. virtual const void *nextRow()
  21575. {
  21576. ActivityTimer t(totalCycles, timeActivities);
  21577. if (done) return NULL;
  21578. done = true;
  21579. unsigned __int64 totalCount = 0;
  21580. bool hasLimit = rowLimit != (unsigned __int64) -1;
  21581. try
  21582. {
  21583. for (;;)
  21584. {
  21585. const void * next = remote.nextRow();
  21586. if (!next)
  21587. break;
  21588. if (meta.getFixedSize() == 1)
  21589. totalCount += *(byte *)next;
  21590. else
  21591. totalCount += *(unsigned __int64 *) next;
  21592. ReleaseRoxieRow(next);
  21593. if (totalCount > rowLimit || (totalCount > choosenLimit && !hasLimit)) // can't break out early if there is a possibility of later slave throwing limit exception
  21594. break;
  21595. }
  21596. if (totalCount > rowLimit)
  21597. {
  21598. unsigned flags = indexHelper.getFlags();
  21599. if (flags & TIRlimitskips)
  21600. totalCount = 0;
  21601. else if (flags & TIRlimitcreates)
  21602. totalCount = 1;
  21603. else
  21604. {
  21605. assertex(limitHelper);
  21606. limitHelper->onLimitExceeded();
  21607. }
  21608. }
  21609. else if (totalCount > choosenLimit)
  21610. totalCount = choosenLimit;
  21611. }
  21612. catch (IException *E)
  21613. {
  21614. if (QUERYINTERFACE(E, LimitSkipException))
  21615. {
  21616. totalCount = 0;
  21617. unsigned flags = indexHelper.getFlags();
  21618. if (E->errorCode() == KeyedLimitSkipErrorCode)
  21619. {
  21620. if (flags & TIRkeyedlimitcreates)
  21621. totalCount++;
  21622. }
  21623. else
  21624. {
  21625. if (flags & TIRlimitcreates)
  21626. totalCount++;
  21627. }
  21628. if (totalCount > choosenLimit)
  21629. totalCount = choosenLimit; // would have to be weird code (and escape the optimizer...)
  21630. E->Release();
  21631. }
  21632. else
  21633. throw ;
  21634. }
  21635. void * result = rowAllocator->createRow();
  21636. if (meta.getFixedSize() == 1)
  21637. *(byte *)result = (byte)totalCount;
  21638. else
  21639. {
  21640. assertex(meta.getFixedSize() == sizeof(unsigned __int64));
  21641. *(unsigned __int64 *)result = totalCount;
  21642. }
  21643. return rowAllocator->finalizeRow(meta.getFixedSize(), result, meta.getFixedSize());
  21644. }
  21645. };
  21646. class CRoxieServerIndexCountActivityFactory : public CRoxieServerBaseIndexActivityFactory
  21647. {
  21648. public:
  21649. CRoxieServerIndexCountActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21650. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId)
  21651. {
  21652. }
  21653. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  21654. {
  21655. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  21656. return new CRoxieServerNullCountActivity(_ctx, this, _probeManager);
  21657. // else if (isSimple)
  21658. // return new CRoxieServerSimpleIndexCountActivity(this, keySet->queryKeyPart(0)->queryPart(0));
  21659. else
  21660. return new CRoxieServerIndexCountActivity(_ctx, this, _probeManager, remoteId, keySet, translatorArray, isLocal);
  21661. }
  21662. };
  21663. IRoxieServerActivityFactory *createRoxieServerIndexCountActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21664. {
  21665. return new CRoxieServerIndexCountActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  21666. }
  21667. //--------------------------------------------------------------------------------------------------------------------------
  21668. class CRoxieServerNullIndexAggregateActivity : public CRoxieServerActivity
  21669. {
  21670. IHThorIndexAggregateArg &aggregateHelper;
  21671. bool done;
  21672. public:
  21673. CRoxieServerNullIndexAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  21674. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  21675. aggregateHelper((IHThorIndexAggregateArg &)basehelper)
  21676. {
  21677. done = false;
  21678. }
  21679. virtual bool needsAllocator() const { return true; }
  21680. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21681. {
  21682. done = false;
  21683. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  21684. }
  21685. virtual const void *nextRow()
  21686. {
  21687. ActivityTimer t(totalCycles, timeActivities);
  21688. if (done) return NULL;
  21689. done = true;
  21690. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  21691. size32_t thisSize = aggregateHelper.clearAggregate(rowBuilder);
  21692. return rowBuilder.finalizeRowClear(thisSize);
  21693. }
  21694. };
  21695. class CRoxieServerIndexAggregateActivity : public CRoxieServerIndexActivity
  21696. {
  21697. IHThorCompoundAggregateExtra & aggregateHelper;
  21698. bool done;
  21699. public:
  21700. CRoxieServerIndexAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  21701. IKeyArray * _keySet, TranslatorArray *_translators, bool _isLocal)
  21702. : CRoxieServerIndexActivity(_ctx, _factory, _probeManager, _remoteId, _keySet, _translators, false, _isLocal, false),
  21703. aggregateHelper((IHThorIndexAggregateArg &)basehelper),
  21704. done(false)
  21705. {
  21706. }
  21707. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21708. {
  21709. done = false;
  21710. CRoxieServerIndexActivity::start(parentExtractSize, parentExtract, paused);
  21711. if (!paused)
  21712. processAllKeys();
  21713. }
  21714. virtual bool needsAllocator() const { return true; }
  21715. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
  21716. {
  21717. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  21718. while (tlk->lookup(true))
  21719. {
  21720. if (!rowBuilder.exists())
  21721. {
  21722. rowBuilder.ensureRow();
  21723. aggregateHelper.clearAggregate(rowBuilder);
  21724. }
  21725. try
  21726. {
  21727. aggregateHelper.processRow(rowBuilder, tlk->queryKeyBuffer(callback.getFPosRef()));
  21728. callback.finishedRow();
  21729. }
  21730. catch (IException *E)
  21731. {
  21732. throw makeWrappedException(E);
  21733. }
  21734. accepted++;
  21735. }
  21736. if (aggregateHelper.processedAnyRows())
  21737. {
  21738. size32_t size = meta.getRecordSize(rowBuilder.getSelf());
  21739. const void * recBuffer = rowBuilder.finalizeRowClear(size);
  21740. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), meta.isVariableSize());
  21741. result->append(recBuffer);
  21742. remote.injectResult(result.getClear());
  21743. }
  21744. return false;
  21745. }
  21746. virtual void onLimitExceeded(bool isKeyed)
  21747. {
  21748. if (traceLevel > 4)
  21749. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  21750. throwUnexpected();
  21751. }
  21752. virtual const void *createLimitFailRow(bool isKeyed)
  21753. {
  21754. throwUnexpected();
  21755. }
  21756. const void * gatherMerged()
  21757. {
  21758. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  21759. const void * firstRow = remote.nextRow();
  21760. size32_t finalSize = 0;
  21761. if (!firstRow)
  21762. {
  21763. rowBuilder.ensureRow();
  21764. finalSize = aggregateHelper.clearAggregate(rowBuilder);
  21765. }
  21766. else
  21767. {
  21768. // NOTE need to clone this because going to modify below, could special case 1 row only
  21769. finalSize = cloneRow(rowBuilder, firstRow, meta);
  21770. ReleaseRoxieRow(firstRow);
  21771. }
  21772. for (;;)
  21773. {
  21774. const void * next = remote.nextRow();
  21775. if (!next)
  21776. break;
  21777. finalSize = aggregateHelper.mergeAggregate(rowBuilder, next);
  21778. ReleaseRoxieRow(next);
  21779. }
  21780. return rowBuilder.finalizeRowClear(finalSize);
  21781. }
  21782. virtual const void *nextRow()
  21783. {
  21784. ActivityTimer t(totalCycles, timeActivities);
  21785. if (done) return NULL;
  21786. const void * ret = gatherMerged();
  21787. done = true;
  21788. return ret;
  21789. }
  21790. };
  21791. class CRoxieServerIndexAggregateActivityFactory : public CRoxieServerBaseIndexActivityFactory
  21792. {
  21793. public:
  21794. CRoxieServerIndexAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21795. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId)
  21796. {
  21797. }
  21798. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  21799. {
  21800. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  21801. return new CRoxieServerNullIndexAggregateActivity(_ctx, this, _probeManager);
  21802. // else if (isSimple)
  21803. // return new CRoxieServerSimpleIndexAggregateActivity(this, keySet->queryKeyPart(0)->queryPart(0));
  21804. else
  21805. return new CRoxieServerIndexAggregateActivity(_ctx, this, _probeManager, remoteId, keySet, translatorArray, isLocal);
  21806. }
  21807. };
  21808. IRoxieServerActivityFactory *createRoxieServerIndexAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21809. {
  21810. return new CRoxieServerIndexAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  21811. }
  21812. //--------------------------------------------------------------------------------------------------------------------------
  21813. class CRoxieServerIndexGroupAggregateActivity : public CRoxieServerIndexActivity, implements IHThorGroupAggregateCallback
  21814. {
  21815. IHThorCompoundGroupAggregateExtra & aggregateHelper;
  21816. RowAggregator singleAggregator;
  21817. RowAggregator resultAggregator;
  21818. unsigned groupSegCount;
  21819. bool gathered;
  21820. bool eof;
  21821. public:
  21822. CRoxieServerIndexGroupAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  21823. IKeyArray * _keySet, TranslatorArray *_translators, bool _isLocal)
  21824. : CRoxieServerIndexActivity(_ctx, _factory, _probeManager, _remoteId, _keySet, _translators, false, _isLocal, false),
  21825. aggregateHelper((IHThorIndexGroupAggregateArg &)basehelper),
  21826. singleAggregator(aggregateHelper, aggregateHelper),
  21827. resultAggregator(aggregateHelper, aggregateHelper),
  21828. gathered(false), eof(true)
  21829. {
  21830. groupSegCount = 0;
  21831. }
  21832. IMPLEMENT_IINTERFACE_USING(CRoxieServerIndexActivity)
  21833. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21834. {
  21835. eof = false;
  21836. gathered= false;
  21837. CRoxieServerIndexActivity::start(parentExtractSize, parentExtract, paused);
  21838. groupSegCount = 0;
  21839. if (!paused)
  21840. processAllKeys();
  21841. resultAggregator.start(rowAllocator);
  21842. }
  21843. virtual bool needsAllocator() const { return true; }
  21844. virtual void reset()
  21845. {
  21846. resultAggregator.reset();
  21847. CRoxieServerIndexActivity::reset();
  21848. }
  21849. virtual void processRow(const void * next)
  21850. {
  21851. singleAggregator.addRow(next);
  21852. }
  21853. virtual void createSegmentMonitors(IKeyManager *key)
  21854. {
  21855. unsigned groupSegSize;
  21856. ThorActivityKind kind = factory->getKind();
  21857. if ((kind==TAKindexgroupcount || kind==TAKindexgroupexists))
  21858. groupSegSize = aggregateHelper.getGroupSegmentMonitorsSize();
  21859. else
  21860. groupSegSize = 0;
  21861. if (groupSegSize)
  21862. {
  21863. key->setMergeBarrier(groupSegSize);
  21864. CRoxieServerIndexActivity::createSegmentMonitors(key);
  21865. unsigned numSegs = tlk->ordinality();
  21866. for (unsigned segNo = 0; segNo < numSegs; segNo++)
  21867. {
  21868. IKeySegmentMonitor *seg = tlk->item(segNo);
  21869. if (seg->getOffset()+seg->getSize()==groupSegSize)
  21870. {
  21871. groupSegCount = segNo+1;
  21872. break;
  21873. }
  21874. }
  21875. assertex(groupSegCount);
  21876. }
  21877. else
  21878. CRoxieServerIndexActivity::createSegmentMonitors(key);
  21879. }
  21880. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
  21881. {
  21882. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), meta.isVariableSize());
  21883. singleAggregator.start(rowAllocator);
  21884. ThorActivityKind kind = factory->getKind();
  21885. while (tlk->lookup(true))
  21886. {
  21887. try
  21888. {
  21889. if (groupSegCount && !trans)
  21890. {
  21891. AggregateRowBuilder &rowBuilder = singleAggregator.addRow(tlk->queryKeyBuffer(callback.getFPosRef()));
  21892. callback.finishedRow();
  21893. if (kind==TAKindexgroupcount)
  21894. {
  21895. unsigned __int64 count = tlk->getCurrentRangeCount(groupSegCount);
  21896. aggregateHelper.processCountGrouping(rowBuilder, count-1);
  21897. }
  21898. if (!tlk->nextRange(groupSegCount))
  21899. break;
  21900. }
  21901. else
  21902. {
  21903. aggregateHelper.processRow(tlk->queryKeyBuffer(callback.getFPosRef()), this);
  21904. callback.finishedRow();
  21905. }
  21906. }
  21907. catch (IException *E)
  21908. {
  21909. throw makeWrappedException(E);
  21910. }
  21911. accepted++;
  21912. }
  21913. for (;;)
  21914. {
  21915. Owned<AggregateRowBuilder> next = singleAggregator.nextResult();
  21916. if (!next)
  21917. break;
  21918. size32_t size = next->querySize();
  21919. result->append(next->finalizeRowClear());
  21920. }
  21921. remote.injectResult(result.getClear());
  21922. singleAggregator.reset();
  21923. return false;
  21924. }
  21925. virtual void onLimitExceeded(bool isKeyed)
  21926. {
  21927. if (traceLevel > 4)
  21928. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  21929. throwUnexpected();
  21930. }
  21931. virtual const void *createLimitFailRow(bool isKeyed)
  21932. {
  21933. throwUnexpected();
  21934. }
  21935. void gatherMerged()
  21936. {
  21937. gathered = true;
  21938. for (;;)
  21939. {
  21940. const void * next = remote.nextRow();
  21941. if (!next)
  21942. break;
  21943. resultAggregator.mergeElement(next);
  21944. ReleaseRoxieRow(next);
  21945. }
  21946. }
  21947. virtual const void *nextRow()
  21948. {
  21949. ActivityTimer t(totalCycles, timeActivities);
  21950. if (eof)
  21951. return NULL;
  21952. if (!gathered)
  21953. gatherMerged();
  21954. Owned<AggregateRowBuilder> next = resultAggregator.nextResult();
  21955. if (next)
  21956. {
  21957. processed++;
  21958. return next->finalizeRowClear();
  21959. }
  21960. eof = true;
  21961. return NULL;
  21962. }
  21963. };
  21964. class CRoxieServerIndexGroupAggregateActivityFactory : public CRoxieServerBaseIndexActivityFactory
  21965. {
  21966. public:
  21967. CRoxieServerIndexGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21968. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId)
  21969. {
  21970. }
  21971. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  21972. {
  21973. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  21974. return new CRoxieServerNullActivity(_ctx, this, _probeManager);
  21975. // else if (isSimple)
  21976. // return new CRoxieServerSimpleIndexGroupAggregateActivity(this, keySet->queryKeyPart(0)->queryPart(0));
  21977. else
  21978. return new CRoxieServerIndexGroupAggregateActivity(_ctx, this, _probeManager, remoteId, keySet, translatorArray, isLocal);
  21979. }
  21980. };
  21981. IRoxieServerActivityFactory *createRoxieServerIndexGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21982. {
  21983. return new CRoxieServerIndexGroupAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  21984. }
  21985. //--------------------------------------------------------------------------------------------------------------------------
  21986. class CRoxieServerIndexNormalizeActivity : public CRoxieServerIndexReadBaseActivity
  21987. {
  21988. IHThorCompoundNormalizeExtra & readHelper;
  21989. public:
  21990. CRoxieServerIndexNormalizeActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  21991. IKeyArray * _keySet, TranslatorArray *_translators, bool _sorted, bool _isLocal)
  21992. : CRoxieServerIndexReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _keySet, _translators, _sorted, _isLocal, false),
  21993. readHelper((IHThorIndexNormalizeArg &)basehelper)
  21994. {
  21995. }
  21996. virtual bool needsAllocator() const { return true; }
  21997. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21998. {
  21999. CRoxieServerIndexReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  22000. rowLimit = readHelper.getRowLimit();
  22001. keyedLimit = readHelper.getKeyedLimit();
  22002. choosenLimit = readHelper.getChooseNLimit();
  22003. if (!paused)
  22004. processAllKeys();
  22005. }
  22006. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
  22007. {
  22008. unsigned keyedCount = 0;
  22009. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  22010. while (tlk->lookup(true))
  22011. {
  22012. keyedCount++;
  22013. if (keyedCount > keyedLimit)
  22014. {
  22015. if (traceLevel > 4)
  22016. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  22017. onLimitExceeded(true);
  22018. break;
  22019. }
  22020. size32_t transformedSize;
  22021. if (readHelper.first(tlk->queryKeyBuffer(callback.getFPosRef())))
  22022. {
  22023. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), meta.isVariableSize());
  22024. do
  22025. {
  22026. if (accepted>=choosenLimit)
  22027. break;
  22028. rowBuilder.ensureRow();
  22029. try
  22030. {
  22031. transformedSize = readHelper.transform(rowBuilder);
  22032. }
  22033. catch (IException *E)
  22034. {
  22035. throw makeWrappedException(E);
  22036. }
  22037. if (transformedSize)
  22038. {
  22039. // MORE - would be a good idea to stop these asap if rowlimit exceeded
  22040. result->append(rowBuilder.finalizeRowClear(transformedSize));
  22041. accepted++;
  22042. }
  22043. else
  22044. rejected++;
  22045. } while (readHelper.next());
  22046. remote.injectResult(result.getClear());
  22047. callback.finishedRow();
  22048. if (accepted>=choosenLimit)
  22049. return true;
  22050. }
  22051. }
  22052. return false;
  22053. }
  22054. virtual void onLimitExceeded(bool isKeyed)
  22055. {
  22056. if (traceLevel > 4)
  22057. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  22058. if (isKeyed)
  22059. {
  22060. if (indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates))
  22061. {
  22062. if (ctx->queryDebugContext())
  22063. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  22064. throw makeLimitSkipException(true);
  22065. }
  22066. else
  22067. readHelper.onKeyedLimitExceeded();
  22068. }
  22069. else
  22070. {
  22071. if (indexHelper.getFlags() & (TIRlimitskips||TIRlimitcreates))
  22072. {
  22073. if (ctx->queryDebugContext())
  22074. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  22075. throw makeLimitSkipException(false);
  22076. }
  22077. else
  22078. readHelper.onLimitExceeded();
  22079. }
  22080. }
  22081. virtual const void *createLimitFailRow(bool isKeyed)
  22082. {
  22083. UNIMPLEMENTED;
  22084. }
  22085. };
  22086. class CRoxieServerIndexNormalizeActivityFactory : public CRoxieServerBaseIndexActivityFactory
  22087. {
  22088. public:
  22089. CRoxieServerIndexNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  22090. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId)
  22091. {
  22092. }
  22093. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  22094. {
  22095. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  22096. return new CRoxieServerNullActivity(_ctx, this, _probeManager);
  22097. else
  22098. return new CRoxieServerIndexNormalizeActivity(_ctx, this, _probeManager, remoteId, keySet, translatorArray, sorted, isLocal);
  22099. }
  22100. };
  22101. IRoxieServerActivityFactory *createRoxieServerIndexNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  22102. {
  22103. return new CRoxieServerIndexNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  22104. }
  22105. //=================================================================================
  22106. class CRoxieServerFetchActivity : public CRoxieServerActivity, implements IRecordPullerCallback, implements IRoxieServerErrorHandler
  22107. {
  22108. IHThorFetchBaseArg &helper;
  22109. IHThorFetchContext * fetchContext;
  22110. Linked<IFilePartMap> map;
  22111. CRemoteResultAdaptor remote;
  22112. RecordPullerThread puller;
  22113. bool needsRHS;
  22114. bool variableFileName;
  22115. bool isOpt;
  22116. Owned<const IResolvedFile> varFileInfo;
  22117. public:
  22118. CRoxieServerFetchActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IFilePartMap *_map)
  22119. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorFetchBaseArg &)basehelper), map(_map), remote(_ctx, this, _remoteId, meta.queryOriginal(), helper, *this, true, true), puller(false)
  22120. {
  22121. fetchContext = static_cast<IHThorFetchContext *>(helper.selectInterface(TAIfetchcontext_1));
  22122. needsRHS = helper.transformNeedsRhs();
  22123. variableFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((fetchContext->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  22124. isOpt = (fetchContext->getFetchFlags() & FFdatafileoptional) != 0;
  22125. }
  22126. virtual const IResolvedFile *queryVarFileInfo() const
  22127. {
  22128. return varFileInfo;
  22129. }
  22130. virtual void onCreate(IHThorArg *_colocalParent)
  22131. {
  22132. CRoxieServerActivity::onCreate(_colocalParent);
  22133. remote.onCreate(_colocalParent);
  22134. }
  22135. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  22136. {
  22137. if (idx)
  22138. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
  22139. puller.setInput(this, _sourceIdx, _in);
  22140. }
  22141. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  22142. {
  22143. puller.connectInputStreams(ctx, consumerOrdered);
  22144. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
  22145. }
  22146. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  22147. {
  22148. if (idx==0)
  22149. return puller.queryInput();
  22150. else
  22151. return NULL;
  22152. }
  22153. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  22154. {
  22155. CRoxieServerActivity::gatherStats(merged);
  22156. remote.gatherStats(merged);
  22157. }
  22158. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  22159. {
  22160. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  22161. remote.onStart(parentExtractSize, parentExtract);
  22162. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  22163. if (variableFileName)
  22164. {
  22165. OwnedRoxieString fname(fetchContext->getFileName());
  22166. varFileInfo.setown(resolveLFN(fname, isOpt));
  22167. if (varFileInfo)
  22168. map.setown(varFileInfo->getFileMap());
  22169. }
  22170. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().fetchPreload, false, ctx);
  22171. }
  22172. virtual void stop()
  22173. {
  22174. // Called from remote, so no need to call back to it....
  22175. puller.stop();
  22176. CRoxieServerActivity::stop();
  22177. }
  22178. virtual void reset()
  22179. {
  22180. processed = remote.processed;
  22181. remote.processed = 0;
  22182. puller.reset();
  22183. if (variableFileName)
  22184. {
  22185. varFileInfo.clear();
  22186. map.clear();
  22187. }
  22188. CRoxieServerActivity::reset();
  22189. }
  22190. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  22191. {
  22192. if (idx==(unsigned)-1)
  22193. idx = 0;
  22194. return idx ? NULL : &remote;
  22195. }
  22196. virtual void processRow(const void *row)
  22197. {
  22198. // called from puller thread
  22199. offset_t rp = fetchContext->extractPosition(row);
  22200. unsigned partNo;
  22201. if (isLocalFpos(rp))
  22202. partNo = getLocalFposPart(rp) + 1;
  22203. else
  22204. partNo = map->mapOffset(rp);
  22205. if (needsRHS)
  22206. {
  22207. Owned<IEngineRowAllocator> extractAllocator = createRowAllocator(helper.queryExtractedSize());
  22208. RtlDynamicRowBuilder rb(extractAllocator, true);
  22209. unsigned rhsSize = helper.extractJoinFields(rb, row);
  22210. char * block = (char *) remote.getMem(partNo, 0, sizeof(rp) + sizeof(rhsSize) + rhsSize); // MORE - superfiles
  22211. *(offset_t *) block = rp;
  22212. block += sizeof(rp);
  22213. *(unsigned *) block = rhsSize;
  22214. block += sizeof(rhsSize);
  22215. memcpy(block, rb.row(), rhsSize);
  22216. }
  22217. else
  22218. *(offset_t *) remote.getMem(partNo, 0, sizeof(rp)) = rp; // MORE - superfiles
  22219. ReleaseRoxieRow(row);
  22220. }
  22221. void processEOG()
  22222. {
  22223. #ifdef FETCH_PRESERVES_GROUPING
  22224. UNIMPLEMENTED;
  22225. #endif
  22226. // else discard is correct
  22227. }
  22228. void processGroup(const ConstPointerArray &)
  22229. {
  22230. throwUnexpected();
  22231. }
  22232. void processDone()
  22233. {
  22234. // called from puller thread
  22235. remote.flush();
  22236. remote.senddone();
  22237. }
  22238. virtual bool fireException(IException *e)
  22239. {
  22240. return remote.fireException(e);
  22241. }
  22242. virtual void onLimitExceeded(bool isKeyed)
  22243. {
  22244. if (traceLevel > 4)
  22245. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  22246. if (isKeyed)
  22247. throwUnexpected();
  22248. helper.onLimitExceeded();
  22249. }
  22250. virtual const void *createLimitFailRow(bool isKeyed)
  22251. {
  22252. UNIMPLEMENTED;
  22253. }
  22254. virtual const void *nextRow()
  22255. {
  22256. throwUnexpected(); // I am nobody's input
  22257. }
  22258. };
  22259. class CRoxieServerFetchActivityFactory : public CRoxieServerActivityFactory
  22260. {
  22261. RemoteActivityId remoteId;
  22262. Owned<IFilePartMap> map;
  22263. bool variableFileName;
  22264. Owned<const IResolvedFile> datafile;
  22265. public:
  22266. CRoxieServerFetchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  22267. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), remoteId(_remoteId)
  22268. {
  22269. Owned<IHThorFetchBaseArg> helper = (IHThorFetchBaseArg *) helperFactory();
  22270. IHThorFetchContext *fetchContext = static_cast<IHThorFetchContext *>(helper->selectInterface(TAIfetchcontext_1));
  22271. variableFileName = allFilesDynamic || _queryFactory.isDynamic() || ((fetchContext->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  22272. if (!variableFileName)
  22273. {
  22274. OwnedRoxieString fname(fetchContext->getFileName());
  22275. datafile.setown(_queryFactory.queryPackage().lookupFileName(fname,
  22276. (fetchContext->getFetchFlags() & FFdatafileoptional) != 0,
  22277. true, true,
  22278. _queryFactory.queryWorkUnit(), true));
  22279. if (datafile)
  22280. map.setown(datafile->getFileMap());
  22281. }
  22282. }
  22283. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  22284. {
  22285. return new CRoxieServerFetchActivity(_ctx, this, _probeManager, remoteId, map);
  22286. }
  22287. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  22288. {
  22289. if (datafile)
  22290. addXrefFileInfo(reply, datafile);
  22291. else
  22292. {
  22293. // Temporarily resolve the file
  22294. Owned<IHThorFetchBaseArg> helper = (IHThorFetchBaseArg *) helperFactory();
  22295. IHThorFetchContext *fetchContext = static_cast<IHThorFetchContext *>(helper->selectInterface(TAIfetchcontext_1));
  22296. if ((fetchContext->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) == 0)
  22297. {
  22298. OwnedRoxieString fileName(fetchContext->getFileName());
  22299. Owned<const IResolvedFile> temp = queryFactory.queryPackage().lookupFileName(fileName, true, true, false, queryFactory.queryWorkUnit(), true);
  22300. if (temp)
  22301. addXrefFileInfo(reply, temp);
  22302. }
  22303. }
  22304. }
  22305. virtual const StatisticsMapping &queryStatsMapping() const
  22306. {
  22307. return diskStatistics;
  22308. }
  22309. };
  22310. IRoxieServerActivityFactory *createRoxieServerFetchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  22311. {
  22312. return new CRoxieServerFetchActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  22313. }
  22314. // MORE - is there any point keeping this now?
  22315. class CRoxieServerDummyActivityFactory : public CRoxieServerActivityFactory // not a real activity - just used to properly link files
  22316. {
  22317. public:
  22318. Owned<const IResolvedFile> indexfile;
  22319. Owned<const IResolvedFile> datafile;
  22320. StringAttr fileName;
  22321. StringAttr indexName;
  22322. Owned<IKeyArray> keySet;
  22323. Owned<IFileIOArray> files;
  22324. TranslatorArray layoutTranslators;
  22325. CRoxieServerDummyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool isLoadDataOnly)
  22326. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  22327. {
  22328. try // does not want any missing file errors to be fatal, or throw traps - just log it
  22329. {
  22330. if (_graphNode.getPropBool("att[@name='_isSpill']/@value", false) || _graphNode.getPropBool("att[@name='_isSpillGlobal']/@value", false))
  22331. return; // ignore 'spills'
  22332. bool isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  22333. ThorActivityKind kind = getActivityKind(_graphNode);
  22334. if (kind != TAKdiskwrite && kind != TAKindexwrite && kind != TAKpiperead && kind != TAKpipewrite)
  22335. {
  22336. fileName.set(queryNodeFileName(_graphNode, kind));
  22337. indexName.set(queryNodeIndexName(_graphNode, kind));
  22338. if (indexName && !allFilesDynamic && !queryFactory.isDynamic())
  22339. {
  22340. bool isOpt = pretendAllOpt || _graphNode.getPropBool("att[@name='_isIndexOpt']/@value");
  22341. indexfile.setown(queryFactory.queryPackage().lookupFileName(indexName, isOpt, true, true, queryFactory.queryWorkUnit(), true));
  22342. if (indexfile)
  22343. keySet.setown(indexfile->getKeyArray(NULL, &layoutTranslators, isOpt, isLocal ? queryFactory.queryChannel() : 0, IRecordLayoutTranslator::NoTranslation));
  22344. }
  22345. if (fileName && !allFilesDynamic && !queryFactory.isDynamic())
  22346. {
  22347. bool isOpt = pretendAllOpt || _graphNode.getPropBool("att[@name='_isOpt']/@value");
  22348. datafile.setown(_queryFactory.queryPackage().lookupFileName(fileName, isOpt, true, true, queryFactory.queryWorkUnit(), true));
  22349. if (datafile)
  22350. {
  22351. if (isLocal)
  22352. files.setown(datafile->getIFileIOArray(isOpt, queryFactory.queryChannel()));
  22353. }
  22354. }
  22355. }
  22356. }
  22357. catch(IException *E)
  22358. {
  22359. StringBuffer errors;
  22360. E->errorMessage(errors);
  22361. DBGLOG("%s File error = %s", (isLoadDataOnly) ? "LOADDATAONLY" : "SUSPENDED QUERY", errors.str());
  22362. E->Release();
  22363. }
  22364. }
  22365. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, 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(), sanitizeSourceFile(__FILE__), __LINE__); }
  22366. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  22367. {
  22368. if (!allFilesDynamic)
  22369. {
  22370. if (datafile)
  22371. addXrefFileInfo(reply, datafile);
  22372. if (indexfile)
  22373. addXrefFileInfo(reply, indexfile);
  22374. }
  22375. else
  22376. {
  22377. Owned<const IResolvedFile> temp;
  22378. if (fileName.length())
  22379. {
  22380. temp.setown(queryFactory.queryPackage().lookupFileName(fileName, true, true, false, queryFactory.queryWorkUnit(), true));
  22381. if (temp)
  22382. addXrefFileInfo(reply, temp);
  22383. }
  22384. if (indexName.length())
  22385. {
  22386. temp.setown(queryFactory.queryPackage().lookupFileName(indexName, true, true, false, queryFactory.queryWorkUnit(), true));
  22387. if (temp)
  22388. addXrefFileInfo(reply, temp);
  22389. }
  22390. }
  22391. }
  22392. };
  22393. IRoxieServerActivityFactory *createRoxieServerDummyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool isLoadDataOnly)
  22394. {
  22395. return new CRoxieServerDummyActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, isLoadDataOnly);
  22396. }
  22397. //=====================================================================================================
  22398. // Keyed joins...
  22399. //
  22400. // Input records are pulled by a puller thread, which checks each LHS record to determine which (if any) channels it
  22401. // may have RHS matches on, and sends the relevant fields to the relevant slaves.
  22402. // 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
  22403. // the transform and returns rows that are created.
  22404. // 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)
  22405. //
  22406. //=====================================================================================================
  22407. class CJoinGroup;
  22408. interface IJoinProcessor
  22409. {
  22410. virtual void processEOG() = 0;
  22411. virtual CJoinGroup *createJoinGroup(const void *row) = 0;
  22412. virtual void noteEndReceived(CJoinGroup *jg, unsigned candidateCount) = 0;
  22413. virtual bool fireException(IException *E) = 0;
  22414. virtual void processCompletedGroups() = 0;
  22415. };
  22416. //------------------------------------------------------------------------------------------------------
  22417. // Class CJoinGroup has a record per LHS row, plus (if preserving grouping) a 'head of group' record
  22418. // It gathers all the corresponding RHS rows, keeping track of how may slave transactions are pending in endMarkersPending
  22419. // If preserving groups, the 'head of group' record keeps track of how many LHS records in the group are still incomplete.
  22420. // CJoinGroup records are allocated out of the Roxie row memory manager by overloading operator new, so that they are included in the
  22421. // per-query limits etc (Note that the pointer array block is not though).
  22422. // Because of that, the exact size is significant - especially whether fit just under or just over a chunking threshold...
  22423. //
  22424. // There are two phases to the life of a JoinGroup - it is created by the puller thread that is also firing off slave requests
  22425. // notePending will be called once for every slave request. Puller thread calls noteEndReceived(0) once when done - this corresponds to the
  22426. // initial count when created.
  22427. // Slave replies and are noted by the consumer thread calling addRightMatch() and noteEndReceived(n).
  22428. // Once endMarkersPending reaches 0, JoinGroup is complete. Last thread to call noteEndReceived will process the rows and destroy the group.
  22429. // There is no need for a critsec because although multiple threads will access at different times, only the consumer thread will
  22430. // access any modifiable member variables while endMarkersPending != 0 (i.e. complete() is false). Once complete returns true there is a single
  22431. // remaining reference and the JoinGroup will be processed and destroyed.
  22432. //
  22433. //------------------------------------------------------------------------------------------------------
  22434. class CJoinGroup : public CInterface
  22435. {
  22436. protected:
  22437. const void *left; // LHS row
  22438. PointerArrayOf<KeyedJoinHeader> rows; // matching RHS rows
  22439. atomic_t endMarkersPending; // How many slave responses still waiting for
  22440. CJoinGroup *groupStart; // Head of group, or NULL if not grouping
  22441. unsigned lastPartNo;
  22442. unsigned pos;
  22443. unsigned candidates; // Number of RHS keyed candidates - note this may not be the same as rows.ordinality()
  22444. public:
  22445. #undef new
  22446. void *operator new(size_t size, IRowManager *a, unsigned activityId)
  22447. {
  22448. return a->allocate(size, activityId);
  22449. }
  22450. #if defined(_DEBUG) && defined(_WIN32) && !defined(USING_MPATROL)
  22451. #define new new(_NORMAL_BLOCK, __FILE__, __LINE__)
  22452. #endif
  22453. void operator delete(void *ptr, IRowManager *a, unsigned activityId)
  22454. {
  22455. ReleaseRoxieRow(ptr);
  22456. }
  22457. void operator delete(void *ptr)
  22458. {
  22459. ReleaseRoxieRow(ptr);
  22460. }
  22461. public:
  22462. CJoinGroup(const void *_left, CJoinGroup *_groupStart)
  22463. {
  22464. #ifdef TRACE_JOINGROUPS
  22465. DBGLOG("Creating joinGroup %p, groupstart %p", this, _groupStart);
  22466. #endif
  22467. candidates = 0;
  22468. lastPartNo = 0;
  22469. pos = 0;
  22470. left = _left;
  22471. groupStart = _groupStart;
  22472. if (_groupStart)
  22473. {
  22474. atomic_inc(&_groupStart->endMarkersPending);
  22475. }
  22476. atomic_set(&endMarkersPending, 1);
  22477. }
  22478. ~CJoinGroup()
  22479. {
  22480. #ifdef TRACE_JOINGROUPS
  22481. DBGLOG("Destroying joinGroup %p", this);
  22482. #endif
  22483. if (left)
  22484. {
  22485. ReleaseRoxieRow(left);
  22486. roxiemem::ReleaseRoxieRowArray(rows.ordinality(), (const void * *)rows.getArray());
  22487. rows.kill();
  22488. }
  22489. }
  22490. inline bool isHeadRecord() const
  22491. {
  22492. return left==NULL;
  22493. }
  22494. inline bool complete() const
  22495. {
  22496. return atomic_read(&endMarkersPending) == 0;
  22497. }
  22498. #ifdef TRACE_JOINGROUPS
  22499. inline void notePending(unsigned lineNo)
  22500. #else
  22501. inline void notePending()
  22502. #endif
  22503. {
  22504. assert(!complete());
  22505. atomic_inc(&endMarkersPending);
  22506. #ifdef TRACE_JOINGROUPS
  22507. DBGLOG("CJoinGroup::notePending %p from %d, count became %d group count %d", this, lineNo, atomic_read(&endMarkersPending), groupStart ? atomic_read(&groupStart->endMarkersPending) : 0);
  22508. #endif
  22509. }
  22510. inline bool inGroup(CJoinGroup *leader) const
  22511. {
  22512. return groupStart==leader;
  22513. }
  22514. inline const KeyedJoinHeader *queryRow(unsigned idx) const
  22515. {
  22516. // Single threaded by now
  22517. assert(complete());
  22518. return rows.item(idx);
  22519. }
  22520. #ifdef TRACE_JOINGROUPS
  22521. bool noteEndReceived(unsigned candidateCount, unsigned lineNo)
  22522. #else
  22523. bool noteEndReceived(unsigned candidateCount)
  22524. #endif
  22525. {
  22526. assert(!complete());
  22527. if (candidateCount)
  22528. {
  22529. candidates += candidateCount;
  22530. }
  22531. #ifdef TRACE_JOINGROUPS
  22532. 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);
  22533. #endif
  22534. // NOTE - as soon as endMarkersPending and groupStart->endMarkersPending are decremented to zero this object may get released asynchronously by other threads
  22535. // There must therefore be nothing in this method after them that acceses member variables. Think of it as a delete this...
  22536. // In particular, we can't safely reference groupStart after the dec_and_test of endMarkersPending, hence copy local first
  22537. CJoinGroup *localGroupStart = groupStart;
  22538. if (atomic_dec_and_test(&endMarkersPending))
  22539. {
  22540. if (localGroupStart)
  22541. return atomic_dec_and_test(&localGroupStart->endMarkersPending);
  22542. else
  22543. return true;
  22544. }
  22545. else
  22546. return false;
  22547. }
  22548. inline const void *queryLeft() const
  22549. {
  22550. return left;
  22551. }
  22552. void addRightMatch(KeyedJoinHeader *right)
  22553. {
  22554. assert(!complete());
  22555. unsigned short partNo = right->partNo;
  22556. if (partNo != lastPartNo)
  22557. {
  22558. // MORE - should we binchop? If we did we would need to be careful to find LAST match
  22559. if (partNo > lastPartNo)
  22560. pos = rows.length();
  22561. while (pos>0)
  22562. {
  22563. if (rows.item(pos-1)->partNo <= partNo)
  22564. break;
  22565. pos--;
  22566. }
  22567. lastPartNo = partNo;
  22568. }
  22569. rows.add(right, pos);
  22570. pos++;
  22571. }
  22572. inline unsigned rowsSeen() const
  22573. {
  22574. assert(complete());
  22575. return rows.length();
  22576. }
  22577. inline unsigned candidateCount() const
  22578. {
  22579. assert(complete());
  22580. return candidates;
  22581. }
  22582. };
  22583. #ifdef TRACE_JOINGROUPS
  22584. #define notePending() notePending(__LINE__)
  22585. #define noteEndReceived(a) noteEndReceived(a, __LINE__)
  22586. #endif
  22587. class KeyedJoinRemoteAdaptor : public CRemoteResultAdaptor // MORE - not sure it should be derived from this - makes processed all wrong, for example
  22588. {
  22589. private:
  22590. SafeQueueOf<const void, true> ready;
  22591. public:
  22592. IHThorKeyedJoinArg &helper;
  22593. unsigned joinProcessed;
  22594. bool isFullKey;
  22595. bool eof;
  22596. bool isSimple;
  22597. bool allPulled;
  22598. ActivityTimeAccumulator totalCycles;
  22599. unsigned activityId;
  22600. RecordPullerThread &puller;
  22601. SafeQueueOf<const void, true> injected; // Used in isSimple mode
  22602. Owned<IEngineRowAllocator> ccdRecordAllocator;
  22603. IJoinProcessor &processor;
  22604. KeyedJoinRemoteAdaptor(IRoxieSlaveContext *_ctx, IRoxieServerErrorHandler *_errorHandler, const RemoteActivityId &_remoteId, IHThorKeyedJoinArg &_helper,
  22605. IRoxieServerActivity &_activity, bool _isFullKey, bool _isSimple,
  22606. RecordPullerThread &_puller, IJoinProcessor &_processor)
  22607. : helper(_helper),
  22608. CRemoteResultAdaptor(_ctx, _errorHandler, _remoteId, 0, _helper, _activity, true, true),
  22609. isFullKey(_isFullKey),
  22610. isSimple(_isSimple),
  22611. puller(_puller),
  22612. processor(_processor),
  22613. activityId(_activity.queryId())
  22614. {
  22615. joinProcessed = 0;
  22616. allPulled = false;
  22617. eof = false;
  22618. }
  22619. virtual void onCreate(IHThorArg *_colocalArg)
  22620. {
  22621. CRemoteResultAdaptor::onCreate(_colocalArg);
  22622. ccdRecordAllocator.setown(activity.createRowAllocator(helper.queryJoinFieldsRecordSize()));
  22623. }
  22624. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  22625. {
  22626. eof = false;
  22627. joinProcessed = 0;
  22628. totalCycles.totalCycles = 0;
  22629. allPulled = false;
  22630. assertex(ready.ordinality()==0);
  22631. CRemoteResultAdaptor::start(parentExtractSize, parentExtract, paused);
  22632. }
  22633. virtual void reset()
  22634. {
  22635. CRemoteResultAdaptor::reset();
  22636. while (ready.ordinality())
  22637. {
  22638. const void *goer = ready.dequeue();
  22639. if (goer)
  22640. ReleaseRoxieRow(goer);
  22641. }
  22642. while (injected.ordinality())
  22643. {
  22644. const void *goer = injected.dequeue();
  22645. if (goer)
  22646. ReleaseRoxieRow(goer);
  22647. }
  22648. }
  22649. inline void addResult(const void *row)
  22650. {
  22651. ready.enqueue(row);
  22652. }
  22653. virtual unsigned __int64 queryTotalCycles() const
  22654. {
  22655. return totalCycles.totalCycles;
  22656. }
  22657. virtual const void *nextRow()
  22658. {
  22659. ActivityTimer t(totalCycles, timeActivities);
  22660. for (;;)
  22661. {
  22662. if (eof)
  22663. return NULL;
  22664. processSlaveResults();
  22665. if (ready.ordinality())
  22666. {
  22667. const void *result = ready.dequeue();
  22668. if (result)
  22669. joinProcessed++;
  22670. return result;
  22671. }
  22672. else
  22673. eof = true;
  22674. }
  22675. }
  22676. void gatherStats(CRuntimeStatisticCollection & merged) const
  22677. {
  22678. CRemoteResultAdaptor::gatherStats(merged);
  22679. if (ccdRecordAllocator)
  22680. ccdRecordAllocator->gatherStats(merged);
  22681. }
  22682. private:
  22683. void processSlaveResults()
  22684. {
  22685. while (!ready.ordinality())
  22686. {
  22687. KeyedJoinHeader *fetchedData;
  22688. if (isSimple)
  22689. {
  22690. while (!allPulled && !injected.ordinality())
  22691. {
  22692. if (!puller.pullRecords(1))
  22693. {
  22694. puller.done();
  22695. allPulled = true;
  22696. }
  22697. }
  22698. fetchedData = (KeyedJoinHeader *) injected.dequeue();
  22699. }
  22700. else
  22701. fetchedData = (KeyedJoinHeader *) CRemoteResultAdaptor::nextRow();
  22702. if (fetchedData)
  22703. {
  22704. CJoinGroup *thisGroup = fetchedData->thisGroup;
  22705. if (fetchedData->partNo == (unsigned short) -1)
  22706. {
  22707. #ifdef TRACE_JOINGROUPS
  22708. CTXLOG("Got end for group %p", thisGroup);
  22709. #endif
  22710. unsigned candidateCount = (unsigned) fetchedData->fpos;
  22711. ReleaseRoxieRow(fetchedData);
  22712. processor.noteEndReceived(thisGroup, candidateCount); // note - this can throw exception. So release fetchdata before calling
  22713. }
  22714. else
  22715. {
  22716. #ifdef TRACE_JOINGROUPS
  22717. CTXLOG("Reading another %d bytes for group %p data", ccdRecordSize, thisGroup);
  22718. #endif
  22719. thisGroup->addRightMatch(fetchedData);
  22720. if (isFullKey)
  22721. {
  22722. #ifdef TRACE_JOINGROUPS
  22723. CTXLOG("Calling noteEndReceived for record returned from FETCH of full keyed join");
  22724. #endif
  22725. processor.noteEndReceived(thisGroup, 0); // note - this can throw exception. So release fetchdata before calling
  22726. }
  22727. }
  22728. }
  22729. else
  22730. break;
  22731. }
  22732. }
  22733. };
  22734. class CRoxieServerFullKeyedJoinHead: public CRoxieServerActivity, implements IRecordPullerCallback, implements IRoxieServerErrorHandler
  22735. {
  22736. IHThorKeyedJoinArg &helper;
  22737. Owned<IKeyManager> tlk;
  22738. Linked<IKeyArray> keySet;
  22739. Linked<TranslatorArray> translators;
  22740. CRemoteResultAdaptor remote;
  22741. RecordPullerThread puller;
  22742. IOutputMetaData *indexReadMeta;
  22743. IJoinProcessor *joinHandler;
  22744. bool variableIndexFileName;
  22745. bool indexReadInputRecordVariable;
  22746. bool isLocal;
  22747. Owned<IEngineRowAllocator> indexReadAllocator;
  22748. Owned<const IResolvedFile> varFileInfo;
  22749. IFinalRoxieInput *indexReadInput;
  22750. unsigned indexReadIdx = 0;
  22751. IIndexReadActivityInfo *rootIndex;
  22752. public:
  22753. CRoxieServerFullKeyedJoinHead(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IKeyArray * _keySet, TranslatorArray *_translators, IOutputMetaData *_indexReadMeta, IJoinProcessor *_joinHandler, bool _isLocal)
  22754. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  22755. helper((IHThorKeyedJoinArg &)basehelper),
  22756. tlk(createKeyManager(NULL, 0, this)),
  22757. translators(_translators),
  22758. keySet(_keySet),
  22759. remote(_ctx, this, _remoteId, 0, helper, *this, true, true),
  22760. indexReadMeta(_indexReadMeta),
  22761. joinHandler(_joinHandler),
  22762. puller(false),
  22763. isLocal(_isLocal)
  22764. {
  22765. variableIndexFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getJoinFlags() & (JFvarindexfilename|JFdynamicindexfilename|JFindexfromactivity)) != 0);
  22766. indexReadInputRecordVariable = indexReadMeta->isVariableSize();
  22767. indexReadInput = NULL;
  22768. rootIndex = NULL;
  22769. }
  22770. virtual const IResolvedFile *queryVarFileInfo() const
  22771. {
  22772. return varFileInfo;
  22773. }
  22774. virtual void onCreate(IHThorArg *_colocalParent)
  22775. {
  22776. CRoxieServerActivity::onCreate(_colocalParent);
  22777. remote.onCreate(_colocalParent);
  22778. indexReadAllocator.setown(createRowAllocator(indexReadMeta));
  22779. }
  22780. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  22781. {
  22782. if (!idx)
  22783. puller.setInput(this, _sourceIdx, _in);
  22784. else if (idx==1)
  22785. {
  22786. indexReadInput = _in;
  22787. indexReadIdx = _sourceIdx;
  22788. }
  22789. else
  22790. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
  22791. }
  22792. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  22793. {
  22794. puller.connectInputStreams(ctx, consumerOrdered);
  22795. //No rows are read from indexReadInput, so no need to extract the streams
  22796. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
  22797. }
  22798. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  22799. {
  22800. switch (idx)
  22801. {
  22802. case 0:
  22803. return puller.queryInput();
  22804. case 1:
  22805. return indexReadInput;
  22806. default:
  22807. return NULL;
  22808. }
  22809. }
  22810. virtual void serializeExtra(MemoryBuffer &out)
  22811. {
  22812. if (helper.getJoinFlags() & JFindexfromactivity)
  22813. {
  22814. assertex(rootIndex);
  22815. const RemoteActivityId& indexId = rootIndex->queryRemoteId();
  22816. indexId.serialize(out);
  22817. // could mess about reserving space for length then patching it again, to avoid copy, but probably not worth it
  22818. MemoryBuffer tmp;
  22819. rootIndex->queryActivity()->serializeCreateStartContext(tmp);
  22820. if (rootIndex->queryActivity()->queryVarFileInfo())
  22821. {
  22822. rootIndex->queryActivity()->queryVarFileInfo()->queryTimeStamp().serialize(tmp);
  22823. tmp.append(rootIndex->queryActivity()->queryVarFileInfo()->queryCheckSum());
  22824. }
  22825. unsigned ctxlen = tmp.length();
  22826. out.append(ctxlen).append(tmp);
  22827. }
  22828. }
  22829. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  22830. {
  22831. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  22832. if (indexReadInput)
  22833. {
  22834. indexReadInput->start(parentExtractSize, parentExtract, true); // paused=true because we don't want to actually run the index read
  22835. rootIndex = indexReadInput->queryIndexReadActivity();
  22836. if (!rootIndex)
  22837. throw MakeStringException(ROXIE_INTERNAL_ERROR,"Index in keyed join %d could not be resolved", queryId());
  22838. }
  22839. remote.onStart(parentExtractSize, parentExtract);
  22840. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  22841. if (rootIndex)
  22842. {
  22843. varFileInfo.setown(rootIndex->getVarFileInfo());
  22844. translators.setown(rootIndex->getTranslators());
  22845. keySet.setown(rootIndex->getKeySet());
  22846. }
  22847. else if (variableIndexFileName)
  22848. {
  22849. OwnedRoxieString indexFileName(helper.getIndexFileName());
  22850. varFileInfo.setown(resolveLFN(indexFileName, (helper.getJoinFlags() & JFindexoptional) != 0));
  22851. if (varFileInfo)
  22852. {
  22853. translators.setown(new TranslatorArray);
  22854. keySet.setown(varFileInfo->getKeyArray(factory->queryActivityMeta(), translators, false, isLocal ? factory->queryQueryFactory().queryChannel() : 0, factory->queryQueryFactory().queryOptions().enableFieldTranslation)); // MORE - isLocal?
  22855. }
  22856. }
  22857. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().fullKeyedJoinPreload, false, ctx);
  22858. }
  22859. virtual void stop()
  22860. {
  22861. puller.stop();
  22862. CRoxieServerActivity::stop();
  22863. }
  22864. virtual void reset()
  22865. {
  22866. CRoxieServerActivity::reset();
  22867. puller.reset();
  22868. if (varFileInfo)
  22869. {
  22870. keySet.clear();
  22871. varFileInfo.clear();
  22872. }
  22873. }
  22874. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  22875. {
  22876. if (idx==(unsigned)-1)
  22877. idx = 0;
  22878. return idx ? NULL : &remote;
  22879. }
  22880. virtual void processRow(const void *row)
  22881. {
  22882. // MORE - this code seems to be pretty much duplicated below in half-keyed....
  22883. // called from front puller thread
  22884. // buffer up an IndexRead request
  22885. if (keySet && helper.leftCanMatch(row))
  22886. {
  22887. RtlDynamicRowBuilder extractedBuilder(indexReadAllocator);
  22888. unsigned indexReadSize = helper.extractIndexReadFields(extractedBuilder, row);
  22889. OwnedConstRoxieRow extracted;
  22890. if (indexReadSize)
  22891. extracted.setown(extractedBuilder.finalizeRowClear(indexReadSize));
  22892. CJoinGroup *jg = joinHandler->createJoinGroup(row);
  22893. for (unsigned partNo = 0; partNo < keySet->length(); partNo++)
  22894. {
  22895. IKeyIndexBase *thisBase = keySet->queryKeyPart(partNo);
  22896. if (thisBase)
  22897. {
  22898. unsigned fileNo = 0;
  22899. IKeyIndex *thisKey = thisBase->queryPart(fileNo);
  22900. try
  22901. {
  22902. tlk->setKey(thisKey);
  22903. tlk->setLayoutTranslator(translators->item(fileNo));
  22904. helper.createSegmentMonitors(tlk, extracted);
  22905. if (rootIndex)
  22906. rootIndex->mergeSegmentMonitors(tlk);
  22907. tlk->finishSegmentMonitors();
  22908. tlk->reset();
  22909. for (;;)
  22910. {
  22911. typedef const void * cvp;
  22912. if (thisKey->isTopLevelKey())
  22913. {
  22914. bool locallySorted = !thisKey->isFullySorted();
  22915. while (locallySorted || tlk->lookup(false))
  22916. {
  22917. unsigned slavePart = locallySorted ? 0 : (unsigned) tlk->queryFpos();
  22918. if (locallySorted || slavePart)
  22919. {
  22920. cvp *outputBuffer = (cvp *) remote.getMem(slavePart, fileNo, indexReadSize + sizeof(cvp) + (indexReadInputRecordVariable ? sizeof(unsigned) : 0));
  22921. *outputBuffer++ = jg;
  22922. if (indexReadInputRecordVariable)
  22923. {
  22924. *(unsigned *) outputBuffer = indexReadSize;
  22925. outputBuffer = (cvp*) (((unsigned *) outputBuffer) + 1);
  22926. }
  22927. jg->notePending();
  22928. memcpy(outputBuffer, extracted, indexReadSize);
  22929. if (locallySorted)
  22930. {
  22931. for (unsigned i = 1; i < numChannels; i++)
  22932. jg->notePending();
  22933. break;
  22934. }
  22935. }
  22936. }
  22937. }
  22938. else
  22939. {
  22940. // MORE - this code seems to be duplicated in half keyed
  22941. unsigned accepted = 0;
  22942. unsigned rejected = 0;
  22943. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), true);
  22944. jg->notePending();
  22945. unsigned candidateCount = 0;
  22946. while (tlk->lookup(true))
  22947. {
  22948. candidateCount++;
  22949. atomic_inc(&indexRecordsRead);
  22950. KLBlobProviderAdapter adapter(tlk);
  22951. offset_t recptr;
  22952. const byte *indexRow = tlk->queryKeyBuffer(recptr);
  22953. if (helper.indexReadMatch(extracted, indexRow, recptr, &adapter))
  22954. {
  22955. KeyedJoinHeader *rhs = (KeyedJoinHeader *) ctx->queryRowManager().allocate(KEYEDJOIN_RECORD_SIZE(0), activityId);
  22956. rhs->fpos = recptr;
  22957. rhs->thisGroup = jg;
  22958. rhs->partNo = partNo;
  22959. result->append(rhs);
  22960. }
  22961. else
  22962. {
  22963. rejected++;
  22964. atomic_inc(&postFiltered);
  22965. }
  22966. }
  22967. // output an end marker for the matches to this group
  22968. KeyedJoinHeader *endMarker = (KeyedJoinHeader *) ctx->queryRowManager().allocate(KEYEDJOIN_RECORD_SIZE(0), activityId);
  22969. endMarker->fpos = (offset_t) candidateCount;
  22970. endMarker->thisGroup = jg;
  22971. endMarker->partNo = (unsigned short) -1;
  22972. result->append(endMarker);
  22973. remote.injectResult(result.getClear());
  22974. if (accepted)
  22975. noteStatistic(StNumIndexAccepted, accepted);
  22976. if (rejected)
  22977. noteStatistic(StNumIndexRejected, rejected);
  22978. }
  22979. if (++fileNo < thisBase->numParts())
  22980. {
  22981. thisKey = thisBase->queryPart(fileNo);
  22982. tlk->setKey(thisKey);
  22983. tlk->setLayoutTranslator(translators->item(fileNo));
  22984. tlk->reset();
  22985. }
  22986. else
  22987. break;
  22988. }
  22989. tlk->releaseSegmentMonitors();
  22990. tlk->setKey(NULL);
  22991. }
  22992. catch (...)
  22993. {
  22994. tlk->releaseSegmentMonitors();
  22995. tlk->setKey(NULL);
  22996. throw;
  22997. }
  22998. }
  22999. }
  23000. joinHandler->noteEndReceived(jg, 0);
  23001. }
  23002. else
  23003. {
  23004. joinHandler->noteEndReceived(joinHandler->createJoinGroup(row), 0);
  23005. }
  23006. }
  23007. void processGroup(const ConstPointerArray &)
  23008. {
  23009. throwUnexpected();
  23010. }
  23011. virtual void processEOG()
  23012. {
  23013. joinHandler->processEOG();
  23014. }
  23015. virtual void processDone()
  23016. {
  23017. // called from puller thread
  23018. remote.flush();
  23019. remote.senddone();
  23020. }
  23021. virtual void onLimitExceeded(bool isKeyed)
  23022. {
  23023. if (traceLevel > 4)
  23024. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  23025. if (isKeyed)
  23026. throwUnexpected();
  23027. helper.onLimitExceeded();
  23028. }
  23029. virtual const void *createLimitFailRow(bool isKeyed)
  23030. {
  23031. throwUnexpected();
  23032. }
  23033. virtual bool fireException(IException *e)
  23034. {
  23035. // called from puller thread on failure
  23036. remote.fireException(LINK(e));
  23037. return joinHandler->fireException(e);
  23038. }
  23039. virtual const void *nextRow()
  23040. {
  23041. throwUnexpected(); // I am nobody's input
  23042. }
  23043. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  23044. {
  23045. CRoxieServerActivity::gatherStats(merged);
  23046. remote.gatherStats(merged);
  23047. if (indexReadAllocator)
  23048. indexReadAllocator->gatherStats(merged);
  23049. }
  23050. };
  23051. class CRoxieServerKeyedJoinBase : public CRoxieServerActivity, implements IRecordPullerCallback, implements IRoxieServerErrorHandler, implements IJoinProcessor
  23052. {
  23053. protected:
  23054. IHThorKeyedJoinArg &helper;
  23055. KeyedJoinRemoteAdaptor remote;
  23056. RecordPullerThread puller;
  23057. OwnedConstRoxieRow defaultRight;
  23058. Owned<IEngineRowAllocator> defaultRightAllocator;
  23059. unsigned joinFlags;
  23060. unsigned atMost;
  23061. unsigned atmostsTriggered;
  23062. unsigned abortLimit;
  23063. unsigned keepLimit;
  23064. bool limitFail;
  23065. bool limitOnFail;
  23066. bool preserveGroups;
  23067. bool cloneLeft;
  23068. bool isSimple;
  23069. bool isLocal;
  23070. ThorActivityKind activityKind;
  23071. CJoinGroup *groupStart;
  23072. CriticalSection groupsCrit;
  23073. QueueOf<CJoinGroup, false> groups;
  23074. IFinalRoxieInput *indexReadInput;
  23075. unsigned indexReadIdx = 0;
  23076. Owned<IStrandJunction> indexReadJunction;
  23077. IEngineRowStream *indexReadStream = NULL; // Never actually pulled
  23078. IIndexReadActivityInfo *rootIndex;
  23079. void createDefaultRight()
  23080. {
  23081. if (!defaultRight)
  23082. {
  23083. if (!defaultRightAllocator)
  23084. defaultRightAllocator.setown(createRowAllocator(helper.queryJoinFieldsRecordSize()));
  23085. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  23086. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  23087. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  23088. }
  23089. }
  23090. public:
  23091. CRoxieServerKeyedJoinBase(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _joinFlags
  23092. , bool isFull, bool _isSimple, bool _isLocal)
  23093. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  23094. helper((IHThorKeyedJoinArg &)basehelper),
  23095. remote(_ctx, this, _remoteId, helper, *this, isFull, _isSimple, puller, *this),
  23096. joinFlags(_joinFlags),
  23097. preserveGroups(meta.isGrouped()),
  23098. puller(false),
  23099. isSimple(_isSimple),
  23100. isLocal(_isLocal),
  23101. abortLimit(0),
  23102. keepLimit(0),
  23103. atMost(0),
  23104. limitFail(false),
  23105. limitOnFail(false),
  23106. cloneLeft(false)
  23107. {
  23108. groupStart = NULL;
  23109. activityKind = _factory->getKind();
  23110. indexReadInput = NULL;
  23111. rootIndex = NULL;
  23112. atmostsTriggered = 0;
  23113. // MORE - code would be easier to read if I got more values from helper rather than passing from factory
  23114. }
  23115. virtual void onCreate(IHThorArg *_colocalParent)
  23116. {
  23117. CRoxieServerActivity::onCreate(_colocalParent);
  23118. remote.onCreate(_colocalParent);
  23119. }
  23120. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  23121. {
  23122. if (!idx)
  23123. puller.setInput(this, _sourceIdx, _in);
  23124. else if (idx==1)
  23125. {
  23126. indexReadInput = _in;
  23127. indexReadIdx = _sourceIdx;
  23128. }
  23129. else
  23130. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
  23131. }
  23132. virtual void connectInputStreams(bool consumerOrdered)
  23133. {
  23134. CRoxieServerActivity::connectInputStreams(consumerOrdered);
  23135. puller.connectInputStreams(ctx, consumerOrdered);
  23136. if (indexReadInput)
  23137. indexReadStream = connectSingleStream(ctx, indexReadInput, indexReadIdx, indexReadJunction, consumerOrdered); // We never actually pull the stream
  23138. }
  23139. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  23140. {
  23141. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  23142. if (indexReadInput)
  23143. {
  23144. indexReadInput->start(parentExtractSize, parentExtract, true); // paused=true because we don't want to actually run the index read
  23145. rootIndex = indexReadInput->queryIndexReadActivity();
  23146. if (!rootIndex)
  23147. throw MakeStringException(ROXIE_INTERNAL_ERROR,"Index in keyed join %d could not be resolved", queryId());
  23148. }
  23149. remote.onStart(parentExtractSize, parentExtract);
  23150. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  23151. atmostsTriggered = 0;
  23152. atMost = helper.getJoinLimit();
  23153. if (atMost == 0) atMost = (unsigned)-1;
  23154. abortLimit = helper.getMatchAbortLimit();
  23155. if (abortLimit == 0 || atMost != (unsigned) -1) abortLimit = (unsigned)-1;
  23156. keepLimit = helper.getKeepLimit();
  23157. if (keepLimit == 0) keepLimit = (unsigned)-1;
  23158. getLimitType(joinFlags, limitFail, limitOnFail);
  23159. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  23160. if (joinFlags & JFleftouter || limitOnFail)
  23161. createDefaultRight();
  23162. }
  23163. virtual void stop()
  23164. {
  23165. puller.stop();
  23166. if (indexReadStream)
  23167. indexReadStream->stop(); // Could probably do this as soon as re have fetched rootIndex?
  23168. CRoxieServerActivity::stop();
  23169. }
  23170. virtual unsigned __int64 queryLocalCycles() const
  23171. {
  23172. __int64 localCycles = remote.totalCycles.totalCycles;
  23173. localCycles -= puller.queryTotalCycles(); // MORE - debatable... but probably fair.
  23174. if (localCycles < 0)
  23175. localCycles = 0;
  23176. return localCycles;
  23177. }
  23178. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  23179. {
  23180. CRoxieServerActivity::gatherStats(merged);
  23181. remote.gatherStats(merged);
  23182. }
  23183. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  23184. {
  23185. if (idx==0)
  23186. return puller.queryInput();
  23187. else if (idx==1)
  23188. return indexReadInput;
  23189. else
  23190. return NULL;
  23191. }
  23192. virtual void reset()
  23193. {
  23194. totalCycles.totalCycles = remote.totalCycles.totalCycles;
  23195. remote.totalCycles.totalCycles = 0;
  23196. processed = remote.joinProcessed;
  23197. remote.joinProcessed = 0;
  23198. defaultRight.clear();
  23199. if (indexReadInput)
  23200. indexReadInput->reset();
  23201. if (atmostsTriggered)
  23202. noteStatistic(StNumAtmostTriggered, atmostsTriggered);
  23203. CRoxieServerActivity::reset();
  23204. puller.reset();
  23205. while (groups.ordinality())
  23206. {
  23207. ::Release(groups.dequeue());
  23208. }
  23209. }
  23210. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  23211. {
  23212. if (idx==(unsigned)-1)
  23213. idx = 0;
  23214. return idx ? NULL : &remote;
  23215. }
  23216. #undef new
  23217. virtual CJoinGroup *createJoinGroup(const void *row)
  23218. {
  23219. // NOTE - we need to protect access to queue, since it's also modified by consumer thread. Groupstart is only modified by puller thread.
  23220. CriticalBlock c(groupsCrit);
  23221. if (preserveGroups && !groupStart)
  23222. {
  23223. groupStart = new (&ctx->queryRowManager(), activityId) CJoinGroup(NULL, NULL);
  23224. groups.enqueue(groupStart);
  23225. }
  23226. CJoinGroup *jg = new (&ctx->queryRowManager(), activityId) CJoinGroup(row, groupStart);
  23227. groups.enqueue(jg);
  23228. return jg;
  23229. }
  23230. #if defined(_DEBUG) && defined(_WIN32) && !defined(USING_MPATROL)
  23231. #define new new(_NORMAL_BLOCK, __FILE__, __LINE__)
  23232. #endif
  23233. void endGroup()
  23234. {
  23235. CriticalBlock c(groupsCrit);
  23236. if (groupStart)
  23237. noteEndReceived(groupStart, 0);
  23238. groupStart = NULL;
  23239. }
  23240. virtual void noteEndReceived(CJoinGroup *jg, unsigned candidateCount)
  23241. {
  23242. if (jg->noteEndReceived(candidateCount))
  23243. processCompletedGroups();
  23244. }
  23245. void processCompletedGroups()
  23246. {
  23247. CriticalBlock c(groupsCrit);
  23248. while (groups.ordinality())
  23249. {
  23250. if (!groups.head()->complete())
  23251. break;
  23252. Owned<CJoinGroup> head = groups.dequeue();
  23253. if (preserveGroups)
  23254. {
  23255. assert(head->isHeadRecord());
  23256. assert(groups.head()->inGroup(head));
  23257. unsigned joinGroupSize = 0;
  23258. while (groups.ordinality() && groups.head()->inGroup(head))
  23259. {
  23260. Owned<CJoinGroup> finger = groups.dequeue();
  23261. joinGroupSize += doJoinGroup(finger);
  23262. }
  23263. if (joinGroupSize)
  23264. remote.addResult(NULL);
  23265. }
  23266. else
  23267. doJoinGroup(head);
  23268. }
  23269. }
  23270. void failLimit(const void * left)
  23271. {
  23272. helper.onMatchAbortLimitExceeded();
  23273. CommonXmlWriter xmlwrite(0);
  23274. if (input && input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  23275. {
  23276. input->queryOutputMeta()->toXML((byte *) left, xmlwrite);
  23277. }
  23278. throw MakeStringException(ROXIE_JOIN_ERROR, "More than %d match candidates in keyed join %d for row %s", abortLimit, queryId(), xmlwrite.str());
  23279. }
  23280. virtual bool needsAllocator() const { return true; }
  23281. unsigned doTransform(const void *left, const void *right, offset_t fpos_or_count, IException *except, const void **group, unsigned counter)
  23282. {
  23283. if (cloneLeft && !except)
  23284. {
  23285. LinkRoxieRow(left);
  23286. remote.addResult((void *) left);
  23287. return 1;
  23288. }
  23289. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  23290. unsigned outSize;
  23291. try
  23292. {
  23293. outSize = except ? helper.onFailTransform(rowBuilder, left, right, fpos_or_count, except) :
  23294. (activityKind == TAKkeyeddenormalizegroup) ? helper.transform(rowBuilder, left, right, (unsigned) fpos_or_count, group) :
  23295. helper.transform(rowBuilder, left, right, fpos_or_count, counter);
  23296. }
  23297. catch (IException *E)
  23298. {
  23299. throw makeWrappedException(E);
  23300. }
  23301. if (outSize)
  23302. {
  23303. const void *shrunk = rowBuilder.finalizeRowClear(outSize);
  23304. remote.addResult(shrunk);
  23305. return 1;
  23306. }
  23307. else
  23308. return 0;
  23309. }
  23310. unsigned doJoinGroup(CJoinGroup *jg)
  23311. {
  23312. unsigned matched = jg->rowsSeen();
  23313. unsigned added = 0;
  23314. const void *left = jg->queryLeft();
  23315. if (jg->candidateCount() > abortLimit)
  23316. {
  23317. if (limitFail)
  23318. failLimit(left);
  23319. if (ctx->queryDebugContext())
  23320. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  23321. if (limitOnFail)
  23322. {
  23323. Owned<IException> except;
  23324. try
  23325. {
  23326. failLimit(left);
  23327. }
  23328. catch(IException * e)
  23329. {
  23330. except.setown(e);
  23331. }
  23332. added = doTransform(left, defaultRight, 0, except, NULL, 0);
  23333. }
  23334. }
  23335. else if (!matched || jg->candidateCount() > atMost)
  23336. {
  23337. if (jg->candidateCount() > atMost)
  23338. atmostsTriggered++;
  23339. switch (joinFlags & JFtypemask)
  23340. {
  23341. case JFleftouter:
  23342. case JFleftonly:
  23343. switch (activityKind)
  23344. {
  23345. case TAKkeyedjoin:
  23346. case TAKkeyeddenormalizegroup:
  23347. added = doTransform(left, defaultRight, 0, NULL, NULL, 0);
  23348. break;
  23349. case TAKkeyeddenormalize:
  23350. LinkRoxieRow(left);
  23351. remote.addResult((void *) left);
  23352. added++;
  23353. break;
  23354. }
  23355. break;
  23356. }
  23357. }
  23358. else if (!(joinFlags & JFexclude))
  23359. {
  23360. unsigned idx = 0;
  23361. switch (activityKind)
  23362. {
  23363. case TAKkeyedjoin:
  23364. while (idx < matched)
  23365. {
  23366. const KeyedJoinHeader *rhs = jg->queryRow(idx);
  23367. added += doTransform(left, &rhs->rhsdata, rhs->fpos, NULL, NULL, idx+1);
  23368. if (added==keepLimit)
  23369. break;
  23370. idx++;
  23371. }
  23372. break;
  23373. case TAKkeyeddenormalize:
  23374. {
  23375. OwnedConstRoxieRow newLeft;
  23376. newLeft.set(left);
  23377. unsigned rowSize = 0;
  23378. unsigned rightAdded = 0;
  23379. while (idx < matched)
  23380. {
  23381. const KeyedJoinHeader *rhs = jg->queryRow(idx);
  23382. try
  23383. {
  23384. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  23385. size32_t transformedSize = helper.transform(rowBuilder, newLeft, &rhs->rhsdata, rhs->fpos, idx+1);
  23386. if (transformedSize)
  23387. {
  23388. rowSize = transformedSize;
  23389. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  23390. rightAdded++;
  23391. if (rightAdded==keepLimit)
  23392. break;
  23393. }
  23394. idx++;
  23395. }
  23396. catch (IException *E)
  23397. {
  23398. throw makeWrappedException(E);
  23399. }
  23400. }
  23401. if (rowSize)
  23402. {
  23403. remote.addResult(newLeft.getClear());
  23404. added++;
  23405. }
  23406. }
  23407. break;
  23408. case TAKkeyeddenormalizegroup:
  23409. {
  23410. ConstPointerArray extractedRows;
  23411. while (idx < matched && idx < keepLimit)
  23412. {
  23413. const KeyedJoinHeader *rhs = jg->queryRow(idx);
  23414. extractedRows.append((void *) &rhs->rhsdata);
  23415. idx++;
  23416. }
  23417. added += doTransform(left, extractedRows.item(0), extractedRows.ordinality(), NULL, (const void * *)extractedRows.getArray(), 0);
  23418. }
  23419. break;
  23420. }
  23421. }
  23422. return added;
  23423. }
  23424. virtual void processDone()
  23425. {
  23426. // called from puller thread
  23427. remote.flush();
  23428. remote.senddone();
  23429. }
  23430. virtual void onLimitExceeded(bool isKeyed)
  23431. {
  23432. if (traceLevel > 4)
  23433. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  23434. if (isKeyed)
  23435. throwUnexpected();
  23436. helper.onLimitExceeded();
  23437. }
  23438. virtual const void *createLimitFailRow(bool isKeyed)
  23439. {
  23440. throwUnexpected();
  23441. }
  23442. virtual bool fireException(IException *e)
  23443. {
  23444. // called from puller thread on failure
  23445. return remote.fireException(e);
  23446. }
  23447. virtual const void *nextRow()
  23448. {
  23449. throwUnexpected(); // I am nobody's input
  23450. }
  23451. };
  23452. #ifdef _MSC_VER
  23453. #pragma warning ( push )
  23454. #pragma warning ( disable: 4355 )
  23455. #endif
  23456. class CRoxieServerKeyedJoinActivity : public CRoxieServerKeyedJoinBase
  23457. {
  23458. CRoxieServerFullKeyedJoinHead head;
  23459. Owned<IEngineRowAllocator> fetchInputAllocator;
  23460. Linked<IFilePartMap> map;
  23461. bool variableFetchFileName;
  23462. Owned<const IResolvedFile> varFetchFileInfo;
  23463. CachedOutputMetaData fetchInputFields;
  23464. public:
  23465. CRoxieServerKeyedJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_headId, IKeyArray * _key, TranslatorArray *_translators, IOutputMetaData *_indexReadMeta,
  23466. const RemoteActivityId &_tailId, IFilePartMap *_map, unsigned _joinFlags, bool _isLocal)
  23467. : CRoxieServerKeyedJoinBase(_ctx, _factory, _probeManager, _tailId, _joinFlags, true, false, _isLocal),
  23468. head(_ctx, _factory, _probeManager, _headId, _key, _translators, _indexReadMeta, this, _isLocal),
  23469. map(_map)
  23470. {
  23471. CRoxieServerKeyedJoinBase::setInput(0, 0, head.queryOutput(0));
  23472. variableFetchFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  23473. }
  23474. virtual const IResolvedFile *queryVarFileInfo() const
  23475. {
  23476. return varFetchFileInfo;
  23477. }
  23478. virtual void onCreate(IHThorArg *_colocalParent)
  23479. {
  23480. CRoxieServerKeyedJoinBase::onCreate(_colocalParent);
  23481. head.onCreate(_colocalParent);
  23482. fetchInputFields.set(helper.queryFetchInputRecordSize());
  23483. fetchInputAllocator.setown(createRowAllocator(helper.queryFetchInputRecordSize()));
  23484. }
  23485. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  23486. {
  23487. CRoxieServerKeyedJoinBase::start(parentExtractSize, parentExtract, paused);
  23488. if (variableFetchFileName)
  23489. {
  23490. bool isFetchOpt = (helper.getFetchFlags() & FFdatafileoptional) != 0;
  23491. OwnedRoxieString fname(helper.getFileName());
  23492. varFetchFileInfo.setown(resolveLFN(fname, isFetchOpt));
  23493. if (varFetchFileInfo)
  23494. map.setown(varFetchFileInfo->getFileMap());
  23495. }
  23496. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().keyedJoinPreload, false, ctx);
  23497. }
  23498. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  23499. {
  23500. head.setInput(idx, _sourceIdx, _in);
  23501. }
  23502. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  23503. {
  23504. connectInputStreams(consumerOrdered);
  23505. return head.getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
  23506. }
  23507. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  23508. {
  23509. return head.queryInput(idx);
  23510. }
  23511. virtual void processRow(const void *_rhs)
  23512. {
  23513. // called from puller thread
  23514. KeyedJoinHeader *rhs = (KeyedJoinHeader *) _rhs;
  23515. CJoinGroup *jg = rhs->thisGroup;
  23516. if (rhs->partNo != (unsigned short) -1)
  23517. {
  23518. unsigned partNo = map->mapOffset(rhs->fpos);
  23519. RtlDynamicRowBuilder fetchBuilder(fetchInputAllocator, true);
  23520. size32_t fisize = helper.extractFetchFields(fetchBuilder, jg->queryLeft());
  23521. if (fetchInputFields.isVariableSize())
  23522. {
  23523. KeyedJoinHeader *outRow = (KeyedJoinHeader *) remote.getMem(partNo, 0, KEYEDJOIN_RECORD_SIZE(fisize + sizeof(fisize)));
  23524. memcpy(outRow, rhs, KEYEDJOIN_RECORD_SIZE(0)); // MORE - copy constructor might be more appropriate....
  23525. ReleaseRoxieRow(rhs);
  23526. jg->notePending();
  23527. memcpy(&outRow->rhsdata, &fisize, sizeof(fisize));
  23528. memcpy((&outRow->rhsdata)+sizeof(fisize), fetchBuilder.row(), fisize);
  23529. }
  23530. else
  23531. {
  23532. KeyedJoinHeader *outRow = (KeyedJoinHeader *) remote.getMem(partNo, 0, KEYEDJOIN_RECORD_SIZE(fisize));
  23533. memcpy(outRow, rhs, KEYEDJOIN_RECORD_SIZE(0)); // MORE - copy constructor might be more appropriate....
  23534. ReleaseRoxieRow(rhs);
  23535. jg->notePending();
  23536. memcpy(&outRow->rhsdata, fetchBuilder.row(), fisize);
  23537. }
  23538. }
  23539. else
  23540. {
  23541. unsigned candidateCount = (unsigned) rhs->fpos;
  23542. // CTXLOG("Full keyed join - all results back from index");
  23543. ReleaseRoxieRow(rhs);
  23544. noteEndReceived(jg, candidateCount); // may throw exception - so release row before calling
  23545. }
  23546. }
  23547. virtual void processEOG()
  23548. {
  23549. // called from front puller thread
  23550. if (preserveGroups)
  23551. endGroup();
  23552. }
  23553. void processGroup(const ConstPointerArray &)
  23554. {
  23555. throwUnexpected();
  23556. }
  23557. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  23558. {
  23559. CRoxieServerKeyedJoinBase::gatherStats(merged);
  23560. if (fetchInputAllocator)
  23561. fetchInputAllocator->gatherStats(merged);
  23562. }
  23563. };
  23564. #ifdef _MSC_VER
  23565. #pragma warning ( pop )
  23566. #endif
  23567. class CRoxieServerHalfKeyedJoinActivity : public CRoxieServerKeyedJoinBase
  23568. {
  23569. IOutputMetaData *indexReadMeta;
  23570. Owned<IEngineRowAllocator> indexReadAllocator;
  23571. Owned<IKeyManager> tlk;
  23572. bool variableIndexFileName;
  23573. bool indexReadInputRecordVariable;
  23574. Owned<const IResolvedFile> varFileInfo;
  23575. Linked<TranslatorArray> translators;
  23576. Linked<IKeyArray> keySet;
  23577. Owned<IOutputMetaData> joinPrefixedMeta;
  23578. Owned<IEngineRowAllocator> joinFieldsAllocator;
  23579. public:
  23580. CRoxieServerHalfKeyedJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IKeyArray * _keySet, TranslatorArray *_translators,
  23581. IOutputMetaData *_indexReadMeta, unsigned _joinFlags, bool _isSimple, bool _isLocal)
  23582. : CRoxieServerKeyedJoinBase(_ctx, _factory, _probeManager, _remoteId, _joinFlags, false, _isSimple, _isLocal),
  23583. indexReadMeta(_indexReadMeta),
  23584. tlk(createKeyManager(NULL, 0, this)),
  23585. keySet(_keySet),
  23586. translators(_translators)
  23587. {
  23588. variableIndexFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getJoinFlags() & (JFvarindexfilename|JFdynamicindexfilename|JFindexfromactivity)) != 0);
  23589. indexReadInputRecordVariable = indexReadMeta->isVariableSize();
  23590. }
  23591. virtual void serializeExtra(MemoryBuffer &out)
  23592. {
  23593. if (helper.getJoinFlags() & JFindexfromactivity)
  23594. {
  23595. assertex(rootIndex);
  23596. const RemoteActivityId& indexId = rootIndex->queryRemoteId();
  23597. indexId.serialize(out);
  23598. // could mess about reserving space for length then patching it again, to avoid copy, but probably not worth it
  23599. MemoryBuffer tmp;
  23600. rootIndex->queryActivity()->serializeCreateStartContext(tmp);
  23601. if (rootIndex->queryActivity()->queryVarFileInfo())
  23602. {
  23603. rootIndex->queryActivity()->queryVarFileInfo()->queryTimeStamp().serialize(tmp);
  23604. tmp.append(rootIndex->queryActivity()->queryVarFileInfo()->queryCheckSum());
  23605. }
  23606. unsigned ctxlen = tmp.length();
  23607. out.append(ctxlen).append(tmp);
  23608. }
  23609. }
  23610. virtual void onCreate(IHThorArg *_colocalParent)
  23611. {
  23612. CRoxieServerKeyedJoinBase::onCreate(_colocalParent);
  23613. indexReadAllocator.setown(createRowAllocator(indexReadMeta));
  23614. IOutputMetaData *joinFieldsMeta = helper.queryJoinFieldsRecordSize();
  23615. joinPrefixedMeta.setown(new CPrefixedOutputMeta(KEYEDJOIN_RECORD_SIZE(0), joinFieldsMeta)); // MORE - not sure if we really need this
  23616. joinFieldsAllocator.setown(createRowAllocator(joinPrefixedMeta));
  23617. }
  23618. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  23619. {
  23620. CRoxieServerKeyedJoinBase::start(parentExtractSize, parentExtract, paused);
  23621. if (rootIndex)
  23622. {
  23623. varFileInfo.setown(rootIndex->getVarFileInfo());
  23624. translators.setown(rootIndex->getTranslators());
  23625. keySet.setown(rootIndex->getKeySet());
  23626. }
  23627. else if (variableIndexFileName)
  23628. {
  23629. OwnedRoxieString indexFileName(helper.getIndexFileName());
  23630. varFileInfo.setown(resolveLFN(indexFileName, (helper.getJoinFlags() & JFindexoptional) != 0));
  23631. if (varFileInfo)
  23632. {
  23633. translators.setown(new TranslatorArray);
  23634. keySet.setown(varFileInfo->getKeyArray(factory->queryActivityMeta(), translators, false, isLocal ? factory->queryQueryFactory().queryChannel() : 0, factory->queryQueryFactory().queryOptions().enableFieldTranslation));
  23635. }
  23636. }
  23637. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().keyedJoinPreload, isSimple, ctx);
  23638. }
  23639. virtual const IResolvedFile *queryVarFileInfo() const
  23640. {
  23641. return varFileInfo;
  23642. }
  23643. virtual void reset()
  23644. {
  23645. CRoxieServerKeyedJoinBase::reset();
  23646. if (varFileInfo)
  23647. {
  23648. keySet.clear();
  23649. varFileInfo.clear();
  23650. }
  23651. }
  23652. virtual void processRow(const void *row)
  23653. {
  23654. // called from front puller thread
  23655. // buffer up an IndexRead request
  23656. if (keySet && helper.leftCanMatch(row))
  23657. {
  23658. RtlDynamicRowBuilder extractBuilder(indexReadAllocator);
  23659. unsigned indexReadRecordSize = helper.extractIndexReadFields(extractBuilder, row);
  23660. OwnedConstRoxieRow extracted;
  23661. if (indexReadRecordSize)
  23662. extracted.setown(extractBuilder.finalizeRowClear(indexReadRecordSize));
  23663. CJoinGroup *jg = createJoinGroup(row);
  23664. for (unsigned partNo = 0; partNo < keySet->length(); partNo++)
  23665. {
  23666. IKeyIndexBase *thisBase = keySet->queryKeyPart(partNo);
  23667. if (thisBase)
  23668. {
  23669. unsigned fileNo = 0;
  23670. IKeyIndex *thisKey = thisBase->queryPart(fileNo);
  23671. tlk->setKey(thisKey);
  23672. tlk->setLayoutTranslator(translators->item(fileNo));
  23673. helper.createSegmentMonitors(tlk, extracted);
  23674. if (rootIndex)
  23675. rootIndex->mergeSegmentMonitors(tlk);
  23676. tlk->finishSegmentMonitors();
  23677. try
  23678. {
  23679. tlk->reset();
  23680. for (;;)
  23681. {
  23682. typedef const void * cvp;
  23683. if (thisKey && thisKey->isTopLevelKey())
  23684. {
  23685. bool locallySorted = (!thisKey->isFullySorted());
  23686. while (locallySorted || tlk->lookup(false))
  23687. {
  23688. unsigned slavePart = locallySorted ? 0 : (unsigned) tlk->queryFpos();
  23689. if (locallySorted || slavePart)
  23690. {
  23691. cvp *outputBuffer = (cvp *) remote.getMem(slavePart, fileNo, indexReadRecordSize + sizeof(cvp) + (indexReadInputRecordVariable ? sizeof(unsigned) : 0));
  23692. *outputBuffer++ = jg;
  23693. if (indexReadInputRecordVariable)
  23694. {
  23695. *(unsigned *) outputBuffer = indexReadRecordSize;
  23696. outputBuffer = (cvp *) (((unsigned *) outputBuffer) + 1);
  23697. }
  23698. jg->notePending();
  23699. memcpy(outputBuffer, extracted, indexReadRecordSize);
  23700. if (locallySorted)
  23701. {
  23702. for (unsigned i = 1; i < numChannels; i++)
  23703. jg->notePending();
  23704. break;
  23705. }
  23706. }
  23707. }
  23708. }
  23709. else
  23710. {
  23711. unsigned accepted = 0;
  23712. unsigned rejected = 0;
  23713. Owned<CRowArrayMessageResult> result;
  23714. if (!isSimple)
  23715. result.setown(new CRowArrayMessageResult(ctx->queryRowManager(), true));
  23716. // MORE - This code seems to be duplicated in keyedJoinHead
  23717. jg->notePending();
  23718. unsigned candidateCount = 0;
  23719. while (tlk->lookup(true))
  23720. {
  23721. candidateCount++;
  23722. atomic_inc(&indexRecordsRead);
  23723. KLBlobProviderAdapter adapter(tlk);
  23724. offset_t recptr;
  23725. const byte *indexRow = tlk->queryKeyBuffer(recptr);
  23726. if (helper.indexReadMatch(extracted, indexRow, recptr, &adapter))
  23727. {
  23728. RtlDynamicRowBuilder rb(joinFieldsAllocator, true);
  23729. CPrefixedRowBuilder pb(KEYEDJOIN_RECORD_SIZE(0), rb);
  23730. accepted++;
  23731. KLBlobProviderAdapter adapter(tlk);
  23732. size32_t joinFieldsSize = helper.extractJoinFields(pb, indexRow, recptr, &adapter);
  23733. KeyedJoinHeader *rec = (KeyedJoinHeader *) rb.getUnfinalizedClear(); // lack of finalize ok as unserialized data here.
  23734. rec->fpos = recptr;
  23735. rec->thisGroup = jg;
  23736. rec->partNo = partNo;
  23737. if (isSimple)
  23738. remote.injected.enqueue(rec);
  23739. else
  23740. result->append(rec);
  23741. }
  23742. else
  23743. {
  23744. rejected++;
  23745. atomic_inc(&postFiltered);
  23746. }
  23747. }
  23748. // output an end marker for the matches to this group
  23749. KeyedJoinHeader *rec = (KeyedJoinHeader *) ctx->queryRowManager().allocate(KEYEDJOIN_RECORD_SIZE(0), activityId);
  23750. rec->fpos = (offset_t) candidateCount;
  23751. rec->thisGroup = jg;
  23752. rec->partNo = (unsigned short) -1;
  23753. if (isSimple)
  23754. remote.injected.enqueue(rec);
  23755. else
  23756. {
  23757. result->append(rec);
  23758. remote.injectResult(result.getClear());
  23759. }
  23760. if (accepted)
  23761. noteStatistic(StNumIndexAccepted, accepted);
  23762. if (rejected)
  23763. noteStatistic(StNumIndexRejected, rejected);
  23764. }
  23765. if (++fileNo < thisBase->numParts())
  23766. {
  23767. thisKey = thisBase->queryPart(fileNo);
  23768. tlk->setKey(thisKey);
  23769. tlk->setLayoutTranslator(translators->item(fileNo));
  23770. tlk->reset();
  23771. }
  23772. else
  23773. break;
  23774. }
  23775. tlk->releaseSegmentMonitors();
  23776. tlk->setKey(NULL);
  23777. }
  23778. catch (...)
  23779. {
  23780. tlk->releaseSegmentMonitors();
  23781. tlk->setKey(NULL);
  23782. throw;
  23783. }
  23784. }
  23785. }
  23786. noteEndReceived(jg, 0);
  23787. }
  23788. else
  23789. {
  23790. noteEndReceived(createJoinGroup(row), 0);
  23791. }
  23792. }
  23793. virtual void processEOG()
  23794. {
  23795. // called from front puller thread
  23796. if (preserveGroups)
  23797. endGroup();
  23798. }
  23799. void processGroup(const ConstPointerArray &)
  23800. {
  23801. throwUnexpected();
  23802. }
  23803. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  23804. {
  23805. CRoxieServerKeyedJoinBase::gatherStats(merged);
  23806. if (indexReadAllocator)
  23807. indexReadAllocator->gatherStats(merged);
  23808. if (joinFieldsAllocator)
  23809. joinFieldsAllocator->gatherStats(merged);
  23810. }
  23811. };
  23812. class CRoxieServerKeyedJoinActivityFactory : public CRoxieServerMultiInputFactory
  23813. {
  23814. Owned<const IResolvedFile> indexfile;
  23815. Owned<const IResolvedFile> datafile;
  23816. Owned<IKeyArray> keySet;
  23817. Owned<TranslatorArray> translatorArray;
  23818. Owned<IDefRecordMeta> activityMeta;
  23819. RemoteActivityId headId;
  23820. RemoteActivityId tailId;
  23821. IOutputMetaData *indexReadMeta;
  23822. Owned<IFilePartMap> map;
  23823. Owned<IFileIOArray> files;
  23824. unsigned joinFlags;
  23825. bool isHalfKeyed;
  23826. bool isLocal;
  23827. IRecordLayoutTranslator::Mode enableFieldTranslation;
  23828. bool variableFetchFileName;
  23829. bool variableIndexFileName;
  23830. bool isSimple;
  23831. public:
  23832. CRoxieServerKeyedJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_headId, const RemoteActivityId &_tailId)
  23833. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), headId(_headId), tailId(_tailId)
  23834. {
  23835. Owned<IHThorKeyedJoinArg> helper = (IHThorKeyedJoinArg *) helperFactory();
  23836. isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  23837. isSimple = isLocal;
  23838. rtlDataAttr indexLayoutMeta;
  23839. size32_t indexLayoutSize;
  23840. if(!helper->getIndexLayout(indexLayoutSize, indexLayoutMeta.refdata()))
  23841. assertex(indexLayoutSize== 0);
  23842. MemoryBuffer m;
  23843. m.setBuffer(indexLayoutSize, indexLayoutMeta.getdata());
  23844. activityMeta.setown(deserializeRecordMeta(m, true));
  23845. enableFieldTranslation = queryFactory.queryOptions().enableFieldTranslation;
  23846. translatorArray.setown(new TranslatorArray);
  23847. joinFlags = helper->getJoinFlags();
  23848. variableIndexFileName = allFilesDynamic || _queryFactory.isDynamic() || ((joinFlags & (JFvarindexfilename|JFdynamicindexfilename|JFindexfromactivity)) != 0);
  23849. variableFetchFileName = allFilesDynamic || _queryFactory.isDynamic() || ((helper->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  23850. if (!variableIndexFileName)
  23851. {
  23852. bool isOpt = (joinFlags & JFindexoptional) != 0;
  23853. OwnedRoxieString indexFileName(helper->getIndexFileName());
  23854. indexfile.setown(queryFactory.queryPackage().lookupFileName(indexFileName, isOpt, true, true, queryFactory.queryWorkUnit(), true));
  23855. if (indexfile)
  23856. keySet.setown(indexfile->getKeyArray(activityMeta, translatorArray, isOpt, isLocal ? queryFactory.queryChannel() : 0, enableFieldTranslation));
  23857. }
  23858. if (keySet && keySet->length()==1 && !isSimple)
  23859. {
  23860. IKeyIndexBase *thisBase = keySet->queryKeyPart(0);
  23861. if (thisBase->numParts()==1 && !thisBase->queryPart(0)->isTopLevelKey() && !_queryFactory.queryOptions().disableLocalOptimizations)
  23862. isSimple = true;
  23863. // MORE - if it's a variable filename then it MAY be simple, we don't know. Tough.
  23864. }
  23865. if (!simpleLocalKeyedJoins)
  23866. isSimple = false;
  23867. isHalfKeyed = !helper->diskAccessRequired();
  23868. indexReadMeta = QUERYINTERFACE(helper->queryIndexReadInputRecordSize(), IOutputMetaData);
  23869. if (!isHalfKeyed && !variableFetchFileName)
  23870. {
  23871. bool isFetchOpt = (helper->getFetchFlags() & FFdatafileoptional) != 0;
  23872. datafile.setown(_queryFactory.queryPackage().lookupFileName(queryNodeFileName(_graphNode, _kind), isFetchOpt, true, true, _queryFactory.queryWorkUnit(), true));
  23873. if (datafile)
  23874. {
  23875. if (isLocal)
  23876. files.setown(datafile->getIFileIOArray(isFetchOpt, queryFactory.queryChannel()));
  23877. else
  23878. map.setown(datafile->getFileMap());
  23879. }
  23880. }
  23881. }
  23882. virtual bool getEnableFieldTranslation() const
  23883. {
  23884. return enableFieldTranslation;
  23885. }
  23886. virtual IDefRecordMeta *queryActivityMeta() const
  23887. {
  23888. return activityMeta;
  23889. }
  23890. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  23891. {
  23892. if (isHalfKeyed)
  23893. return new CRoxieServerHalfKeyedJoinActivity(_ctx, this, _probeManager,
  23894. headId, keySet, translatorArray, indexReadMeta, joinFlags, isSimple, isLocal);
  23895. else
  23896. return new CRoxieServerKeyedJoinActivity(_ctx, this, _probeManager,
  23897. headId, keySet, translatorArray, indexReadMeta,
  23898. tailId, map, joinFlags, isLocal);
  23899. }
  23900. virtual const StatisticsMapping &queryStatsMapping() const
  23901. {
  23902. return keyedJoinStatistics;
  23903. }
  23904. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  23905. {
  23906. if (datafile)
  23907. addXrefFileInfo(reply, datafile);
  23908. if (indexfile)
  23909. addXrefFileInfo(reply, indexfile);
  23910. }
  23911. };
  23912. IRoxieServerActivityFactory *createRoxieServerKeyedJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId, const RemoteActivityId &_remoteId2)
  23913. {
  23914. return new CRoxieServerKeyedJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId, _remoteId2);
  23915. }
  23916. //=================================================================================
  23917. class CRoxieServerSoapActivityBase : public CRoxieServerActivity, implements ISoapCallRowProvider, implements IRoxieAbortMonitor
  23918. {
  23919. protected:
  23920. Owned<ISoapCallHelper> soaphelper;
  23921. IHThorSoapActionArg & helper;
  23922. StringBuffer authToken;
  23923. bool eof;
  23924. CriticalSection crit;
  23925. ClientCertificate *pClientCert;
  23926. public:
  23927. IMPLEMENT_IINTERFACE_USING(CRoxieServerActivity)
  23928. CRoxieServerSoapActivityBase(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  23929. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorSoapActionArg &)basehelper)
  23930. {
  23931. eof = false;
  23932. if (clientCert.certificate.length() > 0 && clientCert.privateKey.length() > 0 && clientCert.passphrase.length() > 0)
  23933. pClientCert = &clientCert;
  23934. else
  23935. pClientCert = NULL;
  23936. }
  23937. // ISoapCallRowProvider
  23938. virtual IHThorSoapActionArg * queryActionHelper() { return &helper; };
  23939. virtual IHThorSoapCallArg * queryCallHelper() { return NULL; };
  23940. virtual const void * getNextRow() { return NULL; };
  23941. virtual void releaseRow(const void * r) { ReleaseRoxieRow(r); };
  23942. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  23943. {
  23944. eof = false;
  23945. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  23946. authToken.append(ctx->queryAuthToken());
  23947. }
  23948. virtual void reset()
  23949. {
  23950. // MORE - Shouldn't we make sure thread is stopped etc???
  23951. soaphelper.clear();
  23952. CRoxieServerActivity::reset();
  23953. }
  23954. // IRoxieAbortMonitor
  23955. virtual void checkForAbort() { checkAbort(); }
  23956. };
  23957. //---------------------------------------------------------------------------
  23958. class CRoxieServerSoapRowCallActivity : public CRoxieServerSoapActivityBase
  23959. {
  23960. IHThorSoapCallArg & callHelper;
  23961. public:
  23962. CRoxieServerSoapRowCallActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  23963. : CRoxieServerSoapActivityBase(_ctx, _factory, _probeManager), callHelper((IHThorSoapCallArg &)basehelper)
  23964. {
  23965. }
  23966. virtual IHThorSoapCallArg * queryCallHelper()
  23967. {
  23968. return &callHelper;
  23969. }
  23970. virtual bool needsAllocator() const { return true; }
  23971. virtual const void *nextRow()
  23972. {
  23973. ActivityTimer t(totalCycles, timeActivities);
  23974. if(eof) return NULL;
  23975. if (soaphelper == NULL)
  23976. {
  23977. if (factory->getKind()==TAKhttp_rowdataset)
  23978. soaphelper.setown(createHttpCallHelper(this, rowAllocator, authToken.str(), SCrow, pClientCert, *this, this));
  23979. else
  23980. soaphelper.setown(createSoapCallHelper(this, rowAllocator, authToken.str(), SCrow, pClientCert, *this, this));
  23981. soaphelper->start();
  23982. }
  23983. OwnedConstRoxieRow ret = soaphelper->getRow();
  23984. if (!ret)
  23985. {
  23986. eof = true;
  23987. return NULL;
  23988. }
  23989. ++processed;
  23990. return ret.getClear();
  23991. }
  23992. };
  23993. class CRoxieServerSoapRowCallActivityFactory : public CRoxieServerActivityFactory
  23994. {
  23995. public:
  23996. CRoxieServerSoapRowCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  23997. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  23998. {
  23999. }
  24000. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  24001. {
  24002. return new CRoxieServerSoapRowCallActivity(_ctx, this, _probeManager);
  24003. }
  24004. virtual const StatisticsMapping &queryStatsMapping() const
  24005. {
  24006. return soapStatistics;
  24007. }
  24008. };
  24009. IRoxieServerActivityFactory *createRoxieServerSoapRowCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  24010. {
  24011. return new CRoxieServerSoapRowCallActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  24012. }
  24013. //---------------------------------------------------------------------------
  24014. class CRoxieServerSoapRowActionActivity : public CRoxieServerSoapActivityBase
  24015. {
  24016. public:
  24017. CRoxieServerSoapRowActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  24018. : CRoxieServerSoapActivityBase(_ctx, _factory, _probeManager)
  24019. {}
  24020. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  24021. {
  24022. //MORE: parentExtract not passed to start - although shouldn't be a problem.
  24023. soaphelper.setown(createSoapCallHelper(this, NULL, ctx->queryAuthToken(), SCrow, pClientCert, *this, this));
  24024. soaphelper->start();
  24025. soaphelper->waitUntilDone();
  24026. IException *e = soaphelper->getError();
  24027. soaphelper.clear();
  24028. if (e)
  24029. throw e;
  24030. }
  24031. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  24032. {
  24033. return NULL;
  24034. }
  24035. virtual const void *nextRow()
  24036. {
  24037. throwUnexpected(); // I am nobody's input
  24038. }
  24039. };
  24040. class CRoxieServerSoapRowActionActivityFactory : public CRoxieServerActivityFactory
  24041. {
  24042. bool isRoot;
  24043. public:
  24044. CRoxieServerSoapRowActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  24045. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  24046. {
  24047. }
  24048. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  24049. {
  24050. return new CRoxieServerSoapRowActionActivity(_ctx, this, _probeManager);
  24051. }
  24052. virtual bool isSink() const
  24053. {
  24054. return isRoot;
  24055. }
  24056. virtual const StatisticsMapping &queryStatsMapping() const
  24057. {
  24058. return soapStatistics;
  24059. }
  24060. };
  24061. IRoxieServerActivityFactory *createRoxieServerSoapRowActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  24062. {
  24063. return new CRoxieServerSoapRowActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  24064. }
  24065. //---------------------------------------------------------------------------
  24066. class CRoxieServerSoapDatasetCallActivity : public CRoxieServerSoapActivityBase
  24067. {
  24068. IHThorSoapCallArg & callHelper;
  24069. public:
  24070. CRoxieServerSoapDatasetCallActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  24071. : CRoxieServerSoapActivityBase(_ctx, _factory, _probeManager), callHelper((IHThorSoapCallArg &)basehelper)
  24072. {
  24073. }
  24074. virtual IHThorSoapCallArg * queryCallHelper()
  24075. {
  24076. return &callHelper;
  24077. }
  24078. virtual const void *getNextRow()
  24079. {
  24080. CriticalBlock b(crit); // MORE - why ?
  24081. return inputStream->ungroupedNextRow();
  24082. }
  24083. virtual bool needsAllocator() const { return true; }
  24084. virtual const void *nextRow()
  24085. {
  24086. ActivityTimer t(totalCycles, timeActivities);
  24087. if(eof) return NULL;
  24088. if (soaphelper == NULL)
  24089. {
  24090. soaphelper.setown(createSoapCallHelper(this, rowAllocator, authToken.str(), SCdataset, pClientCert, *this, this));
  24091. soaphelper->start();
  24092. }
  24093. OwnedConstRoxieRow ret = soaphelper->getRow();
  24094. if (!ret)
  24095. {
  24096. eof = true;
  24097. return NULL;
  24098. }
  24099. ++processed;
  24100. return ret.getClear();
  24101. }
  24102. };
  24103. class CRoxieServerSoapDatasetCallActivityFactory : public CRoxieServerActivityFactory
  24104. {
  24105. public:
  24106. CRoxieServerSoapDatasetCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  24107. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  24108. {
  24109. }
  24110. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  24111. {
  24112. return new CRoxieServerSoapDatasetCallActivity(_ctx, this, _probeManager);
  24113. }
  24114. virtual const StatisticsMapping &queryStatsMapping() const
  24115. {
  24116. return soapStatistics;
  24117. }
  24118. };
  24119. IRoxieServerActivityFactory *createRoxieServerSoapDatasetCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  24120. {
  24121. return new CRoxieServerSoapDatasetCallActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  24122. }
  24123. //---------------------------------------------------------------------------
  24124. class CRoxieServerSoapDatasetActionActivity : public CRoxieServerSoapActivityBase
  24125. {
  24126. public:
  24127. CRoxieServerSoapDatasetActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  24128. : CRoxieServerSoapActivityBase(_ctx, _factory, _probeManager)
  24129. {}
  24130. virtual const void *getNextRow()
  24131. {
  24132. CriticalBlock b(crit); // MORE - Why?
  24133. const void *nextrec = inputStream->ungroupedNextRow();
  24134. if (nextrec)
  24135. processed++;
  24136. return nextrec;
  24137. }
  24138. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  24139. {
  24140. try
  24141. {
  24142. start(parentExtractSize, parentExtract, false);
  24143. soaphelper.setown(createSoapCallHelper(this, NULL, ctx->queryAuthToken(), SCdataset, pClientCert, *this, this));
  24144. soaphelper->start();
  24145. soaphelper->waitUntilDone();
  24146. IException *e = soaphelper->getError();
  24147. soaphelper.clear();
  24148. if (e)
  24149. throw e;
  24150. stop();
  24151. }
  24152. catch (IException *E)
  24153. {
  24154. ctx->notifyAbort(E);
  24155. abort();
  24156. throw;
  24157. }
  24158. catch(...)
  24159. {
  24160. Owned<IException> E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught at %s:%d", sanitizeSourceFile(__FILE__), __LINE__);
  24161. ctx->notifyAbort(E);
  24162. abort();
  24163. throw;
  24164. }
  24165. }
  24166. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  24167. {
  24168. return NULL;
  24169. }
  24170. virtual const void *nextRow()
  24171. {
  24172. throwUnexpected(); // I am nobody's input
  24173. }
  24174. };
  24175. class CRoxieServerSoapDatasetActionActivityFactory : public CRoxieServerActivityFactory
  24176. {
  24177. bool isRoot;
  24178. public:
  24179. CRoxieServerSoapDatasetActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  24180. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  24181. {
  24182. }
  24183. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  24184. {
  24185. return new CRoxieServerSoapDatasetActionActivity(_ctx, this, _probeManager);
  24186. }
  24187. virtual bool isSink() const
  24188. {
  24189. return isRoot;
  24190. }
  24191. virtual const StatisticsMapping &queryStatsMapping() const
  24192. {
  24193. return soapStatistics;
  24194. }
  24195. };
  24196. IRoxieServerActivityFactory *createRoxieServerSoapDatasetActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  24197. {
  24198. return new CRoxieServerSoapDatasetActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  24199. }
  24200. //=====================================================================================================
  24201. class CGraphResults : implements IRoxieGraphResults, public CInterface
  24202. {
  24203. IArrayOf<IGraphResult> results;
  24204. CriticalSection cs;
  24205. IGraphResult & select(unsigned idx)
  24206. {
  24207. CriticalBlock procedure(cs);
  24208. if (idx >= results.ordinality())
  24209. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Error reading graph result %d before it is calculated", idx);
  24210. return results.item(idx);
  24211. }
  24212. public:
  24213. IMPLEMENT_IINTERFACE
  24214. void clear()
  24215. {
  24216. CriticalBlock procedure(cs);
  24217. results.kill();
  24218. }
  24219. virtual IEngineRowStream * createIterator(unsigned id)
  24220. {
  24221. return select(id).createIterator();
  24222. }
  24223. virtual void getLinkedResult(unsigned & count, byte * * & ret, unsigned id)
  24224. {
  24225. select(id).getLinkedResult(count, ret);
  24226. }
  24227. virtual void getDictionaryResult(unsigned & count, byte * * & ret, unsigned id)
  24228. {
  24229. select(id).getLinkedResult(count, ret);
  24230. }
  24231. virtual const void * getLinkedRowResult(unsigned id)
  24232. {
  24233. return select(id).getLinkedRowResult();
  24234. }
  24235. void setResult(unsigned id, IGraphResult * result)
  24236. {
  24237. CriticalBlock procedure(cs);
  24238. if (results.ordinality() <= id)
  24239. {
  24240. while (results.ordinality() < id)
  24241. results.append(*new CGraphResult);
  24242. results.append(*LINK(result));
  24243. }
  24244. else
  24245. results.replace(*LINK(result), id);
  24246. }
  24247. void appendResult(IGraphResult * result)
  24248. {
  24249. CriticalBlock procedure(cs);
  24250. results.append(*LINK(result));
  24251. }
  24252. };
  24253. //===================================================================================================================
  24254. class CPseudoArg : implements IHThorArg, public CInterface
  24255. {
  24256. public:
  24257. IMPLEMENT_IINTERFACE
  24258. virtual IOutputMetaData * queryOutputMeta() { return NULL; }
  24259. };
  24260. class CPseudoActivity : public CRoxieServerActivity
  24261. {
  24262. public:
  24263. CPseudoActivity(IRoxieSlaveContext *_ctx, IHThorArg & _helper) : CRoxieServerActivity(_ctx, _helper) {}
  24264. virtual const void *nextRow()
  24265. {
  24266. throwUnexpected(); // I am nobody's input
  24267. }
  24268. };
  24269. class CActivityGraph : implements IActivityGraph, implements IThorChildGraph, implements ILocalGraphEx, implements IRoxieServerChildGraph, public CInterface
  24270. {
  24271. protected:
  24272. class ActivityGraphSlaveContext : public IndirectSlaveContext
  24273. {
  24274. SpinLock abortLock;
  24275. bool aborted;
  24276. Owned<IException> exception;
  24277. public:
  24278. ActivityGraphSlaveContext(IRoxieSlaveContext *_ctx, const IRoxieContextLogger &_logctx) : IndirectSlaveContext(_ctx), logctx(_logctx), loopCounter(0), codeContext(NULL)
  24279. {
  24280. aborted = false;
  24281. }
  24282. // Note - we must track exceptions at the child level in case there is a CATCH in parent
  24283. virtual void notifyAbort(IException *E)
  24284. {
  24285. SpinBlock b(abortLock);
  24286. if (!aborted && QUERYINTERFACE(E, InterruptedSemaphoreException) == NULL)
  24287. {
  24288. aborted = true;
  24289. exception.set(E);
  24290. }
  24291. }
  24292. virtual void checkAbort()
  24293. {
  24294. if (aborted) // NOTE - don't bother getting lock before reading this (for speed) - a false read is very unlikely and not a problem
  24295. {
  24296. SpinBlock b(abortLock);
  24297. if (!exception)
  24298. exception.setown(MakeStringException(ROXIE_INTERNAL_ERROR, "Query was aborted"));
  24299. throw exception.getLink();
  24300. }
  24301. IndirectSlaveContext::checkAbort();
  24302. }
  24303. virtual ICodeContext *queryCodeContext()
  24304. {
  24305. return codeContext;
  24306. }
  24307. void setCodeContext(ICodeContext * _codeContext)
  24308. {
  24309. codeContext = _codeContext;
  24310. }
  24311. void setLoopCounter(unsigned _loopCounter)
  24312. {
  24313. loopCounter = _loopCounter;
  24314. }
  24315. virtual void noteChildGraph(unsigned id, IActivityGraph *childGraph)
  24316. {
  24317. childGraphs.setValue(id, childGraph);
  24318. }
  24319. virtual IActivityGraph * queryChildGraph(unsigned id)
  24320. {
  24321. if (queryTraceLevel() > 10)
  24322. CTXLOG("resolveChildGraph %d", id);
  24323. IActivityGraph *childGraph = childGraphs.getValue(id);
  24324. assertex(childGraph);
  24325. return childGraph;
  24326. }
  24327. // 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
  24328. virtual StringBuffer &getLogPrefix(StringBuffer &ret) const
  24329. {
  24330. logctx.getLogPrefix(ret);
  24331. if (loopCounter)
  24332. ret.appendf("{%u}", loopCounter);
  24333. return ret;
  24334. }
  24335. protected:
  24336. const IRoxieContextLogger &logctx;
  24337. unsigned loopCounter;
  24338. ICodeContext * codeContext;
  24339. MapXToMyClass<unsigned, unsigned, IActivityGraph> childGraphs;
  24340. } graphSlaveContext;
  24341. class ActivityGraphCodeContext : public IndirectCodeContext
  24342. {
  24343. public:
  24344. virtual IEclGraphResults * resolveLocalQuery(__int64 activityId)
  24345. {
  24346. if ((unsigned) activityId == container->queryId())
  24347. return container;
  24348. IActivityGraph * match = slaveContext->queryChildGraph((unsigned) activityId);
  24349. if (match)
  24350. return match->queryLocalGraph();
  24351. return IndirectCodeContext::resolveLocalQuery(activityId);
  24352. }
  24353. virtual IThorChildGraph * resolveChildQuery(__int64 activityId, IHThorArg * colocal)
  24354. {
  24355. IActivityGraph * match = slaveContext->queryChildGraph((unsigned) activityId);
  24356. return LINK(match->queryChildGraph());
  24357. }
  24358. virtual unsigned getGraphLoopCounter() const
  24359. {
  24360. return container->queryLoopCounter(); // only called if value is valid
  24361. }
  24362. void setContainer(IRoxieSlaveContext * _slaveContext, CActivityGraph * _container)
  24363. {
  24364. slaveContext = _slaveContext;
  24365. container = _container;
  24366. }
  24367. protected:
  24368. IRoxieSlaveContext * slaveContext;
  24369. CActivityGraph * container;
  24370. } graphCodeContext;
  24371. // NOTE - destructor order is significant - need to destroy graphCodeContext and graphSlaveContext last
  24372. IArrayOf<IRoxieServerActivity> activities;
  24373. IArrayOf<IRoxieProbe> probes;
  24374. IRoxieServerActivityCopyArray sinks;
  24375. StringAttr graphName;
  24376. Owned<CGraphResults> results;
  24377. CGraphResults graphLoopResults;
  24378. const ActivityArray & graphDefinition;
  24379. CriticalSection evaluateCrit;
  24380. IProbeManager *probeManager;
  24381. unsigned id;
  24382. unsigned loopCounter;
  24383. public:
  24384. IMPLEMENT_IINTERFACE;
  24385. CActivityGraph(IRoxieSlaveContext *_ctx, const char *_graphName, unsigned _id, const ActivityArray &x, IProbeManager *_probeManager, const IRoxieContextLogger &_logctx)
  24386. : probeManager(_probeManager), graphDefinition(x), graphName(_graphName), graphSlaveContext(_ctx, _logctx)
  24387. {
  24388. id = x.getLibraryGraphId();
  24389. if (!id)
  24390. id = _id;
  24391. loopCounter = 0;
  24392. graphSlaveContext.setCodeContext(&graphCodeContext);
  24393. graphCodeContext.setContainer(&graphSlaveContext, this);
  24394. }
  24395. ~CActivityGraph()
  24396. {
  24397. ForEachItemIn(i, activities)
  24398. activities.item(i).updateFactoryStatistics();
  24399. if (probeManager)
  24400. probeManager->deleteGraph((IArrayOf<IActivityBase>*)&activities, (IArrayOf<IInputBase>*)&probes);
  24401. }
  24402. virtual const char *queryName() const
  24403. {
  24404. return graphName.get();
  24405. }
  24406. void createGraph(IRoxieSlaveContext *_ctx)
  24407. {
  24408. if (graphDefinition.isMultiInstance())
  24409. {
  24410. graphCodeContext.set(_ctx->queryCodeContext());
  24411. _ctx = &graphSlaveContext;
  24412. }
  24413. ForEachItemIn(idx, graphDefinition)
  24414. {
  24415. IRoxieServerActivityFactory &donor = graphDefinition.serverItem(idx);
  24416. IRoxieServerActivity &activity = *donor.createActivity(_ctx, probeManager);
  24417. activities.append(activity);
  24418. if (donor.isSink())
  24419. {
  24420. sinks.append(activity);
  24421. if (probeManager)
  24422. probeManager->noteSink(&activity);
  24423. }
  24424. }
  24425. ForEachItemIn(idx1, graphDefinition)
  24426. {
  24427. IRoxieServerActivityFactory &donor = graphDefinition.serverItem(idx1);
  24428. IRoxieServerActivity &activity = activities.item(idx1);
  24429. unsigned inputidx = 0;
  24430. for (;;)
  24431. {
  24432. unsigned outputidx;
  24433. unsigned source = donor.getInput(inputidx, outputidx);
  24434. if (source==(unsigned) -1)
  24435. break;
  24436. connectInput(idx1, inputidx, source, outputidx, 0);
  24437. inputidx++;
  24438. }
  24439. IntArray &dependencies = donor.queryDependencies();
  24440. IntArray &dependencyIndexes = donor.queryDependencyIndexes();
  24441. IntArray &dependencyControlIds = donor.queryDependencyControlIds();
  24442. StringArray &dependencyEdgeIds = donor.queryDependencyEdgeIds();
  24443. ForEachItemIn(idx2, dependencies)
  24444. {
  24445. IRoxieServerActivity &dependencySourceActivity = activities.item(dependencies.item(idx2));
  24446. unsigned dependencySourceIndex = dependencyIndexes.item(idx2);
  24447. unsigned dependencyControlId = dependencyControlIds.item(idx2);
  24448. activity.addDependency(dependencySourceActivity, dependencySourceIndex, dependencyControlId);
  24449. if (probeManager)
  24450. probeManager->noteDependency( &dependencySourceActivity, dependencySourceIndex, dependencyControlId, dependencyEdgeIds.item(idx2), &activity);
  24451. }
  24452. }
  24453. ForEachItemIn(idx2, sinks)
  24454. {
  24455. IRoxieServerActivity &sink = sinks.item(idx2);
  24456. sink.connectInputStreams(true);
  24457. }
  24458. }
  24459. void connectInput(unsigned target, unsigned targetIdx, unsigned source, unsigned sourceIdx, unsigned iteration)
  24460. {
  24461. IRoxieServerActivity &targetActivity = activities.item(target);
  24462. IRoxieServerActivity &sourceActivity = activities.item(source);
  24463. IFinalRoxieInput * output = sourceActivity.queryOutput(sourceIdx);
  24464. if (probeManager)
  24465. {
  24466. IRoxieProbe * inputProbe = probeManager->createProbe(static_cast<IInputBase*>(output), &sourceActivity, &targetActivity, sourceIdx, targetIdx, iteration);
  24467. probes.append(*LINK(inputProbe));
  24468. output = &dynamic_cast<IFinalRoxieInput &>(inputProbe->queryInput());
  24469. }
  24470. targetActivity.setInput(targetIdx, sourceIdx, output);
  24471. }
  24472. virtual void onCreate(IHThorArg *_colocalParent)
  24473. {
  24474. ForEachItemIn(idx, activities)
  24475. {
  24476. IRoxieServerActivity *activity = &activities.item(idx);
  24477. if (activity)
  24478. activity->onCreate(_colocalParent);
  24479. }
  24480. }
  24481. virtual void abort()
  24482. {
  24483. ForEachItemIn(idx, sinks)
  24484. {
  24485. IRoxieServerActivity &sink = sinks.item(idx);
  24486. sink.abort();
  24487. }
  24488. }
  24489. virtual void reset()
  24490. {
  24491. ForEachItemIn(idx, sinks)
  24492. {
  24493. IRoxieServerActivity &sink = sinks.item(idx);
  24494. sink.reset();
  24495. }
  24496. }
  24497. Linked<IException> exception;
  24498. CriticalSection eCrit;
  24499. virtual void noteException(IException *E)
  24500. {
  24501. CriticalBlock b(eCrit);
  24502. if (!exception)
  24503. {
  24504. if (graphSlaveContext.queryDebugContext())
  24505. {
  24506. graphSlaveContext.queryDebugContext()->checkBreakpoint(DebugStateException, NULL, exception);
  24507. }
  24508. exception.set(E);
  24509. }
  24510. }
  24511. virtual void checkAbort()
  24512. {
  24513. CriticalBlock b(eCrit);
  24514. if (exception)
  24515. throw exception.getLink();
  24516. }
  24517. virtual void execute()
  24518. {
  24519. results.setown(new CGraphResults);
  24520. doExecute(0, NULL);
  24521. }
  24522. //New child query code...
  24523. virtual IThorChildGraph * queryChildGraph()
  24524. {
  24525. return this;
  24526. }
  24527. virtual IEclGraphResults * queryLocalGraph()
  24528. {
  24529. return this;
  24530. }
  24531. virtual IRoxieServerChildGraph * queryLoopGraph()
  24532. {
  24533. return this;
  24534. }
  24535. inline unsigned queryId() const
  24536. {
  24537. return id;
  24538. }
  24539. inline unsigned queryLoopCounter() const
  24540. {
  24541. return loopCounter;
  24542. }
  24543. void doExecute(unsigned parentExtractSize, const byte * parentExtract)
  24544. {
  24545. if (sinks.ordinality()==1)
  24546. sinks.item(0).execute(parentExtractSize, parentExtract);
  24547. #ifdef PARALLEL_EXECUTE
  24548. else if (!probeManager && !graphDefinition.isSequential())
  24549. {
  24550. class casyncfor: public CAsyncFor
  24551. {
  24552. public:
  24553. IActivityGraph &parent;
  24554. unsigned parentExtractSize;
  24555. const byte * parentExtract;
  24556. casyncfor(IRoxieServerActivityCopyArray &_sinks, IActivityGraph &_parent, unsigned _parentExtractSize, const byte * _parentExtract) :
  24557. sinks(_sinks), parent(_parent), parentExtractSize(_parentExtractSize), parentExtract(_parentExtract) { }
  24558. void Do(unsigned i)
  24559. {
  24560. try
  24561. {
  24562. sinks.item(i).execute(parentExtractSize, parentExtract);
  24563. }
  24564. catch (IException *E)
  24565. {
  24566. parent.noteException(E);
  24567. throw;
  24568. }
  24569. }
  24570. private:
  24571. IRoxieServerActivityCopyArray &sinks;
  24572. } afor(sinks, *this, parentExtractSize, parentExtract);
  24573. afor.For(sinks.ordinality(), sinks.ordinality());
  24574. }
  24575. #endif
  24576. else
  24577. {
  24578. ForEachItemIn(idx, sinks)
  24579. {
  24580. IRoxieServerActivity &sink = sinks.item(idx);
  24581. sink.execute(parentExtractSize, parentExtract);
  24582. }
  24583. }
  24584. }
  24585. virtual IEclGraphResults *evaluate(unsigned parentExtractSize, const byte * parentExtract)
  24586. {
  24587. CriticalBlock block(evaluateCrit);
  24588. results.setown(new CGraphResults);
  24589. try
  24590. {
  24591. doExecute(parentExtractSize, parentExtract);
  24592. }
  24593. catch (...)
  24594. {
  24595. DBGLOG("Exception thrown in child query - cleaning up");
  24596. reset();
  24597. throw;
  24598. }
  24599. reset();
  24600. return results.getClear();
  24601. }
  24602. //interface IRoxieServerChildGraph
  24603. virtual void beforeExecute()
  24604. {
  24605. results.setown(new CGraphResults);
  24606. }
  24607. virtual IFinalRoxieInput * startOutput(unsigned id, unsigned parentExtractSize, const byte *parentExtract, bool paused)
  24608. {
  24609. IFinalRoxieInput * ret = selectOutput(id);
  24610. ret->start(parentExtractSize, parentExtract, paused);
  24611. return ret;
  24612. }
  24613. virtual IFinalRoxieInput * selectOutput(unsigned id)
  24614. {
  24615. ForEachItemIn(i, sinks)
  24616. {
  24617. IFinalRoxieInput * ret = sinks.item(i).querySelectOutput(id);
  24618. if (ret)
  24619. return ret;
  24620. }
  24621. throwUnexpected();
  24622. return NULL;
  24623. }
  24624. virtual void setInputResult(unsigned id, IGraphResult * result)
  24625. {
  24626. results->setResult(id, result);
  24627. }
  24628. virtual bool querySetInputResult(unsigned id, unsigned _sourceIdx, IFinalRoxieInput * input)
  24629. {
  24630. ForEachItemIn(i, activities)
  24631. {
  24632. if (activities.item(i).querySetStreamInput(id, _sourceIdx, input))
  24633. return true;
  24634. }
  24635. return false;
  24636. }
  24637. virtual void stopUnusedOutputs()
  24638. {
  24639. //Hmm not sure how to do this...
  24640. }
  24641. virtual void afterExecute()
  24642. {
  24643. ForEachItemIn(i, sinks)
  24644. {
  24645. sinks.item(i).stop();
  24646. }
  24647. if (graphSlaveContext.queryDebugContext())
  24648. {
  24649. graphSlaveContext.queryDebugContext()->checkBreakpoint(DebugStateGraphFinished, NULL, NULL);
  24650. }
  24651. reset();
  24652. }
  24653. virtual IRoxieGraphResults * execute(size32_t parentExtractSize, const byte *parentExtract)
  24654. {
  24655. doExecute(parentExtractSize, parentExtract);
  24656. return LINK(results);
  24657. }
  24658. virtual void getLinkedResult(unsigned & count, byte * * & ret, unsigned id)
  24659. {
  24660. results->getLinkedResult(count, ret, id);
  24661. }
  24662. virtual void getDictionaryResult(unsigned & count, byte * * & ret, unsigned id)
  24663. {
  24664. results->getLinkedResult(count, ret, id);
  24665. }
  24666. virtual const void * getLinkedRowResult(unsigned id)
  24667. {
  24668. return results->getLinkedRowResult(id);
  24669. }
  24670. virtual void setResult(unsigned id, IGraphResult * result)
  24671. {
  24672. results->setResult(id, result);
  24673. }
  24674. virtual IEngineRowStream * createResultIterator(unsigned id)
  24675. {
  24676. return results->createIterator(id);
  24677. }
  24678. virtual void setGraphLoopResult(IGraphResult * result)
  24679. {
  24680. graphLoopResults.appendResult(result);
  24681. }
  24682. virtual IEngineRowStream * createGraphLoopResultIterator(unsigned id)
  24683. {
  24684. try
  24685. {
  24686. return graphLoopResults.createIterator(id);
  24687. }
  24688. catch (IException * e)
  24689. {
  24690. e->Release();
  24691. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Error reading graph result %d before it is calculated", id);
  24692. }
  24693. }
  24694. virtual void clearGraphLoopResults()
  24695. {
  24696. graphLoopResults.clear();
  24697. }
  24698. virtual void executeGraphLoop(size32_t parentExtractSize, const byte *parentExtract)
  24699. {
  24700. doExecute(parentExtractSize, parentExtract);
  24701. }
  24702. virtual void setGraphLoopResult(unsigned id, IGraphResult * result)
  24703. {
  24704. graphLoopResults.setResult(id, result);
  24705. }
  24706. virtual IEngineRowStream * getGraphLoopResult(unsigned id)
  24707. {
  24708. return graphLoopResults.createIterator(id);
  24709. }
  24710. virtual void getProbeResponse(IPropertyTree *query)
  24711. {
  24712. if (probeManager)
  24713. probeManager->getProbeResponse(query);
  24714. }
  24715. virtual IRoxieServerChildGraph * createGraphLoopInstance(IRoxieSlaveContext *ctx, unsigned loopCounter, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &logctx)
  24716. {
  24717. throwUnexpected();
  24718. }
  24719. virtual CGraphIterationInfo *selectGraphLoopOutput()
  24720. {
  24721. return NULL;
  24722. }
  24723. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor)
  24724. {
  24725. throwUnexpected();
  24726. }
  24727. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor)
  24728. {
  24729. throwUnexpected();
  24730. }
  24731. };
  24732. class CProxyActivityGraph : implements IActivityGraph, implements IThorChildGraph, public CInterface
  24733. {
  24734. public:
  24735. IMPLEMENT_IINTERFACE;
  24736. CProxyActivityGraph(IRoxieSlaveContext *_ctx, const char *_graphName, unsigned _id, ActivityArray &_graphDefinition, const IRoxieContextLogger &_logctx, unsigned _numParallel)
  24737. : ctx(_ctx), graphName(_graphName), id(_id), graphDefinition(_graphDefinition), logctx(_logctx), numParallel(_numParallel)
  24738. {
  24739. }
  24740. virtual void abort() { throwUnexpected(); }
  24741. virtual void reset() { throwUnexpected(); }
  24742. virtual void execute() { throwUnexpected(); }
  24743. virtual void getProbeResponse(IPropertyTree *query) { throwUnexpected(); }
  24744. virtual void onCreate(IHThorArg *_colocalArg)
  24745. {
  24746. colocalArg = _colocalArg;
  24747. }
  24748. virtual void noteException(IException *E) { throwUnexpected(); }
  24749. virtual void checkAbort() { throwUnexpected(); }
  24750. virtual IThorChildGraph * queryChildGraph() { return this; }
  24751. virtual IEclGraphResults * queryLocalGraph() { throwUnexpected(); }
  24752. virtual IRoxieServerChildGraph * queryLoopGraph() { throwUnexpected(); }
  24753. virtual IRoxieServerChildGraph * createGraphLoopInstance(IRoxieSlaveContext *ctx, unsigned loopCounter, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &logctx) { throwUnexpected(); }
  24754. virtual const char *queryName() const { throwUnexpected(); }
  24755. virtual IRoxieServerActivity *queryActivity(unsigned _activityId) { return nullptr; } // MORE - may need something here!?
  24756. virtual IEclGraphResults * evaluate(unsigned parentExtractSize, const byte * parentExtract)
  24757. {
  24758. Owned<CActivityGraph> realGraph;
  24759. {
  24760. CriticalBlock b(graphCrit);
  24761. if (stack.length())
  24762. realGraph.setown(&stack.popGet());
  24763. }
  24764. if (!realGraph)
  24765. {
  24766. realGraph.setown(new CActivityGraph(ctx, graphName, id, graphDefinition, NULL, logctx));
  24767. realGraph->createGraph(ctx);
  24768. realGraph->onCreate(colocalArg);
  24769. }
  24770. Owned<IEclGraphResults> results = realGraph->evaluate(parentExtractSize, parentExtract);
  24771. {
  24772. CriticalBlock b(graphCrit);
  24773. stack.append(*realGraph.getClear());
  24774. }
  24775. return results.getClear();
  24776. }
  24777. protected:
  24778. IRoxieSlaveContext *ctx;
  24779. StringAttr graphName;
  24780. unsigned id;
  24781. ActivityArray &graphDefinition;
  24782. const IRoxieContextLogger &logctx;
  24783. unsigned numParallel;
  24784. IHThorArg *colocalArg = nullptr;
  24785. CriticalSection graphCrit;
  24786. CIArrayOf<CActivityGraph> stack;
  24787. };
  24788. class CIterationActivityGraph : public CActivityGraph
  24789. {
  24790. IHThorArg * colocalParent;
  24791. unsigned fixedParentExtractSize;
  24792. const byte * fixedParentExtract;
  24793. unsigned graphOutputActivityIndex;
  24794. public:
  24795. CIterationActivityGraph(const char *_graphName, unsigned _id, ActivityArray &x, IProbeManager *_probeManager,
  24796. unsigned _loopCounter, IRoxieSlaveContext *_ctx, IHThorArg * _colocalParent, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &_logctx)
  24797. : CActivityGraph(_ctx, _graphName, _id, x, _probeManager, _logctx)
  24798. {
  24799. graphOutputActivityIndex = 0;
  24800. loopCounter = _loopCounter;
  24801. colocalParent = _colocalParent;
  24802. graphSlaveContext.setLoopCounter(loopCounter);
  24803. graphCodeContext.set(_ctx->queryCodeContext());
  24804. fixedParentExtractSize = parentExtractSize;
  24805. fixedParentExtract = parentExtract;
  24806. }
  24807. void createIterationGraph(IRoxieSlaveContext *_ctx)
  24808. {
  24809. Owned<IRoxieServerActivity> pseudoActivity = new CPseudoActivity(_ctx, *new CPseudoArg);
  24810. ForEachItemIn(idx1, graphDefinition)
  24811. activities.append(*LINK(pseudoActivity));
  24812. graphOutputActivityIndex = queryGraphOutputIndex();
  24813. recursiveCreateGraph(_ctx, graphOutputActivityIndex);
  24814. }
  24815. unsigned queryGraphOutputIndex() const
  24816. {
  24817. ForEachItemIn(i, graphDefinition)
  24818. if (graphDefinition.serverItem(i).getKind() == TAKgraphloopresultwrite)
  24819. return i;
  24820. throwUnexpected();
  24821. }
  24822. void recursiveCreateGraph(IRoxieSlaveContext *_ctx, unsigned whichActivity)
  24823. {
  24824. //Check to see if already created
  24825. IRoxieServerActivity & prevActivity = activities.item(whichActivity);
  24826. if (prevActivity.queryId() != 0)
  24827. {
  24828. prevActivity.noteOutputUsed(); //We need to patch up the number of outputs for splitters.
  24829. return;
  24830. }
  24831. IRoxieServerActivityFactory &donor = graphDefinition.serverItem(whichActivity);
  24832. IRoxieServerActivity * activity = NULL;
  24833. if (donor.isGraphInvariant())
  24834. {
  24835. ThorActivityKind kind = donor.getKind();
  24836. switch (kind)
  24837. {
  24838. case TAKif:
  24839. case TAKchildif:
  24840. case TAKcase:
  24841. case TAKchildcase: // MORE RKC->GH - what about FILTER with a graph-invariant condition and other latestart activities?
  24842. {
  24843. Owned<IHThorArg> helper = &donor.getHelper();
  24844. helper->onCreate(&graphCodeContext, colocalParent, NULL);
  24845. helper->onStart(fixedParentExtract, NULL);
  24846. unsigned branch;
  24847. switch (kind)
  24848. {
  24849. case TAKif: case TAKchildif:
  24850. branch = static_cast<IHThorIfArg *>(helper.get())->getCondition() ? 0 : 1;
  24851. break;
  24852. case TAKcase: case TAKchildcase:
  24853. branch = static_cast<IHThorCaseArg *>(helper.get())->getBranch();
  24854. if (branch >= donor.numInputs())
  24855. branch = donor.numInputs() - 1;
  24856. break;
  24857. default:
  24858. throwUnexpected();
  24859. }
  24860. helper.clear();
  24861. unsigned outputidx;
  24862. unsigned source = donor.getInput(branch, outputidx);
  24863. if (source ==(unsigned) -1)
  24864. activity = createRoxieServerNullActivity(&graphSlaveContext, &donor, probeManager);
  24865. else
  24866. activity = createRoxieServerPassThroughActivity(&graphSlaveContext, &donor, probeManager);
  24867. activities.replace(*activity, whichActivity);
  24868. activity->onCreate(colocalParent);
  24869. if (source ==(unsigned) -1)
  24870. return;
  24871. recursiveCreateGraph(_ctx, source);
  24872. connectInput(whichActivity, 0, source, outputidx, loopCounter);
  24873. break;
  24874. }
  24875. }
  24876. }
  24877. if (!activity)
  24878. {
  24879. activity = donor.createActivity(&graphSlaveContext, probeManager);
  24880. activities.replace(*activity, whichActivity);
  24881. activity->onCreate(colocalParent);
  24882. activity->resetOutputsUsed();
  24883. unsigned inputidx = 0;
  24884. for (;;)
  24885. {
  24886. unsigned outputidx;
  24887. unsigned source = donor.getInput(inputidx, outputidx);
  24888. if (source==(unsigned) -1)
  24889. break;
  24890. recursiveCreateGraph(_ctx, source);
  24891. connectInput(whichActivity, inputidx, source, outputidx, loopCounter);
  24892. inputidx++;
  24893. }
  24894. }
  24895. IntArray &dependencies = donor.queryDependencies();
  24896. IntArray &dependencyIndexes = donor.queryDependencyIndexes();
  24897. IntArray &dependencyControlIds = donor.queryDependencyControlIds();
  24898. ForEachItemIn(idx2, dependencies)
  24899. {
  24900. unsigned input = dependencies.item(idx2);
  24901. recursiveCreateGraph(_ctx, input);
  24902. activity->addDependency(activities.item(input),dependencyIndexes.item(idx2),dependencyControlIds.item(idx2));
  24903. }
  24904. }
  24905. virtual CGraphIterationInfo *selectGraphLoopOutput()
  24906. {
  24907. IRoxieServerActivity &sourceActivity = activities.item(graphOutputActivityIndex);
  24908. IFinalRoxieInput *sourceInput = sourceActivity.queryOutput(0);
  24909. return new CGraphIterationInfo(&sourceActivity, sourceInput, 0, loopCounter);
  24910. }
  24911. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor)
  24912. {
  24913. ForEachItemIn(i, activities)
  24914. activities.item(i).gatherIterationUsage(processor, fixedParentExtractSize, fixedParentExtract);
  24915. }
  24916. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor)
  24917. {
  24918. ForEachItemIn(i, activities)
  24919. activities.item(i).associateIterationOutputs(processor, fixedParentExtractSize, fixedParentExtract, probeManager, probes);
  24920. }
  24921. };
  24922. class CDelayedActivityGraph : implements IActivityGraph, public CInterface
  24923. {
  24924. StringAttr graphName;
  24925. ActivityArray & graphDefinition;
  24926. IProbeManager *probeManager;
  24927. unsigned id;
  24928. IRoxieSlaveContext * ctx;
  24929. IHThorArg * colocalParent;
  24930. public:
  24931. IMPLEMENT_IINTERFACE;
  24932. CDelayedActivityGraph(const char *_graphName, unsigned _id, ActivityArray &x, IProbeManager *_probeManager)
  24933. : probeManager(_probeManager), graphDefinition(x)
  24934. {
  24935. graphName.set(_graphName);
  24936. id = _id;
  24937. ctx = NULL;
  24938. colocalParent = NULL;
  24939. }
  24940. virtual const char *queryName() const { return graphName.get(); }
  24941. virtual void abort() { throwUnexpected(); }
  24942. virtual void reset() { }
  24943. virtual void execute() { throwUnexpected(); }
  24944. virtual void getProbeResponse(IPropertyTree *query) { throwUnexpected(); }
  24945. virtual void noteException(IException *E) { throwUnexpected(); }
  24946. virtual void checkAbort() { throwUnexpected(); }
  24947. virtual IThorChildGraph * queryChildGraph() { throwUnexpected(); }
  24948. virtual IEclGraphResults * queryLocalGraph() { throwUnexpected(); }
  24949. virtual IRoxieServerChildGraph * queryLoopGraph() { throwUnexpected(); }
  24950. virtual IRoxieServerActivity *queryActivity(unsigned _activityId) { return nullptr; } // MORE - may need something here!?
  24951. virtual void onCreate(IHThorArg *_colocalParent)
  24952. {
  24953. colocalParent = _colocalParent;
  24954. }
  24955. virtual IRoxieServerChildGraph * createGraphLoopInstance(IRoxieSlaveContext *ctx, unsigned loopCounter, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &logctx)
  24956. {
  24957. Owned<CIterationActivityGraph> ret = new CIterationActivityGraph(graphName, id, graphDefinition, probeManager, loopCounter, ctx, colocalParent, parentExtractSize, parentExtract, logctx);
  24958. ret->createIterationGraph(ctx);
  24959. return ret.getClear();
  24960. }
  24961. };
  24962. IActivityGraph *createActivityGraph(IRoxieSlaveContext *ctx, const char *_graphName, unsigned id, ActivityArray &childFactories, IRoxieServerActivity *parentActivity, IProbeManager *_probeManager, const IRoxieContextLogger &_logctx, unsigned numParallel)
  24963. {
  24964. if (childFactories.isDelayed())
  24965. {
  24966. assertex(numParallel==1);
  24967. return new CDelayedActivityGraph(_graphName, id, childFactories, _probeManager);
  24968. }
  24969. else
  24970. {
  24971. if (numParallel==1 || _probeManager != nullptr)
  24972. {
  24973. Owned<IProbeManager> childProbe;
  24974. if (_probeManager)
  24975. childProbe.setown(_probeManager->startChildGraph(id, parentActivity));
  24976. Owned<CActivityGraph> ret = new CActivityGraph(ctx, _graphName, id, childFactories, childProbe, _logctx);
  24977. ret->createGraph(ctx);
  24978. if (_probeManager)
  24979. _probeManager->endChildGraph(childProbe, parentActivity);
  24980. return ret.getClear();
  24981. }
  24982. else
  24983. return new CProxyActivityGraph(ctx, _graphName, id, childFactories, _logctx, numParallel);
  24984. }
  24985. }
  24986. //================================================================================================================
  24987. #ifdef _USE_CPPUNIT
  24988. #include "unittests.hpp"
  24989. // 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...
  24990. #if _MSC_VER==1200
  24991. #undef protected
  24992. #endif
  24993. static const char *sortAlgorithm;
  24994. class TestMetaData : public CInterface, implements IOutputMetaData
  24995. {
  24996. public:
  24997. IMPLEMENT_IINTERFACE;
  24998. virtual size32_t getRecordSize(const void *) { return 10; }
  24999. virtual size32_t getMinRecordSize() const { return 10; }
  25000. virtual size32_t getFixedSize() const { return 10; }
  25001. virtual void toXML(const byte * self, IXmlWriter & out) {}
  25002. virtual unsigned getVersion() const { return OUTPUTMETADATA_VERSION; }
  25003. virtual unsigned getMetaFlags() { return 0; }
  25004. virtual void destruct(byte * self) {}
  25005. virtual IOutputRowSerializer * createDiskSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  25006. virtual IOutputRowDeserializer * createDiskDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  25007. virtual ISourceRowPrefetcher * createDiskPrefetcher(ICodeContext * ctx, unsigned activityId) { return NULL; }
  25008. virtual IOutputMetaData * querySerializedDiskMeta() { return NULL; }
  25009. virtual IOutputRowSerializer * createInternalSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  25010. virtual IOutputRowDeserializer * createInternalDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  25011. virtual void walkIndirectMembers(const byte * self, IIndirectMemberVisitor & visitor) {}
  25012. virtual IOutputMetaData * queryChildMeta(unsigned i) { return NULL; }
  25013. } testMeta;
  25014. class TestInput : public CInterface, implements IFinalRoxieInput, implements IEngineRowStream
  25015. {
  25016. char const * const *input;
  25017. IRoxieSlaveContext *ctx;
  25018. unsigned endSeen;
  25019. bool eof;
  25020. unsigned count;
  25021. ActivityTimeAccumulator totalCycles;
  25022. size32_t recordSize;
  25023. unsigned activityId;
  25024. public:
  25025. enum { STATEreset, STATEstarted, STATEstopped } state;
  25026. bool allRead;
  25027. unsigned repeat;
  25028. IMPLEMENT_IINTERFACE;
  25029. TestInput(IRoxieSlaveContext *_ctx, char const * const *_input)
  25030. {
  25031. ctx = _ctx;
  25032. input = _input;
  25033. count = 0;
  25034. eof = false;
  25035. allRead = false;
  25036. endSeen = 0;
  25037. recordSize = testMeta.getFixedSize();
  25038. state = STATEreset;
  25039. activityId = 1;
  25040. repeat = 0;
  25041. }
  25042. virtual IOutputMetaData * queryOutputMeta() const { return &testMeta; }
  25043. virtual void prestart(unsigned parentExtractSize, const byte *parentExtract)
  25044. {
  25045. ASSERT(state == STATEreset);
  25046. }
  25047. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  25048. {
  25049. ASSERT(state == STATEreset);
  25050. state = STATEstarted;
  25051. }
  25052. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  25053. {
  25054. streams.append(this);
  25055. return NULL;
  25056. }
  25057. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { assertex(whichInput==0); return this; }
  25058. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { assertex(idx==0); return nullptr; }
  25059. virtual IRoxieServerActivity *queryActivity()
  25060. {
  25061. throwUnexpected();
  25062. }
  25063. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  25064. {
  25065. throwUnexpected();
  25066. }
  25067. virtual void stop()
  25068. {
  25069. state = STATEstopped;
  25070. }
  25071. virtual void reset()
  25072. {
  25073. ASSERT(state == STATEstopped);
  25074. eof = false; count = 0; endSeen = 0; allRead = false; state = STATEreset;
  25075. }
  25076. virtual void resetEOF()
  25077. {
  25078. throwUnexpected();
  25079. }
  25080. virtual void checkAbort() {}
  25081. virtual unsigned queryId() const { return activityId; };
  25082. virtual const void *nextRow()
  25083. {
  25084. ActivityTimer t(totalCycles, ctx->queryOptions().timeActivities);
  25085. ASSERT(state == STATEstarted);
  25086. ASSERT(allRead || !eof);
  25087. if (eof)
  25088. return NULL;
  25089. again:
  25090. const char *nextSource = input[count++];
  25091. if (nextSource)
  25092. {
  25093. endSeen = 0;
  25094. void *ret = ctx->queryRowManager().ALLOCATE(recordSize);
  25095. memset(ret, 0, recordSize);
  25096. strncpy((char *) ret, nextSource, recordSize);
  25097. return ret;
  25098. }
  25099. else if (repeat)
  25100. {
  25101. repeat--;
  25102. count = 0;
  25103. goto again;
  25104. }
  25105. else
  25106. {
  25107. endSeen++;
  25108. if (endSeen==2)
  25109. eof = true;
  25110. return NULL;
  25111. }
  25112. }
  25113. virtual bool nextGroup(ConstPointerArray & group)
  25114. {
  25115. const void * next;
  25116. while ((next = nextRow()) != NULL)
  25117. group.append(next);
  25118. if (group.ordinality())
  25119. return true;
  25120. return false;
  25121. }
  25122. virtual unsigned __int64 queryTotalCycles() const { return totalCycles.totalCycles; }
  25123. virtual unsigned __int64 queryLocalCycles() const { return totalCycles.totalCycles; }
  25124. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  25125. {
  25126. return NULL;
  25127. }
  25128. };
  25129. struct SortActivityTest : public ccdserver_hqlhelper::CThorSortArg {
  25130. public:
  25131. struct CompareClass : public ICompare {
  25132. virtual int docompare(const void * _left, const void * _right) const {
  25133. return memcmp(_left, _right, 5);
  25134. }
  25135. } compare;
  25136. virtual ICompare * queryCompare() { return &compare; }
  25137. virtual IOutputMetaData * queryOutputMeta()
  25138. {
  25139. return &testMeta;
  25140. }
  25141. virtual unsigned getAlgorithmFlags() { return TAFunstable; }
  25142. virtual const char * getAlgorithm() { return sortAlgorithm; }
  25143. };
  25144. extern "C" IHThorArg * sortActivityTestFactory() { return new SortActivityTest; }
  25145. struct MergeActivityTest : public ccdserver_hqlhelper::CThorMergeArg {
  25146. static bool isDedup;
  25147. public:
  25148. struct CompareClass : public ICompare {
  25149. virtual int docompare(const void * _left, const void * _right) const {
  25150. return memcmp(_left, _right, 5);
  25151. }
  25152. } compare;
  25153. virtual ICompare * queryCompare() { return &compare; }
  25154. virtual IOutputMetaData * queryOutputMeta()
  25155. {
  25156. return &testMeta;
  25157. }
  25158. virtual bool dedup() { return isDedup; }
  25159. };
  25160. bool MergeActivityTest::isDedup = false;
  25161. extern "C" IHThorArg * mergeActivityTestFactory() { return new MergeActivityTest; }
  25162. struct SplitActivityTest : public ccdserver_hqlhelper::CThorSplitArg {
  25163. public:
  25164. virtual unsigned numBranches() { return 2; }
  25165. virtual IOutputMetaData * queryOutputMeta()
  25166. {
  25167. return &testMeta;
  25168. }
  25169. };
  25170. extern "C" IHThorArg * splitActivityTestFactory() { return new SplitActivityTest; }
  25171. class CcdServerTest : public CppUnit::TestFixture
  25172. {
  25173. CPPUNIT_TEST_SUITE(CcdServerTest);
  25174. CPPUNIT_TEST(testSetup);
  25175. CPPUNIT_TEST(testHeapSort);
  25176. CPPUNIT_TEST(testQuickSort);
  25177. CPPUNIT_TEST(testMerge);
  25178. CPPUNIT_TEST(testMergeDedup);
  25179. CPPUNIT_TEST(testMiscellaneous);
  25180. CPPUNIT_TEST(testSplitter);
  25181. CPPUNIT_TEST(testCleanup);
  25182. CPPUNIT_TEST_SUITE_END();
  25183. protected:
  25184. SlaveContextLogger logctx;
  25185. Owned<const IQueryDll> queryDll;
  25186. Owned<IRoxiePackage> package;
  25187. Owned<IPropertyTree> stateInfo;
  25188. Owned<IQueryFactory> queryFactory;
  25189. Owned<IRoxieSlaveContext> ctx;
  25190. void testSetup()
  25191. {
  25192. selfTestMode = true;
  25193. roxiemem::setTotalMemoryLimit(false, true, false, 100 * 1024 * 1024, 0, NULL, NULL);
  25194. }
  25195. void testCleanup()
  25196. {
  25197. roxiemem::releaseRoxieHeap();
  25198. }
  25199. void init()
  25200. {
  25201. package.setown(createRoxiePackage(NULL, NULL));
  25202. queryDll.setown(createExeQueryDll("roxie"));
  25203. stateInfo.setown(createPTreeFromXMLString("<test memoryLimit='50000000'/>"));
  25204. queryFactory.setown(createServerQueryFactory("test", queryDll.getLink(), *package, stateInfo, false, false));
  25205. ctx.setown(createSlaveContext(queryFactory, logctx, NULL, false));
  25206. queryActiveTimer()->reset();
  25207. }
  25208. void testActivity(IRoxieServerActivity *activity, char const * const *input, char const * const *output)
  25209. {
  25210. testActivity(activity, input, NULL, output);
  25211. }
  25212. void testActivity(IRoxieServerActivity *activity, char const * const *input, char const * const *input2, char const * const *output, unsigned outputIdx = 0)
  25213. {
  25214. TestInput in(ctx, input);
  25215. TestInput in2(ctx, input2);
  25216. activity->setInput(0, 0, &in);
  25217. if (input2)
  25218. activity->setInput(1, 0, &in2);
  25219. IFinalRoxieInput *out = activity->queryOutput(outputIdx);
  25220. IEngineRowStream *outStream = connectSingleStream(ctx, out, outputIdx, true);
  25221. IOutputMetaData *meta = out->queryOutputMeta();
  25222. void *buf = alloca(meta->getFixedSize());
  25223. for (unsigned iteration = 0; iteration < 8; iteration++)
  25224. {
  25225. // 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)
  25226. // This should be true whether we read all, some, or none of the data.
  25227. // Should not matter if an activity is not started
  25228. if (iteration % 4 == 0)
  25229. activity->onCreate(NULL);
  25230. unsigned count = 0;
  25231. if (iteration % 4 != 3)
  25232. {
  25233. activity->start(0, NULL, false);
  25234. ASSERT(in.state == TestInput::STATEstarted);
  25235. ASSERT(!input2 || in2.state == TestInput::STATEstarted);
  25236. for (;;)
  25237. {
  25238. const void *next = outStream->nextRow();
  25239. if (!next)
  25240. {
  25241. ASSERT(output[count++] == NULL);
  25242. next = outStream->nextRow();
  25243. if (!next)
  25244. {
  25245. ASSERT(output[count++] == NULL);
  25246. break;
  25247. }
  25248. }
  25249. ASSERT(output[count] != NULL);
  25250. unsigned outsize = meta->getRecordSize(next);
  25251. memset(buf, 0, outsize);
  25252. strncpy((char *) buf, output[count++], outsize);
  25253. ASSERT(memcmp(next, buf, outsize) == 0);
  25254. ReleaseRoxieRow(next);
  25255. if (iteration % 4 == 2)
  25256. break;
  25257. }
  25258. if (iteration % 4 != 2)
  25259. {
  25260. // Check that reading after end is harmless
  25261. in.allRead = true;
  25262. const void *next = outStream->nextRow();
  25263. ASSERT(next == NULL);
  25264. }
  25265. }
  25266. activity->stop();
  25267. ASSERT(in.state == TestInput::STATEstopped);
  25268. ASSERT(!input2 || in2.state == TestInput::STATEstopped);
  25269. activity->reset();
  25270. ASSERT(in.state == TestInput::STATEreset);
  25271. ASSERT(!input2 || in2.state == TestInput::STATEreset);
  25272. ctx->queryRowManager().reportLeaks();
  25273. ASSERT(ctx->queryRowManager().numPagesAfterCleanup(true) == 0);
  25274. }
  25275. }
  25276. void testSplitActivity(IRoxieServerActivityFactory *factory, char const * const *input, char const * const *output, unsigned numOutputs, unsigned repeat)
  25277. {
  25278. Owned <IRoxieServerActivity> activity = factory->createActivity(ctx, NULL);
  25279. TestInput in(ctx, input);
  25280. in.repeat = repeat;
  25281. activity->setInput(0, 0, &in);
  25282. ArrayOf<IFinalRoxieInput *> out;
  25283. for (unsigned i = 0; i < numOutputs; i++)
  25284. {
  25285. out.append(activity->queryOutput(i));
  25286. }
  25287. activity->onCreate(NULL);
  25288. class casyncfor: public CAsyncFor
  25289. {
  25290. public:
  25291. casyncfor(CcdServerTest *_parent, IRoxieServerActivity *_activity, ArrayOf<IFinalRoxieInput *> &_outputs, char const * const *_input, char const * const *_output, unsigned _repeat)
  25292. : parent(_parent), activity(_activity), outputs(_outputs), input(_input), output(_output), repeat(_repeat)
  25293. {}
  25294. void Do(unsigned i)
  25295. {
  25296. IFinalRoxieInput *out = outputs.item(i);
  25297. IEngineRowStream *outStream = connectSingleStream(NULL, out, 0, true);
  25298. out->start(0, NULL, false);
  25299. IOutputMetaData *meta = out->queryOutputMeta();
  25300. void *buf = alloca(meta->getFixedSize());
  25301. unsigned count = 0;
  25302. unsigned repeats = repeat;
  25303. for (;;)
  25304. {
  25305. const void *next = outStream->nextRow();
  25306. if (!next)
  25307. {
  25308. ASSERT(repeats==0);
  25309. ASSERT(output[count] == NULL);
  25310. count++;
  25311. next = outStream->nextRow();
  25312. if (!next)
  25313. {
  25314. ASSERT(output[count] == NULL);
  25315. count++;
  25316. break;
  25317. }
  25318. }
  25319. if (output[count] == NULL && repeats)
  25320. {
  25321. repeats--;
  25322. count = 0;
  25323. }
  25324. ASSERT(output[count] != NULL);
  25325. unsigned outsize = meta->getRecordSize(next);
  25326. memset(buf, 0, outsize);
  25327. strncpy((char *) buf, output[count++], outsize);
  25328. ASSERT(memcmp(next, buf, outsize) == 0);
  25329. ReleaseRoxieRow(next);
  25330. }
  25331. outStream->stop();
  25332. }
  25333. private:
  25334. IRoxieServerActivity *activity;
  25335. ArrayOf<IFinalRoxieInput *> &outputs;
  25336. char const * const *input;
  25337. char const * const *output;
  25338. unsigned repeat;
  25339. CcdServerTest *parent;
  25340. } afor(this, activity, out, input, output, repeat);
  25341. afor.For(numOutputs, numOutputs);
  25342. ASSERT(in.state == TestInput::STATEstopped);
  25343. for (unsigned i2 = 0; i2 < numOutputs; i2++)
  25344. {
  25345. out.item(i2)->reset();
  25346. }
  25347. ASSERT(in.state == TestInput::STATEreset);
  25348. ctx->queryRowManager().reportLeaks();
  25349. ASSERT(ctx->queryRowManager().numPagesAfterCleanup(true) == 0);
  25350. }
  25351. static int compareFunc(const void *l, const void *r)
  25352. {
  25353. return strcmp(*(char **) l, *(char **) r);
  25354. }
  25355. void testSort(unsigned type)
  25356. {
  25357. init();
  25358. sortAlgorithm = NULL;
  25359. if (type==2)
  25360. sortAlgorithm = "heapSort";
  25361. else
  25362. sortAlgorithm = "quickSort";
  25363. DBGLOG("Testing %s activity", sortAlgorithm);
  25364. Owned<IPropertyTree> dummyNode = createPTree("node");
  25365. Owned <IRoxieServerActivityFactory> factory = createRoxieServerSortActivityFactory(1, 1, *queryFactory, sortActivityTestFactory, TAKsort, *dummyNode);
  25366. Owned <IRoxieServerActivity> activity = factory->createActivity(ctx, NULL);
  25367. const char * test[] = { NULL, NULL };
  25368. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  25369. const char * test54321[] = { "5", "4", "3", "2", "1", NULL, NULL };
  25370. const char * test11111[] = { "1", "1", "1", "1", "1", NULL, NULL };
  25371. const char * test11111_12345[] = { "1", "1", "1", "1", "1", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  25372. const char * test11111_54321[] = { "1", "1", "1", "1", "1", NULL, "5", "4", "3", "2", "1", NULL, NULL };
  25373. const char * test54321_54321[] = { "5", "4", "3", "2", "1", NULL, "5", "4", "3", "2", "1", NULL, NULL };
  25374. const char * test12345_12345[] = { "1", "2", "3", "4", "5", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  25375. testActivity(activity, test, test);
  25376. testActivity(activity, test12345, test12345);
  25377. testActivity(activity, test54321, test12345);
  25378. testActivity(activity, test11111, test11111);
  25379. testActivity(activity, test11111_12345, test11111_12345);
  25380. testActivity(activity, test11111_54321, test11111_12345);
  25381. testActivity(activity, test54321_54321, test12345_12345);
  25382. // A few larger tests
  25383. char *input[2002];
  25384. char *output[2002];
  25385. input[2000] = input[2001] = output[2000] = output[2001] = NULL;
  25386. unsigned i;
  25387. // identical
  25388. for (i=0; i<2000; i++)
  25389. {
  25390. input[i] = new char[11];
  25391. output[i] = new char[11];
  25392. sprintf(input[i], "1");
  25393. sprintf(output[i], "1");
  25394. }
  25395. testActivity(activity, input, output);
  25396. // Ascending
  25397. for (i=0; i<2000; i++)
  25398. {
  25399. sprintf(input[i], "%04d", i);
  25400. sprintf(output[i], "%04d", i);
  25401. }
  25402. testActivity(activity, input, output);
  25403. // Almost sorted
  25404. for (i=0; i<20; i++)
  25405. {
  25406. unsigned h = i*100;
  25407. sprintf(input[h], "%04d", 1900-h);
  25408. }
  25409. testActivity(activity, input, output);
  25410. // Descending
  25411. for (i=0; i<2000; i++)
  25412. {
  25413. sprintf(input[i], "%04d", 1999-i);
  25414. sprintf(output[i], "%04d", i);
  25415. }
  25416. testActivity(activity, input, output);
  25417. // Random
  25418. for (i=0; i<2000; i++)
  25419. {
  25420. unsigned r = rand() % 1500;
  25421. sprintf(input[i], "%04d", r);
  25422. sprintf(output[i], "%04d", r);
  25423. }
  25424. qsort(output, 2000, sizeof(output[0]), compareFunc);
  25425. testActivity(activity, input, output);
  25426. unsigned __int64 us = factory->queryLocalTimeNs();
  25427. DBGLOG("Simple %s sorts: activity time %u.%u ms", type==2?"Heap" : (type==1 ? "Insertion" : "Quick"), (int)(us/1000), (int)(us%1000));
  25428. factory->resetNodeProgressInfo();
  25429. if (type)
  25430. {
  25431. // Other than quicksort, it's supposed to be stable. Let's check that it is
  25432. // All sort identical
  25433. for (i=0; i<2000; i++)
  25434. {
  25435. sprintf(input[i], "1 %d", i);
  25436. sprintf(output[i], "1 %d", i);
  25437. }
  25438. testActivity(activity, input, output);
  25439. // Already sorted
  25440. for (i=0; i<2000; i++)
  25441. {
  25442. sprintf(input[i], "%04d %d", i / 10, i);
  25443. sprintf(output[i], "%04d %d", i / 10, i);
  25444. }
  25445. testActivity(activity, input, output);
  25446. // Reverse order
  25447. for (i=0; i<2000; i++)
  25448. {
  25449. sprintf(input[i], "%04d %d", 199 - (i / 10), i%10);
  25450. sprintf(output[i], "%04d %d", i / 10, i%10);
  25451. }
  25452. testActivity(activity, input, output);
  25453. }
  25454. for (i=0; i<2000; i++)
  25455. {
  25456. delete [] input[i];
  25457. delete [] output[i];
  25458. }
  25459. DBGLOG("Finished testing %s sort", type==2?"Heap" : (type==1 ? "Insertion" : "Quick"));
  25460. }
  25461. void testQuickSort()
  25462. {
  25463. testSort(0);
  25464. }
  25465. void testHeapSort()
  25466. {
  25467. testSort(2);
  25468. }
  25469. void testMerge()
  25470. {
  25471. DBGLOG("testMerge");
  25472. init();
  25473. Owned<IPropertyTree> splitterNode = createPTree();
  25474. Owned <IRoxieServerActivityFactory> factory = createRoxieServerMergeActivityFactory(1, 1, *queryFactory, mergeActivityTestFactory, TAKmerge, *splitterNode);
  25475. factory->setInput(0,0,0);
  25476. factory->setInput(1,0,0);
  25477. Owned <IRoxieServerActivity> activity = factory->createActivity(ctx, NULL);
  25478. const char * test[] = { NULL, NULL };
  25479. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  25480. const char * test1122334455[] = { "1", "1", "2", "2", "3", "3", "4", "4", "5", "5", NULL, NULL };
  25481. const char * test11111[] = { "1", "1", "1", "1", "1", NULL, NULL };
  25482. const char * test1111111111[] = { "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", NULL, NULL };
  25483. const char * test11111_12345[] = { "1", "1", "1", "1", "1", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  25484. const char * test1111112345[] = { "1", "1", "1", "1", "1", "1", "2", "3", "4", "5", NULL, NULL };
  25485. 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 };
  25486. testActivity(activity, test, test, test);
  25487. testActivity(activity, test12345, test, test12345);
  25488. testActivity(activity, test, test12345, test12345);
  25489. testActivity(activity, test12345, test12345, test1122334455);
  25490. testActivity(activity, test11111, test, test11111);
  25491. testActivity(activity, test, test11111, test11111);
  25492. testActivity(activity, test11111, test11111, test1111111111);
  25493. testActivity(activity, test11111_12345, test, test1111112345);
  25494. testActivity(activity, test11111_12345, test11111_12345, test11111111111122334455);
  25495. // Should really test WHICH side gets kept...
  25496. // Should test with more than 2 inputs...
  25497. DBGLOG("testMerge done");
  25498. }
  25499. void testMergeDedup()
  25500. {
  25501. DBGLOG("testMergeDedup");
  25502. init();
  25503. MergeActivityTest::isDedup = true;
  25504. Owned<IPropertyTree> splitterNode = createPTree();
  25505. Owned <IRoxieServerActivityFactory> factory = createRoxieServerMergeActivityFactory(1, 1, *queryFactory, mergeActivityTestFactory, TAKmerge, *splitterNode);
  25506. factory->setInput(0,0,0);
  25507. factory->setInput(1,0,0);
  25508. Owned <IRoxieServerActivity> activity = factory->createActivity(ctx, NULL);
  25509. const char * test[] = { NULL, NULL };
  25510. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  25511. const char * test11111[] = { "1", "1", "1", "1", "1", NULL, NULL };
  25512. const char * test11111_12345[] = { "1", "1", "1", "1", "1", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  25513. const char * test1111112345[] = { "1", "1", "1", "1", "1", "1", "2", "3", "4", "5", NULL, NULL };
  25514. testActivity(activity, test11111, test, test11111); // No dedup within a stream
  25515. testActivity(activity, test11111, test11111, test11111); // No dedup within a stream
  25516. testActivity(activity, test, test11111, test11111);
  25517. testActivity(activity, test, test, test);
  25518. testActivity(activity, test12345, test, test12345);
  25519. testActivity(activity, test, test12345, test12345);
  25520. testActivity(activity, test12345, test12345, test12345);
  25521. testActivity(activity, test11111_12345, test, test1111112345);
  25522. testActivity(activity, test11111_12345, test11111_12345, test1111112345);
  25523. // Should really test WHICH side gets kept...
  25524. // Should test with more than 2 inputs...
  25525. DBGLOG("testMergeDedup done");
  25526. }
  25527. void doTestSplitter(unsigned numOutputs)
  25528. {
  25529. DBGLOG("testSplit %d", numOutputs);
  25530. init();
  25531. Owned<IPropertyTree> splitterNode = createPTree();
  25532. Owned <IRoxieServerActivityFactory> factory = createRoxieServerThroughSpillActivityFactory(*queryFactory, splitActivityTestFactory, numOutputs, *splitterNode);
  25533. factory->setInput(0,0,0);
  25534. Owned <IRoxieServerActivity> activity = factory->createActivity(ctx, NULL);
  25535. const char * test[] = { NULL, NULL };
  25536. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  25537. unsigned start = msTick();
  25538. testSplitActivity(factory, test, test, numOutputs, 0);
  25539. testSplitActivity(factory, test12345, test12345, numOutputs, 0);
  25540. testSplitActivity(factory, test12345, test12345, numOutputs, 100);
  25541. unsigned elapsed = msTick() - start;
  25542. DBGLOG("testSplit %d done in %dms", numOutputs, elapsed);
  25543. }
  25544. void testSplitter()
  25545. {
  25546. doTestSplitter(1);
  25547. doTestSplitter(2);
  25548. doTestSplitter(3);
  25549. doTestSplitter(10);
  25550. }
  25551. void testMiscellaneous()
  25552. {
  25553. DBGLOG("sizeof(CriticalSection)=%u", (unsigned) sizeof(CriticalSection));
  25554. DBGLOG("sizeof(SpinLock)=%u", (unsigned) sizeof(SpinLock));
  25555. DBGLOG("sizeof(CJoinGroup)=%u", (unsigned) sizeof(CJoinGroup));
  25556. ASSERT(sizeof(CJoinGroup) <= 120);
  25557. }
  25558. };
  25559. CPPUNIT_TEST_SUITE_REGISTRATION( CcdServerTest );
  25560. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( CcdServerTest, "CcdServerTest" );
  25561. #endif