ccdserver.cpp 976 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005
  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_imp.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 : public CInterface, implements IRoxieSlaveContext
  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 const CRuntimeStatisticCollection &queryStats() const
  186. {
  187. return ctx->queryStats();
  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 ActivityTimeAccumulator &_totalCycles, cycle_t _localCycles) const
  258. {
  259. ctx->mergeActivityStats(fromStats, subgraphId, activityId, _totalCycles, _localCycles);
  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, StKindNone);
  317. static const StatisticsMapping joinStatistics(&actStatistics, StNumAtmostTriggered, StKindNone);
  318. static const StatisticsMapping keyedJoinStatistics(&joinStatistics, StNumServerCacheHits, StNumIndexSeeks, StNumIndexScans, StNumIndexWildSeeks,
  319. StNumIndexSkips, StNumIndexNullSkips, StNumIndexMerges, StNumIndexMergeCompares,
  320. StNumPreFiltered, StNumPostFiltered, StNumIndexAccepted, StNumIndexRejected,
  321. StNumIndexRowsRead, StNumDiskRowsRead, StNumDiskSeeks, StNumDiskAccepted,
  322. StNumBlobCacheHits, StNumLeafCacheHits, StNumNodeCacheHits,
  323. StNumBlobCacheAdds, StNumLeafCacheAdds, StNumNodeCacheAdds,
  324. StNumDiskRejected, StKindNone);
  325. static const StatisticsMapping indexStatistics(&actStatistics, StNumServerCacheHits, StNumIndexSeeks, StNumIndexScans, StNumIndexWildSeeks,
  326. StNumIndexSkips, StNumIndexNullSkips, StNumIndexMerges, StNumIndexMergeCompares,
  327. StNumPreFiltered, StNumPostFiltered, StNumIndexAccepted, StNumIndexRejected,
  328. StNumBlobCacheHits, StNumLeafCacheHits, StNumNodeCacheHits,
  329. StNumBlobCacheAdds, StNumLeafCacheAdds, StNumNodeCacheAdds,
  330. StNumIndexRowsRead, StKindNone);
  331. static const StatisticsMapping diskStatistics(&actStatistics, StNumServerCacheHits, StNumDiskRowsRead, StNumDiskSeeks, StNumDiskAccepted,
  332. StNumDiskRejected, StKindNone);
  333. static const StatisticsMapping soapStatistics(&actStatistics, StTimeSoapcall, StKindNone);
  334. static const StatisticsMapping groupStatistics(&actStatistics, StNumGroups, StNumGroupMax, StKindNone);
  335. static const StatisticsMapping sortStatistics(&actStatistics, StTimeSortElapsed, StKindNone);
  336. //=================================================================================
  337. const static unsigned minus1U = (0U-1U);
  338. class CRoxieServerActivityFactoryBase : public CActivityFactory, implements IRoxieServerActivityFactory
  339. {
  340. protected:
  341. IntArray dependencies; // things I am dependent on
  342. IntArray dependencyIndexes; // things I am dependent on
  343. IntArray dependencyControlIds; // things I am dependent on
  344. StringArray dependencyEdgeIds; // How to describe them to the debugger
  345. unsigned dependentCount; // things dependent on me
  346. unsigned optParallel = 0; // -1=enable,0=not specified,1=single-threaded,n=<num threads>
  347. bool optStableInput = true; // is the input forced to ordered?
  348. bool optUnstableInput = false; // is the input forced to unordered?
  349. bool optUnordered = false; // is the output specified as unordered?
  350. mutable CriticalSection statsCrit;
  351. mutable __int64 processed;
  352. mutable __int64 started;
  353. mutable __int64 totalCycles;
  354. mutable __int64 localCycles;
  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. totalCycles = 0;
  363. localCycles = 0;
  364. dependentCount = 0;
  365. optParallel = _graphNode.getPropInt("att[@name='parallel']/@value", 0);
  366. optUnordered = !_graphNode.getPropBool("att[@name='ordered']/@value", true);
  367. }
  368. ~CRoxieServerActivityFactoryBase()
  369. {
  370. }
  371. StringBuffer &toString(StringBuffer &ret) const
  372. {
  373. return ret.appendf("%p", this);
  374. }
  375. virtual void addDependency(unsigned _source, ThorActivityKind _kind, unsigned _sourceIdx, int controlId, const char *edgeId)
  376. {
  377. dependencies.append(_source);
  378. dependencyIndexes.append(_sourceIdx);
  379. dependencyControlIds.append(controlId);
  380. dependencyEdgeIds.append(edgeId);
  381. }
  382. virtual bool isInputOrdered(bool consumerOrdered, unsigned idx) const
  383. {
  384. if (optStableInput)
  385. return true;
  386. if (optUnstableInput)
  387. return false;
  388. if (optUnordered)
  389. return false;
  390. return consumerOrdered;
  391. }
  392. virtual void noteDependent(unsigned target)
  393. {
  394. dependentCount++;
  395. }
  396. virtual IntArray &queryDependencies() { return dependencies; }
  397. virtual IntArray &queryDependencyIndexes() { return dependencyIndexes; }
  398. virtual IntArray &queryDependencyControlIds() { return dependencyControlIds; }
  399. virtual StringArray &queryDependencyEdgeIds() { return dependencyEdgeIds; }
  400. virtual unsigned queryId() const { return id; }
  401. virtual unsigned querySubgraphId() const { return subgraphId; }
  402. virtual ThorActivityKind getKind() const { return kind; }
  403. virtual IOutputMetaData * queryOutputMeta() const
  404. {
  405. return meta;
  406. }
  407. virtual bool isSink() const
  408. {
  409. return false;
  410. }
  411. virtual bool isFunction() const
  412. {
  413. return false;
  414. }
  415. virtual bool isGraphInvariant() const
  416. {
  417. return false;
  418. }
  419. virtual IHThorArg &getHelper() const
  420. {
  421. return *helperFactory();
  422. }
  423. virtual IRoxieServerActivity *createFunction(IHThorArg &arg, IProbeManager *_probeManager) const
  424. {
  425. arg.Release();
  426. throwUnexpected();
  427. }
  428. virtual void mergeStats(const CRuntimeStatisticCollection &from) const
  429. {
  430. CActivityFactory::mergeStats(from);
  431. }
  432. virtual void noteProcessed(unsigned _idx, unsigned _processed) const
  433. {
  434. dbgassertex(!_idx);
  435. if (_processed)
  436. {
  437. CriticalBlock b(statsCrit);
  438. processed += _processed;
  439. }
  440. }
  441. virtual void mergeActivityStats(const CRuntimeStatisticCollection &fromStats, const ActivityTimeAccumulator &_totalCycles, cycle_t _localCycles) const
  442. {
  443. if (_totalCycles.totalCycles || _localCycles)
  444. {
  445. CriticalBlock b(statsCrit);
  446. dbgassertex(_totalCycles.totalCycles >= _localCycles);
  447. totalCycles += _totalCycles.totalCycles;
  448. localCycles += _localCycles;
  449. }
  450. CActivityFactory::mergeStats(fromStats);
  451. }
  452. virtual void noteStarted() const
  453. {
  454. CriticalBlock b(statsCrit);
  455. started ++;
  456. }
  457. virtual void noteStarted(unsigned idx) const
  458. {
  459. throwUnexpected(); // should be implemented/required by multiOutput cases only
  460. }
  461. virtual void getEdgeProgressInfo(unsigned output, IPropertyTree &edge) const
  462. {
  463. CriticalBlock b(statsCrit);
  464. if (output == 0)
  465. {
  466. putStatsValue(&edge, "count", "sum", processed);
  467. if (started)
  468. putStatsValue(&edge, "started", "sum", started);
  469. }
  470. else
  471. ERRLOG("unexpected call to getEdgeProcessInfo for output %d in activity %d", output, queryId());
  472. }
  473. virtual void getNodeProgressInfo(IPropertyTree &node) const
  474. {
  475. CActivityFactory::getNodeProgressInfo(node);
  476. CriticalBlock b(statsCrit);
  477. if (started)
  478. putStatsValue(&node, "_roxieStarted", "sum", started);
  479. if (totalCycles)
  480. putStatsValue(&node, "totalTime", "sum", (unsigned) (cycle_to_nanosec(totalCycles)/1000));
  481. if (localCycles)
  482. putStatsValue(&node, "localTime", "sum", (unsigned) (cycle_to_nanosec(localCycles)/1000));
  483. }
  484. virtual void resetNodeProgressInfo()
  485. {
  486. CActivityFactory::resetNodeProgressInfo();
  487. CriticalBlock b(statsCrit);
  488. processed = 0;
  489. started = 0;
  490. totalCycles = 0;
  491. localCycles = 0;
  492. }
  493. virtual void getActivityMetrics(StringBuffer &reply) const
  494. {
  495. CActivityFactory::getActivityMetrics(reply);
  496. CriticalBlock b(statsCrit);
  497. putStatsValue(reply, "_roxieStarted", "sum", started);
  498. putStatsValue(reply, "totalTime", "sum", (unsigned) (cycle_to_nanosec(totalCycles)/1000));
  499. putStatsValue(reply, "localTime", "sum", (unsigned) (cycle_to_nanosec(localCycles)/1000));
  500. }
  501. virtual unsigned __int64 queryLocalCycles() const
  502. {
  503. return localCycles;
  504. }
  505. virtual IQueryFactory &queryQueryFactory() const
  506. {
  507. return CActivityFactory::queryQueryFactory();
  508. }
  509. virtual ActivityArray *queryChildQuery(unsigned idx, unsigned &id)
  510. {
  511. return CActivityFactory::queryChildQuery(idx, id);
  512. }
  513. virtual void addChildQuery(unsigned id, ActivityArray *childQuery)
  514. {
  515. CActivityFactory::addChildQuery(id, childQuery);
  516. }
  517. virtual void onCreateChildQueries(IRoxieSlaveContext *ctx, IHThorArg *colocalArg, IArrayOf<IActivityGraph> &childGraphs, IRoxieServerActivity *parentActivity, IProbeManager *_probeManager, const IRoxieContextLogger &_logctx, unsigned numParallel) const
  518. {
  519. ForEachItemIn(idx, childQueries)
  520. {
  521. childGraphs.append(*createActivityGraph(ctx, NULL, childQueryIndexes.item(idx), childQueries.item(idx), parentActivity, _probeManager, _logctx, numParallel));
  522. ctx->noteChildGraph(childQueryIndexes.item(idx), &childGraphs.item(idx));
  523. childGraphs.item(idx).onCreate(colocalArg);
  524. }
  525. }
  526. IActivityGraph * createChildGraph(IRoxieSlaveContext * ctx, IHThorArg *colocalArg, unsigned childId, IRoxieServerActivity *parentActivity, IProbeManager * _probeManager, const IRoxieContextLogger &_logctx) const
  527. {
  528. unsigned match = childQueryIndexes.find(childId);
  529. assertex(match != NotFound);
  530. Owned<IActivityGraph> graph = createActivityGraph(ctx, NULL, childQueryIndexes.item(match), childQueries.item(match), parentActivity, _probeManager, _logctx, 1);
  531. graph->onCreate(colocalArg);
  532. return graph.getClear();
  533. }
  534. virtual IRoxieServerSideCache *queryServerSideCache() const
  535. {
  536. return NULL; // Activities that wish to support server-side caching will need to do better....
  537. }
  538. virtual bool getEnableFieldTranslation() const
  539. {
  540. throwUnexpected(); // only implemented by index-related subclasses
  541. }
  542. virtual IDefRecordMeta *queryActivityMeta() const
  543. {
  544. throwUnexpected(); // only implemented by index-related subclasses
  545. }
  546. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  547. {
  548. // Most activities have nothing to say...
  549. }
  550. virtual const StatisticsMapping &queryStatsMapping() const
  551. {
  552. return actStatistics; // Overridden by anyone that needs more
  553. }
  554. };
  555. class CRoxieServerMultiInputInfo
  556. {
  557. private:
  558. UnsignedArray inputs;
  559. UnsignedArray inputIndexes;
  560. public:
  561. void set(unsigned idx, unsigned source, unsigned sourceidx)
  562. {
  563. if (idx==inputs.length())
  564. {
  565. inputs.append(source);
  566. inputIndexes.append(sourceidx);
  567. }
  568. else
  569. {
  570. while (!inputs.isItem(idx))
  571. {
  572. inputs.append(0);
  573. inputIndexes.append(0);
  574. }
  575. inputs.replace(source, idx);
  576. inputIndexes.replace(sourceidx, idx);
  577. }
  578. }
  579. unsigned get(unsigned idx, unsigned &sourceidx) const
  580. {
  581. if (inputs.isItem(idx))
  582. {
  583. sourceidx = inputIndexes.item(idx);
  584. return inputs.item(idx);
  585. }
  586. else
  587. return (unsigned) -1;
  588. }
  589. inline unsigned ordinality() const { return inputs.ordinality(); }
  590. };
  591. class CRoxieServerMultiInputFactory : public CRoxieServerActivityFactoryBase
  592. {
  593. private:
  594. CRoxieServerMultiInputInfo inputs;
  595. public:
  596. IMPLEMENT_IINTERFACE;
  597. CRoxieServerMultiInputFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  598. : CRoxieServerActivityFactoryBase(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  599. {
  600. }
  601. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  602. {
  603. inputs.set(idx, source, sourceidx);
  604. }
  605. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  606. {
  607. return inputs.get(idx, sourceidx);
  608. }
  609. virtual unsigned numInputs() const { return inputs.ordinality(); }
  610. };
  611. class CWrappedException : public CInterface, implements IException
  612. {
  613. Owned<IException> wrapped;
  614. ThorActivityKind kind;
  615. unsigned queryId;
  616. public:
  617. IMPLEMENT_IINTERFACE;
  618. CWrappedException(IException *_wrapped, ThorActivityKind _kind, unsigned _queryId)
  619. : wrapped(_wrapped), kind(_kind), queryId(_queryId)
  620. {
  621. }
  622. virtual int errorCode() const { return wrapped->errorCode(); }
  623. virtual StringBuffer & errorMessage(StringBuffer &msg) const { return wrapped->errorMessage(msg).appendf(" (in %s %d)", getActivityText(kind), queryId); }
  624. virtual MessageAudience errorAudience() const { return wrapped->errorAudience(); }
  625. };
  626. class CRoxieServerActivityFactory : public CRoxieServerActivityFactoryBase
  627. {
  628. protected:
  629. unsigned input;
  630. unsigned inputidx;
  631. public:
  632. IMPLEMENT_IINTERFACE;
  633. CRoxieServerActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  634. : CRoxieServerActivityFactoryBase(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  635. {
  636. input = (unsigned) -1;
  637. inputidx = 0;
  638. }
  639. inline void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  640. {
  641. if (idx != 0)
  642. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: id = %d : setInput() parameter out of bounds idx = %d at %s(%d)", id, idx, __FILE__, __LINE__);
  643. if (input != -1)
  644. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: id = %d : setInput() called twice for input = %d source = %d inputidx = %d sourceidx = %d at %s(%d)", id, input, source, inputidx, sourceidx, __FILE__, __LINE__);
  645. input = source;
  646. inputidx = sourceidx;
  647. }
  648. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  649. {
  650. if (!idx)
  651. {
  652. sourceidx = inputidx;
  653. return input;
  654. }
  655. return (unsigned) -1;
  656. }
  657. virtual unsigned numInputs() const { return (input == (unsigned)-1) ? 0 : 1; }
  658. };
  659. class CRoxieServerMultiOutputFactory : public CRoxieServerActivityFactory
  660. {
  661. protected:
  662. unsigned numOutputs;
  663. unsigned __int64 *processedArray;
  664. bool *startedArray;
  665. CRoxieServerMultiOutputFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  666. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  667. {
  668. numOutputs = 0;
  669. processedArray = NULL;
  670. startedArray = NULL;
  671. }
  672. ~CRoxieServerMultiOutputFactory()
  673. {
  674. delete [] processedArray;
  675. delete [] startedArray;
  676. }
  677. void setNumOutputs(unsigned num)
  678. {
  679. numOutputs = num;
  680. if (!num)
  681. num = 1; // Even sink activities like to track how many records they process
  682. processedArray = new unsigned __int64[num];
  683. startedArray = new bool[num];
  684. for (unsigned i = 0; i < num; i++)
  685. {
  686. processedArray[i] = 0;
  687. startedArray[i] = 0;
  688. }
  689. }
  690. virtual void getEdgeProgressInfo(unsigned idx, IPropertyTree &edge) const
  691. {
  692. assertex(numOutputs ? idx < numOutputs : idx==0);
  693. CriticalBlock b(statsCrit);
  694. putStatsValue(&edge, "count", "sum", processedArray[idx]);
  695. putStatsValue(&edge, "started", "sum", startedArray[idx]);
  696. }
  697. virtual void resetNodeProgressInfo()
  698. {
  699. CRoxieServerActivityFactory::resetNodeProgressInfo();
  700. CriticalBlock b(statsCrit);
  701. for (unsigned i = 0; i < numOutputs; i++)
  702. {
  703. processedArray[i] = 0;
  704. startedArray[i] = 0;
  705. }
  706. }
  707. virtual void noteProcessed(unsigned idx, unsigned _processed) const
  708. {
  709. assertex(numOutputs ? idx < numOutputs : idx==0);
  710. CriticalBlock b(statsCrit);
  711. processedArray[idx] += _processed;
  712. }
  713. virtual void noteStarted(unsigned idx) const
  714. {
  715. assertex(numOutputs ? idx < numOutputs : idx==0);
  716. CriticalBlock b(statsCrit);
  717. startedArray[idx] = true;
  718. }
  719. };
  720. class CRoxieServerInternalSinkFactory : public CRoxieServerActivityFactory
  721. {
  722. protected:
  723. bool isInternal;
  724. bool isRoot;
  725. unsigned usageCount;
  726. public:
  727. CRoxieServerInternalSinkFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  728. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  729. {
  730. usageCount = _usageCount;
  731. isRoot = _isRoot;
  732. isInternal = false; // filled in by derived class constructor
  733. }
  734. virtual bool isSink() const
  735. {
  736. //only a sink if a root activity
  737. 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?
  738. }
  739. virtual void getEdgeProgressInfo(unsigned idx, IPropertyTree &edge) const
  740. {
  741. // 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
  742. // Just leave it blank is safest.
  743. }
  744. };
  745. typedef enum { STATEreset, STATEstarted, STATEstopped, STATEstarting } activityState;
  746. const char *queryStateText(activityState state)
  747. {
  748. switch (state)
  749. {
  750. case STATEreset: return "reset";
  751. case STATEstarted: return "started";
  752. case STATEstopped: return "stopped";
  753. case STATEstarting: return "starting";
  754. default: return "unknown";
  755. }
  756. }
  757. typedef ICopyArrayOf<IRoxieServerActivity> IRoxieServerActivityCopyArray;
  758. class CParallelActivityExecutor : public CAsyncFor
  759. {
  760. public:
  761. unsigned parentExtractSize;
  762. const byte * parentExtract;
  763. CParallelActivityExecutor(IRoxieServerActivityCopyArray & _activities, unsigned _parentExtractSize, const byte * _parentExtract) :
  764. activities(_activities), parentExtractSize(_parentExtractSize), parentExtract(_parentExtract) { }
  765. void Do(unsigned i)
  766. {
  767. activities.item(i).execute(parentExtractSize, parentExtract);
  768. }
  769. private:
  770. IRoxieServerActivityCopyArray & activities;
  771. };
  772. extern IEngineRowStream * ensureSingleStream(IRoxieSlaveContext *ctx, PointerArrayOf<IEngineRowStream> & instreams, Owned<IStrandJunction> &junction)
  773. {
  774. if (instreams.length() != 1)
  775. {
  776. assertex(instreams.length());
  777. if (!junction)
  778. junction.setown(createStrandJunction(ctx->queryRowManager(), instreams.length(), 1, ctx->queryOptions().strandBlockSize, false));
  779. ForEachItemIn(stream, instreams)
  780. {
  781. junction->setInput(stream, instreams.item(stream));
  782. }
  783. return junction->queryOutput(0);
  784. }
  785. else
  786. return instreams.item(0);
  787. }
  788. extern IEngineRowStream *connectSingleStream(IRoxieSlaveContext *ctx, IFinalRoxieInput *input, unsigned idx, Owned<IStrandJunction> &junction, bool consumerOrdered)
  789. {
  790. if (input)
  791. {
  792. PointerArrayOf<IEngineRowStream> instreams;
  793. junction.setown(input->getOutputStreams(ctx, idx, instreams, NULL, consumerOrdered, nullptr));
  794. return ensureSingleStream(ctx, instreams, junction);
  795. }
  796. else
  797. return NULL;
  798. }
  799. extern IEngineRowStream *connectSingleStream(IRoxieSlaveContext *ctx, IFinalRoxieInput *input, unsigned idx, bool consumerOrdered)
  800. {
  801. Owned<IStrandJunction> junction;
  802. IEngineRowStream * result = connectSingleStream(ctx, input, idx, junction, consumerOrdered);
  803. assertex(!junction);
  804. return result;
  805. }
  806. class CRoxieServerActivity : public CInterface, implements IRoxieServerActivity, implements IFinalRoxieInput, implements IEngineRowStream, implements IRoxieContextLogger
  807. {
  808. friend class StrandProcessor;
  809. protected:
  810. IFinalRoxieInput *input;
  811. unsigned sourceIdx;
  812. IEngineRowStream *inputStream;
  813. Owned<IStrandJunction> junction;
  814. IHThorArg &basehelper;
  815. IRoxieSlaveContext *ctx;
  816. const IRoxieServerActivityFactory *factory;
  817. IRoxieServerActivityCopyArray dependencies;
  818. IntArray dependencyIndexes;
  819. IntArray dependencyControlIds;
  820. IArrayOf<IActivityGraph> childGraphs;
  821. CachedOutputMetaData meta;
  822. IHThorArg *colocalParent;
  823. IEngineRowAllocator *rowAllocator;
  824. CriticalSection statecrit;
  825. CriticalSection statscrit;
  826. mutable CRuntimeStatisticCollection stats;
  827. MapStringToMyClass<ThorSectionTimer> functionTimers;
  828. unsigned processed;
  829. ActivityTimeAccumulator totalCycles;
  830. cycle_t localCycles;
  831. unsigned activityId;
  832. activityState state;
  833. bool createPending;
  834. bool debugging;
  835. bool timeActivities;
  836. bool aborted;
  837. bool connected = false;
  838. IProbeManager *probeManager = NULL;
  839. public:
  840. IMPLEMENT_IINTERFACE;
  841. CRoxieServerActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  842. : ctx(_ctx),
  843. factory(_factory),
  844. basehelper(_factory->getHelper()),
  845. activityId(_factory->queryId()),
  846. stats(_factory ? _factory->queryStatsMapping() : actStatistics),
  847. probeManager(_probeManager)
  848. {
  849. input = NULL;
  850. sourceIdx = 0;
  851. inputStream = NULL;
  852. meta.set(basehelper.queryOutputMeta());
  853. processed = 0;
  854. localCycles = 0;
  855. state=STATEreset;
  856. rowAllocator = NULL;
  857. debugging = _probeManager != NULL; // Don't want to collect timing stats from debug sessions
  858. colocalParent = NULL;
  859. createPending = true;
  860. timeActivities = defaultTimeActivities;
  861. aborted = false;
  862. }
  863. CRoxieServerActivity(IRoxieSlaveContext *_ctx, IHThorArg & _helper) : ctx(_ctx), factory(NULL), basehelper(_helper), stats(allStatistics)
  864. {
  865. activityId = 0;
  866. input = NULL;
  867. inputStream = NULL;
  868. ctx = NULL;
  869. meta.set(basehelper.queryOutputMeta());
  870. processed = 0;
  871. localCycles = 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. if (traceStartStop)
  883. {
  884. // There was an old comment here stating // Note- CTXLOG may not be safe
  885. // There were problems in the destruction order of graphs that might mean an IndirectSlaveContext
  886. // was released while activities still referenced it.
  887. // However these should now all be fixed
  888. DBGLOG("%p destroy %d state=%s", this, activityId, queryStateText(state));
  889. if (watchActivityId && watchActivityId==activityId)
  890. {
  891. DBGLOG("WATCH: %p destroy %d state=%s", this, activityId, queryStateText(state));
  892. }
  893. }
  894. if (state!=STATEreset)
  895. {
  896. DBGLOG("STATE: Activity %d destroyed but not reset", activityId);
  897. state = STATEreset; // bit pointless but there you go...
  898. }
  899. if (factory && !debugging)
  900. {
  901. if (processed)
  902. factory->noteProcessed(0, processed);
  903. factory->mergeActivityStats(stats, totalCycles, localCycles);
  904. }
  905. if (ctx)
  906. {
  907. if (processed)
  908. ctx->noteProcessed(factory->querySubgraphId(), activityId, 0, processed, 0);
  909. ctx->mergeActivityStats(stats, factory->querySubgraphId(), activityId, totalCycles, localCycles);
  910. }
  911. basehelper.Release();
  912. ::Release(rowAllocator);
  913. }
  914. virtual const IRoxieContextLogger &queryLogCtx()const
  915. {
  916. return *this;
  917. }
  918. inline const StatisticsMapping & queryStatsMapping() const
  919. {
  920. return factory ? factory->queryStatsMapping() : actStatistics;
  921. }
  922. virtual void mergeStats(MemoryBuffer &buf)
  923. {
  924. stats.deserializeMerge(buf);
  925. }
  926. virtual ISectionTimer *registerTimer(unsigned activityId, const char * name)
  927. {
  928. CriticalBlock b(statscrit); // reuse statscrit to protect functionTimers - it will not be held concurrently
  929. ISectionTimer *timer = functionTimers.getValue(name);
  930. if (!timer)
  931. {
  932. timer = ThorSectionTimer::createTimer(stats, name);
  933. functionTimers.setValue(name, timer);
  934. timer->Release(); // Value returned is not linked
  935. }
  936. return timer;
  937. }
  938. virtual IRoxieServerActivity * queryChildActivity(unsigned activityId)
  939. {
  940. ForEachItemIn(i, childGraphs)
  941. {
  942. IRoxieServerActivity * activity = childGraphs.item(i).queryActivity(activityId);
  943. if (activity)
  944. return activity;
  945. }
  946. #ifdef _DEBUG
  947. throwUnexpectedX("Unable to map child activity id to an activity");
  948. #endif
  949. return nullptr;
  950. }
  951. void mergeStrandStats(unsigned strandProcessed, const ActivityTimeAccumulator & strandCycles, const CRuntimeStatisticCollection & strandStats)
  952. {
  953. CriticalBlock cb(statscrit);
  954. processed += strandProcessed;
  955. totalCycles.merge(strandCycles);
  956. stats.merge(strandStats);
  957. }
  958. inline void createRowAllocator()
  959. {
  960. if (!rowAllocator)
  961. rowAllocator = ctx->queryCodeContext()->getRowAllocator(meta.queryOriginal(), activityId);
  962. }
  963. inline ICodeContext *queryCodeContext()
  964. {
  965. return ctx->queryCodeContext();
  966. }
  967. // MORE - most of this is copied from ccd.hpp - can't we refactor?
  968. virtual void CTXLOGa(TracingCategory category, const char *prefix, const char *text) const
  969. {
  970. if (ctx)
  971. ctx->CTXLOGa(category, prefix, text);
  972. else
  973. DBGLOG("[%s] %s", prefix, text);
  974. }
  975. 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)))
  976. {
  977. if (ctx)
  978. ctx->CTXLOGaeva(E, file, line, prefix, format, args);
  979. else
  980. {
  981. StringBuffer ss;
  982. ss.appendf("[%s] ERROR", prefix);
  983. if (E)
  984. ss.append(": ").append(E->errorCode());
  985. if (file)
  986. ss.appendf(": %s(%d) ", file, line);
  987. if (E)
  988. E->errorMessage(ss.append(": "));
  989. if (format)
  990. {
  991. ss.append(": ").valist_appendf(format, args);
  992. }
  993. LOG(MCoperatorProgress, unknownJob, "%s", ss.str());
  994. }
  995. }
  996. virtual void CTXLOGl(LogItem *log) const
  997. {
  998. if (ctx)
  999. ctx->CTXLOGl(log);
  1000. else
  1001. {
  1002. assert(ctx);
  1003. log->Release(); // Should never happen
  1004. }
  1005. }
  1006. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value) const
  1007. {
  1008. stats.addStatistic(kind, value);
  1009. }
  1010. virtual void mergeStats(const CRuntimeStatisticCollection &from) const
  1011. {
  1012. stats.merge(from);
  1013. }
  1014. virtual const CRuntimeStatisticCollection &queryStats() const
  1015. {
  1016. return stats;
  1017. }
  1018. virtual StringBuffer &getLogPrefix(StringBuffer &ret) const
  1019. {
  1020. if (ctx)
  1021. ctx->getLogPrefix(ret);
  1022. return ret.append('@').append(activityId);
  1023. }
  1024. virtual bool isIntercepted() const
  1025. {
  1026. return ctx ? ctx->isIntercepted() : false;
  1027. }
  1028. virtual bool isBlind() const
  1029. {
  1030. return ctx ? ctx->isBlind() : blindLogging;
  1031. }
  1032. virtual unsigned queryTraceLevel() const
  1033. {
  1034. if (ctx)
  1035. return ctx->queryTraceLevel();
  1036. else
  1037. return traceLevel;
  1038. }
  1039. virtual bool isPassThrough()
  1040. {
  1041. return false;
  1042. }
  1043. virtual const IResolvedFile *resolveLFN(const char *filename, bool isOpt)
  1044. {
  1045. return ctx->resolveLFN(filename, isOpt);
  1046. }
  1047. virtual const IResolvedFile *queryVarFileInfo() const
  1048. {
  1049. throwUnexpected(); // should be implemented in more derived class by anyone that has a remote adaptor
  1050. return NULL;
  1051. }
  1052. virtual void serializeSkipInfo(MemoryBuffer &out, unsigned seekLen, const void *rawSeek, unsigned numFields, const void * seek, const SmartStepExtra &stepExtra) const
  1053. {
  1054. throwUnexpected(); // should be implemented in more derived class wherever needed
  1055. }
  1056. virtual IRoxieSlaveContext *queryContext()
  1057. {
  1058. return ctx;
  1059. }
  1060. virtual IRoxieServerActivity *queryActivity() { return this; }
  1061. virtual IIndexReadActivityInfo *queryIndexReadActivity() { return NULL; }
  1062. virtual bool needsAllocator() const { return false; }
  1063. void _onCreate(IHThorArg *_colocalParent, unsigned _numParallel)
  1064. {
  1065. colocalParent = _colocalParent;
  1066. createPending = true;
  1067. if (needsAllocator())
  1068. createRowAllocator();
  1069. processed = 0;
  1070. if (factory)
  1071. factory->onCreateChildQueries(ctx, &basehelper, childGraphs, this, probeManager, *this, _numParallel);
  1072. if (ctx)
  1073. timeActivities = ctx->queryOptions().timeActivities;
  1074. }
  1075. virtual void onCreate(IHThorArg *_colocalParent)
  1076. {
  1077. _onCreate(_colocalParent, 1);
  1078. }
  1079. virtual void serializeCreateStartContext(MemoryBuffer &out)
  1080. {
  1081. //This should only be called after onStart has been called on the helper
  1082. assertex(!createPending);
  1083. assertex(state==STATEstarted);
  1084. unsigned startlen = out.length();
  1085. basehelper.serializeCreateContext(out);
  1086. basehelper.serializeStartContext(out);
  1087. if (queryTraceLevel() > 10)
  1088. CTXLOG("serializeCreateStartContext for %d added %d bytes", activityId, out.length()-startlen);
  1089. }
  1090. virtual void serializeExtra(MemoryBuffer &out) {}
  1091. inline void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  1092. {
  1093. CriticalBlock cb(statecrit);
  1094. if (state != STATEreset && state != STATEstarting)
  1095. {
  1096. CTXLOG("STATE: Expected state to be reset, but was %s, in activity %d", queryStateText(state), activityId);
  1097. }
  1098. state=STATEstarted;
  1099. #ifdef TRACE_STARTSTOP
  1100. if (traceStartStop)
  1101. {
  1102. CTXLOG("start %p %d", this, activityId);
  1103. if (watchActivityId && watchActivityId==activityId)
  1104. {
  1105. CTXLOG("WATCH: start %p %d", this, activityId);
  1106. }
  1107. }
  1108. #endif
  1109. executeDependencies(parentExtractSize, parentExtract, 0);
  1110. if (input)
  1111. input->start(parentExtractSize, parentExtract, paused);
  1112. ensureCreated();
  1113. basehelper.onStart(parentExtract, NULL);
  1114. if (factory)
  1115. factory->noteStarted();
  1116. startJunction(junction);
  1117. }
  1118. void executeDependencies(unsigned parentExtractSize, const byte *parentExtract, unsigned controlId)
  1119. {
  1120. //MORE: Create a filtered list and then use asyncfor
  1121. ForEachItemIn(idx, dependencies)
  1122. {
  1123. if (dependencyControlIds.item(idx) == controlId)
  1124. dependencies.item(idx).execute(parentExtractSize, parentExtract);
  1125. }
  1126. }
  1127. void stopDependencies(unsigned parentExtractSize, const byte *parentExtract, unsigned controlId)
  1128. {
  1129. ForEachItemIn(idx, dependencies)
  1130. {
  1131. if (dependencyControlIds.item(idx) == controlId)
  1132. dependencies.item(idx).stop();
  1133. }
  1134. }
  1135. virtual unsigned __int64 queryTotalCycles() const
  1136. {
  1137. return totalCycles.totalCycles;
  1138. }
  1139. virtual unsigned __int64 queryLocalCycles() const
  1140. {
  1141. __int64 ret = totalCycles.totalCycles;
  1142. if (input) ret -= input->queryTotalCycles();
  1143. if (ret < 0)
  1144. ret = 0;
  1145. return ret;
  1146. }
  1147. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  1148. {
  1149. if (idx==0)
  1150. return input;
  1151. else
  1152. return NULL;
  1153. }
  1154. inline void ensureCreated()
  1155. {
  1156. if (createPending)
  1157. {
  1158. createPending = false;
  1159. basehelper.onCreate(ctx->queryCodeContext(), colocalParent, NULL);
  1160. }
  1161. }
  1162. virtual void stop()
  1163. {
  1164. // NOTE - don't be tempted to skip the stop for activities that are reset - splitters need to see the stops
  1165. if (state != STATEstopped)
  1166. {
  1167. CriticalBlock cb(statecrit);
  1168. if (state != STATEstopped)
  1169. {
  1170. #ifdef TRACE_STARTSTOP
  1171. if (traceStartStop)
  1172. {
  1173. CTXLOG("stop %p %d (state currently %s)", this, activityId, queryStateText(state));
  1174. if (watchActivityId && watchActivityId==activityId)
  1175. {
  1176. CTXLOG("WATCH: stop %p %d", this, activityId);
  1177. }
  1178. }
  1179. #endif
  1180. state=STATEstopped;
  1181. // NOTE - this is needed to ensure that dependencies which were not used are properly stopped
  1182. ForEachItemIn(idx, dependencies)
  1183. {
  1184. if (dependencyControlIds.item(idx) == 0)
  1185. dependencies.item(idx).stopSink(dependencyIndexes.item(idx));
  1186. }
  1187. if (inputStream)
  1188. inputStream->stop();
  1189. }
  1190. }
  1191. }
  1192. virtual void abort()
  1193. {
  1194. aborted = true;
  1195. // MORE - should abort dependencies here?
  1196. stop();
  1197. }
  1198. inline void reset()
  1199. {
  1200. if (state != STATEreset)
  1201. {
  1202. CriticalBlock cb(statecrit);
  1203. if (state != STATEreset)
  1204. {
  1205. if (state==STATEstarted || state==STATEstarting)
  1206. {
  1207. if (traceStartStop || traceLevel > 2)
  1208. CTXLOG("STATE: activity %d reset without stop", activityId);
  1209. stop();
  1210. }
  1211. state = STATEreset;
  1212. #ifdef TRACE_STARTSTOP
  1213. if (traceStartStop)
  1214. {
  1215. CTXLOG("reset %p %d", this, activityId);
  1216. if (watchActivityId && watchActivityId==activityId)
  1217. {
  1218. CTXLOG("WATCH: reset %p %d", this, activityId);
  1219. }
  1220. }
  1221. #endif
  1222. resetJunction(junction);
  1223. ForEachItemIn(idx, dependencies)
  1224. dependencies.item(idx).reset();
  1225. localCycles = queryLocalCycles(); // We can't call queryLocalCycles() in the destructor, so save the information here when we can.
  1226. if (input)
  1227. input->reset();
  1228. }
  1229. }
  1230. aborted = false;
  1231. }
  1232. virtual void addDependency(IRoxieServerActivity &source, unsigned sourceIdx, int controlId)
  1233. {
  1234. dependencies.append(source);
  1235. dependencyIndexes.append(sourceIdx);
  1236. dependencyControlIds.append(controlId);
  1237. }
  1238. virtual void resetEOF()
  1239. {
  1240. //would make more sense if the default implementation (and eof member) were in the base class
  1241. }
  1242. // Sink activities should override this....
  1243. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  1244. {
  1245. throw MakeStringException(ROXIE_SINK, "Internal error: execute() requires a sink");
  1246. }
  1247. virtual void executeChild(size32_t & retSize, void * & ret, unsigned parentExtractSize, const byte * parentExtract)
  1248. {
  1249. throw MakeStringException(ROXIE_SINK, "Internal error: executeChild() requires a suitable sink");
  1250. }
  1251. virtual void stopSink(unsigned idx)
  1252. {
  1253. throw MakeStringException(ROXIE_SINK, "Internal error: stopSink() requires a suitable sink");
  1254. }
  1255. virtual void connectInputStreams(bool consumerOrdered)
  1256. {
  1257. if (input && !inputStream)
  1258. inputStream = connectSingleStream(ctx, input, sourceIdx, junction, isInputOrdered(consumerOrdered, 0));
  1259. if (!connected)
  1260. {
  1261. connectDependencies();
  1262. connected = true;
  1263. }
  1264. }
  1265. void connectDependencies()
  1266. {
  1267. ForEachItemIn(i, dependencies)
  1268. dependencies.item(i).connectInputStreams(true);
  1269. }
  1270. virtual __int64 evaluate()
  1271. {
  1272. throw MakeStringException(ROXIE_SINK, "Internal error: evaluate() requires a function");
  1273. }
  1274. virtual IFinalRoxieInput * querySelectOutput(unsigned id)
  1275. {
  1276. return NULL;
  1277. }
  1278. virtual bool querySetStreamInput(unsigned id, unsigned _sourceIdx, IFinalRoxieInput * _input)
  1279. {
  1280. return false;
  1281. }
  1282. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  1283. {
  1284. assertex(!idx);
  1285. input = _in;
  1286. sourceIdx = _sourceIdx;
  1287. inputStream = NULL;
  1288. }
  1289. bool isInputOrdered(bool consumerOrdered, unsigned idx) const
  1290. {
  1291. if (!factory)
  1292. return true;
  1293. //Grouping implies the stream processing must be ordered - I think this always applies
  1294. IFinalRoxieInput * curInput = queryInput(idx);
  1295. if (curInput && curInput->queryOutputMeta()->isGrouped())
  1296. return true;
  1297. return factory->isInputOrdered(consumerOrdered, idx);
  1298. }
  1299. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  1300. {
  1301. assertex(!idx);
  1302. // By default, activities are assumed NOT to support streams
  1303. bool inputOrdered = isInputOrdered(consumerOrdered, 0);
  1304. connectInputStreams(inputOrdered);
  1305. // Return a single stream
  1306. streams.append(this);
  1307. return NULL;
  1308. }
  1309. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  1310. {
  1311. if (idx == (unsigned) -1)
  1312. idx = 0;
  1313. return idx ? NULL : this;
  1314. }
  1315. virtual IOutputMetaData *queryOutputMeta() const
  1316. {
  1317. return meta.queryOriginal();
  1318. }
  1319. virtual unsigned queryId() const
  1320. {
  1321. return activityId;
  1322. }
  1323. virtual unsigned querySubgraphId() const
  1324. {
  1325. return factory->querySubgraphId();
  1326. }
  1327. virtual void checkAbort()
  1328. {
  1329. ctx->checkAbort();
  1330. }
  1331. IException *makeWrappedException(IException *e)
  1332. {
  1333. StringBuffer msg;
  1334. ThorActivityKind activityKind = factory ? factory->getKind() : TAKnone;
  1335. CTXLOG("makeWrappedException - %s (in %s %d)", e->errorMessage(msg).str(), getActivityText(activityKind), activityId);
  1336. if (QUERYINTERFACE(e, CWrappedException) || QUERYINTERFACE(e, IUserException))
  1337. return e;
  1338. else
  1339. return new CWrappedException(e, activityKind, activityId);
  1340. }
  1341. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract)
  1342. {
  1343. }
  1344. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract, IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes)
  1345. {
  1346. }
  1347. virtual void resetOutputsUsed()
  1348. {
  1349. }
  1350. virtual void noteOutputUsed()
  1351. {
  1352. }
  1353. virtual IRoxieServerSideCache *queryServerSideCache() const
  1354. {
  1355. return factory->queryServerSideCache();
  1356. }
  1357. virtual const IRoxieServerActivityFactory *queryFactory() const
  1358. {
  1359. return factory;
  1360. }
  1361. inline ThorActivityKind getKind() const
  1362. {
  1363. return factory->getKind();
  1364. }
  1365. inline bool isSink() const
  1366. {
  1367. return (factory != NULL) && factory->isSink();
  1368. }
  1369. };
  1370. //=====================================================================================================
  1371. class CRoxieServerLateStartActivity : public CRoxieServerActivity
  1372. {
  1373. protected:
  1374. bool prefiltered;
  1375. bool eof;
  1376. void lateStart(unsigned parentExtractSize, const byte *parentExtract, bool any)
  1377. {
  1378. prefiltered = !any;
  1379. eof = prefiltered;
  1380. if (!prefiltered)
  1381. {
  1382. input->start(parentExtractSize, parentExtract, false);
  1383. startJunction(junction);
  1384. }
  1385. else
  1386. {
  1387. if (traceStartStop)
  1388. CTXLOG("lateStart activity stopping input early as prefiltered");
  1389. inputStream->stop();
  1390. }
  1391. }
  1392. public:
  1393. CRoxieServerLateStartActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  1394. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  1395. {
  1396. prefiltered = false;
  1397. eof = false;
  1398. }
  1399. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  1400. {
  1401. IFinalRoxieInput *saveInput = input;
  1402. Owned<IStrandJunction> saveJunction = junction.getClear();
  1403. input = NULL; // Make sure parent does not start the chain yet
  1404. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  1405. input = saveInput;
  1406. junction.setown(saveJunction.getClear());
  1407. }
  1408. virtual void stop()
  1409. {
  1410. if (!prefiltered)
  1411. {
  1412. inputStream->stop();
  1413. }
  1414. else if (traceStartStop)
  1415. CTXLOG("lateStart activity NOT stopping input late as prefiltered");
  1416. IEngineRowStream *save = inputStream;
  1417. inputStream = NULL; // We already stopped inputStream - prevent parent from doing so again
  1418. CRoxieServerActivity::stop();
  1419. inputStream = save;
  1420. }
  1421. virtual void reset()
  1422. {
  1423. CRoxieServerActivity::reset();
  1424. prefiltered = false;
  1425. }
  1426. };
  1427. //=================================================================================
  1428. class StrandOptions
  1429. {
  1430. // Typically set from hints, common to many stranded activities
  1431. public:
  1432. explicit StrandOptions(IPropertyTree &_graphNode)
  1433. {
  1434. //PARALLEL(1) can be used to explicitly disable parallel processing.
  1435. numStrands = _graphNode.getPropInt("att[@name='parallel']/@value", 0);
  1436. if ((numStrands == minus1U) || (numStrands > MAX_SENSIBLE_STRANDS))
  1437. numStrands = getAffinityCpus();
  1438. blockSize = _graphNode.getPropInt("hint[@name='strandblocksize']/@value", 0);
  1439. }
  1440. StrandOptions(const StrandOptions &from, IRoxieSlaveContext *ctx)
  1441. {
  1442. numStrands = from.numStrands;
  1443. blockSize = from.blockSize;
  1444. if (!blockSize)
  1445. blockSize = ctx->queryOptions().strandBlockSize;
  1446. if (numStrands == 0)
  1447. numStrands = ctx->queryOptions().forceNumStrands;
  1448. }
  1449. public:
  1450. unsigned numStrands = 0; // if 1 it forces single-stranded operations. (Useful for testing.)
  1451. unsigned blockSize = 0;
  1452. };
  1453. class StrandProcessor : public CInterfaceOf<IEngineRowStream>
  1454. {
  1455. protected:
  1456. CRoxieServerActivity &parent;
  1457. IEngineRowAllocator *rowAllocator;
  1458. IEngineRowStream *inputStream;
  1459. ActivityTimeAccumulator totalCycles;
  1460. mutable CRuntimeStatisticCollection stats;
  1461. unsigned processed = 0;
  1462. unsigned numProcessedLastGroup = 0;
  1463. const bool timeActivities;
  1464. bool stopped = false;
  1465. std::atomic<bool> abortRequested;
  1466. public:
  1467. explicit StrandProcessor(CRoxieServerActivity &_parent, IEngineRowStream *_inputStream, bool needsAllocator)
  1468. : parent(_parent), inputStream(_inputStream), stats(parent.queryStatsMapping()), timeActivities(_parent.timeActivities), abortRequested(false)
  1469. {
  1470. if (needsAllocator)
  1471. rowAllocator = parent.queryContext()->getRowAllocatorEx(parent.queryOutputMeta(), parent.queryId(), roxiemem::RHFunique);
  1472. else
  1473. rowAllocator = NULL;
  1474. }
  1475. ~StrandProcessor()
  1476. {
  1477. ::Release(rowAllocator);
  1478. }
  1479. virtual void start()
  1480. {
  1481. processed = 0;
  1482. numProcessedLastGroup = 0;
  1483. totalCycles.reset();
  1484. stats.reset();
  1485. }
  1486. virtual void stop()
  1487. {
  1488. if (!stopped)
  1489. {
  1490. if (inputStream)
  1491. inputStream->stop();
  1492. parent.stop();
  1493. parent.mergeStrandStats(processed, totalCycles, stats);
  1494. }
  1495. stopped = true;
  1496. }
  1497. virtual void reset()
  1498. {
  1499. stopped = false;
  1500. abortRequested.store(false, std::memory_order_relaxed);
  1501. }
  1502. virtual void resetEOF()
  1503. {
  1504. inputStream->resetEOF();
  1505. }
  1506. inline void requestAbort() { abortRequested.store(true, std::memory_order_relaxed); }
  1507. inline bool isAborting() { return abortRequested.load(std::memory_order_relaxed); }
  1508. };
  1509. class CRoxieServerStrandedActivity : public CRoxieServerActivity
  1510. {
  1511. protected:
  1512. StrandOptions strandOptions;
  1513. IArrayOf<StrandProcessor> strands;
  1514. Owned<IStrandBranch> branch;
  1515. Owned<IStrandJunction> splitter;
  1516. Owned<IStrandJunction> sourceJunction; // A junction applied to the output of a source activity
  1517. std::atomic<unsigned> active;
  1518. public:
  1519. CRoxieServerStrandedActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const StrandOptions &_strandOptions)
  1520. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  1521. strandOptions(_strandOptions, ctx)
  1522. {
  1523. active = 0;
  1524. }
  1525. ~CRoxieServerStrandedActivity()
  1526. {
  1527. if (strands.ordinality() > 1)
  1528. {
  1529. if (factory && !debugging)
  1530. factory->noteProcessed(0, processed);
  1531. if (ctx)
  1532. ctx->noteProcessed(factory->querySubgraphId(), activityId, 0, processed, strands.ordinality());
  1533. processed = 0; // To avoid reprocessing in base destructor
  1534. }
  1535. }
  1536. virtual void onCreate(IHThorArg *_colocalArg)
  1537. {
  1538. CRoxieServerActivity::_onCreate(_colocalArg, strands.ordinality());
  1539. }
  1540. //This function is pure (But also implemented out of line) to force the derived classes to implement it.
  1541. //After calling the base class start method, and initialising any values from the helper they must call onStartStrands(),
  1542. //this must also happen before any rows are read from the strands (e.g., by a source junction)
  1543. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused) = 0;
  1544. virtual void reset()
  1545. {
  1546. assertex(active==0);
  1547. ForEachItemIn(idx, strands)
  1548. strands.item(idx).reset();
  1549. resetJunction(splitter);
  1550. CRoxieServerActivity::reset();
  1551. resetJunction(sourceJunction);
  1552. }
  1553. virtual void stop()
  1554. {
  1555. // Called from the strands... which should ensure that stop is not called more than once per strand
  1556. //The first strand to call
  1557. if (active)
  1558. --active;
  1559. if (!active)
  1560. CRoxieServerActivity::stop();
  1561. }
  1562. void requestAbort()
  1563. {
  1564. ForEachItemIn(idx, strands)
  1565. strands.item(idx).requestAbort();
  1566. }
  1567. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  1568. {
  1569. assertex(idx == 0);
  1570. assertex(strands.empty());
  1571. CRoxieServerActivity::connectDependencies();
  1572. bool inputOrdered = isInputOrdered(consumerOrdered, idx);
  1573. //Note, numStrands == 1 is an explicit request to disable threading
  1574. if (consumerOptions && (consumerOptions->numStrands != 1) && (strandOptions.numStrands != 1))
  1575. {
  1576. //Check to see if the consumer's settings should override
  1577. if (strandOptions.numStrands == 0)
  1578. {
  1579. strandOptions.numStrands = consumerOptions->numStrands;
  1580. strandOptions.blockSize = consumerOptions->blockSize;
  1581. }
  1582. else if (consumerOptions->numStrands > strandOptions.numStrands)
  1583. {
  1584. strandOptions.numStrands = consumerOptions->numStrands;
  1585. }
  1586. }
  1587. Owned <IStrandJunction> recombiner;
  1588. if (input)
  1589. {
  1590. if (strandOptions.numStrands == 1)
  1591. {
  1592. // 1 means explicitly requested single-strand.
  1593. IEngineRowStream *instream = connectSingleStream(ctx, input, sourceIdx, junction, inputOrdered);
  1594. strands.append(*createStrandProcessor(instream));
  1595. }
  1596. else
  1597. {
  1598. PointerArrayOf<IEngineRowStream> instreams;
  1599. recombiner.setown(input->getOutputStreams(ctx, sourceIdx, instreams, &strandOptions, inputOrdered, orderedCallbacks));
  1600. if ((instreams.length() == 1) && (strandOptions.numStrands != 0)) // 0 means did not specify - we should use the strands that our upstream provides
  1601. {
  1602. assertex(recombiner == NULL);
  1603. // Create a splitter to split the input into n... and a recombiner if need to preserve sorting
  1604. if (inputOrdered)
  1605. {
  1606. branch.setown(createStrandBranch(ctx->queryRowManager(), strandOptions.numStrands, strandOptions.blockSize, true, input->queryOutputMeta()->isGrouped(), false, orderedCallbacks));
  1607. splitter.set(branch->queryInputJunction());
  1608. recombiner.set(branch->queryOutputJunction());
  1609. }
  1610. else
  1611. {
  1612. splitter.setown(createStrandJunction(ctx->queryRowManager(), 1, strandOptions.numStrands, strandOptions.blockSize, false));
  1613. }
  1614. splitter->setInput(0, instreams.item(0));
  1615. for (unsigned strandNo = 0; strandNo < strandOptions.numStrands; strandNo++)
  1616. strands.append(*createStrandProcessor(splitter->queryOutput(strandNo)));
  1617. }
  1618. else
  1619. {
  1620. // Ignore my hint and just use the width already split into...
  1621. ForEachItemIn(strandNo, instreams)
  1622. strands.append(*createStrandProcessor(instreams.item(strandNo)));
  1623. }
  1624. }
  1625. }
  1626. else
  1627. {
  1628. unsigned numStrands = strandOptions.numStrands ? strandOptions.numStrands : 1;
  1629. for (unsigned i=0; i < numStrands; i++)
  1630. strands.append(*createStrandSourceProcessor(inputOrdered));
  1631. if (inputOrdered && (numStrands > 1))
  1632. {
  1633. if (consumerOptions)
  1634. {
  1635. //If the output activities are also stranded then need to create a version of the branch
  1636. bool isGrouped = queryOutputMeta()->isGrouped();
  1637. branch.setown(createStrandBranch(ctx->queryRowManager(), strandOptions.numStrands, strandOptions.blockSize, true, isGrouped, true, orderedCallbacks));
  1638. sourceJunction.set(branch->queryInputJunction());
  1639. recombiner.set(branch->queryOutputJunction());
  1640. assertex((orderedCallbacks && !recombiner) || (!orderedCallbacks && recombiner));
  1641. //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
  1642. for (unsigned strandNo = 0; strandNo < strandOptions.numStrands; strandNo++)
  1643. {
  1644. sourceJunction->setInput(strandNo, &strands.item(strandNo));
  1645. streams.append(sourceJunction->queryOutput(strandNo));
  1646. }
  1647. #ifdef TRACE_STRANDS
  1648. if (traceLevel > 2)
  1649. DBGLOG("Executing activity %u with %u strands", activityId, strands.ordinality());
  1650. #endif
  1651. return recombiner.getClear();
  1652. }
  1653. else
  1654. {
  1655. //Feeding into a non threaded activity, so create a M:1 junction to combine the source strands
  1656. recombiner.setown(createStrandJunction(ctx->queryRowManager(), numStrands, 1, strandOptions.blockSize, inputOrdered));
  1657. }
  1658. }
  1659. }
  1660. ForEachItemIn(i, strands)
  1661. streams.append(&strands.item(i));
  1662. #ifdef TRACE_STRANDS
  1663. if (traceLevel > 2)
  1664. DBGLOG("Executing activity %u with %u strands", activityId, strands.ordinality());
  1665. #endif
  1666. return recombiner.getClear();
  1667. }
  1668. virtual StrandProcessor *createStrandProcessor(IEngineRowStream *instream) = 0;
  1669. //MORE: Possibly this class should be split into two for sinks and non sinks...
  1670. virtual StrandProcessor *createStrandSourceProcessor(bool inputOrdered) = 0;
  1671. virtual const void * nextRow()
  1672. {
  1673. throwUnexpected();
  1674. }
  1675. inline unsigned numStrands() const { return strands.ordinality(); }
  1676. protected:
  1677. void onStartStrands()
  1678. {
  1679. ForEachItemIn(idx, strands)
  1680. {
  1681. strands.item(idx).start();
  1682. active++;
  1683. }
  1684. }
  1685. };
  1686. //For some reason gcc doesn't let you specify a function as pure virtual and define it at the same time.
  1687. void CRoxieServerStrandedActivity::start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  1688. {
  1689. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  1690. startJunction(splitter);
  1691. }
  1692. class CRoxieServerStrandedLateStartActivity : public CRoxieServerStrandedActivity
  1693. {
  1694. protected:
  1695. bool prefiltered;
  1696. bool eof;
  1697. void lateStart(unsigned parentExtractSize, const byte *parentExtract, bool any)
  1698. {
  1699. prefiltered = !any;
  1700. eof = prefiltered;
  1701. if (!prefiltered)
  1702. {
  1703. //At this point
  1704. input->start(parentExtractSize, parentExtract, false);
  1705. startJunction(splitter);
  1706. onStartStrands(); // Initialise the strands - the helper will have been correctly initialized by this point.
  1707. startJunction(sourceJunction);
  1708. }
  1709. else
  1710. {
  1711. if (traceStartStop)
  1712. CTXLOG("strandedLateStart activity stopping input early as prefiltered");
  1713. ForEachItemIn(idx, strands)
  1714. strands.item(idx).stop();
  1715. }
  1716. }
  1717. public:
  1718. CRoxieServerStrandedLateStartActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const StrandOptions &_strandOptions)
  1719. : CRoxieServerStrandedActivity(_ctx, _factory, _probeManager, _strandOptions)
  1720. {
  1721. prefiltered = false;
  1722. eof = false;
  1723. }
  1724. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  1725. {
  1726. IFinalRoxieInput *save = input;
  1727. 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)
  1728. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  1729. input = save;
  1730. }
  1731. virtual void reset()
  1732. {
  1733. CRoxieServerStrandedActivity::reset();
  1734. prefiltered = false;
  1735. }
  1736. };
  1737. //=====================================================================================================
  1738. atomic_t nextInstanceId;
  1739. extern unsigned getNextInstanceId()
  1740. {
  1741. return atomic_add_exchange(&nextInstanceId, 1)+1;
  1742. }
  1743. atomic_t nextRuid;
  1744. ruid_t getNextRuid()
  1745. {
  1746. ruid_t ret = atomic_add_exchange(&nextRuid, 1)+1;
  1747. while (ret < RUID_FIRST)
  1748. ret = atomic_add_exchange(&nextRuid, 1)+1; // ruids 0 and 1 are reserved for pings/unwanted discarder.
  1749. return ret;
  1750. }
  1751. void setStartRuid(unsigned restarts)
  1752. {
  1753. atomic_set(&nextRuid, restarts * 0x10000);
  1754. atomic_set(&nextInstanceId, restarts * 10000);
  1755. }
  1756. enum { LimitSkipErrorCode = 0, KeyedLimitSkipErrorCode = 1 };
  1757. class LimitSkipException : public CInterface, public IException
  1758. {
  1759. int code;
  1760. public:
  1761. LimitSkipException(int _code) { code = _code; }
  1762. IMPLEMENT_IINTERFACE;
  1763. virtual int errorCode() const { return code; }
  1764. virtual StringBuffer & errorMessage(StringBuffer &msg) const { return msg.append("LimitSkipException"); }
  1765. virtual MessageAudience errorAudience() const { return MSGAUD_internal; }
  1766. };
  1767. IException *makeLimitSkipException(bool isKeyed)
  1768. {
  1769. // We need to make sure what we throw is IException not something derived from it....
  1770. return new LimitSkipException(isKeyed ? KeyedLimitSkipErrorCode : LimitSkipErrorCode);
  1771. }
  1772. //=================================================================================
  1773. interface IRecordPullerCallback : extends IExceptionHandler
  1774. {
  1775. virtual void processRow(const void *row) = 0;
  1776. virtual void processEOG() = 0;
  1777. virtual void processGroup(const ConstPointerArray &rows) = 0;
  1778. virtual void processDone() = 0;
  1779. };
  1780. class RecordPullerThread : public RestartableThread
  1781. {
  1782. protected:
  1783. IFinalRoxieInput *input;
  1784. Owned<IStrandJunction> junction;
  1785. unsigned sourceIdx = 0;
  1786. IEngineRowStream *inputStream;
  1787. IRecordPullerCallback *helper;
  1788. Semaphore started; // MORE: GH->RKC I'm pretty sure this can be deleted, since handled by RestartableThread
  1789. bool groupAtOnce, eof, eog;
  1790. CriticalSection crit;
  1791. public:
  1792. RecordPullerThread(bool _groupAtOnce)
  1793. : RestartableThread("RecordPullerThread"), groupAtOnce(_groupAtOnce)
  1794. {
  1795. input = NULL;
  1796. inputStream = NULL;
  1797. helper = NULL;
  1798. eof = eog = FALSE;
  1799. }
  1800. inline unsigned __int64 queryTotalCycles() const
  1801. {
  1802. return input->queryTotalCycles();
  1803. }
  1804. void setInput(IRecordPullerCallback *_helper, unsigned _sourceIdx, IFinalRoxieInput *_input)
  1805. {
  1806. helper = _helper;
  1807. input = _input;
  1808. sourceIdx = _sourceIdx;
  1809. }
  1810. IFinalRoxieInput *queryInput() const
  1811. {
  1812. return input;
  1813. }
  1814. virtual void connectInputStreams(IRoxieSlaveContext *ctx, bool consumerOrdered)
  1815. {
  1816. inputStream = connectSingleStream(ctx, input, sourceIdx, junction, consumerOrdered);
  1817. }
  1818. IEngineRowStream *queryStream() const
  1819. {
  1820. return inputStream;
  1821. }
  1822. void start(unsigned parentExtractSize, const byte *parentExtract, bool paused, unsigned preload, bool noThread, IRoxieSlaveContext *ctx)
  1823. {
  1824. eof = false;
  1825. eog = false;
  1826. input->start(parentExtractSize, parentExtract, paused);
  1827. startJunction(junction);
  1828. try
  1829. {
  1830. if (preload && !paused)
  1831. {
  1832. if (traceLevel > 4)
  1833. DBGLOG("Preload fetching first %d records", preload);
  1834. if (groupAtOnce)
  1835. pullGroups(preload);
  1836. else
  1837. pullRecords(preload);
  1838. }
  1839. if (eof)
  1840. {
  1841. if (traceLevel > 4)
  1842. DBGLOG("No need to start puller after preload");
  1843. helper->processDone();
  1844. }
  1845. else
  1846. {
  1847. if (!noThread)
  1848. {
  1849. StringBuffer logPrefix("[");
  1850. if (ctx) ctx->getLogPrefix(logPrefix);
  1851. logPrefix.append("] ");
  1852. RestartableThread::start(logPrefix);
  1853. started.wait();
  1854. }
  1855. }
  1856. }
  1857. catch (IException *e)
  1858. {
  1859. helper->fireException(e);
  1860. }
  1861. catch (...)
  1862. {
  1863. helper->fireException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unexpected exception caught in RecordPullerThread::start"));
  1864. }
  1865. }
  1866. void stop()
  1867. {
  1868. if (traceStartStop)
  1869. DBGLOG("RecordPullerThread::stop");
  1870. {
  1871. 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.
  1872. inputStream->stop();
  1873. }
  1874. RestartableThread::join();
  1875. }
  1876. void reset()
  1877. {
  1878. input->reset();
  1879. resetJunction(junction);
  1880. }
  1881. virtual int run()
  1882. {
  1883. started.signal();
  1884. try
  1885. {
  1886. if (groupAtOnce)
  1887. pullGroups((unsigned) -1);
  1888. else
  1889. pullRecords((unsigned) -1);
  1890. helper->processDone();
  1891. }
  1892. catch (IException *e)
  1893. {
  1894. helper->fireException(e);
  1895. }
  1896. catch (...)
  1897. {
  1898. helper->fireException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unexpected exception caught in RecordPullerThread::run"));
  1899. }
  1900. return 0;
  1901. }
  1902. void done()
  1903. {
  1904. helper->processDone();
  1905. }
  1906. bool pullRecords(unsigned preload)
  1907. {
  1908. if (eof)
  1909. return false;
  1910. while (preload)
  1911. {
  1912. const void * row;
  1913. {
  1914. CriticalBlock c(crit); // See comments in stop for why this is needed
  1915. row = inputStream->nextRow();
  1916. }
  1917. if (row)
  1918. {
  1919. eog = false;
  1920. helper->processRow(row);
  1921. }
  1922. else if (!eog)
  1923. {
  1924. helper->processEOG();
  1925. eog = true;
  1926. }
  1927. else
  1928. {
  1929. eof = true;
  1930. return false;
  1931. }
  1932. if (preload != (unsigned) -1)
  1933. preload--;
  1934. }
  1935. return true;
  1936. }
  1937. void pullGroups(unsigned preload)
  1938. {
  1939. ConstPointerArray thisGroup;
  1940. unsigned rowsDone = 0;
  1941. while (preload && !eof)
  1942. {
  1943. const void *row;
  1944. {
  1945. CriticalBlock c(crit);
  1946. row = inputStream->nextRow();
  1947. }
  1948. if (row)
  1949. {
  1950. thisGroup.append(row);
  1951. rowsDone++;
  1952. }
  1953. else if (thisGroup.length())
  1954. {
  1955. helper->processGroup(thisGroup);
  1956. thisGroup.kill();
  1957. if (preload != (unsigned) -1)
  1958. {
  1959. if (preload > rowsDone)
  1960. preload -= rowsDone;
  1961. else
  1962. break;
  1963. }
  1964. rowsDone = 0;
  1965. }
  1966. else
  1967. {
  1968. eof = true;
  1969. break;
  1970. }
  1971. }
  1972. }
  1973. };
  1974. //=================================================================================
  1975. #define READAHEAD_SIZE 1000
  1976. // MORE - this code copied from ThreadedConcat code - may be able to common up some.
  1977. class CRoxieServerReadAheadInput : public CInterface, implements IFinalRoxieInput, implements IRecordPullerCallback, implements IEngineRowStream
  1978. {
  1979. QueueOf<const void, true> buffer;
  1980. InterruptableSemaphore ready;
  1981. InterruptableSemaphore space;
  1982. CriticalSection crit;
  1983. bool eof;
  1984. bool disabled;
  1985. IRoxieSlaveContext *ctx;
  1986. RecordPullerThread puller;
  1987. unsigned preload;
  1988. cycle_t totalCycles;
  1989. bool timeActivities;
  1990. public:
  1991. IMPLEMENT_IINTERFACE;
  1992. CRoxieServerReadAheadInput(IRoxieSlaveContext *_ctx, unsigned _preload) : ctx(_ctx), puller(true), preload(_preload)
  1993. {
  1994. eof = false;
  1995. disabled = (ctx->queryDebugContext() != NULL);
  1996. totalCycles = 0;
  1997. timeActivities = ctx->queryOptions().timeActivities;
  1998. }
  1999. virtual IRoxieServerActivity *queryActivity()
  2000. {
  2001. return puller.queryInput()->queryActivity();
  2002. }
  2003. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  2004. {
  2005. assertex(!idx);
  2006. puller.connectInputStreams(ctx, consumerOrdered);
  2007. streams.append(this);
  2008. return NULL;
  2009. }
  2010. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  2011. {
  2012. return puller.queryInput()->queryIndexReadActivity();
  2013. }
  2014. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  2015. {
  2016. eof = false;
  2017. if (disabled)
  2018. puller.queryInput()->start(parentExtractSize, parentExtract, paused);
  2019. else
  2020. {
  2021. space.reinit(READAHEAD_SIZE);
  2022. ready.reinit();
  2023. puller.start(parentExtractSize, parentExtract, paused, preload, false, ctx);
  2024. }
  2025. }
  2026. virtual void stop()
  2027. {
  2028. if (disabled)
  2029. puller.queryStream()->stop();
  2030. else
  2031. {
  2032. space.interrupt();
  2033. ready.interrupt();
  2034. puller.stop();
  2035. }
  2036. }
  2037. virtual void reset()
  2038. {
  2039. if (disabled)
  2040. puller.queryInput()->reset();
  2041. else
  2042. {
  2043. puller.reset();
  2044. ForEachItemIn(idx1, buffer)
  2045. ReleaseRoxieRow(buffer.item(idx1));
  2046. buffer.clear();
  2047. }
  2048. }
  2049. virtual void resetEOF()
  2050. {
  2051. throwUnexpected();
  2052. }
  2053. virtual IOutputMetaData * queryOutputMeta() const
  2054. {
  2055. return puller.queryInput()->queryOutputMeta();
  2056. }
  2057. void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  2058. {
  2059. assertex(!idx);
  2060. puller.setInput(this, _sourceIdx, _in);
  2061. }
  2062. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  2063. {
  2064. if (idx==0)
  2065. return puller.queryInput();
  2066. else
  2067. return NULL;
  2068. }
  2069. virtual unsigned __int64 queryTotalCycles() const
  2070. {
  2071. return totalCycles;
  2072. }
  2073. virtual const void * nextRow()
  2074. {
  2075. SimpleActivityTimer t(totalCycles, timeActivities);
  2076. if (disabled)
  2077. return puller.queryStream()->nextRow();
  2078. else
  2079. {
  2080. loop
  2081. {
  2082. {
  2083. CriticalBlock b(crit);
  2084. if (eof && !buffer.ordinality())
  2085. return NULL; // eof
  2086. }
  2087. ready.wait();
  2088. const void *ret;
  2089. {
  2090. CriticalBlock b(crit);
  2091. ret = buffer.dequeue();
  2092. }
  2093. space.signal();
  2094. return ret;
  2095. }
  2096. }
  2097. }
  2098. virtual bool fireException(IException *e)
  2099. {
  2100. // called from puller thread on failure
  2101. ready.interrupt(LINK(e));
  2102. space.interrupt(e);
  2103. return true;
  2104. }
  2105. virtual void processRow(const void *row)
  2106. {
  2107. {
  2108. CriticalBlock b(crit);
  2109. buffer.enqueue(row);
  2110. }
  2111. ready.signal();
  2112. space.wait();
  2113. }
  2114. virtual void processGroup(const ConstPointerArray &rows)
  2115. {
  2116. // NOTE - a bit bizarre in that it waits for the space AFTER using it.
  2117. // But the space semaphore is only there to stop infinite readahead. And otherwise it would deadlock
  2118. // if group was larger than max(space)
  2119. {
  2120. CriticalBlock b(crit);
  2121. ForEachItemIn(idx, rows)
  2122. buffer.enqueue(rows.item(idx));
  2123. buffer.enqueue(NULL);
  2124. }
  2125. for (unsigned i2 = 0; i2 <= rows.length(); i2++) // note - does 1 extra for the null
  2126. {
  2127. ready.signal();
  2128. space.wait();
  2129. }
  2130. }
  2131. virtual void processEOG()
  2132. {
  2133. // Used when output is not grouped - just ignore
  2134. }
  2135. virtual void processDone()
  2136. {
  2137. CriticalBlock b(crit);
  2138. eof = true;
  2139. ready.signal();
  2140. }
  2141. };
  2142. //=================================================================================
  2143. class CRoxieServerTwoInputActivity : public CRoxieServerActivity
  2144. {
  2145. protected:
  2146. IFinalRoxieInput *input1;
  2147. IEngineRowStream *inputStream1;
  2148. Owned<IStrandJunction> junction1;
  2149. unsigned sourceIdx1 = 0;
  2150. Owned<CRoxieServerReadAheadInput> puller;
  2151. public:
  2152. CRoxieServerTwoInputActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  2153. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  2154. {
  2155. input1 = NULL;
  2156. inputStream1 = NULL;
  2157. }
  2158. ~CRoxieServerTwoInputActivity()
  2159. {
  2160. }
  2161. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  2162. {
  2163. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  2164. input1->start(parentExtractSize, parentExtract, paused);
  2165. startJunction(junction1);
  2166. }
  2167. virtual void stop()
  2168. {
  2169. inputStream1->stop();
  2170. CRoxieServerActivity::stop();
  2171. }
  2172. virtual unsigned __int64 queryLocalCycles() const
  2173. {
  2174. __int64 ret;
  2175. __int64 inputCycles = input->queryTotalCycles();
  2176. __int64 input1Cycles = input1->queryTotalCycles();
  2177. if (puller)
  2178. ret = totalCycles.totalCycles - (inputCycles > input1Cycles ? inputCycles : input1Cycles);
  2179. else
  2180. ret = totalCycles.totalCycles - (inputCycles + input1Cycles);
  2181. if (ret < 0)
  2182. ret = 0;
  2183. return ret;
  2184. }
  2185. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  2186. {
  2187. switch (idx)
  2188. {
  2189. case 0:
  2190. return input;
  2191. case 1:
  2192. return input1;
  2193. default:
  2194. return NULL;
  2195. }
  2196. }
  2197. virtual void reset()
  2198. {
  2199. CRoxieServerActivity::reset();
  2200. if (input1)
  2201. input1->reset();
  2202. resetJunction(junction1);
  2203. }
  2204. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  2205. {
  2206. switch(idx)
  2207. {
  2208. case 0:
  2209. CRoxieServerActivity::setInput(idx, _sourceIdx, _in);
  2210. break;
  2211. case 1:
  2212. input1 = _in;
  2213. sourceIdx1 = _sourceIdx;
  2214. break;
  2215. default:
  2216. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  2217. }
  2218. }
  2219. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  2220. {
  2221. inputStream1 = connectSingleStream(ctx, input1, sourceIdx1, junction1, isInputOrdered(consumerOrdered, 1));
  2222. //Assumes input1 will be stranded if any.
  2223. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
  2224. }
  2225. };
  2226. //=================================================================================
  2227. class CRoxieServerMultiInputBaseActivity : public CRoxieServerActivity
  2228. {
  2229. protected:
  2230. unsigned numInputs;
  2231. unsigned numStreams;
  2232. IFinalRoxieInput **inputArray;
  2233. unsigned *sourceIdxArray;
  2234. IEngineRowStream **streamArray;
  2235. Owned<IStrandJunction> *junctionArray;
  2236. public:
  2237. CRoxieServerMultiInputBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  2238. : CRoxieServerActivity(_ctx, _factory, _probeManager), numInputs(_numInputs)
  2239. {
  2240. numStreams = numInputs;
  2241. inputArray = new IFinalRoxieInput*[numInputs];
  2242. sourceIdxArray = new unsigned[numInputs];
  2243. streamArray = new IEngineRowStream*[numStreams];
  2244. junctionArray = new Owned<IStrandJunction>[numStreams];
  2245. for (unsigned i1 = 0; i1 < numInputs; i1++)
  2246. {
  2247. inputArray[i1] = NULL;
  2248. sourceIdxArray[i1] = 0;
  2249. }
  2250. for (unsigned i2 = 0; i2 < numStreams; i2++)
  2251. streamArray[i2] = NULL;
  2252. }
  2253. ~CRoxieServerMultiInputBaseActivity()
  2254. {
  2255. delete [] inputArray;
  2256. delete [] sourceIdxArray;
  2257. delete [] streamArray;
  2258. delete [] junctionArray;
  2259. }
  2260. virtual unsigned __int64 queryLocalCycles() const
  2261. {
  2262. __int64 localCycles = totalCycles.totalCycles;
  2263. for (unsigned i = 0; i < numInputs; i++)
  2264. localCycles -= inputArray[i]->queryTotalCycles();
  2265. if (localCycles < 0)
  2266. localCycles = 0;
  2267. return localCycles;
  2268. }
  2269. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  2270. {
  2271. if (idx < numInputs)
  2272. return inputArray[idx];
  2273. else
  2274. return NULL;
  2275. }
  2276. virtual void reset()
  2277. {
  2278. for (unsigned i = 0; i < numInputs; i++)
  2279. inputArray[i]->reset();
  2280. for (unsigned iS = 0; iS < numStreams; iS++)
  2281. {
  2282. resetJunction(junctionArray[iS]);
  2283. }
  2284. CRoxieServerActivity::reset();
  2285. }
  2286. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  2287. {
  2288. assertex(idx < numInputs && idx < numStreams);
  2289. inputArray[idx] = _in;
  2290. sourceIdxArray[idx] = _sourceIdx;
  2291. }
  2292. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  2293. {
  2294. //There could be situations (e.g., NONEMPTY), where you might want to strand the activity.
  2295. for (unsigned i = 0; i < numInputs; i++)
  2296. streamArray[i] = connectSingleStream(ctx, inputArray[i], sourceIdxArray[i], junctionArray[i], consumerOrdered);
  2297. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, NULL, consumerOrdered, nullptr); // The input basesclass does not have an input
  2298. }
  2299. };
  2300. //=================================================================================
  2301. class CRoxieServerMultiInputActivity : public CRoxieServerMultiInputBaseActivity
  2302. {
  2303. public:
  2304. CRoxieServerMultiInputActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  2305. : CRoxieServerMultiInputBaseActivity(_ctx, _factory, _probeManager, _numInputs)
  2306. {
  2307. }
  2308. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  2309. {
  2310. CRoxieServerMultiInputBaseActivity::start(parentExtractSize, parentExtract, paused);
  2311. for (unsigned i = 0; i < numInputs; i++)
  2312. {
  2313. inputArray[i]->start(parentExtractSize, parentExtract, paused);
  2314. }
  2315. for (unsigned iS = 0; iS < numStreams; iS++)
  2316. {
  2317. startJunction(junctionArray[iS]);
  2318. }
  2319. }
  2320. virtual void stop()
  2321. {
  2322. for (unsigned i = 0; i < numStreams; i++)
  2323. {
  2324. streamArray[i]->stop();
  2325. }
  2326. CRoxieServerMultiInputBaseActivity::stop();
  2327. }
  2328. };
  2329. //=====================================================================================================
  2330. class CRoxieServerInternalSinkActivity : public CRoxieServerActivity
  2331. {
  2332. protected:
  2333. unsigned numOutputs;
  2334. bool executed;
  2335. bool *stopped;
  2336. CriticalSection ecrit;
  2337. Owned<IException> exception;
  2338. public:
  2339. CRoxieServerInternalSinkActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  2340. : CRoxieServerActivity(_ctx, _factory, _probeManager), numOutputs(_numOutputs)
  2341. {
  2342. executed = false;
  2343. stopped = new bool[numOutputs];
  2344. for (unsigned s = 0; s < numOutputs; s++)
  2345. stopped[s] = false;
  2346. }
  2347. ~CRoxieServerInternalSinkActivity()
  2348. {
  2349. delete [] stopped;
  2350. }
  2351. virtual void reset()
  2352. {
  2353. for (unsigned s = 0; s < numOutputs; s++)
  2354. stopped[s] = false;
  2355. executed = false;
  2356. exception.clear();
  2357. CRoxieServerActivity::reset();
  2358. }
  2359. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  2360. {
  2361. return NULL;
  2362. }
  2363. virtual void stopSink(unsigned outputIdx)
  2364. {
  2365. if (!stopped[outputIdx])
  2366. {
  2367. stopped[outputIdx] = true;
  2368. for (unsigned s = 0; s < numOutputs; s++)
  2369. if (!stopped[s])
  2370. return;
  2371. stop(); // all outputs stopped - stop parent.
  2372. }
  2373. }
  2374. virtual const void *nextRow()
  2375. {
  2376. throwUnexpected(); // I am nobody's input
  2377. }
  2378. virtual void onExecute() = 0;
  2379. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  2380. {
  2381. CriticalBlock b(ecrit);
  2382. if (exception)
  2383. throw exception.getLink();
  2384. if (!executed)
  2385. {
  2386. try
  2387. {
  2388. start(parentExtractSize, parentExtract, false);
  2389. {
  2390. ActivityTimer t(totalCycles, timeActivities); // unfortunately this is not really best place for seeing in debugger.
  2391. onExecute();
  2392. }
  2393. stop();
  2394. executed = true;
  2395. }
  2396. catch (IException *E)
  2397. {
  2398. exception.set(E); // (or maybe makeWrappedException?)
  2399. abort();
  2400. throw;
  2401. }
  2402. catch (...)
  2403. {
  2404. exception.set(MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught at %s:%d", __FILE__, __LINE__));
  2405. abort();
  2406. throw;
  2407. }
  2408. }
  2409. }
  2410. };
  2411. //=================================================================================
  2412. class CRoxieServerQueryPacket : public CInterface, implements IRoxieServerQueryPacket
  2413. {
  2414. protected:
  2415. Owned<IMessageResult> result;
  2416. Owned<IRoxieQueryPacket> packet;
  2417. Linked<IRoxieServerQueryPacket> continuation;
  2418. unsigned hash;
  2419. unsigned seq;
  2420. unsigned lastDebugSequence;
  2421. Owned<IRoxieQueryPacket> lastDebugResponse;
  2422. ILRUChain *prev;
  2423. ILRUChain *next;
  2424. bool delayed;
  2425. public:
  2426. IMPLEMENT_IINTERFACE;
  2427. CRoxieServerQueryPacket(IRoxieQueryPacket *p) : packet(p)
  2428. {
  2429. hash = 0;
  2430. seq = 0;
  2431. prev = NULL;
  2432. next = NULL;
  2433. delayed = false;
  2434. lastDebugSequence = 0;
  2435. }
  2436. virtual IRoxieQueryPacket *queryPacket() const
  2437. {
  2438. return packet;
  2439. }
  2440. virtual bool isContinuation() const
  2441. {
  2442. return packet && (packet->queryHeader().continueSequence & ~CONTINUE_SEQUENCE_SKIPTO) != 0;
  2443. }
  2444. virtual bool isDelayed() const
  2445. {
  2446. return delayed;
  2447. }
  2448. virtual bool isEnd() const
  2449. {
  2450. return false;
  2451. }
  2452. virtual bool isLimit(unsigned __int64 &_rowLimit, unsigned __int64 &_keyedLimit, unsigned __int64 &_stopAfter) const
  2453. {
  2454. return false;
  2455. }
  2456. virtual bool hasResult() const
  2457. {
  2458. return result != NULL;
  2459. }
  2460. virtual bool hasContinuation() const
  2461. {
  2462. return continuation != NULL;
  2463. }
  2464. virtual void setDelayed(bool _delayed)
  2465. {
  2466. delayed = _delayed;
  2467. }
  2468. virtual void setPacket(IRoxieQueryPacket *_packet)
  2469. {
  2470. packet.setown(_packet);
  2471. }
  2472. virtual void setSequence(unsigned _seq)
  2473. {
  2474. assertex(!IsShared());
  2475. seq = _seq;
  2476. }
  2477. virtual unsigned getSequence() const
  2478. {
  2479. return seq;
  2480. }
  2481. IMessageResult *getResult()
  2482. {
  2483. return result.getLink();
  2484. }
  2485. IMessageResult *queryResult()
  2486. {
  2487. return result;
  2488. }
  2489. void setResult(IMessageResult *r)
  2490. {
  2491. result.setown(r);
  2492. }
  2493. IRoxieServerQueryPacket *queryContinuation()
  2494. {
  2495. return continuation;
  2496. }
  2497. void setContinuation(IRoxieServerQueryPacket *c)
  2498. {
  2499. continuation.setown(c);
  2500. }
  2501. virtual unsigned queryHash() const
  2502. {
  2503. return hash;
  2504. }
  2505. virtual void setHash(unsigned _hash)
  2506. {
  2507. hash = _hash;
  2508. }
  2509. virtual ILRUChain *queryPrev() const { return prev; }
  2510. virtual ILRUChain *queryNext() const { return next; }
  2511. virtual void setPrev(ILRUChain *p) { prev = p; }
  2512. virtual void setNext(ILRUChain *n) { next = n; }
  2513. virtual void unchain()
  2514. {
  2515. if (prev && next)
  2516. {
  2517. prev->setNext(next);
  2518. next->setPrev(prev);
  2519. }
  2520. next = NULL;
  2521. prev = NULL;
  2522. }
  2523. virtual IRoxieQueryPacket *getDebugResponse(unsigned sequence)
  2524. {
  2525. if (sequence == lastDebugSequence)
  2526. return lastDebugResponse.getLink();
  2527. else if (sequence > lastDebugSequence)
  2528. {
  2529. lastDebugResponse.clear();
  2530. return NULL;
  2531. }
  2532. else
  2533. throwUnexpected();
  2534. }
  2535. virtual void setDebugResponse(unsigned sequence, IRoxieQueryPacket *response)
  2536. {
  2537. lastDebugSequence = sequence;
  2538. lastDebugResponse.set(response);
  2539. }
  2540. };
  2541. class CRoxieServerQueryPacketEndMarker : public CRoxieServerQueryPacket
  2542. {
  2543. public:
  2544. CRoxieServerQueryPacketEndMarker() : CRoxieServerQueryPacket(NULL)
  2545. {
  2546. }
  2547. virtual bool isEnd() const
  2548. {
  2549. return true;
  2550. }
  2551. };
  2552. class CRoxieServerQueryPacketLimitMarker : public CRoxieServerQueryPacket
  2553. {
  2554. unsigned __int64 rowLimit;
  2555. unsigned __int64 keyedLimit;
  2556. unsigned __int64 stopAfter;
  2557. public:
  2558. CRoxieServerQueryPacketLimitMarker(unsigned __int64 _rowLimit, unsigned __int64 _keyedLimit, unsigned __int64 _stopAfter) : CRoxieServerQueryPacket(NULL)
  2559. {
  2560. rowLimit = _rowLimit;
  2561. keyedLimit = _keyedLimit;
  2562. stopAfter = _stopAfter;
  2563. }
  2564. virtual bool isLimit(unsigned __int64 &_rowLimit, unsigned __int64 &_keyedLimit, unsigned __int64 &_stopAfter) const
  2565. {
  2566. _rowLimit = rowLimit;
  2567. _keyedLimit = keyedLimit;
  2568. _stopAfter = stopAfter;
  2569. return true;
  2570. }
  2571. };
  2572. class CRoxieServerSideCache : implements IRoxieServerSideCache, implements ILRUChain
  2573. {
  2574. protected:
  2575. unsigned cacheTableSize;
  2576. unsigned cacheTableSpace;
  2577. IRoxieServerQueryPacket **cacheTable;
  2578. mutable ILRUChain *prev;
  2579. mutable ILRUChain *next;
  2580. mutable CriticalSection crit;
  2581. virtual ILRUChain *queryPrev() const { return prev; }
  2582. virtual ILRUChain *queryNext() const { return next; }
  2583. virtual void setPrev(ILRUChain *p) { prev = p; }
  2584. virtual void setNext(ILRUChain *n) { next = n; }
  2585. virtual void unchain()
  2586. {
  2587. prev->setNext(next);
  2588. next->setPrev(prev);
  2589. next = NULL;
  2590. prev = NULL;
  2591. }
  2592. void moveToHead(IRoxieServerQueryPacket *mru)
  2593. {
  2594. mru->unchain();
  2595. mru->setNext(next);
  2596. next->setPrev(mru);
  2597. mru->setPrev(this);
  2598. next = mru;
  2599. }
  2600. IRoxieServerQueryPacket *removeLRU()
  2601. {
  2602. if (next==this)
  2603. assertex(next != this);
  2604. IRoxieServerQueryPacket *goer = (IRoxieServerQueryPacket *) next;
  2605. goer->unchain(); // NOTE - this will modify the value of next
  2606. return goer;
  2607. }
  2608. void removeEntry(IRoxieServerQueryPacket *goer)
  2609. {
  2610. unsigned v = goer->queryHash() % cacheTableSize;
  2611. loop
  2612. {
  2613. IRoxieServerQueryPacket *found = cacheTable[v];
  2614. assertex(found);
  2615. if (found == goer)
  2616. {
  2617. cacheTable[v] = NULL;
  2618. unsigned vn = v;
  2619. loop
  2620. {
  2621. vn++;
  2622. if (vn==cacheTableSize) vn = 0;
  2623. IRoxieServerQueryPacket *found2 = cacheTable[vn];
  2624. if (!found2)
  2625. break;
  2626. unsigned vm = found2->queryHash() % cacheTableSize;
  2627. if (((vn+cacheTableSize-vm) % cacheTableSize)>=((vn+cacheTableSize-v) % cacheTableSize)) // diff(vn,vm)>=diff(vn,v)
  2628. {
  2629. cacheTable[v] = found2;
  2630. v = vn;
  2631. cacheTable[v] = NULL;
  2632. }
  2633. }
  2634. cacheTableSpace++;
  2635. break;
  2636. }
  2637. v++;
  2638. if (v==cacheTableSize)
  2639. v = 0;
  2640. }
  2641. goer->Release();
  2642. }
  2643. public:
  2644. CRoxieServerSideCache(unsigned _cacheSize)
  2645. {
  2646. cacheTableSize = (_cacheSize*4)/3;
  2647. cacheTable = new IRoxieServerQueryPacket *[cacheTableSize];
  2648. memset(cacheTable, 0, cacheTableSize * sizeof(IRoxieServerQueryPacket *));
  2649. cacheTableSpace = _cacheSize;
  2650. prev = this;
  2651. next = this;
  2652. }
  2653. ~CRoxieServerSideCache()
  2654. {
  2655. for (unsigned i = 0; i < cacheTableSize; i++)
  2656. {
  2657. ::Release(cacheTable[i]);
  2658. }
  2659. delete [] cacheTable;
  2660. }
  2661. virtual IRoxieServerQueryPacket *findCachedResult(const IRoxieContextLogger &logctx, IRoxieQueryPacket *p) const
  2662. {
  2663. unsigned hash = p->hash();
  2664. unsigned et = hash % cacheTableSize;
  2665. if (traceServerSideCache)
  2666. {
  2667. StringBuffer s;
  2668. logctx.CTXLOG("CRoxieServerSideCache::findCachedResult hash %x slot %d %s", hash, et, p->queryHeader().toString(s).str());
  2669. }
  2670. CriticalBlock b(crit);
  2671. loop
  2672. {
  2673. IRoxieServerQueryPacket *found = cacheTable[et];
  2674. if (!found)
  2675. return NULL;
  2676. if (found->queryHash() == hash && found->queryPacket()->cacheMatch(p))
  2677. {
  2678. const_cast<CRoxieServerSideCache *>(this)->moveToHead(found);
  2679. if (traceServerSideCache)
  2680. logctx.CTXLOG("CRoxieServerSideCache::findCachedResult cache hit");
  2681. logctx.noteStatistic(StNumServerCacheHits, 1);
  2682. return NULL;
  2683. // 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....
  2684. //IRoxieServerQueryPacket *ret = new CRoxieServerQueryPacket(p);
  2685. //ret->setResult(found->getResult());
  2686. //return ret;
  2687. }
  2688. et++;
  2689. if (et == cacheTableSize)
  2690. et = 0;
  2691. }
  2692. }
  2693. virtual void noteCachedResult(IRoxieServerQueryPacket *out, IMessageResult *in)
  2694. {
  2695. if (true) //!in->getLength()) // MORE - separate caches for hits and nohits
  2696. {
  2697. unsigned hash = out->queryPacket()->hash();
  2698. out->setHash(hash);
  2699. unsigned et = hash % cacheTableSize;
  2700. if (traceServerSideCache)
  2701. {
  2702. StringBuffer s;
  2703. DBGLOG("CRoxieServerSideCache::noteCachedResult hash %x slot %d %s", hash, et, out->queryPacket()->queryHeader().toString(s).str());
  2704. }
  2705. CriticalBlock b(crit);
  2706. loop
  2707. {
  2708. IRoxieServerQueryPacket *found = cacheTable[et];
  2709. if (!found)
  2710. {
  2711. if (cacheTableSpace)
  2712. {
  2713. out->setResult(LINK(in));
  2714. cacheTable[et] = LINK(out);
  2715. cacheTableSpace--;
  2716. moveToHead(out);
  2717. break;
  2718. }
  2719. else
  2720. {
  2721. IRoxieServerQueryPacket *goer = removeLRU();
  2722. removeEntry(goer);
  2723. et = hash % cacheTableSize;
  2724. continue;
  2725. }
  2726. }
  2727. else if (found->queryHash()==hash && found->queryPacket()->cacheMatch(out->queryPacket()))
  2728. {
  2729. moveToHead(found);
  2730. return; // already in the cache. Because we don't cache until we have result, this can happen where
  2731. // multiple copies of a slave query are in-flight at once.
  2732. }
  2733. et++;
  2734. if (et == cacheTableSize)
  2735. et = 0;
  2736. }
  2737. }
  2738. // MORE - do we need to worry about the attachment between the MessageUnpacker and the current row manager. May all fall out ok...
  2739. // Can I easily spot a null result? Do I want to cache null results separately? only?
  2740. }
  2741. // Note that this caching mechanism (unlike the old keyed-join specific one) does not common up cases where multiple
  2742. // identical queries are in-flight at the same time. But if we can make it persistent between queries that will
  2743. // more than make up for it
  2744. };
  2745. class CRowArrayMessageUnpackCursor : public CInterface, implements IMessageUnpackCursor
  2746. {
  2747. ConstPointerArray &data;
  2748. Linked<IMessageResult> result;
  2749. public:
  2750. IMPLEMENT_IINTERFACE;
  2751. CRowArrayMessageUnpackCursor(ConstPointerArray &_data, IMessageResult *_result)
  2752. : data(_data), result(_result)
  2753. {
  2754. }
  2755. virtual bool atEOF() const
  2756. {
  2757. return data.length()==0;
  2758. }
  2759. virtual bool isSerialized() const
  2760. {
  2761. return false;
  2762. }
  2763. virtual const void * getNext(int length)
  2764. {
  2765. if (!data.length())
  2766. return NULL;
  2767. const void *ret = data.item(0);
  2768. data.remove(0);
  2769. return ret;
  2770. }
  2771. };
  2772. // MORE - should possibly move more over to the lazy version used in indexread?
  2773. class CRowArrayMessageResult : public CInterface, implements IMessageResult
  2774. {
  2775. ConstPointerArray data;
  2776. IRowManager &rowManager;
  2777. bool variableSize;
  2778. public:
  2779. IMPLEMENT_IINTERFACE;
  2780. CRowArrayMessageResult(IRowManager &_rowManager, bool _variableSize) : rowManager(_rowManager), variableSize(_variableSize)
  2781. {
  2782. }
  2783. ~CRowArrayMessageResult()
  2784. {
  2785. ReleaseRoxieRows(data);
  2786. }
  2787. virtual IMessageUnpackCursor *getCursor(IRowManager *rowMgr) const
  2788. {
  2789. CRowArrayMessageResult *_this = (CRowArrayMessageResult *) this;
  2790. return new CRowArrayMessageUnpackCursor(_this->data, _this);
  2791. }
  2792. virtual const void *getMessageHeader(unsigned &length) const
  2793. {
  2794. throwUnexpected(); // should never get called - I don't have a header available
  2795. length = 0;
  2796. return NULL;
  2797. }
  2798. virtual const void *getMessageMetadata(unsigned &length) const
  2799. {
  2800. length = 0;
  2801. return NULL;
  2802. }
  2803. virtual void discard() const
  2804. {
  2805. throwUnexpected();
  2806. }
  2807. void append(const void *row)
  2808. {
  2809. data.append(row);
  2810. }
  2811. };
  2812. void throwRemoteException(IMessageUnpackCursor *extra)
  2813. {
  2814. RecordLengthType *rowlen = (RecordLengthType *) extra->getNext(sizeof(RecordLengthType));
  2815. if (rowlen)
  2816. {
  2817. char *xml = (char *) extra->getNext(*rowlen);
  2818. ReleaseRoxieRow(rowlen);
  2819. Owned<IPropertyTree> p = createPTreeFromXMLString(xml);
  2820. ReleaseRoxieRow(xml);
  2821. unsigned code = p->getPropInt("Code", 0);
  2822. const char *msg = p->queryProp("Message");
  2823. if (!msg)
  2824. msg = xml;
  2825. throw MakeStringException(code, "%s", msg);
  2826. }
  2827. throwUnexpected();
  2828. }
  2829. class CRemoteResultAdaptor :public CInterface, implements IFinalRoxieInput, implements IExceptionHandler, implements IEngineRowStream
  2830. {
  2831. friend class CRemoteResultMerger;
  2832. class CRemoteResultMerger
  2833. {
  2834. class HeapEntry : public CInterface
  2835. {
  2836. private:
  2837. CRemoteResultAdaptor &adaptor;
  2838. IMessageUnpackCursor *cursor;
  2839. public:
  2840. const void *current;
  2841. bool isLast;
  2842. bool lastIsComplete;
  2843. IRoxieServerQueryPacket *packet;
  2844. unsigned seq;
  2845. public:
  2846. inline const void *noteResult(IMessageUnpackCursor *_cursor, bool _lastIsComplete)
  2847. {
  2848. cursor = _cursor;
  2849. lastIsComplete = _lastIsComplete;
  2850. return next();
  2851. }
  2852. public:
  2853. HeapEntry(CRemoteResultAdaptor &_adaptor, IRoxieServerQueryPacket *_packet, unsigned _seq) : adaptor(_adaptor), packet(_packet), seq(_seq)
  2854. {
  2855. cursor = NULL;
  2856. current = NULL;
  2857. isLast = false;
  2858. lastIsComplete = true;
  2859. }
  2860. ~HeapEntry()
  2861. {
  2862. ::Release(packet);
  2863. ::Release(cursor);
  2864. ReleaseRoxieRow(current);
  2865. }
  2866. bool isCompleteMatch() const
  2867. {
  2868. if (!isLast || lastIsComplete)
  2869. return true;
  2870. else
  2871. return false;
  2872. }
  2873. const void *next()
  2874. {
  2875. if (cursor)
  2876. {
  2877. ReleaseClearRoxieRow(current);
  2878. current = adaptor.getRow(cursor);
  2879. isLast = cursor->atEOF();
  2880. if (!current)
  2881. {
  2882. cursor->Release();
  2883. cursor = NULL;
  2884. }
  2885. }
  2886. return current;
  2887. }
  2888. unsigned skipTo(IRangeCompare *compare, const void *seek, unsigned numFields, bool requireExactMatch)
  2889. {
  2890. // MORE - This loop should possibly be a binchop... though it's not absolutely clear that is true (depends on term frequencies)
  2891. unsigned skipped = 0;
  2892. loop
  2893. {
  2894. int c = compare->docompare(current, seek, numFields);
  2895. //If larger than the seek values, then we may be allowed to return an inexact match,
  2896. //if equal then it is required to be an exact match,
  2897. if (c > 0)
  2898. {
  2899. if (!requireExactMatch || isCompleteMatch())
  2900. break;
  2901. }
  2902. else if ((c == 0) && isCompleteMatch())
  2903. break;
  2904. skipped++;
  2905. if (!next())
  2906. break;
  2907. }
  2908. return skipped;
  2909. }
  2910. };
  2911. CRemoteResultAdaptor &adaptor;
  2912. CIArrayOf<HeapEntry> heapEntries;
  2913. UnsignedArray heap;
  2914. IRowManager *rowManager;
  2915. unsigned numPending;
  2916. unsigned numFields;
  2917. bool endSeen;
  2918. bool remakePending;
  2919. IRangeCompare *compare;
  2920. bool deferredContinuation;
  2921. inline int doCompare(unsigned l, unsigned r)
  2922. {
  2923. int ret = compare->docompare(heapEntries.item(l).current, heapEntries.item(r).current, numFields);
  2924. if (!ret) ret = heapEntries.item(l).seq - heapEntries.item(r).seq;
  2925. return ret;
  2926. }
  2927. void makeHeap()
  2928. {
  2929. /* Permute blocks to establish the heap property
  2930. For each element p, the children are p*2+1 and p*2+2 (provided these are in range)
  2931. The children of p must both be greater than or equal to p
  2932. The parent of a child c is given by p = (c-1)/2
  2933. */
  2934. unsigned i;
  2935. unsigned n = heap.length();
  2936. unsigned *s = heap.getArray();
  2937. for (i=1; i<n; i++)
  2938. {
  2939. unsigned r = s[i];
  2940. int c = i; /* child */
  2941. while (c > 0)
  2942. {
  2943. int p = (c-1)/2; /* parent */
  2944. if ( doCompare( s[c], s[p] ) >= 0 )
  2945. break;
  2946. s[c] = s[p];
  2947. s[p] = r;
  2948. c = p;
  2949. }
  2950. }
  2951. remakePending = false;
  2952. }
  2953. void remakeHeap()
  2954. {
  2955. /* The row associated with block[0] will have changed
  2956. This code restores the heap property
  2957. */
  2958. unsigned p = 0; /* parent */
  2959. unsigned n = heap.length();
  2960. unsigned *s = heap.getArray();
  2961. while (1)
  2962. {
  2963. unsigned c = p*2 + 1; /* child */
  2964. if ( c >= n )
  2965. break;
  2966. /* Select smaller child */
  2967. if ( c+1 < n && doCompare( s[c+1], s[c] ) < 0 ) c += 1;
  2968. /* If child is greater or equal than parent then we are done */
  2969. if ( doCompare( s[c], s[p] ) >= 0 )
  2970. break;
  2971. /* Swap parent and child */
  2972. unsigned r = s[c];
  2973. s[c] = s[p];
  2974. s[p] = r;
  2975. /* child becomes parent */
  2976. p = c;
  2977. }
  2978. remakePending = false;
  2979. }
  2980. void append(IRoxieServerQueryPacket *p, unsigned seq)
  2981. {
  2982. HeapEntry &h = *new HeapEntry(adaptor, LINK(p), seq);
  2983. IMessageResult *result = p->queryResult();
  2984. assertex(result);
  2985. if (h.noteResult(result->getCursor(rowManager), isCompleteMatchFlag(result)))
  2986. {
  2987. heapEntries.append(h);
  2988. heap.append(heap.ordinality());
  2989. }
  2990. else
  2991. h.Release();
  2992. }
  2993. void removeHeap(unsigned idx)
  2994. {
  2995. heapEntries.remove(idx);
  2996. ForEachItemIn(i, heap)
  2997. {
  2998. unsigned v = heap.item(i);
  2999. assertex(v != idx);
  3000. if (v > idx)
  3001. heap.replace(v-1, i);
  3002. }
  3003. }
  3004. bool isCompleteMatchFlag(IMessageResult *result)
  3005. {
  3006. unsigned metaLen;
  3007. const byte *metaInfo = (const byte *) result->getMessageMetadata(metaLen);
  3008. if (metaLen)
  3009. {
  3010. unsigned short continuationLen = *(unsigned short *) metaInfo;
  3011. if (continuationLen >= sizeof(bool))
  3012. {
  3013. metaInfo += sizeof(unsigned short);
  3014. return *(bool *) metaInfo;
  3015. }
  3016. }
  3017. return true; // if no continuation info, last row was complete.
  3018. }
  3019. public:
  3020. CRemoteResultMerger(CRemoteResultAdaptor &_adaptor) : adaptor(_adaptor)
  3021. {
  3022. init(NULL, NULL);
  3023. }
  3024. void init(ISteppingMeta *meta, IRowManager *_rowManager)
  3025. {
  3026. if (meta)
  3027. {
  3028. numFields = meta->getNumFields();
  3029. compare = meta->queryCompare();
  3030. }
  3031. else
  3032. {
  3033. numFields = 0;
  3034. compare = NULL;
  3035. }
  3036. rowManager = _rowManager;
  3037. numPending = 0;
  3038. endSeen = false;
  3039. remakePending = false;
  3040. deferredContinuation = false;
  3041. }
  3042. void reset()
  3043. {
  3044. heapEntries.kill();
  3045. heap.kill();
  3046. numPending = 0;
  3047. endSeen = false;
  3048. remakePending = false;
  3049. deferredContinuation = false;
  3050. }
  3051. inline bool noteEndSeen()
  3052. {
  3053. bool hadSeen = endSeen;
  3054. if (!endSeen)
  3055. makeHeap();
  3056. endSeen = true;
  3057. return !hadSeen;
  3058. }
  3059. void noteResult(IRoxieServerQueryPacket *p, unsigned seq)
  3060. {
  3061. if (!p->isContinuation())
  3062. append(p, seq);
  3063. else
  3064. {
  3065. ForEachItemIn(idx, heapEntries)
  3066. {
  3067. HeapEntry &h = heapEntries.item(idx);
  3068. if (h.packet == p)
  3069. {
  3070. IMessageResult *result = p->queryResult();
  3071. if (!h.noteResult(result->getCursor(rowManager), isCompleteMatchFlag(result)))
  3072. {
  3073. heap.zap(idx);
  3074. removeHeap(idx);
  3075. }
  3076. numPending--;
  3077. if (!numPending)
  3078. makeHeap();
  3079. return;
  3080. }
  3081. }
  3082. }
  3083. // If we get here it must be a continuation for one that I have not yet consumed... we don't need to do anything.
  3084. return;
  3085. }
  3086. unsigned skipRows(unsigned &idx, const void *seek, const void *rawSeek, unsigned numFields, unsigned seekLen, const SmartStepExtra & stepExtra)
  3087. {
  3088. HeapEntry &entry = heapEntries.item(idx);
  3089. unsigned skipped = entry.current ? entry.skipTo(compare, seek, numFields, !stepExtra.returnMismatches()) : 0;
  3090. if (!entry.current)
  3091. {
  3092. IRoxieServerQueryPacket *continuation = entry.packet->queryContinuation();
  3093. if (continuation)
  3094. {
  3095. continuation->Link();
  3096. entry.packet->Release();
  3097. entry.packet = continuation;
  3098. if (continuation->hasResult())
  3099. {
  3100. IMessageResult *result = continuation->queryResult();
  3101. bool lastIsCompleteMatch = isCompleteMatchFlag(result);
  3102. entry.noteResult(result->getCursor(rowManager), lastIsCompleteMatch);
  3103. }
  3104. else
  3105. {
  3106. if (continuation->isDelayed())
  3107. {
  3108. continuation->setDelayed(false);
  3109. MemoryBuffer serializedSkip;
  3110. adaptor.activity.serializeSkipInfo(serializedSkip, seekLen, rawSeek, numFields, seek, stepExtra);
  3111. continuation->setPacket(continuation->queryPacket()->insertSkipData(serializedSkip.length(), serializedSkip.toByteArray()));
  3112. ROQ->sendPacket(continuation->queryPacket(), adaptor.activity.queryLogCtx());
  3113. adaptor.sentsome.signal();
  3114. }
  3115. numPending++;
  3116. }
  3117. }
  3118. else
  3119. {
  3120. heap.zap(idx);
  3121. removeHeap(idx);
  3122. idx--;
  3123. }
  3124. }
  3125. return skipped;
  3126. }
  3127. const void * nextRowGE(const void * seek, const void *rawSeek, unsigned numFields, unsigned seeklen, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  3128. {
  3129. // We discard all rows < seekval from all entries in heap
  3130. // If this results in additional slave requests, we return NULL so that we can wait for them
  3131. // If not, we rebuild the heap (if any were skipped) and return the first row
  3132. deferredContinuation = false;
  3133. if (heap.length())
  3134. {
  3135. unsigned skipped = 0;
  3136. unsigned idx = 0;
  3137. while(heapEntries.isItem(idx))
  3138. {
  3139. skipped += skipRows(idx, seek, rawSeek, numFields, seeklen, stepExtra);
  3140. idx++;
  3141. }
  3142. if (numPending)
  3143. return NULL; // can't answer yet, need more results from slaves
  3144. else
  3145. {
  3146. if (skipped)
  3147. makeHeap();
  3148. return next(wasCompleteMatch, stepExtra);
  3149. }
  3150. }
  3151. else
  3152. return NULL;
  3153. }
  3154. bool doContinuation(HeapEntry &topEntry, bool canDefer)
  3155. {
  3156. IRoxieServerQueryPacket *continuation = topEntry.packet->queryContinuation();
  3157. if (continuation)
  3158. {
  3159. if (continuation->isDelayed() && canDefer)
  3160. {
  3161. if (adaptor.activity.queryLogCtx().queryTraceLevel() > 10)
  3162. adaptor.activity.queryLogCtx().CTXLOG("Deferring continuation");
  3163. deferredContinuation = true;
  3164. }
  3165. else
  3166. {
  3167. deferredContinuation = false;
  3168. continuation->Link();
  3169. topEntry.packet->Release();
  3170. topEntry.packet = continuation;
  3171. if (continuation->hasResult())
  3172. {
  3173. IMessageResult *result = continuation->queryResult();
  3174. bool lastIsCompleteMatch = isCompleteMatchFlag(result);
  3175. topEntry.noteResult(result->getCursor(rowManager), lastIsCompleteMatch);
  3176. }
  3177. else
  3178. {
  3179. if (continuation->isDelayed()) // has the continuation been requested yet?
  3180. {
  3181. continuation->Link();
  3182. topEntry.packet->Release();
  3183. topEntry.packet = continuation;
  3184. continuation->setDelayed(false);
  3185. if (adaptor.activity.queryLogCtx().queryTraceLevel() > 10)
  3186. adaptor.activity.queryLogCtx().CTXLOG("About to send continuation, from doContinuation");
  3187. ROQ->sendPacket(continuation->queryPacket(), adaptor.activity.queryLogCtx());
  3188. adaptor.sentsome.signal();
  3189. }
  3190. numPending++; // we are waiting for one that is already in flight
  3191. }
  3192. }
  3193. return true; // next not known yet
  3194. }
  3195. else
  3196. return false;
  3197. }
  3198. const void *next(bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  3199. {
  3200. OwnedConstRoxieRow ret;
  3201. if (heap.length())
  3202. {
  3203. if (deferredContinuation)
  3204. {
  3205. unsigned top = heap.item(0);
  3206. HeapEntry &topEntry = heapEntries.item(top);
  3207. doContinuation(topEntry, false);
  3208. return NULL;
  3209. }
  3210. if (remakePending)
  3211. remakeHeap();
  3212. unsigned top = heap.item(0);
  3213. HeapEntry &topEntry = heapEntries.item(top);
  3214. ret.set(topEntry.current);
  3215. wasCompleteMatch = topEntry.isCompleteMatch();
  3216. const void *next = topEntry.next();
  3217. if (!next)
  3218. {
  3219. if (!doContinuation(topEntry, stepExtra.returnMismatches()))
  3220. {
  3221. unsigned last = heap.popGet();
  3222. if (heap.length())
  3223. heap.replace(last, 0);
  3224. removeHeap(top);
  3225. }
  3226. }
  3227. remakePending = true;
  3228. }
  3229. return ret.getClear();
  3230. }
  3231. bool ready()
  3232. {
  3233. return endSeen && numPending == 0;
  3234. }
  3235. };
  3236. IRoxieServerQueryPacket *createRoxieServerQueryPacket(IRoxieQueryPacket *p, bool &cached)
  3237. {
  3238. if (serverSideCache && !debugContext)
  3239. {
  3240. IRoxieServerQueryPacket *ret = serverSideCache->findCachedResult(activity.queryLogCtx(), p);
  3241. if (ret)
  3242. {
  3243. p->Release();
  3244. cached = true;
  3245. return ret;
  3246. }
  3247. }
  3248. cached = false;
  3249. return new CRoxieServerQueryPacket(p);
  3250. }
  3251. #ifdef _DEBUG
  3252. void dumpPending()
  3253. {
  3254. CriticalBlock b(pendingCrit);
  3255. ForEachItemIn(idx, pending)
  3256. {
  3257. IRoxieServerQueryPacket &p = pending.item(idx);
  3258. StringBuffer s;
  3259. unsigned __int64 dummy;
  3260. if (p.isEnd())
  3261. s.append("END");
  3262. else if (p.isLimit(dummy, dummy, dummy))
  3263. s.append("LIMIT");
  3264. else
  3265. {
  3266. IRoxieQueryPacket *i = p.queryPacket();
  3267. s.appendf("%s", p.hasResult() ? "COMPLETE " : "PENDING ");
  3268. if (i)
  3269. {
  3270. RoxiePacketHeader &header = i->queryHeader();
  3271. header.toString(s);
  3272. }
  3273. }
  3274. DBGLOG("Pending %d %s", idx, s.str());
  3275. }
  3276. }
  3277. #endif
  3278. void abortPending()
  3279. {
  3280. CriticalBlock b(pendingCrit);
  3281. ForEachItemIn(idx, pending)
  3282. {
  3283. IRoxieServerQueryPacket &p = pending.item(idx);
  3284. if (!p.hasResult())
  3285. {
  3286. IRoxieQueryPacket *i = p.queryPacket();
  3287. if (i)
  3288. {
  3289. RoxiePacketHeader &header = i->queryHeader();
  3290. ROQ->sendAbort(header, activity.queryLogCtx());
  3291. }
  3292. }
  3293. }
  3294. pending.kill();
  3295. }
  3296. void checkDelayed()
  3297. {
  3298. if (ctx->queryDebugContext() && ctx->queryDebugContext()->getExecuteSequentially())
  3299. {
  3300. bool allDelayed = true;
  3301. CriticalBlock b(pendingCrit);
  3302. unsigned sendIdx = (unsigned) -1;
  3303. ForEachItemIn(idx, pending)
  3304. {
  3305. IRoxieServerQueryPacket &p = pending.item(idx);
  3306. if (p.queryPacket())
  3307. {
  3308. if (p.isDelayed())
  3309. {
  3310. if (sendIdx == (unsigned) -1)
  3311. sendIdx = idx;
  3312. }
  3313. else if (!p.hasResult())
  3314. {
  3315. allDelayed = false;
  3316. break;
  3317. }
  3318. }
  3319. }
  3320. if (allDelayed && sendIdx != (unsigned) -1)
  3321. {
  3322. if (activity.queryLogCtx().queryTraceLevel() > 10)
  3323. activity.queryLogCtx().CTXLOG("About to send debug-deferred from next");
  3324. pending.item(sendIdx).setDelayed(false);
  3325. ROQ->sendPacket(pending.item(sendIdx).queryPacket(), activity.queryLogCtx());
  3326. sentsome.signal();
  3327. }
  3328. }
  3329. else if (deferredStart)
  3330. {
  3331. CriticalBlock b(pendingCrit);
  3332. ForEachItemIn(idx, pending)
  3333. {
  3334. IRoxieServerQueryPacket &p = pending.item(idx);
  3335. if (p.isDelayed())
  3336. {
  3337. if (activity.queryLogCtx().queryTraceLevel() > 10)
  3338. activity.queryLogCtx().CTXLOG("About to send deferred start from next");
  3339. p.setDelayed(false);
  3340. ROQ->sendPacket(p.queryPacket(), activity.queryLogCtx());
  3341. sentsome.signal();
  3342. }
  3343. }
  3344. deferredStart = false;
  3345. }
  3346. }
  3347. void retryPending()
  3348. {
  3349. CriticalBlock b(pendingCrit);
  3350. checkDelayed();
  3351. ForEachItemIn(idx, pending)
  3352. {
  3353. IRoxieServerQueryPacket &p = pending.item(idx);
  3354. if (!p.hasResult() && !p.isDelayed())
  3355. {
  3356. IRoxieQueryPacket *i = p.queryPacket();
  3357. if (i)
  3358. {
  3359. if (!i->queryHeader().retry())
  3360. {
  3361. StringBuffer s;
  3362. 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());
  3363. activity.queryLogCtx().logOperatorException(E, __FILE__, __LINE__, "CRemoteResultAdaptor::retry");
  3364. throw E;
  3365. }
  3366. if (!localSlave)
  3367. {
  3368. ROQ->sendPacket(i, activity.queryLogCtx());
  3369. atomic_inc(&retriesSent);
  3370. }
  3371. }
  3372. }
  3373. }
  3374. }
  3375. class ChannelBuffer
  3376. {
  3377. protected:
  3378. unsigned bufferLeft;
  3379. MemoryBuffer buffer;
  3380. char *nextBuf;
  3381. unsigned overflowSequence;
  3382. unsigned channel; // == bonded channel
  3383. bool needsFlush;
  3384. InterruptableSemaphore flowController;
  3385. const CRemoteResultAdaptor &owner;
  3386. CriticalSection crit;
  3387. public:
  3388. ChannelBuffer(const CRemoteResultAdaptor &_owner, unsigned _channel) : owner(_owner), channel(_channel), flowController(perChannelFlowLimit)
  3389. {
  3390. overflowSequence = 0;
  3391. needsFlush = false;
  3392. bufferLeft = 0;
  3393. nextBuf = NULL;
  3394. }
  3395. void init(unsigned minSize)
  3396. {
  3397. assertex(!buffer.length());
  3398. if (minSize < MIN_PAYLOAD_SIZE)
  3399. minSize = MIN_PAYLOAD_SIZE;
  3400. unsigned headerSize = sizeof(RoxiePacketHeader)+owner.headerLength();
  3401. unsigned bufferSize = headerSize+minSize;
  3402. if (bufferSize < mtu_size)
  3403. bufferSize = mtu_size;
  3404. buffer.reserveTruncate(bufferSize);
  3405. bufferLeft = bufferSize - headerSize;
  3406. assertex(buffer.toByteArray());
  3407. nextBuf = (char *) buffer.toByteArray() + headerSize;
  3408. needsFlush = false;
  3409. }
  3410. inline IRoxieQueryPacket *flush()
  3411. {
  3412. CriticalBlock cb(crit);
  3413. Owned<IRoxieQueryPacket> ret;
  3414. if (needsFlush)
  3415. {
  3416. buffer.setLength(nextBuf - buffer.toByteArray());
  3417. RoxiePacketHeader *h = (RoxiePacketHeader *) buffer.toByteArray();
  3418. h->init(owner.remoteId, owner.ruid, channel, overflowSequence);
  3419. //patch logPrefix, cachedContext and parent extract into the place reserved in the message buffer
  3420. byte * tgt = (byte*)(h+1);
  3421. owner.copyHeader(tgt, channel);
  3422. ret.setown(createRoxiePacket(buffer));
  3423. if (overflowSequence == OVERFLOWSEQUENCE_MAX)
  3424. overflowSequence = 1; // don't wrap to 0 - that is a bit special
  3425. else
  3426. overflowSequence++;
  3427. needsFlush = false;
  3428. bufferLeft = 0;
  3429. if (owner.flowControlled)
  3430. {
  3431. CriticalUnblock cub(crit);
  3432. while (!flowController.wait(1000))
  3433. {
  3434. StringBuffer s;
  3435. owner.activity.queryLogCtx().CTXLOG("Channel %d blocked by flow control: %s", channel, h->toString(s).str());
  3436. }
  3437. }
  3438. }
  3439. return ret.getClear();
  3440. }
  3441. inline void signal()
  3442. {
  3443. if (owner.flowControlled)
  3444. flowController.signal();
  3445. }
  3446. inline void interrupt(IException *e)
  3447. {
  3448. flowController.interrupt(e);
  3449. }
  3450. inline void *getBuffer(unsigned size)
  3451. {
  3452. CriticalBlock cb(crit);
  3453. if (bufferLeft >= size)
  3454. {
  3455. needsFlush = true;
  3456. void * ret = nextBuf;
  3457. nextBuf += size;
  3458. bufferLeft -= size;
  3459. return ret;
  3460. }
  3461. else if (!needsFlush)
  3462. {
  3463. init(size);
  3464. return getBuffer(size);
  3465. }
  3466. else if (owner.mergeOrder)
  3467. {
  3468. return buffer.reserve(size); // whole query needs to go as single packet if we are to merge
  3469. }
  3470. else
  3471. return NULL; // will force it to flush and start a new packet
  3472. }
  3473. };
  3474. private:
  3475. friend class CRemoteResultMerger;
  3476. bool allread;
  3477. bool contextCached;
  3478. bool preserveOrder;
  3479. InterruptableSemaphore sentsome;
  3480. Owned <IMessageCollator> mc;
  3481. Owned<IMessageUnpackCursor> mu;
  3482. Owned<IMessageResult> mr;
  3483. ChannelBuffer **buffers;
  3484. IHThorArg &helper;
  3485. unsigned __int64 stopAfter;
  3486. unsigned resendSequence;
  3487. IHThorArg *colocalArg;
  3488. IArrayOf<IRoxieServerQueryPacket> pending;
  3489. CriticalSection pendingCrit;
  3490. IRoxieServerSideCache *serverSideCache;
  3491. unsigned sentSequence;
  3492. Owned<IOutputRowDeserializer> deserializer;
  3493. Owned<IEngineRowAllocator> rowAllocator;
  3494. CRemoteResultMerger merger;
  3495. // this is only used to avoid recreating a bufferStream for each row. A better solution may be needed
  3496. MemoryBuffer tempRowBuffer;
  3497. Owned<ISerialStream> bufferStream;
  3498. CThorStreamDeserializerSource rowSource;
  3499. protected:
  3500. IRowManager *rowManager;
  3501. unsigned __int64 rowLimit;
  3502. unsigned __int64 keyedLimit;
  3503. IRoxieServerErrorHandler *errorHandler;
  3504. CachedOutputMetaData meta;
  3505. public:
  3506. ISteppingMeta *mergeOrder;
  3507. IRoxieSlaveContext *ctx;
  3508. IDebuggableContext *debugContext;
  3509. IRoxieServerActivity &activity;
  3510. unsigned parentExtractSize;
  3511. const byte * parentExtract;
  3512. bool flowControlled;
  3513. bool deferredStart;
  3514. MemoryBuffer logInfo;
  3515. MemoryBuffer cachedContext;
  3516. const RemoteActivityId &remoteId;
  3517. ruid_t ruid;
  3518. mutable CriticalSection buffersCrit;
  3519. unsigned processed;
  3520. cycle_t totalCycles;
  3521. bool timeActivities;
  3522. //private: //vc6 doesn't like this being private yet accessed by nested class...
  3523. const void *getRow(IMessageUnpackCursor *mu)
  3524. {
  3525. if (!mu->isSerialized() || (meta.isFixedSize() && !deserializer))
  3526. return mu->getNext(meta.getFixedSize());
  3527. else
  3528. {
  3529. RecordLengthType *rowlen = (RecordLengthType *) mu->getNext(sizeof(RecordLengthType));
  3530. if (rowlen)
  3531. {
  3532. RecordLengthType len = *rowlen;
  3533. ReleaseRoxieRow(rowlen);
  3534. const void *slaveRec = mu->getNext(len);
  3535. if (deserializer && mu->isSerialized())
  3536. {
  3537. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  3538. tempRowBuffer.setBuffer(len, const_cast<void *>(slaveRec), false);
  3539. size_t outsize = deserializer->deserialize(rowBuilder, rowSource);
  3540. ReleaseRoxieRow(slaveRec);
  3541. return rowBuilder.finalizeRowClear(outsize);
  3542. }
  3543. else
  3544. return slaveRec;
  3545. }
  3546. else
  3547. return NULL;
  3548. }
  3549. }
  3550. private:
  3551. ChannelBuffer *queryChannelBuffer(unsigned channel, bool force=false)
  3552. {
  3553. CriticalBlock cb(buffersCrit);
  3554. ChannelBuffer *b = buffers[channel];
  3555. if (!b && force)
  3556. {
  3557. if (!contextCached)
  3558. {
  3559. logInfo.clear();
  3560. unsigned char loggingFlags = LOGGING_FLAGSPRESENT | LOGGING_TRACELEVELSET;
  3561. unsigned char ctxTraceLevel = activity.queryLogCtx().queryTraceLevel() + 1; // Avoid passing a 0
  3562. const QueryOptions &options = ctx->queryOptions();
  3563. if (activity.queryLogCtx().isIntercepted())
  3564. loggingFlags |= LOGGING_INTERCEPTED;
  3565. if (options.timeActivities)
  3566. loggingFlags |= LOGGING_TIMEACTIVITIES;
  3567. if (activity.queryLogCtx().isBlind())
  3568. loggingFlags |= LOGGING_BLIND;
  3569. if (options.checkingHeap)
  3570. loggingFlags |= LOGGING_CHECKINGHEAP;
  3571. if (ctx->queryWorkUnit())
  3572. loggingFlags |= LOGGING_WUID;
  3573. if (debugContext)
  3574. {
  3575. loggingFlags |= LOGGING_DEBUGGERACTIVE;
  3576. logInfo.append(loggingFlags).append(ctxTraceLevel);
  3577. MemoryBuffer bpInfo;
  3578. debugContext->serialize(bpInfo);
  3579. bpInfo.append((__uint64)(memsize_t) &activity);
  3580. logInfo.append((unsigned short) bpInfo.length());
  3581. logInfo.append(bpInfo.length(), bpInfo.toByteArray());
  3582. }
  3583. else
  3584. logInfo.append(loggingFlags).append(ctxTraceLevel);
  3585. StringBuffer logPrefix;
  3586. activity.queryLogCtx().getLogPrefix(logPrefix);
  3587. logInfo.append(logPrefix);
  3588. activity.serializeCreateStartContext(cachedContext.clear());
  3589. activity.serializeExtra(cachedContext);
  3590. if (activity.queryVarFileInfo())
  3591. {
  3592. activity.queryVarFileInfo()->queryTimeStamp().serialize(cachedContext);
  3593. cachedContext.append(activity.queryVarFileInfo()->queryCheckSum());
  3594. }
  3595. contextCached = true;
  3596. }
  3597. b = buffers[channel] = new ChannelBuffer(*this, channel);
  3598. }
  3599. return b;
  3600. }
  3601. void processRow(const void *got)
  3602. {
  3603. processed++;
  3604. if (processed > rowLimit)
  3605. {
  3606. ReleaseRoxieRow(got);
  3607. errorHandler->onLimitExceeded(false); // NOTE - should throw exception
  3608. throwUnexpected();
  3609. }
  3610. else if (processed > keyedLimit)
  3611. {
  3612. ReleaseRoxieRow(got);
  3613. errorHandler->onLimitExceeded(true); // NOTE - should throw exception
  3614. throwUnexpected();
  3615. }
  3616. }
  3617. public:
  3618. IMPLEMENT_IINTERFACE;
  3619. CRemoteResultAdaptor(IRoxieSlaveContext *_ctx, IRoxieServerErrorHandler *_errorHandler, const RemoteActivityId &_remoteId, IOutputMetaData *_meta, IHThorArg &_helper, IRoxieServerActivity &_activity, bool _preserveOrder, bool _flowControlled)
  3620. : remoteId(_remoteId), meta(_meta), activity(_activity), helper(_helper), preserveOrder(_preserveOrder), flowControlled(_flowControlled), merger(*this)
  3621. {
  3622. ctx = _ctx;
  3623. errorHandler = _errorHandler;
  3624. colocalArg = NULL;
  3625. allread = false;
  3626. ruid = 0;
  3627. rowLimit = (unsigned __int64) -1;
  3628. keyedLimit = (unsigned __int64) -1;
  3629. contextCached = false;
  3630. stopAfter = I64C(0x7FFFFFFFFFFFFFFF);
  3631. buffers = new ChannelBuffer*[numChannels+1];
  3632. memset(buffers, 0, (numChannels+1)*sizeof(ChannelBuffer *));
  3633. parentExtractSize = 0;
  3634. rowManager = NULL;
  3635. parentExtract = NULL;
  3636. debugContext = NULL;
  3637. mergeOrder = NULL;
  3638. deferredStart = false;
  3639. processed = 0;
  3640. sentSequence = 0;
  3641. resendSequence = 0;
  3642. totalCycles = 0;
  3643. serverSideCache = activity.queryServerSideCache();
  3644. bufferStream.setown(createMemoryBufferSerialStream(tempRowBuffer));
  3645. rowSource.setStream(bufferStream);
  3646. timeActivities = defaultTimeActivities;
  3647. }
  3648. ~CRemoteResultAdaptor()
  3649. {
  3650. if (mc)
  3651. {
  3652. ROQ->queryReceiveManager()->detachCollator(mc);
  3653. mc.clear();
  3654. }
  3655. for (unsigned channel = 0; channel <= numChannels; channel++)
  3656. {
  3657. delete(buffers[channel]);
  3658. }
  3659. delete [] buffers;
  3660. }
  3661. void setMeta(IOutputMetaData *newmeta)
  3662. {
  3663. meta.set(newmeta);
  3664. }
  3665. virtual IRoxieServerActivity *queryActivity()
  3666. {
  3667. return &activity;
  3668. }
  3669. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  3670. {
  3671. return NULL;
  3672. }
  3673. void setMergeInfo(ISteppingMeta *_mergeOrder)
  3674. {
  3675. mergeOrder = _mergeOrder;
  3676. deferredStart = true;
  3677. }
  3678. void send(IRoxieQueryPacket *p)
  3679. {
  3680. if (p)
  3681. {
  3682. Linked<IRoxieQueryPacket> saver(p); // avoids a race with abortPending, without keeping pendingCrit locked over the send which we might prefer not to
  3683. assertex(p->queryHeader().uid==ruid);
  3684. // MORE: Maybe we should base the fastlane flag on some other
  3685. // criteria !! (i.e A Roxie server prediction based on the
  3686. // activity type/activity behaviour/expected reply size .. etc).
  3687. //
  3688. // Currently (code below) based on high priority, seq=0, and none-child activity.
  3689. // But this could still cause too many reply packets on the fatlane
  3690. // (higher priority output Q), which may cause the activities on the
  3691. // low priority output Q to not get service on time.
  3692. if ((colocalArg == 0) && // not a child query activity??
  3693. (p->queryHeader().activityId & (ROXIE_SLA_PRIORITY | ROXIE_HIGH_PRIORITY)) &&
  3694. (p->queryHeader().overflowSequence == 0) &&
  3695. (p->queryHeader().continueSequence & ~CONTINUE_SEQUENCE_SKIPTO)==0)
  3696. p->queryHeader().retries |= ROXIE_FASTLANE;
  3697. if (p->queryHeader().channel)
  3698. {
  3699. bool cached = false;
  3700. IRoxieServerQueryPacket *rsqp = createRoxieServerQueryPacket(p, cached);
  3701. if (deferredStart)
  3702. rsqp->setDelayed(true);
  3703. rsqp->setSequence(sentSequence++);
  3704. {
  3705. CriticalBlock b(pendingCrit);
  3706. pending.append(*rsqp);
  3707. }
  3708. if (!deferredStart)
  3709. {
  3710. if (!cached)
  3711. ROQ->sendPacket(p, activity.queryLogCtx());
  3712. sentsome.signal();
  3713. }
  3714. }
  3715. else
  3716. {
  3717. // 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
  3718. // Need to add first, then send
  3719. unsigned i;
  3720. bool allCached = true;
  3721. for (i = 1; i <= numChannels; i++)
  3722. {
  3723. IRoxieQueryPacket *q = p->clonePacket(i);
  3724. bool thisChannelCached;
  3725. IRoxieServerQueryPacket *rsqp = createRoxieServerQueryPacket(q, thisChannelCached);
  3726. if (!thisChannelCached)
  3727. allCached = false;
  3728. rsqp->setSequence(sentSequence++);
  3729. if (deferredStart)
  3730. {
  3731. rsqp->setDelayed(true);
  3732. }
  3733. {
  3734. CriticalBlock b(pendingCrit);
  3735. pending.append(*rsqp);
  3736. }
  3737. if (!deferredStart)
  3738. sentsome.signal();
  3739. }
  3740. if (!allCached && !deferredStart)
  3741. ROQ->sendPacket(p, activity.queryLogCtx());
  3742. buffers[0]->signal(); // since replies won't come back on that channel...
  3743. p->Release();
  3744. }
  3745. }
  3746. }
  3747. void *getMem(unsigned partNo, unsigned fileNo, unsigned size)
  3748. {
  3749. unsigned channel = partNo ? getBondedChannel(partNo) : 0;
  3750. size += sizeof(PartNoType);
  3751. ChannelBuffer *b = queryChannelBuffer(channel, true);
  3752. char *buffer = (char *) b->getBuffer(size);
  3753. if (!buffer)
  3754. {
  3755. send(b->flush());
  3756. buffer = (char *) b->getBuffer(size);
  3757. }
  3758. PartNoType sp;
  3759. sp.partNo = partNo;
  3760. sp.fileNo = fileNo;
  3761. memcpy(buffer, &sp, sizeof(sp));
  3762. buffer += sizeof(sp);
  3763. return buffer;
  3764. }
  3765. void injectResult(IMessageResult *result)
  3766. {
  3767. IRoxieServerQueryPacket *f = new CRoxieServerQueryPacket(NULL);
  3768. f->setSequence(sentSequence++);
  3769. f->setResult(result);
  3770. CriticalBlock b(pendingCrit);
  3771. pending.append(*f);
  3772. sentsome.signal(); // MORE - arguably should only send if there is any point waking up the listener thread, to save context swicth
  3773. }
  3774. void flush()
  3775. {
  3776. for (unsigned channel = 0; channel <= numChannels; channel++)
  3777. {
  3778. ChannelBuffer *b = queryChannelBuffer(channel, false);
  3779. if (b)
  3780. send(b->flush());
  3781. }
  3782. }
  3783. void interruptBuffers(IException *e)
  3784. {
  3785. for (unsigned channel = 0; channel <= numChannels; channel++)
  3786. {
  3787. ChannelBuffer *b = queryChannelBuffer(channel, false);
  3788. if (b)
  3789. b->interrupt(LINK(e));
  3790. }
  3791. }
  3792. void senddone()
  3793. {
  3794. CriticalBlock b(pendingCrit);
  3795. pending.append(*new CRoxieServerQueryPacketEndMarker);
  3796. sentsome.signal();
  3797. }
  3798. bool fireException(IException *e)
  3799. {
  3800. {
  3801. CriticalBlock b(pendingCrit);
  3802. pending.append(*new CRoxieServerQueryPacketEndMarker);
  3803. }
  3804. interruptBuffers(e);
  3805. if (mc)
  3806. mc->interrupt(LINK(e));
  3807. sentsome.interrupt(e);
  3808. return true;
  3809. }
  3810. virtual void onCreate(IHThorArg *_colocalArg)
  3811. {
  3812. debugContext = ctx->queryDebugContext();
  3813. colocalArg = _colocalArg;
  3814. if (meta.needsSerializeDisk())
  3815. {
  3816. deserializer.setown(meta.createDiskDeserializer(ctx->queryCodeContext(), activity.queryId()));
  3817. rowAllocator.setown(ctx->queryCodeContext()->getRowAllocator(meta.queryOriginal(), activity.queryId()));
  3818. }
  3819. if (ctx->queryDebugContext() && ctx->queryDebugContext()->getExecuteSequentially())
  3820. deferredStart = true;
  3821. if (ctx)
  3822. timeActivities = ctx->queryOptions().timeActivities;
  3823. }
  3824. virtual void onStart(unsigned _parentExtractSize, const byte * _parentExtract)
  3825. {
  3826. #ifdef TRACE_STARTSTOP
  3827. if (traceStartStop)
  3828. activity.queryLogCtx().CTXLOG("RRAonstart");
  3829. #endif
  3830. sentsome.reinit();
  3831. ruid = getNextRuid();
  3832. rowManager = &ctx->queryRowManager();
  3833. if (mergeOrder)
  3834. merger.init(mergeOrder, rowManager);
  3835. if (mc)
  3836. {
  3837. ROQ->queryReceiveManager()->detachCollator(mc); // Should never happen - implies someone forgot to call onReset!
  3838. }
  3839. mc.setown(ROQ->queryReceiveManager()->createMessageCollator(rowManager, ruid));
  3840. allread = false;
  3841. mu.clear();
  3842. contextCached = false;
  3843. processed = 0;
  3844. resendSequence = 0;
  3845. sentSequence = 0;
  3846. for (unsigned channel = 0; channel <= numChannels; channel++)
  3847. {
  3848. delete(buffers[channel]);
  3849. buffers[channel] = NULL;
  3850. }
  3851. flush();
  3852. parentExtractSize = _parentExtractSize;
  3853. parentExtract = _parentExtract;
  3854. }
  3855. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  3856. {
  3857. #ifdef TRACE_STARTSTOP
  3858. if (traceStartStop)
  3859. activity.queryLogCtx().CTXLOG("RRAstart");
  3860. #endif
  3861. activity.start(parentExtractSize, parentExtract, paused);
  3862. }
  3863. void setLimits(unsigned __int64 _rowLimit, unsigned __int64 _keyedLimit, unsigned __int64 _stopAfter)
  3864. {
  3865. if (ctx->queryProbeManager())
  3866. {
  3867. if (_rowLimit != (unsigned __int64) -1) ctx->queryProbeManager()->setNodePropertyInt(&activity, "rowLimit", _rowLimit);
  3868. if (_keyedLimit != (unsigned __int64) -1) ctx->queryProbeManager()->setNodePropertyInt(&activity, "keyedLimit", _keyedLimit);
  3869. if (_stopAfter != I64C(0x7FFFFFFFFFFFFFFF)) ctx->queryProbeManager()->setNodePropertyInt(&activity, "choosenLimit", _stopAfter);
  3870. }
  3871. {
  3872. CriticalBlock b(pendingCrit);
  3873. if (pending.length())
  3874. {
  3875. #ifdef _DEBUG
  3876. dumpPending(); // MORE - only defined in debug build - could have put the ifdef inside the dumpPending method
  3877. #endif
  3878. assertex(pending.length()==0);
  3879. }
  3880. pending.append(*new CRoxieServerQueryPacketLimitMarker(_rowLimit, _keyedLimit, _stopAfter));
  3881. }
  3882. sentsome.signal();
  3883. rowLimit = _rowLimit;
  3884. keyedLimit = _keyedLimit;
  3885. stopAfter = _stopAfter;
  3886. }
  3887. virtual void stop()
  3888. {
  3889. #ifdef TRACE_STARTSTOP
  3890. if (traceStartStop)
  3891. activity.queryLogCtx().CTXLOG("RRAstop");
  3892. #endif
  3893. onStop();
  3894. activity.stop();
  3895. }
  3896. void onStop()
  3897. {
  3898. #ifdef TRACE_STARTSTOP
  3899. if (traceStartStop)
  3900. activity.queryLogCtx().CTXLOG("RRAonstop");
  3901. #endif
  3902. abortPending();
  3903. interruptBuffers(NULL);
  3904. sentsome.interrupt();
  3905. if (mc) // May not be set if start() chain threw exception
  3906. mc->interrupt();
  3907. }
  3908. virtual void reset()
  3909. {
  3910. #ifdef TRACE_STARTSTOP
  3911. if (traceStartStop)
  3912. activity.queryLogCtx().CTXLOG("RRAreset");
  3913. #endif
  3914. activity.reset();
  3915. onReset();
  3916. }
  3917. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  3918. {
  3919. // Make sure parent activity calls up the tree
  3920. PointerArrayOf<IEngineRowStream> instreams;
  3921. IStrandJunction *junction = activity.getOutputStreams(ctx, idx, instreams, consumerOptions, consumerOrdered, orderedCallbacks);
  3922. assertex (junction == NULL);
  3923. // I return a single strand (we could change that sometime I guess...)
  3924. streams.append(this);
  3925. return NULL;
  3926. }
  3927. virtual void resetEOF()
  3928. {
  3929. throwUnexpected();
  3930. }
  3931. virtual void onReset()
  3932. {
  3933. #ifdef TRACE_STARTSTOP
  3934. if (traceStartStop)
  3935. activity.queryLogCtx().CTXLOG("RRAonreset");
  3936. #endif
  3937. if (mc)
  3938. ROQ->queryReceiveManager()->detachCollator(mc);
  3939. merger.reset();
  3940. pending.kill();
  3941. if (mc && ctx)
  3942. ctx->addSlavesReplyLen(mc->queryBytesReceived());
  3943. mc.clear(); // Or we won't free memory for graphs that get recreated
  3944. mu.clear(); //ditto
  3945. deferredStart = false;
  3946. // NOTE: do NOT clear mergeOrder - this is set at create time not per child query
  3947. }
  3948. virtual IOutputMetaData * queryOutputMeta() const
  3949. {
  3950. return helper.queryOutputMeta();
  3951. }
  3952. virtual unsigned __int64 queryTotalCycles() const
  3953. {
  3954. return totalCycles;
  3955. }
  3956. const void * nextRowGE(const void *seek, const void *rawSeek, unsigned numFields, unsigned seekLen, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  3957. {
  3958. if (activity.queryLogCtx().queryTraceLevel() > 20)
  3959. {
  3960. StringBuffer recstr;
  3961. unsigned i;
  3962. for (i = 0; i < seekLen; i++)
  3963. {
  3964. recstr.appendf("%02x ", ((unsigned char *) rawSeek)[i]);
  3965. }
  3966. activity.queryLogCtx().CTXLOG("CRemoteResultAdaptor::nextRowGE(rawSeek=%s numFields=%d, seeklen=%d, returnMismatches=%d)", recstr.str(), numFields, seekLen, stepExtra.returnMismatches());
  3967. }
  3968. assertex(mergeOrder);
  3969. if (deferredStart)
  3970. {
  3971. CriticalBlock b(pendingCrit);
  3972. ForEachItemIn(idx, pending)
  3973. {
  3974. IRoxieServerQueryPacket &p = pending.item(idx);
  3975. if (p.isDelayed())
  3976. {
  3977. p.setDelayed(false);
  3978. if (activity.queryLogCtx().queryTraceLevel() > 10)
  3979. activity.queryLogCtx().CTXLOG("About to send deferred start from nextRowGE, setting requireExact to %d", !stepExtra.returnMismatches());
  3980. MemoryBuffer serializedSkip;
  3981. activity.serializeSkipInfo(serializedSkip, seekLen, rawSeek, numFields, seek, stepExtra);
  3982. p.setPacket(p.queryPacket()->insertSkipData(serializedSkip.length(), serializedSkip.toByteArray()));
  3983. ROQ->sendPacket(p.queryPacket(), activity.queryLogCtx());
  3984. sentsome.signal();
  3985. }
  3986. }
  3987. deferredStart = false;
  3988. }
  3989. SimpleActivityTimer t(totalCycles, timeActivities);
  3990. if (processed==stopAfter)
  3991. return NULL;
  3992. if (allread)
  3993. return NULL;
  3994. loop
  3995. {
  3996. if (merger.ready())
  3997. {
  3998. const void *got = merger.nextRowGE(seek, rawSeek, numFields, seekLen, wasCompleteMatch, stepExtra);
  3999. if (got)
  4000. {
  4001. processRow(got);
  4002. return got;
  4003. }
  4004. }
  4005. if (!reload()) // MORE - should pass the seek info here...
  4006. return NULL;
  4007. }
  4008. }
  4009. virtual const void *nextRow()
  4010. {
  4011. // If we are merging then we need to do a heapsort on all
  4012. SimpleActivityTimer t(totalCycles, timeActivities);
  4013. if (activity.queryLogCtx().queryTraceLevel() > 10)
  4014. {
  4015. activity.queryLogCtx().CTXLOG("CRemoteResultAdaptor::nextRow()");
  4016. }
  4017. loop
  4018. {
  4019. checkDelayed();
  4020. if (processed==stopAfter)
  4021. return NULL;
  4022. if (allread)
  4023. return NULL;
  4024. // If we can still consume from the merger or the most recently retrieved mu, do so.
  4025. const void *got = NULL;
  4026. if (mergeOrder && merger.ready())
  4027. {
  4028. bool matched = true;
  4029. got = merger.next(matched, dummySmartStepExtra);
  4030. }
  4031. else if (mu)
  4032. got = getRow(mu);
  4033. if (got)
  4034. {
  4035. processRow(got);
  4036. return got;
  4037. }
  4038. if (!reload())
  4039. return NULL;
  4040. }
  4041. }
  4042. bool reload()
  4043. {
  4044. // Wait for something to be returned from a slave....
  4045. mu.clear();
  4046. sentsome.wait();
  4047. // must be at least an endMarker on the queue since sentsome was signalled
  4048. {
  4049. CriticalBlock b(pendingCrit);
  4050. IRoxieServerQueryPacket &top = pending.item(0);
  4051. if (top.isLimit(rowLimit, keyedLimit, stopAfter)) // This is really a start marker...
  4052. {
  4053. pending.remove(0);
  4054. return true;
  4055. }
  4056. else if (top.isEnd())
  4057. {
  4058. pending.remove(0);
  4059. allread = true;
  4060. if (activity.queryLogCtx().queryTraceLevel() > 5)
  4061. activity.queryLogCtx().CTXLOG("All read on ruid %x", ruid);
  4062. return false;
  4063. }
  4064. else if (mergeOrder)
  4065. {
  4066. unsigned idx = 0;
  4067. bool added = false;
  4068. while (pending.isItem(idx))
  4069. {
  4070. IRoxieServerQueryPacket &item = pending.item(idx);
  4071. if (item.isEnd())
  4072. {
  4073. if (merger.noteEndSeen())
  4074. {
  4075. sentsome.signal(); // Because we waited, yet didn't actually consume anything
  4076. added = true;
  4077. }
  4078. break;
  4079. }
  4080. else if (item.hasResult())
  4081. {
  4082. merger.noteResult(&item, item.getSequence());
  4083. pending.remove(idx);
  4084. added = true;
  4085. }
  4086. else if (item.isContinuation())
  4087. idx++;
  4088. else
  4089. break;
  4090. }
  4091. if (added)
  4092. return true;
  4093. }
  4094. else if (top.hasResult())
  4095. {
  4096. mr.setown(pending.item(0).getResult());
  4097. mu.setown(mr->getCursor(rowManager));
  4098. pending.remove(0);
  4099. return true;
  4100. }
  4101. }
  4102. getNextUnpacker();
  4103. return true;
  4104. }
  4105. void getNextUnpacker()
  4106. {
  4107. mu.clear();
  4108. unsigned ctxTraceLevel = activity.queryLogCtx().queryTraceLevel();
  4109. loop
  4110. {
  4111. checkDelayed();
  4112. unsigned timeout = remoteId.isSLAPriority() ? slaTimeout : (remoteId.isHighPriority() ? highTimeout : lowTimeout);
  4113. activity.queryContext()->checkAbort();
  4114. bool anyActivity;
  4115. if (ctxTraceLevel > 5)
  4116. activity.queryLogCtx().CTXLOG("Calling getNextUnpacker(%d)", timeout);
  4117. mr.setown(mc->getNextResult(timeout, anyActivity));
  4118. if (ctxTraceLevel > 6)
  4119. activity.queryLogCtx().CTXLOG("Called getNextUnpacker(%d), activity=%d", timeout, anyActivity);
  4120. activity.queryContext()->checkAbort();
  4121. if (mr)
  4122. {
  4123. unsigned roxieHeaderLen;
  4124. const RoxiePacketHeader &header = *(const RoxiePacketHeader *) mr->getMessageHeader(roxieHeaderLen);
  4125. #ifdef _DEBUG
  4126. assertex(roxieHeaderLen == sizeof(RoxiePacketHeader));
  4127. #endif
  4128. if (ctxTraceLevel > 5)
  4129. {
  4130. StringBuffer s;
  4131. activity.queryLogCtx().CTXLOG("getNextUnpacker got packet %s", header.toString(s).str());
  4132. }
  4133. CriticalBlock b(pendingCrit);
  4134. unsigned idx = 0;
  4135. IRoxieServerQueryPacket *original = NULL;
  4136. IRoxieQueryPacket *op;
  4137. while (pending.isItem(idx))
  4138. {
  4139. original = &pending.item(idx);
  4140. op = original->queryPacket();
  4141. if (op && header.matchPacket(op->queryHeader()))
  4142. break;
  4143. original = NULL;
  4144. idx++;
  4145. }
  4146. if (!original || original->hasResult())
  4147. {
  4148. switch (header.activityId)
  4149. {
  4150. case ROXIE_FILECALLBACK:
  4151. {
  4152. // tell slave to abort
  4153. //if (ctxTraceLevel > 5)
  4154. {
  4155. StringBuffer s;
  4156. activity.queryLogCtx().CTXLOG("Redundant callback on query %s", header.toString(s).str());
  4157. }
  4158. Owned<IMessageUnpackCursor> callbackData = mr->getCursor(rowManager);
  4159. OwnedConstRoxieRow len = callbackData->getNext(sizeof(RecordLengthType));
  4160. if (len)
  4161. {
  4162. RecordLengthType *rowlen = (RecordLengthType *) len.get();
  4163. OwnedConstRoxieRow row = callbackData->getNext(*rowlen);
  4164. const char *rowdata = (const char *) row.get();
  4165. // bool isOpt = * (bool *) rowdata;
  4166. // bool isLocal = * (bool *) (rowdata+1);
  4167. ROQ->sendAbortCallback(header, rowdata+2, activity.queryLogCtx());
  4168. }
  4169. else
  4170. throwUnexpected();
  4171. break;
  4172. }
  4173. // MORE - ROXIE_ALIVE perhaps should go here too
  4174. default:
  4175. if (ctxTraceLevel > 3)
  4176. activity.queryLogCtx().CTXLOG("Discarding packet %p - original %p is NULL or has result already", mr.get(), original);
  4177. mr->discard();
  4178. break;
  4179. }
  4180. mr.clear();
  4181. }
  4182. else
  4183. {
  4184. atomic_inc(&resultsReceived);
  4185. switch (header.activityId)
  4186. {
  4187. case ROXIE_DEBUGCALLBACK:
  4188. {
  4189. Owned<IMessageUnpackCursor> callbackData = mr->getCursor(rowManager);
  4190. OwnedConstRoxieRow len = callbackData->getNext(sizeof(RecordLengthType));
  4191. if (len)
  4192. {
  4193. RecordLengthType *rowlen = (RecordLengthType *) len.get();
  4194. OwnedConstRoxieRow row = callbackData->getNext(*rowlen);
  4195. char *rowdata = (char *) row.get();
  4196. if (ctxTraceLevel > 5)
  4197. {
  4198. StringBuffer s;
  4199. activity.queryLogCtx().CTXLOG("Callback on query %s for debug", header.toString(s).str());
  4200. }
  4201. MemoryBuffer slaveInfo;
  4202. slaveInfo.setBuffer(*rowlen, rowdata, false);
  4203. unsigned debugSequence;
  4204. slaveInfo.read(debugSequence);
  4205. Owned<IRoxieQueryPacket> reply = original->getDebugResponse(debugSequence);
  4206. if (!reply)
  4207. reply.setown(activity.queryContext()->queryDebugContext()->onDebugCallback(header, *rowlen, rowdata));
  4208. if (reply)
  4209. {
  4210. original->setDebugResponse(debugSequence, reply);
  4211. ROQ->sendPacket(reply, activity.queryLogCtx());
  4212. }
  4213. }
  4214. else
  4215. throwUnexpected();
  4216. // MORE - somehow we need to make sure slave gets a reply even if I'm not waiting (in udp layer)
  4217. // Leave original message on pending queue in original location - this is not a reply to it.
  4218. break;
  4219. }
  4220. case ROXIE_FILECALLBACK:
  4221. {
  4222. // we need to send back to the slave a message containing the file info requested.
  4223. Owned<IMessageUnpackCursor> callbackData = mr->getCursor(rowManager);
  4224. OwnedConstRoxieRow len = callbackData->getNext(sizeof(RecordLengthType));
  4225. if (len)
  4226. {
  4227. RecordLengthType *rowlen = (RecordLengthType *) len.get();
  4228. OwnedConstRoxieRow row = callbackData->getNext(*rowlen);
  4229. const char *rowdata = (const char *) row.get();
  4230. bool isOpt = * (bool *) rowdata;
  4231. bool isLocal = * (bool *) (rowdata+1);
  4232. const char *lfn = rowdata+2;
  4233. if (ctxTraceLevel > 5)
  4234. {
  4235. StringBuffer s;
  4236. activity.queryLogCtx().CTXLOG("Callback on query %s file %s", header.toString(s).str(),(const char *) lfn);
  4237. }
  4238. activity.queryContext()->onFileCallback(header, lfn, isOpt, isLocal);
  4239. }
  4240. else
  4241. throwUnexpected();
  4242. // MORE - somehow we need to make sure slave gets a reply even if I'm not waiting (in udp layer)
  4243. // Leave original message on pending queue in original location - this is not a reply to it.
  4244. break;
  4245. }
  4246. case ROXIE_KEYEDLIMIT_EXCEEDED:
  4247. activity.queryLogCtx().CTXLOG("ROXIE_KEYEDLIMIT_EXCEEDED");
  4248. errorHandler->onLimitExceeded(true); // NOTE - should throw exception!
  4249. throwUnexpected();
  4250. case ROXIE_LIMIT_EXCEEDED:
  4251. activity.queryLogCtx().CTXLOG("ROXIE_LIMIT_EXCEEDED");
  4252. errorHandler->onLimitExceeded(false); // NOTE - should throw exception!
  4253. throwUnexpected();
  4254. case ROXIE_TRACEINFO:
  4255. {
  4256. Owned<IMessageUnpackCursor> extra = mr->getCursor(rowManager);
  4257. loop
  4258. {
  4259. RecordLengthType *rowlen = (RecordLengthType *) extra->getNext(sizeof(RecordLengthType));
  4260. if (rowlen)
  4261. {
  4262. char *logInfo = (char *) extra->getNext(*rowlen);
  4263. MemoryBuffer buf;
  4264. buf.setBuffer(*rowlen, logInfo, false);
  4265. switch ((TracingCategory) *logInfo)
  4266. {
  4267. case LOG_TRACING:
  4268. case LOG_ERROR:
  4269. activity.queryLogCtx().CTXLOGl(new LogItem(buf));
  4270. break;
  4271. case LOG_STATVALUES:
  4272. buf.skip(1);
  4273. activity.mergeStats(buf);
  4274. break;
  4275. case LOG_CHILDCOUNT:
  4276. case LOG_CHILDSTATS:
  4277. unsigned graphId, childId;
  4278. buf.skip(1);
  4279. buf.read(graphId);
  4280. buf.read(childId);
  4281. if (*logInfo == LOG_CHILDCOUNT)
  4282. {
  4283. unsigned idx;
  4284. unsigned childProcessed;
  4285. unsigned childStrands;
  4286. buf.read(idx);
  4287. buf.read(childProcessed);
  4288. buf.read(childStrands);
  4289. if (traceLevel > 5)
  4290. activity.queryLogCtx().CTXLOG("Processing ChildCount %d idx %d strands %d for child %d subgraph %d", childProcessed, idx, childStrands, childId, graphId);
  4291. activity.queryContext()->noteProcessed(graphId, childId, idx, childProcessed, childStrands);
  4292. }
  4293. else
  4294. {
  4295. ActivityTimeAccumulator dummy; // We could serialize from slave? Would get confusing though
  4296. CRuntimeStatisticCollection childStats(allStatistics);
  4297. childStats.deserialize(buf);
  4298. if (traceLevel > 5)
  4299. {
  4300. StringBuffer s;
  4301. activity.queryLogCtx().CTXLOG("Processing ChildStats for child %d subgraph %d: %s", childId, graphId, childStats.toStr(s).str());
  4302. }
  4303. activity.queryContext()->mergeActivityStats(childStats, graphId, childId, dummy, 0);
  4304. }
  4305. }
  4306. ReleaseRoxieRow(rowlen);
  4307. ReleaseRoxieRow(logInfo);
  4308. }
  4309. else
  4310. break;
  4311. }
  4312. break;
  4313. }
  4314. case ROXIE_EXCEPTION:
  4315. if (ctxTraceLevel > 1)
  4316. {
  4317. StringBuffer s;
  4318. activity.queryLogCtx().CTXLOG("Exception on query %s", header.toString(s).str());
  4319. }
  4320. op->queryHeader().noteException(header.retries);
  4321. if (op->queryHeader().allChannelsFailed())
  4322. {
  4323. activity.queryLogCtx().CTXLOG("Multiple exceptions on query - aborting");
  4324. Owned<IMessageUnpackCursor> exceptionData = mr->getCursor(rowManager);
  4325. throwRemoteException(exceptionData);
  4326. }
  4327. // Leave it on pending queue in original location
  4328. break;
  4329. case ROXIE_ALIVE:
  4330. if (ctxTraceLevel > 4)
  4331. {
  4332. StringBuffer s;
  4333. activity.queryLogCtx().CTXLOG("ROXIE_ALIVE: %s", header.toString(s).str());
  4334. }
  4335. op->queryHeader().noteAlive(header.retries & ROXIE_RETRIES_MASK);
  4336. // Leave it on pending queue in original location
  4337. break;
  4338. default:
  4339. if (header.retries & ROXIE_RETRIES_MASK)
  4340. atomic_inc(&retriesNeeded);
  4341. unsigned metaLen;
  4342. const void *metaData = mr->getMessageMetadata(metaLen);
  4343. if (metaLen)
  4344. {
  4345. // We got back first chunk but there is more.
  4346. // resend the packet, with the cursor info provided.
  4347. // MORE - if smart-stepping, we don't want to send the continuation immediately. Other cases it's not clear that we do.
  4348. if (ctxTraceLevel > 1)
  4349. {
  4350. StringBuffer s;
  4351. activity.queryLogCtx().CTXLOG("Additional data size %d on query %s mergeOrder %p", metaLen, header.toString(s).str(), mergeOrder);
  4352. }
  4353. if (*((unsigned short *) metaData) + sizeof(unsigned short) != metaLen)
  4354. {
  4355. StringBuffer s;
  4356. activity.queryLogCtx().CTXLOG("Additional data size %d on query %s mergeOrder %p", metaLen, header.toString(s).str(), mergeOrder);
  4357. activity.queryLogCtx().CTXLOG("Additional data is corrupt");
  4358. throwUnexpected();
  4359. }
  4360. MemoryBuffer nextQuery;
  4361. nextQuery.append(sizeof(RoxiePacketHeader), &header);
  4362. nextQuery.append(metaLen, metaData);
  4363. nextQuery.append(op->getTraceLength(), op->queryTraceInfo());
  4364. nextQuery.append(op->getContextLength(), op->queryContextData());
  4365. if (resendSequence == CONTINUESEQUENCE_MAX)
  4366. {
  4367. activity.queryLogCtx().CTXLOG("ERROR: Continuation sequence wrapped"); // shouldn't actually matter.... but suggests a very iffy query!
  4368. resendSequence = 1;
  4369. }
  4370. else
  4371. resendSequence++;
  4372. RoxiePacketHeader *newHeader = (RoxiePacketHeader *) nextQuery.toByteArray();
  4373. newHeader->continueSequence = resendSequence; // NOTE - we clear the skipTo flag since continuation of a skip is NOT a skip...
  4374. newHeader->retries &= ~ROXIE_RETRIES_MASK;
  4375. IRoxieQueryPacket *resend = createRoxiePacket(nextQuery);
  4376. CRoxieServerQueryPacket *fqp = new CRoxieServerQueryPacket(resend);
  4377. fqp->setSequence(original->getSequence());
  4378. pending.add(*fqp, idx+1); // note that pending takes ownership. sendPacket does not release.
  4379. original->setContinuation(LINK(fqp));
  4380. if (mergeOrder)
  4381. fqp->setDelayed(true);
  4382. else
  4383. {
  4384. ROQ->sendPacket(resend, activity.queryLogCtx());
  4385. sentsome.signal();
  4386. }
  4387. // Note that we don't attempt to cache results that have continuation records - too tricky !
  4388. }
  4389. else
  4390. {
  4391. if (serverSideCache)
  4392. serverSideCache->noteCachedResult(original, mr);
  4393. }
  4394. unsigned channel = header.channel;
  4395. {
  4396. ChannelBuffer *b = queryChannelBuffer(channel); // If not something is wrong, or we sent out on channel 0?
  4397. if (b)
  4398. b->signal();
  4399. }
  4400. original->setResult(mr.getClear());
  4401. sentsome.signal();
  4402. return;
  4403. }
  4404. }
  4405. }
  4406. else
  4407. {
  4408. if (!anyActivity && !localSlave)
  4409. {
  4410. activity.queryLogCtx().CTXLOG("Input has stalled - retry required?");
  4411. retryPending();
  4412. }
  4413. }
  4414. }
  4415. }
  4416. inline unsigned headerLength() const
  4417. {
  4418. return logInfo.length() + cachedContext.length() + sizeof(unsigned) + parentExtractSize;
  4419. }
  4420. void copyHeader(byte *tgt, unsigned channel) const
  4421. {
  4422. unsigned len = logInfo.length();
  4423. memcpy(tgt, logInfo.toByteArray(), len);
  4424. tgt += len;
  4425. *(unsigned *) tgt = parentExtractSize;
  4426. tgt += sizeof(unsigned);
  4427. memcpy(tgt, parentExtract, parentExtractSize);
  4428. tgt += parentExtractSize;
  4429. memcpy(tgt, cachedContext.toByteArray(), cachedContext.length());
  4430. tgt += cachedContext.length();
  4431. }
  4432. };
  4433. class CSkippableRemoteResultAdaptor : public CRemoteResultAdaptor
  4434. {
  4435. Owned <IException> exception;
  4436. bool skipping;
  4437. ConstPointerArray buff;
  4438. unsigned index;
  4439. bool pulled;
  4440. void pullInput()
  4441. {
  4442. try
  4443. {
  4444. if (exception)
  4445. throw exception.getClear();
  4446. unsigned __int64 count = 0;
  4447. loop
  4448. {
  4449. const void * next = CRemoteResultAdaptor::nextRow();
  4450. if (next == NULL)
  4451. {
  4452. next = CRemoteResultAdaptor::nextRow();
  4453. if(next == NULL)
  4454. break;
  4455. buff.append(NULL);
  4456. }
  4457. count++;
  4458. if (count > rowLimit)
  4459. {
  4460. ReleaseRoxieRow(next);
  4461. ReleaseRoxieRows(buff);
  4462. errorHandler->onLimitExceeded(false); // throws an exception - user or LimitSkipException
  4463. throwUnexpected();
  4464. }
  4465. else if (count > keyedLimit)
  4466. {
  4467. ReleaseRoxieRow(next);
  4468. ReleaseRoxieRows(buff);
  4469. errorHandler->onLimitExceeded(true); // throws an exception - user or LimitSkipException
  4470. throwUnexpected();
  4471. }
  4472. buff.append(next);
  4473. }
  4474. }
  4475. catch (IException *E)
  4476. {
  4477. if (QUERYINTERFACE(E, LimitSkipException))
  4478. {
  4479. Owned<IException> cleanup = E;
  4480. ReleaseRoxieRows(buff);
  4481. const void *onfail = errorHandler->createLimitFailRow(E->errorCode() == KeyedLimitSkipErrorCode);
  4482. if (onfail)
  4483. buff.append(onfail);
  4484. }
  4485. else
  4486. throw;
  4487. }
  4488. pulled = true;
  4489. }
  4490. public:
  4491. CSkippableRemoteResultAdaptor(IRoxieSlaveContext *_ctx, IRoxieServerErrorHandler *_errorHandler, const RemoteActivityId &_remoteId, IOutputMetaData *_meta, IHThorArg &_helper, IRoxieServerActivity &_activity, bool _preserveOrder, bool _flowControlled, bool _skipping) :
  4492. CRemoteResultAdaptor(_ctx, _errorHandler, _remoteId, _meta, _helper, _activity, _preserveOrder, _flowControlled)
  4493. {
  4494. skipping = _skipping;
  4495. index = 0;
  4496. pulled = false;
  4497. }
  4498. void setException(IException *E)
  4499. {
  4500. exception.setown(E);
  4501. }
  4502. virtual void onReset()
  4503. {
  4504. roxiemem::ReleaseRoxieRowRange(buff.getArray(), index, buff.ordinality());
  4505. buff.kill();
  4506. index = 0;
  4507. pulled = false;
  4508. exception.clear();
  4509. CRemoteResultAdaptor::onReset();
  4510. }
  4511. void onStart(unsigned _parentExtractSize, const byte * _parentExtract)
  4512. {
  4513. index = 0;
  4514. pulled = false;
  4515. CRemoteResultAdaptor::onStart(_parentExtractSize, _parentExtract);
  4516. }
  4517. virtual const void * nextRowGE(const void *seek, const void *rawSeek, unsigned numFields, unsigned seeklen, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  4518. {
  4519. // 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
  4520. if (exception)
  4521. throw exception.getClear();
  4522. return CRemoteResultAdaptor::nextRowGE(seek, rawSeek, numFields, seeklen, wasCompleteMatch, stepExtra);
  4523. }
  4524. virtual const void *nextRow()
  4525. {
  4526. if (skipping)
  4527. {
  4528. if(!pulled)
  4529. pullInput();
  4530. if(buff.isItem(index))
  4531. {
  4532. const void * next = buff.item(index++);
  4533. if(next)
  4534. processed++;
  4535. return next;
  4536. }
  4537. return NULL;
  4538. }
  4539. else
  4540. {
  4541. if (exception)
  4542. throw exception.getClear();
  4543. return CRemoteResultAdaptor::nextRow();
  4544. }
  4545. }
  4546. };
  4547. //=================================================================================
  4548. class CRoxieServerApplyActivity : public CRoxieServerInternalSinkActivity
  4549. {
  4550. IHThorApplyArg &helper;
  4551. public:
  4552. CRoxieServerApplyActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4553. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, 0), helper((IHThorApplyArg &) basehelper)
  4554. {
  4555. }
  4556. virtual void onExecute()
  4557. {
  4558. helper.start();
  4559. loop
  4560. {
  4561. const void * next = inputStream->ungroupedNextRow();
  4562. if (!next)
  4563. break;
  4564. helper.apply(next);
  4565. ReleaseRoxieRow(next);
  4566. }
  4567. helper.end();
  4568. }
  4569. };
  4570. class CRoxieServerApplyActivityFactory : public CRoxieServerActivityFactory
  4571. {
  4572. bool isRoot;
  4573. public:
  4574. CRoxieServerApplyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  4575. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  4576. {
  4577. }
  4578. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  4579. {
  4580. return new CRoxieServerApplyActivity(_ctx, this, _probeManager);
  4581. }
  4582. virtual bool isSink() const
  4583. {
  4584. return isRoot;
  4585. }
  4586. };
  4587. IRoxieServerActivityFactory *createRoxieServerApplyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  4588. {
  4589. return new CRoxieServerApplyActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  4590. }
  4591. //=================================================================================
  4592. class CRoxieServerNullActivity : public CRoxieServerActivity
  4593. {
  4594. public:
  4595. CRoxieServerNullActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4596. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  4597. {
  4598. }
  4599. virtual const void *nextRow()
  4600. {
  4601. return NULL;
  4602. }
  4603. };
  4604. IRoxieServerActivity * createRoxieServerNullActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4605. {
  4606. return new CRoxieServerNullActivity(_ctx, _factory, _probeManager);
  4607. }
  4608. class CRoxieServerNullActivityFactory : public CRoxieServerActivityFactory
  4609. {
  4610. public:
  4611. CRoxieServerNullActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4612. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  4613. {
  4614. }
  4615. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  4616. {
  4617. return new CRoxieServerNullActivity(_ctx, this, _probeManager);
  4618. }
  4619. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  4620. {
  4621. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for null activity");
  4622. }
  4623. };
  4624. IRoxieServerActivityFactory *createRoxieServerNullActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4625. {
  4626. return new CRoxieServerNullActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  4627. }
  4628. //=================================================================================
  4629. class CRoxieServerPassThroughActivity : public CRoxieServerActivity
  4630. {
  4631. public:
  4632. CRoxieServerPassThroughActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4633. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  4634. {
  4635. }
  4636. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  4637. {
  4638. return input->gatherConjunctions(collector);
  4639. }
  4640. virtual void resetEOF()
  4641. {
  4642. inputStream->resetEOF();
  4643. }
  4644. virtual const void *nextRow()
  4645. {
  4646. const void * next = inputStream->nextRow();
  4647. if (next)
  4648. processed++;
  4649. return next;
  4650. }
  4651. virtual bool isPassThrough()
  4652. {
  4653. return true;
  4654. }
  4655. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  4656. {
  4657. ActivityTimer t(totalCycles, timeActivities);
  4658. const void * next = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  4659. if (next)
  4660. processed++;
  4661. return next;
  4662. }
  4663. IInputSteppingMeta * querySteppingMeta()
  4664. {
  4665. return input->querySteppingMeta();
  4666. }
  4667. };
  4668. IRoxieServerActivity * createRoxieServerPassThroughActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4669. {
  4670. return new CRoxieServerPassThroughActivity(_ctx, _factory, _probeManager);
  4671. }
  4672. //=================================================================================
  4673. class CRoxieServerChildBaseActivity : public CRoxieServerActivity
  4674. {
  4675. protected:
  4676. bool eof;
  4677. bool first;
  4678. public:
  4679. CRoxieServerChildBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4680. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  4681. {
  4682. eof = false;
  4683. first = true;
  4684. }
  4685. ~CRoxieServerChildBaseActivity()
  4686. {
  4687. }
  4688. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4689. {
  4690. eof = false;
  4691. first = true;
  4692. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  4693. }
  4694. };
  4695. class CRoxieServerChildBaseActivityFactory : public CRoxieServerActivityFactory
  4696. {
  4697. public:
  4698. CRoxieServerChildBaseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4699. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  4700. {
  4701. }
  4702. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  4703. {
  4704. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  4705. }
  4706. };
  4707. //=================================================================================
  4708. class CRoxieServerChildIteratorActivity : public CRoxieServerChildBaseActivity
  4709. {
  4710. IHThorChildIteratorArg &helper;
  4711. public:
  4712. CRoxieServerChildIteratorActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4713. : CRoxieServerChildBaseActivity(_ctx, _factory, _probeManager), helper((IHThorChildIteratorArg &) basehelper)
  4714. {
  4715. }
  4716. virtual bool needsAllocator() const { return true; }
  4717. virtual const void *nextRow()
  4718. {
  4719. ActivityTimer t(totalCycles, timeActivities);
  4720. if (eof)
  4721. return NULL;
  4722. bool ok;
  4723. if (first)
  4724. {
  4725. ok = helper.first();
  4726. first = false;
  4727. }
  4728. else
  4729. ok = helper.next();
  4730. try
  4731. {
  4732. while (ok)
  4733. {
  4734. processed++;
  4735. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  4736. unsigned outSize = helper.transform(rowBuilder);
  4737. if (outSize)
  4738. return rowBuilder.finalizeRowClear(outSize);
  4739. ok = helper.next();
  4740. }
  4741. }
  4742. catch (IException *E)
  4743. {
  4744. throw makeWrappedException(E);
  4745. }
  4746. eof = true;
  4747. return NULL;
  4748. }
  4749. };
  4750. class CRoxieServerChildIteratorActivityFactory : public CRoxieServerChildBaseActivityFactory
  4751. {
  4752. public:
  4753. CRoxieServerChildIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4754. : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  4755. {
  4756. }
  4757. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  4758. {
  4759. return new CRoxieServerChildIteratorActivity(_ctx, this, _probeManager);
  4760. }
  4761. };
  4762. IRoxieServerActivityFactory *createRoxieServerChildIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4763. {
  4764. return new CRoxieServerChildIteratorActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  4765. }
  4766. //=================================================================================
  4767. class CRoxieServerChildNormalizeActivity : public CRoxieServerChildBaseActivity
  4768. {
  4769. IHThorChildNormalizeArg &helper;
  4770. public:
  4771. CRoxieServerChildNormalizeActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4772. : CRoxieServerChildBaseActivity(_ctx, _factory, _probeManager), helper((IHThorChildNormalizeArg &) 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. if (ok)
  4790. {
  4791. try
  4792. {
  4793. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  4794. do {
  4795. unsigned outSize = helper.transform(rowBuilder);
  4796. if (outSize)
  4797. {
  4798. processed++;
  4799. return rowBuilder.finalizeRowClear(outSize);
  4800. }
  4801. ok = helper.next();
  4802. }
  4803. while (ok);
  4804. }
  4805. catch (IException *E)
  4806. {
  4807. throw makeWrappedException(E);
  4808. }
  4809. }
  4810. eof = true;
  4811. return NULL;
  4812. }
  4813. };
  4814. class CRoxieServerChildNormalizeActivityFactory : public CRoxieServerChildBaseActivityFactory
  4815. {
  4816. public:
  4817. CRoxieServerChildNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4818. : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  4819. {
  4820. }
  4821. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  4822. {
  4823. return new CRoxieServerChildNormalizeActivity(_ctx, this, _probeManager);
  4824. }
  4825. };
  4826. IRoxieServerActivityFactory *createRoxieServerNewChildNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4827. {
  4828. return new CRoxieServerChildNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  4829. }
  4830. //=================================================================================
  4831. class CRoxieServerChildAggregateActivity : public CRoxieServerChildBaseActivity
  4832. {
  4833. IHThorChildAggregateArg &helper;
  4834. public:
  4835. CRoxieServerChildAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4836. : CRoxieServerChildBaseActivity(_ctx, _factory, _probeManager), helper((IHThorChildAggregateArg &) basehelper)
  4837. {
  4838. }
  4839. virtual bool needsAllocator() const { return true; }
  4840. virtual const void *nextRow()
  4841. {
  4842. ActivityTimer t(totalCycles, timeActivities);
  4843. if (eof)
  4844. return NULL;
  4845. eof = true;
  4846. processed++;
  4847. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  4848. helper.clearAggregate(rowBuilder);
  4849. helper.processRows(rowBuilder);
  4850. size32_t finalSize = meta.getRecordSize(rowBuilder.getSelf());
  4851. return rowBuilder.finalizeRowClear(finalSize);
  4852. }
  4853. };
  4854. class CRoxieServerChildAggregateActivityFactory : public CRoxieServerChildBaseActivityFactory
  4855. {
  4856. public:
  4857. CRoxieServerChildAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4858. : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  4859. {
  4860. }
  4861. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  4862. {
  4863. return new CRoxieServerChildAggregateActivity(_ctx, this, _probeManager);
  4864. }
  4865. };
  4866. IRoxieServerActivityFactory *createRoxieServerNewChildAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4867. {
  4868. return new CRoxieServerChildAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  4869. }
  4870. //=================================================================================
  4871. class CRoxieServerChildGroupAggregateActivity : public CRoxieServerChildBaseActivity, public IHThorGroupAggregateCallback
  4872. {
  4873. IHThorChildGroupAggregateArg &helper;
  4874. RowAggregator aggregated;
  4875. public:
  4876. IMPLEMENT_IINTERFACE
  4877. CRoxieServerChildGroupAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4878. : CRoxieServerChildBaseActivity(_ctx, _factory, _probeManager), helper((IHThorChildGroupAggregateArg &) basehelper),
  4879. aggregated(helper, helper)
  4880. {
  4881. }
  4882. void processRow(const void * next)
  4883. {
  4884. aggregated.addRow(next);
  4885. }
  4886. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4887. {
  4888. CRoxieServerChildBaseActivity::start(parentExtractSize, parentExtract, paused);
  4889. aggregated.start(rowAllocator);
  4890. }
  4891. virtual void reset()
  4892. {
  4893. aggregated.reset();
  4894. CRoxieServerChildBaseActivity::reset();
  4895. }
  4896. virtual bool needsAllocator() const { return true; }
  4897. virtual const void *nextRow()
  4898. {
  4899. ActivityTimer t(totalCycles, timeActivities);
  4900. if (eof)
  4901. return NULL;
  4902. if (first)
  4903. {
  4904. helper.processRows(this);
  4905. first = false;
  4906. }
  4907. Owned<AggregateRowBuilder> next = aggregated.nextResult();
  4908. if (next)
  4909. {
  4910. processed++;
  4911. return next->finalizeRowClear();
  4912. }
  4913. eof = true;
  4914. return NULL;
  4915. }
  4916. };
  4917. class CRoxieServerChildGroupAggregateActivityFactory : public CRoxieServerChildBaseActivityFactory
  4918. {
  4919. public:
  4920. CRoxieServerChildGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4921. : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  4922. {
  4923. }
  4924. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  4925. {
  4926. return new CRoxieServerChildGroupAggregateActivity(_ctx, this, _probeManager);
  4927. }
  4928. };
  4929. IRoxieServerActivityFactory *createRoxieServerNewChildGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4930. {
  4931. return new CRoxieServerChildGroupAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  4932. }
  4933. //=================================================================================
  4934. class CRoxieServerChildThroughNormalizeActivity : public CRoxieServerChildBaseActivity
  4935. {
  4936. IHThorChildThroughNormalizeArg &helper;
  4937. const void * lastInput;
  4938. unsigned numProcessedLastGroup;
  4939. bool ok;
  4940. public:
  4941. CRoxieServerChildThroughNormalizeActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4942. : CRoxieServerChildBaseActivity(_ctx, _factory, _probeManager), helper((IHThorChildThroughNormalizeArg &) basehelper)
  4943. {
  4944. lastInput = NULL;
  4945. numProcessedLastGroup = 0;
  4946. ok = false;
  4947. }
  4948. virtual void stop()
  4949. {
  4950. CRoxieServerChildBaseActivity::stop();
  4951. ReleaseRoxieRow(lastInput);
  4952. lastInput = NULL;
  4953. }
  4954. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4955. {
  4956. CRoxieServerChildBaseActivity::start(parentExtractSize, parentExtract, paused);
  4957. numProcessedLastGroup = processed;
  4958. ok = false;
  4959. }
  4960. virtual bool needsAllocator() const { return true; }
  4961. virtual const void *nextRow()
  4962. {
  4963. ActivityTimer t(totalCycles, timeActivities);
  4964. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  4965. loop
  4966. {
  4967. if (ok)
  4968. ok = helper.next();
  4969. while (!ok)
  4970. {
  4971. ReleaseRoxieRow(lastInput);
  4972. lastInput = inputStream->nextRow();
  4973. if (!lastInput)
  4974. {
  4975. if (numProcessedLastGroup != processed)
  4976. {
  4977. numProcessedLastGroup = processed;
  4978. return NULL;
  4979. }
  4980. lastInput = inputStream->nextRow();
  4981. if (!lastInput)
  4982. return NULL;
  4983. }
  4984. ok = helper.first(lastInput);
  4985. }
  4986. try
  4987. {
  4988. do
  4989. {
  4990. unsigned outSize = helper.transform(rowBuilder);
  4991. if (outSize)
  4992. {
  4993. processed++;
  4994. return rowBuilder.finalizeRowClear(outSize);
  4995. }
  4996. ok = helper.next();
  4997. } while (ok);
  4998. }
  4999. catch (IException *E)
  5000. {
  5001. throw makeWrappedException(E);
  5002. }
  5003. }
  5004. }
  5005. };
  5006. class CRoxieServerChildThroughNormalizeActivityFactory : public CRoxieServerActivityFactory
  5007. {
  5008. public:
  5009. CRoxieServerChildThroughNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5010. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  5011. {
  5012. }
  5013. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  5014. {
  5015. return new CRoxieServerChildThroughNormalizeActivity(_ctx, this, _probeManager);
  5016. }
  5017. };
  5018. IRoxieServerActivityFactory *createRoxieServerNewChildThroughNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5019. {
  5020. return new CRoxieServerChildThroughNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  5021. }
  5022. //=================================================================================
  5023. class CRoxieServerDistributionActivity : public CRoxieServerInternalSinkActivity
  5024. {
  5025. IHThorDistributionArg &helper;
  5026. public:
  5027. CRoxieServerDistributionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5028. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, 0), helper((IHThorDistributionArg &)basehelper)
  5029. {
  5030. }
  5031. virtual void onExecute()
  5032. {
  5033. MemoryAttr ma;
  5034. IDistributionTable * * accumulator = (IDistributionTable * *)ma.allocate(helper.queryInternalRecordSize()->getMinRecordSize());
  5035. helper.clearAggregate(accumulator);
  5036. OwnedConstRoxieRow nextrec(inputStream->nextRow());
  5037. loop
  5038. {
  5039. if (!nextrec)
  5040. {
  5041. nextrec.setown(inputStream->nextRow());
  5042. if (!nextrec)
  5043. break;
  5044. }
  5045. helper.process(accumulator, nextrec);
  5046. nextrec.setown(inputStream->nextRow());
  5047. }
  5048. StringBuffer result;
  5049. result.append("<XML>");
  5050. helper.gatherResult(accumulator, result);
  5051. result.append("</XML>");
  5052. helper.sendResult(result.length(), result.str());
  5053. helper.destruct(accumulator);
  5054. }
  5055. };
  5056. class CRoxieServerDistributionActivityFactory : public CRoxieServerActivityFactory
  5057. {
  5058. bool isRoot;
  5059. public:
  5060. CRoxieServerDistributionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  5061. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  5062. {
  5063. }
  5064. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  5065. {
  5066. return new CRoxieServerDistributionActivity(_ctx, this, _probeManager);
  5067. }
  5068. virtual bool isSink() const
  5069. {
  5070. return isRoot;
  5071. }
  5072. };
  5073. IRoxieServerActivityFactory *createRoxieServerDistributionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  5074. {
  5075. return new CRoxieServerDistributionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  5076. }
  5077. //=================================================================================
  5078. class CRoxieServerLinkedRawIteratorActivity : public CRoxieServerActivity
  5079. {
  5080. IHThorLinkedRawIteratorArg &helper;
  5081. public:
  5082. CRoxieServerLinkedRawIteratorActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5083. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorLinkedRawIteratorArg &) basehelper)
  5084. {
  5085. }
  5086. virtual const void *nextRow()
  5087. {
  5088. ActivityTimer t(totalCycles, timeActivities);
  5089. const void *ret =helper.next();
  5090. if (ret)
  5091. {
  5092. LinkRoxieRow(ret);
  5093. processed++;
  5094. }
  5095. return ret;
  5096. }
  5097. };
  5098. class CRoxieServerLinkedRawIteratorActivityFactory : public CRoxieServerActivityFactory
  5099. {
  5100. public:
  5101. CRoxieServerLinkedRawIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5102. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  5103. {
  5104. }
  5105. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  5106. {
  5107. return new CRoxieServerLinkedRawIteratorActivity(_ctx, this, _probeManager);
  5108. }
  5109. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  5110. {
  5111. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  5112. }
  5113. };
  5114. IRoxieServerActivityFactory *createRoxieServerLinkedRawIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5115. {
  5116. return new CRoxieServerLinkedRawIteratorActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  5117. }
  5118. //=================================================================================
  5119. class CRoxieServerDatasetResultActivity : public CRoxieServerActivity
  5120. {
  5121. public:
  5122. CRoxieServerDatasetResultActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5123. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  5124. {
  5125. }
  5126. virtual const void *nextRow()
  5127. {
  5128. throwUnexpected();
  5129. }
  5130. virtual void executeChild(size32_t & retSize, void * & ret, unsigned parentExtractSize, const byte * parentExtract)
  5131. {
  5132. try
  5133. {
  5134. start(parentExtractSize, parentExtract, false);
  5135. {
  5136. ActivityTimer t(totalCycles, timeActivities);
  5137. MemoryBuffer result;
  5138. IRecordSize * inputMeta = input->queryOutputMeta();
  5139. loop
  5140. {
  5141. const void *nextrec = inputStream->ungroupedNextRow();
  5142. if (!nextrec)
  5143. break;
  5144. result.append(inputMeta->getRecordSize(nextrec), nextrec);
  5145. ReleaseRoxieRow(nextrec);
  5146. }
  5147. retSize = result.length();
  5148. ret = result.detach();
  5149. }
  5150. stop();
  5151. reset();
  5152. }
  5153. catch(IException *E)
  5154. {
  5155. ctx->notifyAbort(E);
  5156. abort();
  5157. reset();
  5158. throw;
  5159. }
  5160. catch(...)
  5161. {
  5162. Owned<IException> E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught at %s:%d", __FILE__, __LINE__);
  5163. ctx->notifyAbort(E);
  5164. abort();
  5165. reset();
  5166. throw;
  5167. }
  5168. }
  5169. };
  5170. class CRoxieServerDatasetResultActivityFactory : public CRoxieServerActivityFactory
  5171. {
  5172. bool isRoot;
  5173. public:
  5174. CRoxieServerDatasetResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  5175. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  5176. {
  5177. }
  5178. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  5179. {
  5180. return new CRoxieServerDatasetResultActivity(_ctx, this, _probeManager);
  5181. }
  5182. virtual bool isSink() const
  5183. {
  5184. return isRoot;
  5185. }
  5186. };
  5187. IRoxieServerActivityFactory *createRoxieServerDatasetResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  5188. {
  5189. return new CRoxieServerDatasetResultActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  5190. }
  5191. //=================================================================================
  5192. class CRoxieServerInlineTableActivity : public CRoxieServerActivity
  5193. {
  5194. IHThorInlineTableArg &helper;
  5195. __uint64 curRow;
  5196. __uint64 numRows;
  5197. public:
  5198. CRoxieServerInlineTableActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5199. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorInlineTableArg &) basehelper)
  5200. {
  5201. curRow = 0;
  5202. numRows = 0;
  5203. }
  5204. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5205. {
  5206. curRow = 0;
  5207. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5208. numRows = helper.numRows();
  5209. }
  5210. virtual bool needsAllocator() const { return true; }
  5211. virtual const void *nextRow()
  5212. {
  5213. ActivityTimer t(totalCycles, timeActivities);
  5214. // Filtering empty rows, returns the next valid row
  5215. while (curRow < numRows)
  5216. {
  5217. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  5218. unsigned outSize = helper.getRow(rowBuilder, curRow++);
  5219. if (outSize)
  5220. {
  5221. processed++;
  5222. return rowBuilder.finalizeRowClear(outSize);
  5223. }
  5224. }
  5225. return NULL;
  5226. }
  5227. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  5228. {
  5229. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  5230. }
  5231. };
  5232. class CRoxieServerStrandedInlineTableActivity : public CRoxieServerStrandedActivity
  5233. {
  5234. IHThorInlineTableArg &helper;
  5235. __uint64 numRows;
  5236. //An inline table that isn't stranded
  5237. class InlineTableSimpleProcessor : public StrandProcessor
  5238. {
  5239. protected:
  5240. IHThorInlineTableArg &helper;
  5241. __uint64 curRow;
  5242. __uint64 maxRows;
  5243. public:
  5244. InlineTableSimpleProcessor(CRoxieServerActivity &_parent, IHThorInlineTableArg &_helper)
  5245. : StrandProcessor(_parent, NULL, true), helper(_helper), curRow(0), maxRows(0)
  5246. {
  5247. }
  5248. virtual void start() override
  5249. {
  5250. StrandProcessor::start();
  5251. curRow = 0;
  5252. maxRows = queryParent().numRows;
  5253. }
  5254. virtual const void * nextRow()
  5255. {
  5256. ActivityTimer t(totalCycles, timeActivities);
  5257. //Return rows while the current section is active
  5258. while (curRow < maxRows)
  5259. {
  5260. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  5261. unsigned outSize = helper.getRow(rowBuilder, curRow++);
  5262. if (outSize)
  5263. {
  5264. processed++;
  5265. return rowBuilder.finalizeRowClear(outSize);
  5266. }
  5267. }
  5268. return NULL;
  5269. }
  5270. CRoxieServerStrandedInlineTableActivity & queryParent() { return static_cast<CRoxieServerStrandedInlineTableActivity&>(parent); }
  5271. };
  5272. class InlineTableStrandProcessor : public StrandProcessor
  5273. {
  5274. protected:
  5275. IHThorInlineTableArg &helper;
  5276. unsigned whichStrand;
  5277. unsigned numStrands;
  5278. __uint64 sectionSize;
  5279. __uint64 curRow;
  5280. __uint64 sectionMaxRows;
  5281. __uint64 maxRows;
  5282. bool isOrdered;
  5283. bool eosPending;
  5284. public:
  5285. InlineTableStrandProcessor(CRoxieServerActivity &_parent, IHThorInlineTableArg &_helper, unsigned _whichStrand, bool _isOrdered)
  5286. : StrandProcessor(_parent, NULL, true), helper(_helper), whichStrand(_whichStrand), isOrdered(_isOrdered)
  5287. {
  5288. sectionSize = queryParent().strandOptions.blockSize;
  5289. eosPending = false;
  5290. }
  5291. virtual void start() override
  5292. {
  5293. StrandProcessor::start();
  5294. numStrands = queryParent().numStrands();
  5295. maxRows = queryParent().numRows;
  5296. curRow = std::min(whichStrand * sectionSize, maxRows);
  5297. sectionMaxRows = std::min(curRow + sectionSize, maxRows);
  5298. eosPending = isOrdered && (curRow != maxRows);
  5299. }
  5300. virtual const void * nextRow()
  5301. {
  5302. ActivityTimer t(totalCycles, timeActivities);
  5303. loop
  5304. {
  5305. //Return rows while the current section is active
  5306. while (curRow < sectionMaxRows)
  5307. {
  5308. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  5309. unsigned outSize = helper.getRow(rowBuilder, curRow++);
  5310. if (outSize)
  5311. {
  5312. processed++;
  5313. return rowBuilder.finalizeRowClear(outSize);
  5314. }
  5315. }
  5316. if (curRow == maxRows)
  5317. return NULL;
  5318. //Update current position to the next section
  5319. curRow += (numStrands - 1) * sectionSize;
  5320. if (curRow > maxRows)
  5321. curRow = maxRows;
  5322. sectionMaxRows = std::min(curRow + sectionSize, maxRows);
  5323. //If we have output a block of rows, then send the block as a unit - results now come from the next strand
  5324. if (eosPending)
  5325. {
  5326. //If there is another block, then second an end of section marker after it, otherwise make sure NULL is returned next.
  5327. eosPending = isOrdered && (curRow != maxRows);
  5328. return queryEndOfSectionMarker();
  5329. }
  5330. }
  5331. }
  5332. CRoxieServerStrandedInlineTableActivity & queryParent() { return static_cast<CRoxieServerStrandedInlineTableActivity&>(parent); }
  5333. };
  5334. public:
  5335. CRoxieServerStrandedInlineTableActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const StrandOptions &_strandOptions)
  5336. : CRoxieServerStrandedActivity(_ctx, _factory, _probeManager, _strandOptions), helper((IHThorInlineTableArg &) basehelper)
  5337. {
  5338. numRows = 0;
  5339. }
  5340. virtual StrandProcessor *createStrandProcessor(IEngineRowStream *instream) { throwUnexpected(); }
  5341. virtual StrandProcessor *createStrandSourceProcessor(bool inputOrdered)
  5342. {
  5343. if (strandOptions.numStrands <= 1)
  5344. return new InlineTableSimpleProcessor(*this, helper);
  5345. return new InlineTableStrandProcessor(*this, helper, strands.ordinality(), inputOrdered);
  5346. }
  5347. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5348. {
  5349. CRoxieServerStrandedActivity::start(parentExtractSize, parentExtract, paused);
  5350. numRows = helper.numRows();
  5351. onStartStrands();
  5352. startJunction(sourceJunction); // This must be started *after* all the strands have been initialised
  5353. }
  5354. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  5355. {
  5356. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  5357. }
  5358. };
  5359. class CRoxieServerInlineTableActivityFactory : public CRoxieServerActivityFactory
  5360. {
  5361. StrandOptions strandOptions;
  5362. public:
  5363. CRoxieServerInlineTableActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5364. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), strandOptions(_graphNode)
  5365. {
  5366. optStableInput = false; // do not force the output to be ordered
  5367. }
  5368. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  5369. {
  5370. return new CRoxieServerStrandedInlineTableActivity(_ctx, this, _probeManager, strandOptions);
  5371. }
  5372. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  5373. {
  5374. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for InlineTable activity");
  5375. }
  5376. };
  5377. IRoxieServerActivityFactory *createRoxieServerInlineTableActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5378. {
  5379. return new CRoxieServerInlineTableActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  5380. }
  5381. //=================================================================================
  5382. class CRoxieServerWorkUnitReadActivity : public CRoxieServerActivity
  5383. {
  5384. IHThorWorkunitReadArg &helper;
  5385. CriticalSection readerCrit;
  5386. Owned<IWorkUnitRowReader> wuReader;
  5387. public:
  5388. CRoxieServerWorkUnitReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5389. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorWorkunitReadArg &)basehelper)
  5390. {
  5391. }
  5392. virtual void onCreate(IHThorArg *_colocalParent)
  5393. {
  5394. CRoxieServerActivity::onCreate(_colocalParent);
  5395. if (!ctx->queryServerContext())
  5396. {
  5397. throw MakeStringException(ROXIE_INTERNAL_ERROR, "Workunit read activity cannot be executed in slave context");
  5398. }
  5399. }
  5400. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5401. {
  5402. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5403. IXmlToRowTransformer * xmlTransformer = helper.queryXmlTransformer();
  5404. OwnedRoxieString fromWuid(helper.getWUID());
  5405. wuReader.setown(ctx->getWorkunitRowReader(fromWuid, helper.queryName(), helper.querySequence(), xmlTransformer, rowAllocator, meta.isGrouped()));
  5406. // MORE _ should that be in onCreate?
  5407. }
  5408. virtual void reset()
  5409. {
  5410. {
  5411. CriticalBlock b(readerCrit);
  5412. wuReader.clear();
  5413. }
  5414. CRoxieServerActivity::reset();
  5415. };
  5416. virtual bool needsAllocator() const { return true; }
  5417. virtual const void *nextRow()
  5418. {
  5419. ActivityTimer t(totalCycles, timeActivities);
  5420. Linked<IWorkUnitRowReader> useReader;
  5421. {
  5422. CriticalBlock b(readerCrit);
  5423. if (!wuReader)
  5424. return NULL;
  5425. useReader.set(wuReader);
  5426. }
  5427. const void *ret = useReader->nextRow();
  5428. if (ret)
  5429. processed++;
  5430. return ret;
  5431. }
  5432. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  5433. {
  5434. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  5435. }
  5436. };
  5437. class CRoxieServerWorkUnitReadActivityFactory : public CRoxieServerActivityFactory
  5438. {
  5439. public:
  5440. CRoxieServerWorkUnitReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5441. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  5442. {
  5443. }
  5444. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  5445. {
  5446. return new CRoxieServerWorkUnitReadActivity(_ctx, this, _probeManager);
  5447. }
  5448. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  5449. {
  5450. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for WorkUnitRead activity");
  5451. }
  5452. };
  5453. IRoxieServerActivityFactory *createRoxieServerWorkUnitReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5454. {
  5455. return new CRoxieServerWorkUnitReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  5456. }
  5457. //=================================================================================
  5458. interface ILocalGraphEx : public IEclGraphResults
  5459. {
  5460. public:
  5461. virtual void setResult(unsigned id, IGraphResult * result) = 0;
  5462. virtual IEngineRowStream * createResultIterator(unsigned id) = 0;
  5463. virtual void setGraphLoopResult(IGraphResult * result) = 0;
  5464. virtual IEngineRowStream * createGraphLoopResultIterator(unsigned id) = 0;
  5465. };
  5466. class CSafeRoxieInput : public CInterface, implements IFinalRoxieInput, implements IEngineRowStream
  5467. {
  5468. public:
  5469. CSafeRoxieInput(unsigned _sourceIdx, IFinalRoxieInput * _input) : input(_input), inputStream(NULL), sourceIdx(_sourceIdx) {}
  5470. IMPLEMENT_IINTERFACE
  5471. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  5472. {
  5473. connectInputStreams(ctx, consumerOrdered);
  5474. streams.append(this);
  5475. return NULL;
  5476. }
  5477. void connectInputStreams(IRoxieSlaveContext *ctx, bool consumerOrdered)
  5478. {
  5479. inputStream.set(connectSingleStream(ctx, input, sourceIdx, junction, consumerOrdered));
  5480. }
  5481. virtual IOutputMetaData * queryOutputMeta() const
  5482. {
  5483. return input->queryOutputMeta();
  5484. }
  5485. virtual unsigned __int64 queryTotalCycles() const
  5486. {
  5487. return input->queryTotalCycles();
  5488. }
  5489. virtual IRoxieServerActivity *queryActivity()
  5490. {
  5491. return input->queryActivity();
  5492. }
  5493. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  5494. {
  5495. return input->queryIndexReadActivity();
  5496. }
  5497. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5498. {
  5499. CriticalBlock procedure(cs);
  5500. input->start(parentExtractSize, parentExtract, paused);
  5501. startJunction(junction);
  5502. }
  5503. virtual void stop()
  5504. {
  5505. CriticalBlock procedure(cs);
  5506. inputStream->stop();
  5507. }
  5508. virtual void reset()
  5509. {
  5510. CriticalBlock procedure(cs);
  5511. input->reset();
  5512. resetJunction(junction);
  5513. }
  5514. virtual void resetEOF()
  5515. {
  5516. CriticalBlock procedure(cs);
  5517. inputStream->resetEOF();
  5518. }
  5519. virtual const void *nextRow()
  5520. {
  5521. CriticalBlock procedure(cs);
  5522. return inputStream->nextRow();
  5523. }
  5524. virtual bool nextGroup(ConstPointerArray & group)
  5525. {
  5526. CriticalBlock procedure(cs);
  5527. return inputStream->nextGroup(group);
  5528. }
  5529. private:
  5530. CriticalSection cs;
  5531. Linked<IFinalRoxieInput> input;
  5532. Linked<IEngineRowStream> inputStream;
  5533. Owned<IStrandJunction> junction;
  5534. unsigned sourceIdx;
  5535. };
  5536. //=================================================================================
  5537. class CPseudoRoxieInput : public CInterface, implements IFinalRoxieInput, implements IEngineRowStream
  5538. {
  5539. public:
  5540. IMPLEMENT_IINTERFACE;
  5541. CPseudoRoxieInput()
  5542. {
  5543. }
  5544. virtual unsigned __int64 queryTotalCycles() const
  5545. {
  5546. return 0;
  5547. }
  5548. virtual IRoxieServerActivity *queryActivity()
  5549. {
  5550. throwUnexpected();
  5551. }
  5552. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  5553. {
  5554. throwUnexpected();
  5555. }
  5556. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  5557. {
  5558. assertex(!idx);
  5559. streams.append(this);
  5560. return NULL;
  5561. }
  5562. virtual IOutputMetaData * queryOutputMeta() const { throwUnexpected(); }
  5563. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused) { }
  5564. virtual void stop() { }
  5565. virtual void reset() { }
  5566. virtual void checkAbort() { }
  5567. virtual void resetEOF() { }
  5568. };
  5569. class CIndirectRoxieInput : public CPseudoRoxieInput
  5570. {
  5571. public:
  5572. CIndirectRoxieInput() : input(NULL)
  5573. {
  5574. stream = NULL;
  5575. sourceIdx = 0;
  5576. }
  5577. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5578. {
  5579. input->start(parentExtractSize, parentExtract, paused);
  5580. startJunction(junction);
  5581. }
  5582. virtual void stop()
  5583. {
  5584. stream->stop();
  5585. }
  5586. virtual void reset()
  5587. {
  5588. input->reset();
  5589. resetJunction(junction);
  5590. }
  5591. virtual const void * nextRow()
  5592. {
  5593. return stream->nextRow();
  5594. }
  5595. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  5596. {
  5597. return stream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  5598. }
  5599. virtual unsigned __int64 queryTotalCycles() const
  5600. {
  5601. return input->queryTotalCycles();
  5602. }
  5603. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  5604. {
  5605. return input->gatherConjunctions(collector);
  5606. }
  5607. virtual void resetEOF()
  5608. {
  5609. stream->resetEOF();
  5610. }
  5611. virtual unsigned numConcreteOutputs() const
  5612. {
  5613. return input->numConcreteOutputs();
  5614. }
  5615. virtual IFinalRoxieInput * queryConcreteInput(unsigned idx)
  5616. {
  5617. return input->queryConcreteInput(idx);
  5618. }
  5619. virtual IOutputMetaData * queryOutputMeta() const
  5620. {
  5621. return input->queryOutputMeta();
  5622. }
  5623. virtual IRoxieServerActivity *queryActivity()
  5624. {
  5625. return input->queryActivity();
  5626. }
  5627. inline void setInput(unsigned _sourceIdx, IFinalRoxieInput * _input)
  5628. {
  5629. input = _input;
  5630. sourceIdx = _sourceIdx;
  5631. }
  5632. inline void connectInputStreams(IRoxieSlaveContext *ctx, bool consumerOrdered)
  5633. {
  5634. stream = connectSingleStream(ctx, input, sourceIdx, junction, consumerOrdered);
  5635. }
  5636. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  5637. {
  5638. assertex(idx == 0);
  5639. connectInputStreams(ctx, consumerOrdered);
  5640. streams.append(this);
  5641. return NULL;
  5642. }
  5643. inline IFinalRoxieInput *queryInput() const
  5644. {
  5645. return input;
  5646. }
  5647. protected:
  5648. unsigned sourceIdx;
  5649. IFinalRoxieInput *input;
  5650. IEngineRowStream *stream;
  5651. Owned<IStrandJunction> junction;
  5652. };
  5653. class CExtractMapperInput : public CIndirectRoxieInput
  5654. {
  5655. unsigned savedParentExtractSize;
  5656. const byte * savedParentExtract;
  5657. public:
  5658. CExtractMapperInput()
  5659. {
  5660. savedParentExtractSize = 0;
  5661. savedParentExtract = NULL;
  5662. }
  5663. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5664. {
  5665. CIndirectRoxieInput::start(savedParentExtractSize, savedParentExtract, paused);
  5666. }
  5667. void setParentExtract(unsigned _savedParentExtractSize, const byte * _savedParentExtract)
  5668. {
  5669. savedParentExtractSize = _savedParentExtractSize;
  5670. savedParentExtract = _savedParentExtract;
  5671. }
  5672. };
  5673. class CGraphResult : public CInterface, implements IGraphResult
  5674. {
  5675. CriticalSection cs;
  5676. byte **rowset;
  5677. size32_t count;
  5678. bool complete;
  5679. void clear()
  5680. {
  5681. CriticalBlock func(cs);
  5682. rtlReleaseRowset(count, rowset);
  5683. rowset = NULL;
  5684. count = 0;
  5685. complete = false;
  5686. }
  5687. public:
  5688. IMPLEMENT_IINTERFACE
  5689. CGraphResult()
  5690. {
  5691. complete = false; // dummy result is not supposed to be used...
  5692. rowset = NULL;
  5693. count = 0;
  5694. }
  5695. CGraphResult(size32_t _count, byte **_rowset)
  5696. : count(_count), rowset(_rowset)
  5697. {
  5698. complete = true;
  5699. }
  5700. ~CGraphResult()
  5701. {
  5702. clear();
  5703. }
  5704. // interface IGraphResult
  5705. virtual IEngineRowStream * createIterator()
  5706. {
  5707. if (!complete)
  5708. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Internal Error: Reading uninitialised graph result");
  5709. return new CGraphResultIterator(this);
  5710. }
  5711. virtual void getLinkedResult(unsigned & countResult, byte * * & result)
  5712. {
  5713. if (!complete)
  5714. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Internal Error: Reading uninitialised graph result");
  5715. result = rtlLinkRowset(rowset);
  5716. countResult = count;
  5717. }
  5718. virtual const void * getLinkedRowResult()
  5719. {
  5720. if (!complete)
  5721. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Internal Error: Reading uninitialised graph result");
  5722. if (count != 1)
  5723. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Internal Error: Expected a single row result");
  5724. const void * ret = rowset[0];
  5725. LinkRoxieRow(ret);
  5726. return ret;
  5727. }
  5728. //other
  5729. const void * getRow(unsigned i)
  5730. {
  5731. CriticalBlock func(cs);
  5732. if (i >= count)
  5733. return NULL;
  5734. const void * ret = rowset[i];
  5735. if (ret) LinkRoxieRow(ret);
  5736. return ret;
  5737. }
  5738. protected:
  5739. class CGraphResultIterator : public CInterfaceOf<IEngineRowStream>
  5740. {
  5741. unsigned i;
  5742. Linked<CGraphResult> result;
  5743. public:
  5744. CGraphResultIterator(CGraphResult * _result) : result(_result) { i = 0; }
  5745. public:
  5746. virtual const void * nextRow()
  5747. {
  5748. return result->getRow(i++);
  5749. }
  5750. virtual void stop()
  5751. {
  5752. }
  5753. virtual void resetEOF()
  5754. {
  5755. throwUnexpected();
  5756. }
  5757. };
  5758. };
  5759. //=================================================================================
  5760. class CRoxieServerLocalResultReadActivity : public CRoxieServerActivity
  5761. {
  5762. IHThorLocalResultReadArg &helper;
  5763. CriticalSection iterCrit;
  5764. Owned<IEngineRowStream> iter;
  5765. ILocalGraphEx * graph;
  5766. unsigned graphId;
  5767. unsigned sequence;
  5768. public:
  5769. CRoxieServerLocalResultReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId)
  5770. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorLocalResultReadArg &)basehelper), graphId(_graphId)
  5771. {
  5772. graph = NULL;
  5773. sequence = 0;
  5774. }
  5775. virtual void onCreate(IHThorArg *_colocalParent)
  5776. {
  5777. CRoxieServerActivity::onCreate(_colocalParent);
  5778. graph = static_cast<ILocalGraphEx *>(ctx->queryCodeContext()->resolveLocalQuery(graphId));
  5779. sequence = helper.querySequence();
  5780. }
  5781. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5782. {
  5783. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5784. iter.setown(graph->createResultIterator(sequence));
  5785. }
  5786. virtual void reset()
  5787. {
  5788. {
  5789. CriticalBlock b(iterCrit);
  5790. iter.clear();
  5791. }
  5792. CRoxieServerActivity::reset();
  5793. };
  5794. virtual const void *nextRow()
  5795. {
  5796. ActivityTimer t(totalCycles, timeActivities);
  5797. Linked<IEngineRowStream> useIter;
  5798. {
  5799. CriticalBlock b(iterCrit);
  5800. if (!iter)
  5801. return NULL;
  5802. useIter.set(iter);
  5803. }
  5804. const void * next = useIter->nextRow();
  5805. if (next)
  5806. {
  5807. processed++;
  5808. atomic_inc(&rowsIn);
  5809. }
  5810. return next;
  5811. }
  5812. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  5813. {
  5814. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  5815. }
  5816. };
  5817. class CRoxieServerLocalResultReadActivityFactory : public CRoxieServerActivityFactory
  5818. {
  5819. unsigned graphId;
  5820. public:
  5821. CRoxieServerLocalResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _graphId)
  5822. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), graphId(_graphId)
  5823. {
  5824. }
  5825. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  5826. {
  5827. return new CRoxieServerLocalResultReadActivity(_ctx, this, _probeManager, graphId);
  5828. }
  5829. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  5830. {
  5831. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for LocalResultRead activity");
  5832. }
  5833. };
  5834. IRoxieServerActivityFactory *createRoxieServerLocalResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned graphId)
  5835. {
  5836. return new CRoxieServerLocalResultReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, graphId);
  5837. }
  5838. //=================================================================================
  5839. class CRoxieServerLocalResultStreamReadActivity : public CRoxieServerActivity
  5840. {
  5841. IHThorLocalResultReadArg &helper;
  5842. unsigned sequence;
  5843. public:
  5844. CRoxieServerLocalResultStreamReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5845. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorLocalResultReadArg &)basehelper)
  5846. {
  5847. sequence = 0;
  5848. }
  5849. virtual void onCreate(IHThorArg *_colocalParent)
  5850. {
  5851. CRoxieServerActivity::onCreate(_colocalParent);
  5852. sequence = helper.querySequence();
  5853. }
  5854. virtual const void *nextRow()
  5855. {
  5856. ActivityTimer t(totalCycles, timeActivities);
  5857. const void * next = inputStream->nextRow();
  5858. if (next)
  5859. {
  5860. processed++;
  5861. atomic_inc(&rowsIn);
  5862. }
  5863. return next;
  5864. }
  5865. virtual bool querySetStreamInput(unsigned id, unsigned _sourceIdx, IFinalRoxieInput * _input)
  5866. {
  5867. if (id == sequence)
  5868. {
  5869. CRoxieServerActivity::setInput(0, _sourceIdx, _input);
  5870. connectInputStreams(true);
  5871. return true;
  5872. }
  5873. return false;
  5874. }
  5875. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  5876. {
  5877. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  5878. }
  5879. };
  5880. class CRoxieServerLocalResultStreamReadActivityFactory : public CRoxieServerActivityFactory
  5881. {
  5882. public:
  5883. CRoxieServerLocalResultStreamReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5884. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  5885. {
  5886. }
  5887. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  5888. {
  5889. return new CRoxieServerLocalResultStreamReadActivity(_ctx, this, _probeManager);
  5890. }
  5891. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  5892. {
  5893. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for LocalResultRead activity");
  5894. }
  5895. };
  5896. IRoxieServerActivityFactory *createRoxieServerLocalResultStreamReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5897. {
  5898. return new CRoxieServerLocalResultStreamReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  5899. }
  5900. //=====================================================================================================
  5901. class CRoxieServerLocalResultWriteActivity : public CRoxieServerInternalSinkActivity
  5902. {
  5903. IHThorLocalResultWriteArg &helper;
  5904. ILocalGraphEx * graph;
  5905. unsigned graphId;
  5906. public:
  5907. CRoxieServerLocalResultWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId, unsigned _numOutputs)
  5908. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _numOutputs), helper((IHThorLocalResultWriteArg &)basehelper), graphId(_graphId)
  5909. {
  5910. graph = NULL;
  5911. }
  5912. virtual bool needsAllocator() const { return true; }
  5913. virtual void onCreate(IHThorArg *_colocalParent)
  5914. {
  5915. CRoxieServerInternalSinkActivity::onCreate(_colocalParent);
  5916. graph = static_cast<ILocalGraphEx *>(ctx->queryCodeContext()->resolveLocalQuery(graphId));
  5917. }
  5918. virtual void onExecute()
  5919. {
  5920. RtlLinkedDatasetBuilder builder(rowAllocator);
  5921. inputStream->readAll(builder);
  5922. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  5923. graph->setResult(helper.querySequence(), result);
  5924. }
  5925. virtual const void *nextRow()
  5926. {
  5927. return inputStream->nextRow(); // I can act as a passthrough input
  5928. }
  5929. IFinalRoxieInput * querySelectOutput(unsigned id)
  5930. {
  5931. if (id == helper.querySequence())
  5932. {
  5933. executed = true; // Ensure that we don't try to pull as a sink as well as via the passthrough
  5934. return LINK(this);
  5935. }
  5936. return NULL;
  5937. }
  5938. };
  5939. class CRoxieServerLocalResultWriteActivityFactory : public CRoxieServerInternalSinkFactory
  5940. {
  5941. unsigned graphId;
  5942. public:
  5943. CRoxieServerLocalResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, unsigned _graphId, bool _isRoot)
  5944. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot), graphId(_graphId)
  5945. {
  5946. isInternal = true;
  5947. Owned<IHThorLocalResultWriteArg> helper = (IHThorLocalResultWriteArg *) helperFactory();
  5948. }
  5949. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  5950. {
  5951. return new CRoxieServerLocalResultWriteActivity(_ctx, this, _probeManager, graphId, usageCount);
  5952. }
  5953. };
  5954. IRoxieServerActivityFactory *createRoxieServerLocalResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, unsigned _graphId, bool _isRoot)
  5955. {
  5956. return new CRoxieServerLocalResultWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _graphId, _isRoot);
  5957. }
  5958. //=====================================================================================================
  5959. class CRoxieServerDictionaryResultWriteActivity : public CRoxieServerInternalSinkActivity
  5960. {
  5961. IHThorDictionaryResultWriteArg &helper;
  5962. ILocalGraphEx * graph;
  5963. unsigned graphId;
  5964. public:
  5965. CRoxieServerDictionaryResultWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _usageCount, unsigned _graphId)
  5966. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _usageCount), helper((IHThorDictionaryResultWriteArg &)basehelper), graphId(_graphId)
  5967. {
  5968. graph = NULL;
  5969. }
  5970. virtual bool needsAllocator() const { return true; }
  5971. virtual void onCreate(IHThorArg *_colocalParent)
  5972. {
  5973. CRoxieServerInternalSinkActivity::onCreate(_colocalParent);
  5974. graph = static_cast<ILocalGraphEx *>(ctx->queryCodeContext()->resolveLocalQuery(graphId));
  5975. }
  5976. virtual void onExecute()
  5977. {
  5978. unsigned sequence = helper.querySequence();
  5979. RtlLinkedDictionaryBuilder builder(rowAllocator, helper.queryHashLookupInfo());
  5980. loop
  5981. {
  5982. const void *row = inputStream->ungroupedNextRow();
  5983. if (!row)
  5984. break;
  5985. builder.appendOwn(row);
  5986. processed++;
  5987. }
  5988. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  5989. graph->setResult(helper.querySequence(), result);
  5990. }
  5991. virtual const void *nextRow()
  5992. {
  5993. return inputStream->nextRow(); // I can act as a passthrough input
  5994. }
  5995. IFinalRoxieInput * querySelectOutput(unsigned id)
  5996. {
  5997. if (id == helper.querySequence())
  5998. {
  5999. executed = true; // Ensure that we don't try to pull as a sink as well as via the passthrough
  6000. return LINK(this);
  6001. }
  6002. return NULL;
  6003. }
  6004. };
  6005. class CRoxieServerDictionaryResultWriteActivityFactory : public CRoxieServerInternalSinkFactory
  6006. {
  6007. unsigned graphId;
  6008. public:
  6009. CRoxieServerDictionaryResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, unsigned _graphId, bool _isRoot)
  6010. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot), graphId(_graphId)
  6011. {
  6012. isInternal = true;
  6013. }
  6014. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  6015. {
  6016. return new CRoxieServerDictionaryResultWriteActivity(_ctx, this, _probeManager, usageCount, graphId);
  6017. }
  6018. };
  6019. IRoxieServerActivityFactory *createRoxieServerDictionaryResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, unsigned _graphId, bool _isRoot)
  6020. {
  6021. return new CRoxieServerDictionaryResultWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _graphId, _isRoot);
  6022. }
  6023. //=================================================================================
  6024. class CRoxieServerGraphLoopResultReadActivity : public CRoxieServerActivity
  6025. {
  6026. protected:
  6027. IHThorGraphLoopResultReadArg &helper;
  6028. CriticalSection iterCrit;
  6029. Owned<IFinalRoxieInput> iterInput;
  6030. Owned<IEngineRowStream> iterStream;
  6031. Owned<IStrandJunction> iterJunction;
  6032. ILocalGraphEx * graph;
  6033. unsigned graphId;
  6034. unsigned sequence;
  6035. public:
  6036. CRoxieServerGraphLoopResultReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId)
  6037. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorGraphLoopResultReadArg &)basehelper), graphId(_graphId)
  6038. {
  6039. graph = NULL;
  6040. sequence = 0;
  6041. }
  6042. virtual void onCreate(IHThorArg *_colocalParent)
  6043. {
  6044. CRoxieServerActivity::onCreate(_colocalParent);
  6045. graph = static_cast<ILocalGraphEx *>(ctx->queryCodeContext()->resolveLocalQuery(graphId));
  6046. }
  6047. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6048. {
  6049. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6050. if (iterInput)
  6051. iterInput->start(parentExtractSize, parentExtract, paused);
  6052. else
  6053. {
  6054. sequence = helper.querySequence();
  6055. if ((int)sequence >= 0)
  6056. {
  6057. try
  6058. {
  6059. iterStream.setown(graph->createGraphLoopResultIterator(sequence));
  6060. iterInput.clear();
  6061. }
  6062. catch (IException * E)
  6063. {
  6064. throw makeWrappedException(E);
  6065. }
  6066. }
  6067. }
  6068. startJunction(iterJunction);
  6069. }
  6070. virtual void stop()
  6071. {
  6072. if (iterStream)
  6073. iterStream->stop();
  6074. CRoxieServerActivity::stop();
  6075. }
  6076. virtual void reset()
  6077. {
  6078. {
  6079. CriticalBlock b(iterCrit);
  6080. if (iterInput)
  6081. iterInput->reset();
  6082. resetJunction(iterJunction);
  6083. iterInput.clear();
  6084. iterStream.clear();
  6085. iterJunction.clear();
  6086. }
  6087. CRoxieServerActivity::reset();
  6088. };
  6089. virtual const void *nextRow()
  6090. {
  6091. ActivityTimer t(totalCycles, timeActivities);
  6092. Linked<IEngineRowStream> useStream;
  6093. {
  6094. CriticalBlock b(iterCrit);
  6095. if (!iterStream)
  6096. return NULL;
  6097. useStream.set(iterStream);
  6098. }
  6099. const void * next = useStream->nextRow();
  6100. if (next)
  6101. {
  6102. processed++;
  6103. atomic_inc(&rowsIn);
  6104. }
  6105. return next;
  6106. }
  6107. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  6108. {
  6109. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  6110. }
  6111. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract)
  6112. {
  6113. ensureCreated();
  6114. basehelper.onStart(parentExtract, NULL);
  6115. processor.noteUseIteration(helper.querySequence());
  6116. }
  6117. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract, IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes)
  6118. {
  6119. //helper already initialised from the gatherIterationUsage() call.
  6120. CRoxieServerActivity::connectInputStreams(true);
  6121. iterInput.set(processor.connectIterationOutput(helper.querySequence(), probeManager, probes, this, 0));
  6122. iterStream.set(connectSingleStream(ctx, iterInput, 0, iterJunction, true));
  6123. }
  6124. virtual IInputSteppingMeta * querySteppingMeta()
  6125. {
  6126. assertex(iterInput);
  6127. return iterInput->querySteppingMeta();
  6128. }
  6129. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  6130. {
  6131. assertex(iterStream);
  6132. return iterStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  6133. }
  6134. };
  6135. //variety of CRoxieServerGraphLoopResultReadActivity created internally with a predefined sequence number
  6136. class CRoxieServerInternalGraphLoopResultReadActivity : public CRoxieServerGraphLoopResultReadActivity
  6137. {
  6138. public:
  6139. CRoxieServerInternalGraphLoopResultReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId, unsigned _sequence)
  6140. : CRoxieServerGraphLoopResultReadActivity(_ctx, _factory, _probeManager, _graphId)
  6141. {
  6142. sequence = _sequence;
  6143. }
  6144. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6145. {
  6146. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6147. if ((int)sequence >= 0)
  6148. {
  6149. try
  6150. {
  6151. iterStream.setown(graph->createGraphLoopResultIterator(sequence));
  6152. iterInput.clear();
  6153. }
  6154. catch (IException * E)
  6155. {
  6156. throw makeWrappedException(E);
  6157. }
  6158. }
  6159. }
  6160. };
  6161. class CRoxieServerGraphLoopResultReadActivityFactory : public CRoxieServerActivityFactory
  6162. {
  6163. unsigned graphId;
  6164. public:
  6165. CRoxieServerGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _graphId)
  6166. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), graphId(_graphId)
  6167. {
  6168. }
  6169. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  6170. {
  6171. return new CRoxieServerGraphLoopResultReadActivity(_ctx, this, _probeManager, graphId);
  6172. }
  6173. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  6174. {
  6175. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for GraphLoopResultRead activity");
  6176. }
  6177. };
  6178. IRoxieServerActivityFactory *createRoxieServerGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned graphId)
  6179. {
  6180. return new CRoxieServerGraphLoopResultReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, graphId);
  6181. }
  6182. //=====================================================================================================
  6183. class CRoxieServerGraphLoopResultWriteActivity : public CRoxieServerInternalSinkActivity
  6184. {
  6185. IHThorGraphLoopResultWriteArg &helper;
  6186. ILocalGraphEx * graph;
  6187. unsigned graphId;
  6188. public:
  6189. CRoxieServerGraphLoopResultWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId, unsigned _numOutputs)
  6190. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _numOutputs), helper((IHThorGraphLoopResultWriteArg &)basehelper), graphId(_graphId)
  6191. {
  6192. graph = NULL;
  6193. }
  6194. virtual bool needsAllocator() const { return true; }
  6195. virtual void onCreate(IHThorArg *_colocalParent)
  6196. {
  6197. CRoxieServerInternalSinkActivity::onCreate(_colocalParent);
  6198. graph = static_cast<ILocalGraphEx *>(ctx->queryCodeContext()->resolveLocalQuery(graphId));
  6199. }
  6200. virtual void onExecute()
  6201. {
  6202. RtlLinkedDatasetBuilder builder(rowAllocator);
  6203. inputStream->readAll(builder);
  6204. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  6205. graph->setGraphLoopResult(result);
  6206. }
  6207. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  6208. {
  6209. if (idx==0)
  6210. return this;
  6211. else
  6212. return NULL;
  6213. }
  6214. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  6215. {
  6216. return input->gatherConjunctions(collector);
  6217. }
  6218. virtual void resetEOF()
  6219. {
  6220. inputStream->resetEOF();
  6221. }
  6222. virtual const void *nextRow()
  6223. {
  6224. const void * next = inputStream->nextRow();
  6225. if (next)
  6226. processed++;
  6227. return next;
  6228. }
  6229. virtual bool isPassThrough()
  6230. {
  6231. return true;
  6232. }
  6233. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  6234. {
  6235. ActivityTimer t(totalCycles, timeActivities);
  6236. const void * next = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  6237. if (next)
  6238. processed++;
  6239. return next;
  6240. }
  6241. IInputSteppingMeta * querySteppingMeta()
  6242. {
  6243. return input->querySteppingMeta();
  6244. }
  6245. virtual IOutputMetaData * queryOutputMeta() const
  6246. {
  6247. return input->queryOutputMeta();
  6248. }
  6249. };
  6250. class CRoxieServerGraphLoopResultWriteActivityFactory : public CRoxieServerInternalSinkFactory
  6251. {
  6252. unsigned graphId;
  6253. public:
  6254. CRoxieServerGraphLoopResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, unsigned _graphId)
  6255. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, true), graphId(_graphId)
  6256. {
  6257. isInternal = true;
  6258. Owned<IHThorGraphLoopResultWriteArg> helper = (IHThorGraphLoopResultWriteArg *) helperFactory();
  6259. }
  6260. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  6261. {
  6262. return new CRoxieServerGraphLoopResultWriteActivity(_ctx, this, _probeManager, graphId, usageCount);
  6263. }
  6264. };
  6265. IRoxieServerActivityFactory *createRoxieServerGraphLoopResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, unsigned _graphId)
  6266. {
  6267. return new CRoxieServerGraphLoopResultWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _graphId);
  6268. }
  6269. //=================================================================================
  6270. class CRoxieServerDedupActivity : public CRoxieServerActivity
  6271. {
  6272. protected:
  6273. IHThorDedupArg &helper;
  6274. unsigned numKept;
  6275. unsigned numToKeep;
  6276. public:
  6277. CRoxieServerDedupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6278. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorDedupArg &)basehelper)
  6279. {
  6280. numKept = 0;
  6281. numToKeep = 0;
  6282. }
  6283. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6284. {
  6285. numKept = 0;
  6286. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6287. numToKeep = helper.numToKeep();
  6288. }
  6289. };
  6290. class CRoxieServerDedupKeepLeftActivity : public CRoxieServerDedupActivity
  6291. {
  6292. IRangeCompare * stepCompare;
  6293. const void *prev;
  6294. public:
  6295. CRoxieServerDedupKeepLeftActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6296. : CRoxieServerDedupActivity(_ctx, _factory, _probeManager)
  6297. {
  6298. prev = NULL;
  6299. stepCompare = NULL;
  6300. }
  6301. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6302. {
  6303. prev = NULL;
  6304. CRoxieServerDedupActivity::start(parentExtractSize, parentExtract, paused);
  6305. IInputSteppingMeta * stepMeta = input->querySteppingMeta();
  6306. stepCompare = NULL;
  6307. if (stepMeta)
  6308. stepCompare = stepMeta->queryCompare();
  6309. }
  6310. virtual void reset()
  6311. {
  6312. ReleaseClearRoxieRow(prev);
  6313. CRoxieServerDedupActivity::reset();
  6314. }
  6315. virtual const void * nextRow()
  6316. {
  6317. ActivityTimer t(totalCycles, timeActivities);
  6318. const void * next;
  6319. loop
  6320. {
  6321. next = inputStream->nextRow();
  6322. if (!prev || !next || !helper.matches(prev,next))
  6323. {
  6324. numKept = 0;
  6325. break;
  6326. }
  6327. if (numKept < numToKeep-1)
  6328. {
  6329. numKept++;
  6330. break;
  6331. }
  6332. ReleaseRoxieRow(next);
  6333. }
  6334. ReleaseRoxieRow(prev);
  6335. prev = next;
  6336. if (next)
  6337. {
  6338. LinkRoxieRow(next);
  6339. processed++;
  6340. }
  6341. return next;
  6342. }
  6343. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  6344. {
  6345. ActivityTimer t(totalCycles, timeActivities);
  6346. const void * next;
  6347. loop
  6348. {
  6349. next = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  6350. //If the record was an in-exact match from the index then return it immediately
  6351. //and don't cause it to dedup following legal records.
  6352. if (!wasCompleteMatch)
  6353. {
  6354. assertex(stepExtra.returnMismatches());
  6355. return next;
  6356. }
  6357. if (!prev || !next || !helper.matches(prev,next))
  6358. {
  6359. numKept = 0;
  6360. break;
  6361. }
  6362. if (numKept < numToKeep-1)
  6363. {
  6364. numKept++;
  6365. break;
  6366. }
  6367. //Unusual - deduping by x,y stepped on x,y,z - still want any record back as soon as possible.
  6368. if (stepExtra.returnMismatches())
  6369. {
  6370. //If asked to return mismatches we are only interested in mismatches that will force the stepped
  6371. //condition to advance
  6372. if (stepCompare->docompare(next, seek, numFields) != 0)
  6373. {
  6374. wasCompleteMatch = false;
  6375. break;
  6376. }
  6377. }
  6378. ReleaseRoxieRow(next);
  6379. }
  6380. ReleaseRoxieRow(prev);
  6381. prev = next;
  6382. if (next)
  6383. {
  6384. LinkRoxieRow(next);
  6385. processed++;
  6386. }
  6387. return next;
  6388. }
  6389. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  6390. {
  6391. return input->gatherConjunctions(collector);
  6392. }
  6393. virtual void resetEOF()
  6394. {
  6395. inputStream->resetEOF();
  6396. }
  6397. IInputSteppingMeta * querySteppingMeta()
  6398. {
  6399. return input->querySteppingMeta();
  6400. }
  6401. };
  6402. //=================================================================================
  6403. class CRoxieServerDedupKeepRightActivity : public CRoxieServerDedupActivity
  6404. {
  6405. const void *kept;
  6406. bool first;
  6407. public:
  6408. CRoxieServerDedupKeepRightActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6409. : CRoxieServerDedupActivity(_ctx, _factory, _probeManager)
  6410. {
  6411. kept = NULL;
  6412. first = true;
  6413. }
  6414. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6415. {
  6416. first = true;
  6417. kept = NULL;
  6418. CRoxieServerDedupActivity::start(parentExtractSize, parentExtract, paused);
  6419. }
  6420. virtual void reset()
  6421. {
  6422. ReleaseClearRoxieRow(kept);
  6423. CRoxieServerActivity::reset();
  6424. }
  6425. virtual const void * nextRow()
  6426. {
  6427. ActivityTimer t(totalCycles, timeActivities);
  6428. if (first)
  6429. {
  6430. kept = inputStream->nextRow();
  6431. first = false;
  6432. }
  6433. const void * next;
  6434. loop
  6435. {
  6436. next = inputStream->nextRow();
  6437. if (!kept || !next || !helper.matches(kept,next))
  6438. {
  6439. numKept = 0;
  6440. break;
  6441. }
  6442. if (numKept < numToKeep-1)
  6443. {
  6444. numKept++;
  6445. break;
  6446. }
  6447. ReleaseRoxieRow(kept);
  6448. kept = next;
  6449. }
  6450. const void * ret = kept;
  6451. kept = next;
  6452. // CTXLOG("dedup returns %p", ret);
  6453. if (ret) processed++;
  6454. return ret;
  6455. }
  6456. };
  6457. class CRoxieServerDedupAllActivity : public CRoxieServerActivity
  6458. {
  6459. IHThorDedupArg &helper;
  6460. unsigned survivorIndex;
  6461. ConstPointerArray survivors;
  6462. bool keepLeft;
  6463. bool eof;
  6464. bool first;
  6465. ICompare *primaryCompare;
  6466. public:
  6467. CRoxieServerDedupAllActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _keepLeft)
  6468. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorDedupArg &)basehelper)
  6469. {
  6470. keepLeft = _keepLeft;
  6471. primaryCompare = helper.queryComparePrimary();
  6472. eof = false;
  6473. first = true;
  6474. survivorIndex = 0;
  6475. }
  6476. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6477. {
  6478. eof = false;
  6479. first = true;
  6480. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6481. }
  6482. virtual void reset()
  6483. {
  6484. #ifdef _DEBUG
  6485. while (survivors.isItem(survivorIndex))
  6486. {
  6487. ReleaseRoxieRow(survivors.item(survivorIndex++));
  6488. }
  6489. #endif
  6490. survivors.kill();
  6491. eof = false;
  6492. first = true;
  6493. CRoxieServerActivity::reset();
  6494. }
  6495. void dedupRange(unsigned first, unsigned last, ConstPointerArray & group)
  6496. {
  6497. for (unsigned idxL = first; idxL < last; idxL++)
  6498. {
  6499. const void * left = group.item(idxL);
  6500. if (left)
  6501. {
  6502. for (unsigned idxR = first; idxR < last; idxR++)
  6503. {
  6504. const void * right = group.item(idxR);
  6505. if ((idxL != idxR) && right)
  6506. {
  6507. if (helper.matches(left, right))
  6508. {
  6509. if (keepLeft)
  6510. {
  6511. group.replace(NULL, idxR);
  6512. ReleaseRoxieRow(right);
  6513. }
  6514. else
  6515. {
  6516. group.replace(NULL, idxL);
  6517. ReleaseRoxieRow(left);
  6518. break;
  6519. }
  6520. }
  6521. }
  6522. }
  6523. }
  6524. }
  6525. }
  6526. void dedupRange(unsigned first, unsigned last, void ** rows)
  6527. {
  6528. for (unsigned idxL = first; idxL < last; idxL++)
  6529. {
  6530. void * left = rows[idxL];
  6531. if (left)
  6532. {
  6533. for (unsigned idxR = first; idxR < last; idxR++)
  6534. {
  6535. void * right = rows[idxR];
  6536. if ((idxL != idxR) && right)
  6537. {
  6538. if (helper.matches(left, right))
  6539. {
  6540. if (keepLeft)
  6541. {
  6542. rows[idxR] = NULL;
  6543. ReleaseRoxieRow(right);
  6544. }
  6545. else
  6546. {
  6547. rows[idxL] = NULL;
  6548. ReleaseRoxieRow(left);
  6549. break;
  6550. }
  6551. }
  6552. }
  6553. }
  6554. }
  6555. }
  6556. }
  6557. bool calcNextDedupAll()
  6558. {
  6559. survivors.kill();
  6560. survivorIndex = 0;
  6561. ConstPointerArray group;
  6562. if (eof || !inputStream->nextGroup(group))
  6563. {
  6564. eof = true;
  6565. return false;
  6566. }
  6567. unsigned max = group.ordinality();
  6568. if (primaryCompare)
  6569. {
  6570. //hard, if not impossible, to hit this code once optimisations in place
  6571. MemoryAttr indexbuff(max*sizeof(void *));
  6572. void ** temp = (void **)indexbuff.bufferBase();
  6573. void * *rows = const_cast<void * *>(group.getArray());
  6574. msortvecstableinplace(rows, max, *primaryCompare, temp);
  6575. unsigned first = 0;
  6576. for (unsigned idx = 1; idx < max; idx++)
  6577. {
  6578. if (primaryCompare->docompare(rows[first], rows[idx]) != 0)
  6579. {
  6580. dedupRange(first, idx, rows);
  6581. first = idx;
  6582. }
  6583. }
  6584. dedupRange(first, max, rows);
  6585. for(unsigned idx2=0; idx2<max; ++idx2)
  6586. {
  6587. void * cur = rows[idx2];
  6588. if(cur)
  6589. survivors.append(cur);
  6590. }
  6591. }
  6592. else
  6593. {
  6594. dedupRange(0, max, group);
  6595. for(unsigned idx=0; idx<max; ++idx)
  6596. {
  6597. const void * cur = group.item(idx);
  6598. if(cur)
  6599. survivors.append(cur);
  6600. }
  6601. }
  6602. return true;
  6603. }
  6604. virtual const void *nextRow()
  6605. {
  6606. ActivityTimer t(totalCycles, timeActivities);
  6607. if (first)
  6608. {
  6609. calcNextDedupAll();
  6610. first = false;
  6611. }
  6612. while (survivors.isItem(survivorIndex))
  6613. {
  6614. const void *ret = survivors.item(survivorIndex++);
  6615. if (ret)
  6616. {
  6617. processed++;
  6618. return ret;
  6619. }
  6620. }
  6621. calcNextDedupAll();
  6622. return NULL;
  6623. }
  6624. };
  6625. class CRoxieServerDedupActivityFactory : public CRoxieServerActivityFactory
  6626. {
  6627. bool compareAll;
  6628. bool keepLeft;
  6629. public:
  6630. CRoxieServerDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  6631. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  6632. {
  6633. Owned<IHThorDedupArg> helper = (IHThorDedupArg *) helperFactory();
  6634. compareAll = helper->compareAll();
  6635. keepLeft = helper->keepLeft();
  6636. }
  6637. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  6638. {
  6639. if (compareAll)
  6640. return new CRoxieServerDedupAllActivity(_ctx, this, _probeManager, keepLeft);
  6641. else if (keepLeft)
  6642. return new CRoxieServerDedupKeepLeftActivity(_ctx, this, _probeManager);
  6643. else
  6644. return new CRoxieServerDedupKeepRightActivity(_ctx, this, _probeManager);
  6645. }
  6646. };
  6647. IRoxieServerActivityFactory *createRoxieServerDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  6648. {
  6649. return new CRoxieServerDedupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  6650. }
  6651. //=================================================================================
  6652. class CRoxieServerHashDedupActivity : public CRoxieServerActivity
  6653. {
  6654. bool eof;
  6655. IHThorHashDedupArg &helper;
  6656. class HashDedupElement
  6657. {
  6658. public:
  6659. HashDedupElement(unsigned _hash, const void *_keyRow)
  6660. : hash(_hash), keyRow(_keyRow)
  6661. {
  6662. }
  6663. ~HashDedupElement()
  6664. {
  6665. ReleaseRoxieRow(keyRow);
  6666. }
  6667. inline unsigned queryHash() const
  6668. {
  6669. return hash;
  6670. }
  6671. inline const void *queryRow() const
  6672. {
  6673. return keyRow;
  6674. }
  6675. private:
  6676. unsigned hash;
  6677. const void *keyRow;
  6678. };
  6679. class HashDedupTable : public SuperHashTable
  6680. {
  6681. public:
  6682. HashDedupTable(IHThorHashDedupArg & _helper, unsigned _activityId)
  6683. : helper(_helper),
  6684. activityId(_activityId),
  6685. keySize(helper.queryKeySize())
  6686. {
  6687. }
  6688. virtual ~HashDedupTable() { _releaseAll(); }
  6689. virtual unsigned getHashFromElement(const void *et) const
  6690. {
  6691. const HashDedupElement *element = reinterpret_cast<const HashDedupElement *>(et);
  6692. return element->queryHash();
  6693. }
  6694. virtual unsigned getHashFromFindParam(const void *fp) const { throwUnexpected(); }
  6695. virtual const void * getFindParam(const void *et) const { throwUnexpected(); }
  6696. virtual bool matchesElement(const void *et, const void *searchET) const { throwUnexpected(); }
  6697. virtual bool matchesFindParam(const void *et, const void *key, unsigned fphash) const
  6698. {
  6699. const HashDedupElement *element = reinterpret_cast<const HashDedupElement *>(et);
  6700. if (fphash != element->queryHash())
  6701. return false;
  6702. return (helper.queryKeyCompare()->docompare(element->queryRow(), key) == 0);
  6703. }
  6704. virtual void onAdd(void *et) {}
  6705. virtual void onRemove(void *et)
  6706. {
  6707. const HashDedupElement *element = reinterpret_cast<const HashDedupElement *>(et);
  6708. delete element;
  6709. }
  6710. void onCreate(IRoxieSlaveContext *ctx)
  6711. {
  6712. keyRowAllocator.setown(ctx->queryCodeContext()->getRowAllocator(keySize.queryOriginal(), activityId));
  6713. }
  6714. void reset()
  6715. {
  6716. kill();
  6717. }
  6718. bool insert(const void * row)
  6719. {
  6720. unsigned hash = helper.queryHash()->hash(row);
  6721. RtlDynamicRowBuilder keyRowBuilder(keyRowAllocator, true);
  6722. size32_t thisKeySize = helper.recordToKey(keyRowBuilder, row);
  6723. OwnedConstRoxieRow keyRow = keyRowBuilder.finalizeRowClear(thisKeySize);
  6724. if (find(hash, keyRow.get()))
  6725. return false;
  6726. addNew(new HashDedupElement(hash, keyRow.getClear()), hash);
  6727. return true;
  6728. }
  6729. private:
  6730. IHThorHashDedupArg & helper;
  6731. CachedOutputMetaData keySize;
  6732. Owned<IEngineRowAllocator> keyRowAllocator;
  6733. unsigned activityId;
  6734. } table;
  6735. public:
  6736. CRoxieServerHashDedupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6737. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorHashDedupArg &)basehelper), table(helper, activityId)
  6738. {
  6739. eof = false;
  6740. }
  6741. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6742. {
  6743. eof = false;
  6744. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6745. }
  6746. virtual void onCreate(IHThorArg *_colocalParent)
  6747. {
  6748. CRoxieServerActivity::onCreate(colocalParent);
  6749. table.onCreate(ctx);
  6750. }
  6751. virtual void reset()
  6752. {
  6753. table.reset();
  6754. eof = false;
  6755. CRoxieServerActivity::reset();
  6756. }
  6757. virtual const void *nextRow()
  6758. {
  6759. ActivityTimer t(totalCycles, timeActivities);
  6760. while(!eof)
  6761. {
  6762. const void * next = inputStream->nextRow();
  6763. if(!next)
  6764. {
  6765. if (table.count() == 0)
  6766. eof = true;
  6767. table.reset();
  6768. return NULL;
  6769. }
  6770. if(table.insert(next))
  6771. return next;
  6772. else
  6773. ReleaseRoxieRow(next);
  6774. }
  6775. return NULL;
  6776. }
  6777. };
  6778. class CRoxieServerHashDedupActivityFactory : public CRoxieServerActivityFactory
  6779. {
  6780. public:
  6781. CRoxieServerHashDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  6782. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  6783. {
  6784. }
  6785. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  6786. {
  6787. return new CRoxieServerHashDedupActivity(_ctx, this, _probeManager);
  6788. }
  6789. };
  6790. IRoxieServerActivityFactory *createRoxieServerHashDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  6791. {
  6792. return new CRoxieServerHashDedupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  6793. }
  6794. //=================================================================================
  6795. class CRoxieServerRollupActivity : public CRoxieServerActivity
  6796. {
  6797. IHThorRollupArg &helper;
  6798. OwnedConstRoxieRow left;
  6799. OwnedConstRoxieRow prev;
  6800. OwnedConstRoxieRow right;
  6801. bool readFirstRow;
  6802. public:
  6803. CRoxieServerRollupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6804. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorRollupArg &)basehelper)
  6805. {
  6806. readFirstRow = false;
  6807. }
  6808. ~CRoxieServerRollupActivity()
  6809. {
  6810. }
  6811. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6812. {
  6813. readFirstRow = false;
  6814. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6815. }
  6816. virtual void reset()
  6817. {
  6818. left.clear();
  6819. prev.clear();
  6820. right.clear();
  6821. CRoxieServerActivity::reset();
  6822. }
  6823. virtual bool needsAllocator() const { return true; }
  6824. virtual const void * nextRow()
  6825. {
  6826. ActivityTimer t(totalCycles, timeActivities);
  6827. if (!readFirstRow)
  6828. {
  6829. left.setown(inputStream->nextRow());
  6830. prev.set(left);
  6831. readFirstRow = true;
  6832. }
  6833. loop
  6834. {
  6835. right.setown(inputStream->nextRow());
  6836. if(!prev || !right || !helper.matches(prev,right))
  6837. {
  6838. const void * ret = left.getClear();
  6839. if(ret)
  6840. processed++;
  6841. left.setown(right.getClear());
  6842. prev.set(left);
  6843. return ret;
  6844. }
  6845. try
  6846. {
  6847. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  6848. unsigned outSize = helper.transform(rowBuilder, left, right);
  6849. if (outSize)
  6850. left.setown(rowBuilder.finalizeRowClear(outSize));
  6851. if (helper.getFlags() & RFrolledismatchleft)
  6852. prev.set(left);
  6853. else
  6854. prev.set(right);
  6855. }
  6856. catch(IException * E)
  6857. {
  6858. throw makeWrappedException(E);
  6859. }
  6860. }
  6861. }
  6862. };
  6863. class CRoxieServerRollupActivityFactory : public CRoxieServerActivityFactory
  6864. {
  6865. public:
  6866. CRoxieServerRollupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  6867. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  6868. {
  6869. }
  6870. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  6871. {
  6872. return new CRoxieServerRollupActivity(_ctx, this, _probeManager);
  6873. }
  6874. };
  6875. IRoxieServerActivityFactory *createRoxieServerRollupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  6876. {
  6877. return new CRoxieServerRollupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  6878. }
  6879. //=================================================================================
  6880. class CRoxieServerNormalizeActivity : public CRoxieServerActivity
  6881. {
  6882. IHThorNormalizeArg &helper;
  6883. unsigned numThisRow;
  6884. unsigned curRow;
  6885. const void *buffer;
  6886. unsigned numProcessedLastGroup;
  6887. public:
  6888. CRoxieServerNormalizeActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6889. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorNormalizeArg &)basehelper)
  6890. {
  6891. buffer = NULL;
  6892. numThisRow = 0;
  6893. curRow = 0;
  6894. numProcessedLastGroup = 0;
  6895. }
  6896. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6897. {
  6898. numThisRow = 0;
  6899. curRow = 0;
  6900. numProcessedLastGroup = 0;
  6901. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6902. }
  6903. virtual void reset()
  6904. {
  6905. ReleaseClearRoxieRow(buffer);
  6906. CRoxieServerActivity::reset();
  6907. }
  6908. virtual bool needsAllocator() const { return true; }
  6909. virtual const void * nextRow()
  6910. {
  6911. ActivityTimer t(totalCycles, timeActivities);
  6912. loop
  6913. {
  6914. while (curRow == numThisRow)
  6915. {
  6916. if (buffer)
  6917. ReleaseClearRoxieRow(buffer);
  6918. buffer = inputStream->nextRow();
  6919. if (!buffer && (processed == numProcessedLastGroup))
  6920. buffer = inputStream->nextRow();
  6921. if (!buffer)
  6922. {
  6923. numProcessedLastGroup = processed;
  6924. return NULL;
  6925. }
  6926. curRow = 0;
  6927. numThisRow = helper.numExpandedRows(buffer);
  6928. }
  6929. try
  6930. {
  6931. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  6932. unsigned actualSize = helper.transform(rowBuilder, buffer, ++curRow);
  6933. if (actualSize != 0)
  6934. {
  6935. processed++;
  6936. return rowBuilder.finalizeRowClear(actualSize);
  6937. }
  6938. }
  6939. catch (IException *E)
  6940. {
  6941. throw makeWrappedException(E);
  6942. }
  6943. }
  6944. }
  6945. };
  6946. class CRoxieServerNormalizeActivityFactory : public CRoxieServerActivityFactory
  6947. {
  6948. public:
  6949. CRoxieServerNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  6950. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  6951. {
  6952. }
  6953. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  6954. {
  6955. return new CRoxieServerNormalizeActivity(_ctx, this, _probeManager);
  6956. }
  6957. };
  6958. IRoxieServerActivityFactory *createRoxieServerNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  6959. {
  6960. return new CRoxieServerNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  6961. }
  6962. //=================================================================================
  6963. class CRoxieServerNormalizeChildActivity : public CRoxieServerActivity
  6964. {
  6965. IHThorNormalizeChildArg &helper;
  6966. unsigned numThisRow;
  6967. unsigned curRow;
  6968. const void *buffer;
  6969. unsigned numProcessedLastGroup;
  6970. INormalizeChildIterator * cursor;
  6971. const void * curChildRow;
  6972. bool advanceInput()
  6973. {
  6974. loop
  6975. {
  6976. ReleaseClearRoxieRow(buffer);
  6977. buffer = inputStream->nextRow();
  6978. if (!buffer && (processed == numProcessedLastGroup))
  6979. buffer = inputStream->nextRow();
  6980. if (!buffer)
  6981. {
  6982. numProcessedLastGroup = processed;
  6983. return false;
  6984. }
  6985. curChildRow = cursor->first(buffer);
  6986. if (curChildRow)
  6987. {
  6988. curRow = 0;
  6989. return true;
  6990. }
  6991. }
  6992. }
  6993. public:
  6994. CRoxieServerNormalizeChildActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6995. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorNormalizeChildArg &)basehelper)
  6996. {
  6997. buffer = NULL;
  6998. cursor = NULL;
  6999. numThisRow = 0;
  7000. curRow = 0;
  7001. numProcessedLastGroup = 0;
  7002. curChildRow = NULL;
  7003. }
  7004. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7005. {
  7006. numThisRow = 0;
  7007. curRow = 0;
  7008. numProcessedLastGroup = 0;
  7009. curChildRow = NULL;
  7010. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7011. cursor = helper.queryIterator();
  7012. }
  7013. virtual void stop()
  7014. {
  7015. CRoxieServerActivity::stop();
  7016. }
  7017. virtual void reset()
  7018. {
  7019. cursor = NULL;
  7020. ReleaseClearRoxieRow(buffer);
  7021. CRoxieServerActivity::reset();
  7022. }
  7023. virtual bool needsAllocator() const { return true; }
  7024. const void *nextRow()
  7025. {
  7026. ActivityTimer t(totalCycles, timeActivities);
  7027. loop
  7028. {
  7029. if (!buffer)
  7030. {
  7031. if (!advanceInput())
  7032. return NULL;
  7033. }
  7034. try
  7035. {
  7036. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  7037. size32_t outSize = helper.transform(rowBuilder, buffer, curChildRow, ++curRow);
  7038. curChildRow = cursor->next();
  7039. if (!curChildRow)
  7040. ReleaseClearRoxieRow(buffer);
  7041. if (outSize != 0)
  7042. {
  7043. processed++;
  7044. return rowBuilder.finalizeRowClear(outSize);
  7045. }
  7046. }
  7047. catch (IException *E)
  7048. {
  7049. throw makeWrappedException(E);
  7050. }
  7051. }
  7052. }
  7053. };
  7054. class CRoxieServerNormalizeChildActivityFactory : public CRoxieServerActivityFactory
  7055. {
  7056. public:
  7057. CRoxieServerNormalizeChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7058. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  7059. {
  7060. }
  7061. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  7062. {
  7063. return new CRoxieServerNormalizeChildActivity(_ctx, this, _probeManager);
  7064. }
  7065. };
  7066. IRoxieServerActivityFactory *createRoxieServerNormalizeChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7067. {
  7068. return new CRoxieServerNormalizeChildActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  7069. }
  7070. //=================================================================================
  7071. class CRoxieServerNormalizeLinkedChildActivity : public CRoxieServerActivity
  7072. {
  7073. IHThorNormalizeLinkedChildArg &helper;
  7074. OwnedConstRoxieRow curParent;
  7075. OwnedConstRoxieRow curChild;
  7076. unsigned numProcessedLastGroup;
  7077. bool advanceInput()
  7078. {
  7079. loop
  7080. {
  7081. curParent.setown(inputStream->nextRow());
  7082. if (!curParent && (processed == numProcessedLastGroup))
  7083. curParent.setown(inputStream->nextRow());
  7084. if (!curParent)
  7085. {
  7086. numProcessedLastGroup = processed;
  7087. return false;
  7088. }
  7089. curChild.set(helper.first(curParent));
  7090. if (curChild)
  7091. return true;
  7092. }
  7093. }
  7094. public:
  7095. CRoxieServerNormalizeLinkedChildActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  7096. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorNormalizeLinkedChildArg &)basehelper)
  7097. {
  7098. numProcessedLastGroup = 0;
  7099. }
  7100. ~CRoxieServerNormalizeLinkedChildActivity()
  7101. {
  7102. }
  7103. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7104. {
  7105. numProcessedLastGroup = 0;
  7106. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7107. }
  7108. virtual void reset()
  7109. {
  7110. curParent.clear();
  7111. curChild.clear();
  7112. CRoxieServerActivity::reset();
  7113. }
  7114. const void *nextRow()
  7115. {
  7116. ActivityTimer t(totalCycles, timeActivities);
  7117. loop
  7118. {
  7119. if (!curParent)
  7120. {
  7121. if (!advanceInput())
  7122. return NULL;
  7123. }
  7124. try
  7125. {
  7126. const void *ret = curChild.getClear();
  7127. curChild.set(helper.next());
  7128. if (!curChild)
  7129. curParent.clear();
  7130. if (ret)
  7131. {
  7132. processed++;
  7133. return ret;
  7134. }
  7135. }
  7136. catch (IException *E)
  7137. {
  7138. throw makeWrappedException(E);
  7139. }
  7140. }
  7141. }
  7142. };
  7143. class CRoxieServerNormalizeLinkedChildActivityFactory : public CRoxieServerActivityFactory
  7144. {
  7145. public:
  7146. CRoxieServerNormalizeLinkedChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7147. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  7148. {
  7149. }
  7150. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  7151. {
  7152. return new CRoxieServerNormalizeLinkedChildActivity(_ctx, this, _probeManager);
  7153. }
  7154. };
  7155. IRoxieServerActivityFactory *createRoxieServerNormalizeLinkedChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7156. {
  7157. return new CRoxieServerNormalizeLinkedChildActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  7158. }
  7159. //=================================================================================
  7160. class CRoxieServerSortActivity : public CRoxieServerActivity
  7161. {
  7162. protected:
  7163. IHThorSortArg &helper;
  7164. ICompare *compare;
  7165. Owned<ISortAlgorithm> sorter;
  7166. bool readInput;
  7167. RoxieSortAlgorithm sortAlgorithm;
  7168. unsigned sortFlags;
  7169. public:
  7170. CRoxieServerSortActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, RoxieSortAlgorithm _sortAlgorithm, unsigned _sortFlags)
  7171. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorSortArg &)basehelper), sortAlgorithm(_sortAlgorithm), sortFlags(_sortFlags)
  7172. {
  7173. compare = helper.queryCompare();
  7174. readInput = false;
  7175. }
  7176. virtual void onCreate(IHThorArg *_colocalParent)
  7177. {
  7178. CRoxieServerActivity::onCreate(_colocalParent);
  7179. if (sortAlgorithm==unknownSortAlgorithm)
  7180. sorter.clear();
  7181. else
  7182. sorter.setown(createSortAlgorithm(sortAlgorithm, compare, ctx->queryRowManager(), meta, ctx->queryCodeContext(), tempDirectory, activityId));
  7183. }
  7184. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7185. {
  7186. assertex(!readInput);
  7187. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7188. }
  7189. virtual void reset()
  7190. {
  7191. if (sorter)
  7192. sorter->reset();
  7193. readInput = false;
  7194. CRoxieServerActivity::reset();
  7195. }
  7196. static RoxieSortAlgorithm useAlgorithm(const char *algorithmName, unsigned sortFlags)
  7197. {
  7198. RoxieSortAlgorithm sortAlgorithm = unknownSortAlgorithm;
  7199. if (!algorithmName)
  7200. algorithmName = "";
  7201. if (stricmp(algorithmName, "quicksort")==0)
  7202. {
  7203. switch (sortFlags & (TAFstable|TAFspill))
  7204. {
  7205. case 0: sortAlgorithm = quickSortAlgorithm; break;
  7206. case TAFstable: sortAlgorithm = stableQuickSortAlgorithm; break;
  7207. case TAFspill: sortAlgorithm = spillingQuickSortAlgorithm; break;
  7208. case TAFstable|TAFspill: sortAlgorithm = stableSpillingQuickSortAlgorithm; break;
  7209. }
  7210. }
  7211. else if (stricmp(algorithmName, "parquicksort")==0)
  7212. {
  7213. switch (sortFlags & TAFstable)
  7214. {
  7215. case 0: sortAlgorithm = parallelQuickSortAlgorithm; break;
  7216. case TAFstable: sortAlgorithm = parallelStableQuickSortAlgorithm; break;
  7217. default: throwUnexpected();
  7218. }
  7219. }
  7220. else if (stricmp(algorithmName, "heapsort")==0)
  7221. sortAlgorithm = heapSortAlgorithm; // NOTE - we do allow UNSTABLE('heapsort') in order to facilitate runtime selection. Also explicit selection of heapsort overrides request to spill
  7222. else if (stricmp(algorithmName, "mergesort")==0)
  7223. sortAlgorithm = (sortFlags & TAFspill) ? spillingMergeSortAlgorithm : mergeSortAlgorithm;
  7224. else if (stricmp(algorithmName, "parmergesort")==0)
  7225. sortAlgorithm = (sortFlags & TAFspill) ? spillingParallelMergeSortAlgorithm : parallelMergeSortAlgorithm;
  7226. else if (stricmp(algorithmName, "tbbqsort")==0)
  7227. sortAlgorithm = tbbQuickSortAlgorithm;
  7228. else if (stricmp(algorithmName, "tbbstableqsort")==0)
  7229. sortAlgorithm = tbbStableQuickSortAlgorithm;
  7230. else
  7231. {
  7232. if (*algorithmName)
  7233. WARNLOG(ROXIE_UNKNOWN_ALGORITHM, "Ignoring unsupported sort order algorithm '%s', using default", algorithmName);
  7234. if (sortFlags & TAFspill)
  7235. sortAlgorithm = ((sortFlags & TAFunstable) != 0) ? spillingQuickSortAlgorithm : stableSpillingQuickSortAlgorithm;
  7236. else if (sortFlags & TAFunstable)
  7237. sortAlgorithm = quickSortAlgorithm;
  7238. else
  7239. sortAlgorithm = heapSortAlgorithm;
  7240. }
  7241. return sortAlgorithm;
  7242. }
  7243. virtual const void * nextRow()
  7244. {
  7245. ActivityTimer t(totalCycles, timeActivities);
  7246. if (!readInput)
  7247. {
  7248. if (sortAlgorithm == unknownSortAlgorithm)
  7249. {
  7250. sorter.clear();
  7251. IHThorAlgorithm *sortMethod = static_cast<IHThorAlgorithm *>(helper.selectInterface(TAIalgorithm_1));
  7252. OwnedRoxieString algorithmName(sortMethod->getAlgorithm());
  7253. sortAlgorithm = useAlgorithm(algorithmName, sortFlags);
  7254. sorter.setown(createSortAlgorithm(sortAlgorithm, compare, ctx->queryRowManager(), meta, ctx->queryCodeContext(), tempDirectory, activityId));
  7255. }
  7256. sorter->prepare(inputStream);
  7257. noteStatistic(StTimeSortElapsed, cycle_to_nanosec(sorter->getElapsedCycles(true)));
  7258. readInput = true;
  7259. }
  7260. const void *ret = sorter->next();
  7261. if (ret)
  7262. processed++;
  7263. else
  7264. {
  7265. sorter->reset();
  7266. readInput = false; // ready for next group
  7267. }
  7268. return ret;
  7269. }
  7270. };
  7271. class CRoxieServerSortActivityFactory : public CRoxieServerActivityFactory
  7272. {
  7273. RoxieSortAlgorithm sortAlgorithm;
  7274. unsigned sortFlags;
  7275. public:
  7276. CRoxieServerSortActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7277. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  7278. {
  7279. Owned<IHThorSortArg> sortHelper = (IHThorSortArg *) helperFactory();
  7280. const char *algorithmName = NULL;
  7281. IHThorAlgorithm *sortMethod = static_cast<IHThorAlgorithm *>(sortHelper->selectInterface(TAIalgorithm_1));
  7282. if (sortMethod)
  7283. {
  7284. sortFlags = sortMethod->getAlgorithmFlags();
  7285. if (sortFlags & TAFconstant)
  7286. algorithmName = sortMethod->getAlgorithm();
  7287. }
  7288. else
  7289. sortFlags = TAFstable|TAFconstant;
  7290. bool forceSpill = _queryFactory.queryOptions().allSortsMaySpill || _graphNode.getPropBool("hint[@name='spill']/@value", false);
  7291. if (forceSpill)
  7292. sortFlags |= TAFspill;
  7293. if (!(sortFlags & TAFunstable))
  7294. sortFlags |= TAFstable; // Assume stable unless specifically requested otherwise
  7295. if (sortFlags & TAFconstant)
  7296. sortAlgorithm = CRoxieServerSortActivity::useAlgorithm(algorithmName, sortFlags);
  7297. else
  7298. sortAlgorithm = unknownSortAlgorithm;
  7299. }
  7300. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  7301. {
  7302. return new CRoxieServerSortActivity(_ctx, this, _probeManager, sortAlgorithm, sortFlags);
  7303. }
  7304. virtual const StatisticsMapping &queryStatsMapping() const
  7305. {
  7306. return sortStatistics;
  7307. }
  7308. };
  7309. IRoxieServerActivityFactory *createRoxieServerSortActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7310. {
  7311. return new CRoxieServerSortActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  7312. }
  7313. //=====================================================================================================
  7314. static int compareUint64(const void * _left, const void * _right)
  7315. {
  7316. const unsigned __int64 left = *static_cast<const unsigned __int64 *>(_left);
  7317. const unsigned __int64 right = *static_cast<const unsigned __int64 *>(_right);
  7318. if (left < right)
  7319. return -1;
  7320. if (left > right)
  7321. return -1;
  7322. return 0;
  7323. }
  7324. class CRoxieServerQuantileActivity : public CRoxieServerActivity
  7325. {
  7326. protected:
  7327. Owned<ISortAlgorithm> sorter;
  7328. IHThorQuantileArg &helper;
  7329. ConstPointerArray sorted;
  7330. ICompare *compare;
  7331. unsigned flags;
  7332. double skew;
  7333. unsigned __int64 numDivisions;
  7334. bool rangeIsAll;
  7335. size32_t rangeSize;
  7336. rtlDataAttr rangeValues;
  7337. bool calculated;
  7338. bool processedAny;
  7339. bool anyThisGroup;
  7340. bool eof;
  7341. unsigned curQuantile;
  7342. unsigned curIndex;
  7343. unsigned curIndexExtra;
  7344. unsigned skipSize;
  7345. unsigned skipExtra;
  7346. unsigned prevIndex;
  7347. public:
  7348. CRoxieServerQuantileActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _flags)
  7349. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorQuantileArg &)basehelper), flags(_flags)
  7350. {
  7351. compare = helper.queryCompare();
  7352. skew = 0.0;
  7353. numDivisions = 0;
  7354. calculated = false;
  7355. processedAny = false;
  7356. anyThisGroup = false;
  7357. eof = false;
  7358. rangeIsAll = true;
  7359. rangeSize = 0;
  7360. curQuantile = 0;
  7361. prevIndex = 0;
  7362. curIndex = 0;
  7363. curIndexExtra = 0;
  7364. skipSize = 0;
  7365. skipExtra = 0;
  7366. if (flags & TQFunstable)
  7367. sorter.setown(createQuickSortAlgorithm(compare));
  7368. else
  7369. sorter.setown(createMergeSortAlgorithm(compare));
  7370. }
  7371. virtual void reset()
  7372. {
  7373. sorter->reset();
  7374. calculated = false;
  7375. processedAny = false;
  7376. anyThisGroup = false;
  7377. CRoxieServerActivity::reset();
  7378. }
  7379. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7380. {
  7381. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7382. skew = helper.getSkew();
  7383. numDivisions = helper.getNumDivisions();
  7384. //Check for -ve integer values and treat as out of range
  7385. if ((__int64)numDivisions < 1)
  7386. numDivisions = 1;
  7387. if (flags & TQFhasrange)
  7388. helper.getRange(rangeIsAll, rangeSize, rangeValues.refdata());
  7389. else
  7390. {
  7391. rangeIsAll = true;
  7392. rangeSize = 0;
  7393. }
  7394. if (rangeSize)
  7395. {
  7396. //Sort the range items into order to allow quick comparison
  7397. qsort(rangeValues.getdata(), rangeSize / sizeof(unsigned __int64), sizeof(unsigned __int64), compareUint64);
  7398. }
  7399. calculated = false;
  7400. processedAny = false;
  7401. anyThisGroup = false;
  7402. eof = false;
  7403. curQuantile = 0;
  7404. prevIndex = 0;
  7405. curIndex = 0;
  7406. curIndexExtra = 0;
  7407. }
  7408. virtual bool needsAllocator() const { return true; }
  7409. virtual const void * nextRow()
  7410. {
  7411. ActivityTimer t(totalCycles, timeActivities);
  7412. if (eof)
  7413. return NULL;
  7414. const void * ret = NULL;
  7415. for(;;)
  7416. {
  7417. if (!calculated)
  7418. {
  7419. if (flags & TQFlocalsorted)
  7420. {
  7421. for (;;)
  7422. {
  7423. const void * next = inputStream->nextRow();
  7424. if (!next)
  7425. break;
  7426. sorted.append(next);
  7427. }
  7428. }
  7429. else
  7430. {
  7431. sorter->prepare(inputStream);
  7432. sorter->getSortedGroup(sorted);
  7433. }
  7434. if (sorted.ordinality() == 0)
  7435. {
  7436. if (processedAny)
  7437. {
  7438. eof = true;
  7439. return NULL;
  7440. }
  7441. //Unusual case 0 rows - add a default row instead
  7442. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  7443. size32_t thisSize = helper.createDefault(rowBuilder);
  7444. sorted.append(rowBuilder.finalizeRowClear(thisSize));
  7445. }
  7446. calculated = true;
  7447. processedAny = true;
  7448. anyThisGroup = false;
  7449. curQuantile = 0;
  7450. curIndex = 0;
  7451. curIndexExtra = (numDivisions-1) / 2; // to ensure correctly rounded up
  7452. prevIndex = curIndex-1; // Ensure it doesn't match
  7453. skipSize = (sorted.ordinality() / numDivisions);
  7454. skipExtra = (sorted.ordinality() % numDivisions);
  7455. }
  7456. if (isQuantileIncluded(curQuantile))
  7457. {
  7458. if (!(flags & TQFdedup) || (prevIndex != curIndex))
  7459. {
  7460. const void * lhs = sorted.item(curIndex);
  7461. if (flags & TQFneedtransform)
  7462. {
  7463. unsigned outSize;
  7464. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  7465. try
  7466. {
  7467. outSize = helper.transform(rowBuilder, lhs, curQuantile);
  7468. }
  7469. catch (IException *E)
  7470. {
  7471. throw makeWrappedException(E);
  7472. }
  7473. if (outSize)
  7474. ret = rowBuilder.finalizeRowClear(outSize);
  7475. }
  7476. else
  7477. {
  7478. LinkRoxieRow(lhs);
  7479. ret = lhs;
  7480. }
  7481. prevIndex = curIndex; // even if output was skipped?
  7482. }
  7483. }
  7484. curIndex += skipSize;
  7485. curIndexExtra += skipExtra;
  7486. if (curIndexExtra >= numDivisions)
  7487. {
  7488. curIndex++;
  7489. curIndexExtra -= numDivisions;
  7490. }
  7491. //Ensure the current index always stays valid.
  7492. if (curIndex >= sorted.ordinality())
  7493. curIndex = sorted.ordinality()-1;
  7494. curQuantile++;
  7495. if (curQuantile > numDivisions)
  7496. {
  7497. sorted.kill();
  7498. sorter->reset();
  7499. calculated = false; // ready for next group
  7500. }
  7501. if (ret)
  7502. {
  7503. anyThisGroup = true;
  7504. processed++;
  7505. return ret;
  7506. }
  7507. if (curQuantile > numDivisions)
  7508. {
  7509. if (anyThisGroup)
  7510. return NULL;
  7511. }
  7512. }
  7513. }
  7514. bool isQuantileIncluded(unsigned quantile) const
  7515. {
  7516. if (quantile == 0)
  7517. return (flags & TQFfirst) != 0;
  7518. if (quantile == numDivisions)
  7519. return (flags & TQFlast) != 0;
  7520. if (rangeIsAll)
  7521. return true;
  7522. //Compare against the list of ranges provided
  7523. //MORE: Since the list is sorted should only need to compare the next (and allow for dups)
  7524. unsigned rangeNum = rangeSize / sizeof(unsigned __int64);
  7525. const unsigned __int64 * ranges = static_cast<const unsigned __int64 *>(rangeValues.getdata());
  7526. for (unsigned i = 0; i < rangeNum; i++)
  7527. {
  7528. if (ranges[i] == quantile)
  7529. return true;
  7530. }
  7531. return false;
  7532. }
  7533. };
  7534. class CRoxieServerQuantileActivityFactory : public CRoxieServerActivityFactory
  7535. {
  7536. unsigned flags;
  7537. public:
  7538. CRoxieServerQuantileActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7539. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  7540. {
  7541. Owned<IHThorQuantileArg> quantileHelper = (IHThorQuantileArg *) helperFactory();
  7542. flags = quantileHelper->getFlags();
  7543. }
  7544. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  7545. {
  7546. return new CRoxieServerQuantileActivity(_ctx, this, _probeManager, flags);
  7547. }
  7548. };
  7549. IRoxieServerActivityFactory *createRoxieServerQuantileActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7550. {
  7551. return new CRoxieServerQuantileActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  7552. }
  7553. //=====================================================================================================
  7554. class CRoxieServerSortedActivity : public CRoxieServerActivity
  7555. {
  7556. IHThorSortedArg &helper;
  7557. ICompare * compare;
  7558. const void *prev;
  7559. IRangeCompare * stepCompare;
  7560. public:
  7561. CRoxieServerSortedActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  7562. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorSortedArg &)basehelper)
  7563. {
  7564. prev = NULL;
  7565. compare = helper.queryCompare();
  7566. stepCompare = NULL;
  7567. }
  7568. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7569. {
  7570. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7571. IInputSteppingMeta * stepMeta = input->querySteppingMeta();
  7572. if (stepMeta)
  7573. stepCompare = stepMeta->queryCompare();
  7574. prev = NULL;
  7575. }
  7576. virtual void reset()
  7577. {
  7578. ReleaseClearRoxieRow(prev);
  7579. CRoxieServerActivity::reset();
  7580. }
  7581. virtual const void * nextRow()
  7582. {
  7583. ActivityTimer t(totalCycles, timeActivities);
  7584. const void *ret = inputStream->nextRow();
  7585. if (ret && prev && compare->docompare(prev, ret) > 0)
  7586. {
  7587. // MORE - better to give mismatching rows that indexes?
  7588. throw MakeStringException(ROXIE_NOT_SORTED, "SORTED(%u) detected incorrectly sorted rows (row %d, %d))", activityId, processed, processed+1);
  7589. }
  7590. ReleaseRoxieRow(prev);
  7591. prev = ret;
  7592. if (ret)
  7593. {
  7594. LinkRoxieRow(prev);
  7595. processed++;
  7596. }
  7597. return ret;
  7598. }
  7599. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  7600. {
  7601. ActivityTimer t(totalCycles, timeActivities);
  7602. const void *ret = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  7603. if (ret && prev && compare->docompare(prev, ret) > 0)
  7604. {
  7605. // MORE - better to give mismatching rows that indexes?
  7606. throw MakeStringException(ROXIE_NOT_SORTED, "SORTED(%u) detected incorrectly sorted rows (row %d, %d))", activityId, processed, processed+1);
  7607. }
  7608. ReleaseRoxieRow(prev);
  7609. prev = ret;
  7610. if (ret)
  7611. {
  7612. LinkRoxieRow(prev);
  7613. processed++;
  7614. }
  7615. return ret;
  7616. }
  7617. IInputSteppingMeta * querySteppingMeta()
  7618. {
  7619. return input->querySteppingMeta();
  7620. }
  7621. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  7622. {
  7623. return input->gatherConjunctions(collector);
  7624. }
  7625. virtual void resetEOF()
  7626. {
  7627. inputStream->resetEOF();
  7628. }
  7629. };
  7630. class CRoxieServerSortedActivityFactory : public CRoxieServerActivityFactory
  7631. {
  7632. public:
  7633. CRoxieServerSortedActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7634. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  7635. {
  7636. }
  7637. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  7638. {
  7639. return new CRoxieServerSortedActivity(_ctx, this, _probeManager);
  7640. }
  7641. };
  7642. IRoxieServerActivityFactory *createRoxieServerSortedActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7643. {
  7644. return new CRoxieServerSortedActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  7645. }
  7646. //=====================================================================================================
  7647. class CRoxieServerThroughSpillActivity : public CRoxieServerActivity
  7648. {
  7649. /*
  7650. BE VERY CAREFUL - this code is tricky.
  7651. Note that starts and stops (and resets) can occur in strange orders
  7652. The FIRST start OR stop must initialize the activity but only the first START should call the upstream start.
  7653. The last stop should call the upstream stop.
  7654. The first reset should call the upstream reset.
  7655. 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
  7656. not yet had start or stop called - for this to happen init() is called on all outputs on the first start or stop.
  7657. Some outputs may be completely pruned away when used in a GRAPH - these outputs should not receive any start/stop/reset and should be
  7658. ignored in the minIndex calculation
  7659. */
  7660. public:
  7661. IHThorArg &helper;
  7662. unsigned activeOutputs;
  7663. unsigned numOutputs;
  7664. unsigned numOriginalOutputs;
  7665. QueueOf<const void, true> buffer;
  7666. CriticalSection crit;
  7667. CriticalSection crit2;
  7668. unsigned tailIdx;
  7669. unsigned headIdx;
  7670. Owned<IException> error;
  7671. class OutputAdaptor : public CInterface, implements IFinalRoxieInput, implements IEngineRowStream
  7672. {
  7673. bool eof, eofpending, stopped;
  7674. public:
  7675. CRoxieServerThroughSpillActivity *parent;
  7676. unsigned idx;
  7677. unsigned oid;
  7678. unsigned processed;
  7679. cycle_t totalCycles; // We track this per output so that the pullers get a meaningful value to use when calculating their localtime
  7680. public:
  7681. IMPLEMENT_IINTERFACE;
  7682. OutputAdaptor()
  7683. {
  7684. parent = NULL;
  7685. oid = 0;
  7686. idx = 0;
  7687. processed = 0;
  7688. totalCycles = 0;
  7689. eofpending = false;
  7690. eof = false;
  7691. stopped = false;
  7692. }
  7693. ~OutputAdaptor()
  7694. {
  7695. if (traceStartStop)
  7696. DBGLOG("%p ~OutputAdaptor %d", this, oid);
  7697. if (processed && parent && parent->factory)
  7698. {
  7699. parent->factory->noteProcessed(oid, processed);
  7700. if (parent->ctx)
  7701. parent->ctx->noteProcessed(parent->querySubgraphId(), parent->activityId, oid, processed, 0);
  7702. }
  7703. }
  7704. void init()
  7705. {
  7706. if (traceStartStop)
  7707. DBGLOG("%p init Input adaptor %d", this, oid);
  7708. idx = 0;
  7709. processed = 0;
  7710. eofpending = false;
  7711. eof = false;
  7712. stopped = false;
  7713. }
  7714. virtual IRoxieServerActivity *queryActivity()
  7715. {
  7716. return parent;
  7717. }
  7718. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  7719. {
  7720. return parent->queryIndexReadActivity();
  7721. }
  7722. virtual unsigned __int64 queryTotalCycles() const
  7723. {
  7724. return totalCycles;
  7725. }
  7726. virtual const void * nextRow()
  7727. {
  7728. SimpleActivityTimer t(totalCycles, parent->timeActivities);
  7729. if (eof)
  7730. return NULL;
  7731. const void *ret = parent->readBuffered(idx, oid);
  7732. #ifdef TRACE_SPLIT
  7733. parent->CTXLOG("Adaptor %d got back %p for record %d", oid, ret, idx);
  7734. #endif
  7735. if (ret)
  7736. {
  7737. processed++;
  7738. eofpending = false;
  7739. }
  7740. else if (eofpending)
  7741. eof = true;
  7742. else
  7743. eofpending = true;
  7744. return ret;
  7745. }
  7746. virtual IOutputMetaData * queryOutputMeta() const
  7747. {
  7748. return parent->queryOutputMeta();
  7749. }
  7750. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7751. {
  7752. // NOTE: it is tempting to move the init() of all output adaptors here. However that is not a good idea,
  7753. // since adaptors that have not yet started or stopped (but are going to) still need to have been init()'ed
  7754. // for minIndex to give the correct answers
  7755. // therefore, we call init() on all adaptors on receipt of the first start() or stop()
  7756. if (traceStartStop)
  7757. parent->CTXLOG("%p start Input adaptor %d stopped = %d", this, oid, stopped);
  7758. parent->start(oid, parentExtractSize, parentExtract, paused);
  7759. }
  7760. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  7761. {
  7762. parent->connectInputStreams(consumerOrdered);
  7763. streams.append(this);
  7764. return NULL;
  7765. }
  7766. virtual void stop()
  7767. {
  7768. if (traceStartStop)
  7769. parent->CTXLOG("%p stop Input adaptor %d stopped = %d", this, oid, stopped);
  7770. if (!stopped)
  7771. {
  7772. parent->stop(oid, idx); // NOTE - may call init()
  7773. stopped = true; // parent code relies on stop being called exactly once per adaptor, so make sure it is!
  7774. }
  7775. };
  7776. virtual void reset()
  7777. {
  7778. if (traceStartStop)
  7779. parent->CTXLOG("%p reset Input adaptor %d stopped = %d", this, oid, stopped);
  7780. parent->reset(oid);
  7781. idx = 0; // value should not be relevant really but this is the safest...
  7782. stopped = false;
  7783. };
  7784. virtual void resetEOF()
  7785. {
  7786. parent->resetEOF();
  7787. }
  7788. virtual void checkAbort()
  7789. {
  7790. parent->checkAbort();
  7791. }
  7792. } *adaptors;
  7793. bool *used;
  7794. unsigned nextFreeOutput()
  7795. {
  7796. unsigned i = numOutputs;
  7797. while (i)
  7798. {
  7799. i--;
  7800. if (!used[i])
  7801. return i;
  7802. }
  7803. throwUnexpected();
  7804. }
  7805. unsigned minIndex(unsigned exceptOid)
  7806. {
  7807. // MORE - yukky code (and slow). Could keep them heapsorted by idx or something
  7808. // this is trying to determine whether any of the adaptors will in the future read a given record
  7809. unsigned minIdx = (unsigned) -1;
  7810. for (unsigned i = 0; i < numOutputs; i++)
  7811. {
  7812. if (i != exceptOid && used[i] && adaptors[i].idx < minIdx)
  7813. minIdx = adaptors[i].idx;
  7814. }
  7815. return minIdx;
  7816. }
  7817. inline bool isLastTailReader(unsigned exceptOid)
  7818. {
  7819. for (unsigned i = 0; i < numOutputs; i++)
  7820. {
  7821. if (i != exceptOid && adaptors[i].idx == tailIdx && used[i])
  7822. return false;
  7823. }
  7824. return true;
  7825. }
  7826. void initOutputs()
  7827. {
  7828. activeOutputs = numOutputs;
  7829. for (unsigned i = 0; i < numOriginalOutputs; i++)
  7830. if (used[i])
  7831. adaptors[i].init();
  7832. state = STATEstarting;
  7833. }
  7834. public:
  7835. CRoxieServerThroughSpillActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  7836. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper(basehelper), numOutputs(_numOutputs)
  7837. {
  7838. numOriginalOutputs = numOutputs;
  7839. adaptors = new OutputAdaptor[numOutputs];
  7840. used = new bool[numOutputs];
  7841. for (unsigned i = 0; i < numOutputs; i++)
  7842. {
  7843. adaptors[i].parent = this;
  7844. adaptors[i].oid = i;
  7845. used[i] = false;
  7846. }
  7847. tailIdx = 0;
  7848. headIdx = 0;
  7849. activeOutputs = numOutputs;
  7850. }
  7851. ~CRoxieServerThroughSpillActivity()
  7852. {
  7853. delete [] adaptors;
  7854. delete [] used;
  7855. }
  7856. const void *readBuffered(unsigned &idx, unsigned oid)
  7857. {
  7858. //False positives are fine, false negatives are not.. so headIdx must only be updated when a row will be available.
  7859. const unsigned curIdx = idx;
  7860. if (curIdx == headIdx) // test once without getting the crit2 sec
  7861. {
  7862. CriticalBlock b2(crit2); // but only one puller gets to read the head
  7863. if (curIdx == headIdx) // test again now that we have it
  7864. {
  7865. 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
  7866. if (error)
  7867. throw error.getLink();
  7868. try
  7869. {
  7870. const void *row = inputStream->nextRow();
  7871. if (activeOutputs==1)
  7872. {
  7873. #ifdef TRACE_SPLIT
  7874. CTXLOG("spill %d optimised return of %p", activityId, row);
  7875. #endif
  7876. headIdx++;
  7877. idx++;
  7878. return row; // optimization for the case where only one output still active.
  7879. }
  7880. CriticalBlock b(crit);
  7881. headIdx++;
  7882. idx++;
  7883. if (activeOutputs==1)
  7884. return row; // optimization for the case where only one output still active.
  7885. buffer.enqueue(row);
  7886. if (row) LinkRoxieRow(row);
  7887. return row;
  7888. }
  7889. catch (IException *E)
  7890. {
  7891. #ifdef TRACE_SPLIT
  7892. CTXLOG("spill %d caught exception", activityId);
  7893. #endif
  7894. error.set(E);
  7895. throw;
  7896. }
  7897. catch (...)
  7898. {
  7899. IException *E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught in CRoxieServerThroughSpillActivity::readBuffered");
  7900. error.set(E);
  7901. throw E;
  7902. }
  7903. }
  7904. }
  7905. CriticalBlock b(crit);
  7906. 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
  7907. unsigned lidx = curIdx - tailIdx;
  7908. idx++;
  7909. if (!lidx)
  7910. {
  7911. // The numOutputs <= 2 check optimizes slightly the common case of 2-way splitters.
  7912. // 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
  7913. if (numOutputs <= 2 || isLastTailReader(oid)) // NOTE - this includes the case where minIndex returns (unsigned) -1, meaning no other active pullers
  7914. {
  7915. tailIdx++;
  7916. const void *ret = buffer.dequeue(); // no need to link - last puller
  7917. #ifdef TRACE_SPLIT
  7918. CTXLOG("last puller return of %p", ret);
  7919. #endif
  7920. return ret;
  7921. }
  7922. }
  7923. const void *ret = buffer.item(lidx);
  7924. if (ret) LinkRoxieRow(ret);
  7925. #ifdef TRACE_SPLIT
  7926. CTXLOG("standard return of %p", ret);
  7927. #endif
  7928. return ret;
  7929. }
  7930. virtual void start(unsigned oid, unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7931. {
  7932. CriticalBlock b(crit);
  7933. if (error)
  7934. throw error.getLink();
  7935. if (factory)
  7936. factory->noteStarted(oid);
  7937. if (traceStartStop)
  7938. CTXLOG("SPLIT %p: start %d child %d activeOutputs %d numOutputs %d numOriginalOutputs %d state %s", this, activityId, oid, activeOutputs, numOutputs, numOriginalOutputs, queryStateText(state));
  7939. if (state != STATEstarted)
  7940. {
  7941. if (state != STATEstarting)
  7942. initOutputs();
  7943. tailIdx = 0;
  7944. headIdx = 0;
  7945. error.clear();
  7946. try
  7947. {
  7948. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7949. }
  7950. catch (IException *E)
  7951. {
  7952. #ifdef TRACE_SPLIT
  7953. CTXLOG("spill %d caught exception in start", activityId);
  7954. #endif
  7955. error.set(E);
  7956. throw;
  7957. }
  7958. catch (...)
  7959. {
  7960. IException *E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught in CRoxieServerThroughSpillActivity::start");
  7961. error.set(E);
  7962. throw E;
  7963. }
  7964. }
  7965. }
  7966. void stop(unsigned oid, unsigned & idx)
  7967. {
  7968. // Note that OutputAdaptor code ensures that stop is not called more than once per adaptor
  7969. CriticalBlock b(crit);
  7970. #ifdef TRACE_STARTSTOP
  7971. if (traceStartStop)
  7972. {
  7973. CTXLOG("SPLIT %p: stop %d child %d activeOutputs %d numOutputs %d numOriginalOutputs %d state %s", this, activityId, oid, activeOutputs, numOutputs, numOriginalOutputs, queryStateText(state));
  7974. if (watchActivityId && watchActivityId==activityId)
  7975. {
  7976. CTXLOG("WATCH: stop %d", activityId);
  7977. }
  7978. }
  7979. #endif
  7980. if (state != STATEstarting && state != STATEstarted)
  7981. initOutputs();
  7982. if (activeOutputs > 1)
  7983. {
  7984. if (tailIdx==idx)
  7985. {
  7986. // Discard all buffered rows that are there purely for this adaptor to read them
  7987. unsigned min = minIndex(oid);
  7988. if (min != (unsigned) -1)
  7989. // what does -1 signify?? No-one wants anything? In which case can't we kill all rows??
  7990. // Should never happen though if there are still some active.
  7991. // there may be a small window where adaptors are blocked on the semaphore...
  7992. {
  7993. #ifdef TRACE_SPLIT
  7994. CTXLOG("%p: Discarding buffered rows from %d to %d for oid %x (%d outputs active)", this, idx, min, oid, activeOutputs);
  7995. #endif
  7996. while (tailIdx < min)
  7997. {
  7998. ReleaseRoxieRow(buffer.dequeue());
  7999. tailIdx++;
  8000. }
  8001. }
  8002. }
  8003. activeOutputs--;
  8004. idx = (unsigned) -1; // causes minIndex not to save rows for me...
  8005. return;
  8006. }
  8007. #ifdef TRACE_SPLIT
  8008. CTXLOG("%p: All outputs done", this);
  8009. #endif
  8010. activeOutputs = numOutputs;
  8011. CRoxieServerActivity::stop();
  8012. };
  8013. void reset(unsigned oid)
  8014. {
  8015. if (traceStartStop)
  8016. CTXLOG("SPLIT %p: reset %d child %d activeOutputs %d numOutputs %d numOriginalOutputs %d state %s", this, activityId, oid, activeOutputs, numOutputs, numOriginalOutputs, queryStateText(state));
  8017. activeOutputs = numOutputs;
  8018. while (buffer.ordinality())
  8019. ReleaseRoxieRow(buffer.dequeue());
  8020. error.clear();
  8021. if (state != STATEreset) // make sure input is only reset once
  8022. CRoxieServerActivity::reset();
  8023. };
  8024. void connectInputStreams(bool consumerOrdered)
  8025. {
  8026. if (!inputStream)
  8027. CRoxieServerActivity::connectInputStreams(consumerOrdered);
  8028. }
  8029. virtual const void *nextRow()
  8030. {
  8031. throwUnexpected(); // Internal logic error - we are not anybody's input
  8032. }
  8033. virtual IOutputMetaData * queryOutputMeta() const
  8034. {
  8035. // if (outputMeta)
  8036. // return outputMeta;
  8037. // else
  8038. return input->queryOutputMeta(); // not always known (e.g. disk write - though Gavin _could_ fill it in)
  8039. }
  8040. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  8041. {
  8042. if (idx==(unsigned)-1)
  8043. idx = nextFreeOutput(); // MORE - what is this used for?
  8044. assertex(idx < numOriginalOutputs);
  8045. assertex(!used[idx]);
  8046. used[idx] = true;
  8047. return &adaptors[idx];
  8048. }
  8049. virtual void resetOutputsUsed()
  8050. {
  8051. numOutputs = 1;
  8052. activeOutputs = 1;
  8053. // MORE RKC->GH should we be clearing the used array here? anywhere?
  8054. }
  8055. virtual void noteOutputUsed()
  8056. {
  8057. assertex(numOutputs < numOriginalOutputs);
  8058. numOutputs++;
  8059. activeOutputs = numOutputs;
  8060. }
  8061. virtual bool isPassThrough()
  8062. {
  8063. return numOutputs==1;
  8064. }
  8065. };
  8066. class CRoxieServerThroughSpillActivityFactory : public CRoxieServerMultiOutputFactory
  8067. {
  8068. public:
  8069. CRoxieServerThroughSpillActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8070. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  8071. {
  8072. Owned<IHThorSpillArg> helper = (IHThorSpillArg *) helperFactory();
  8073. setNumOutputs(helper->getTempUsageCount() + 1);
  8074. }
  8075. CRoxieServerThroughSpillActivityFactory(IQueryFactory &_queryFactory, HelperFactory *_helperFactory, unsigned _numOutputs, IPropertyTree &_graphNode)
  8076. : CRoxieServerMultiOutputFactory(0, 0, _queryFactory, _helperFactory, TAKsplit, _graphNode)
  8077. {
  8078. setNumOutputs(_numOutputs);
  8079. }
  8080. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  8081. {
  8082. return new CRoxieServerThroughSpillActivity(_ctx, this, _probeManager, numOutputs);
  8083. }
  8084. };
  8085. IRoxieServerActivityFactory *createRoxieServerThroughSpillActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8086. {
  8087. return new CRoxieServerThroughSpillActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  8088. }
  8089. IRoxieServerActivityFactory *createRoxieServerThroughSpillActivityFactory(IQueryFactory &_queryFactory, HelperFactory *_factory, unsigned _numOutputs, IPropertyTree &_graphNode)
  8090. {
  8091. return new CRoxieServerThroughSpillActivityFactory(_queryFactory, _factory, _numOutputs, _graphNode);
  8092. }
  8093. //----------------------------------------------------------------------------------------------
  8094. class CRoxieServerSplitActivityFactory : public CRoxieServerMultiOutputFactory
  8095. {
  8096. public:
  8097. CRoxieServerSplitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8098. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  8099. {
  8100. Owned<IHThorSplitArg> helper = (IHThorSplitArg *) helperFactory();
  8101. setNumOutputs(helper->numBranches());
  8102. }
  8103. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  8104. {
  8105. return new CRoxieServerThroughSpillActivity(_ctx, this, _probeManager, numOutputs);
  8106. }
  8107. };
  8108. IRoxieServerActivityFactory *createRoxieServerSplitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8109. {
  8110. return new CRoxieServerSplitActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  8111. }
  8112. //=====================================================================================================
  8113. #define PIPE_BUFSIZE 0x8000
  8114. static IException *createPipeFailureException(const char *cmd, unsigned retcode, IPipeProcess *pipe)
  8115. {
  8116. StringBuffer msg;
  8117. if(pipe->hasError())
  8118. {
  8119. try
  8120. {
  8121. char error[512];
  8122. size32_t sz = pipe->readError(sizeof(error), error);
  8123. if(sz && sz!=(size32_t)-1)
  8124. msg.append(", stderr: '").append(sz, error).append("'");
  8125. }
  8126. catch (IException *e)
  8127. {
  8128. EXCLOG(e, "Error reading pipe stderr");
  8129. e->Release();
  8130. }
  8131. }
  8132. return MakeStringException(ROXIE_PIPE_ERROR, "Pipe process %s returned error %u%s", cmd, retcode, msg.str());
  8133. }
  8134. class CRoxieServerPipeReadActivity : public CRoxieServerActivity
  8135. {
  8136. IHThorPipeReadArg &helper;
  8137. Owned<IPipeProcess> pipe;
  8138. StringAttr pipeCommand;
  8139. Owned<IOutputRowDeserializer> rowDeserializer;
  8140. Owned<IReadRowStream> readTransformer;
  8141. bool groupSignalled;
  8142. public:
  8143. CRoxieServerPipeReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8144. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorPipeReadArg &)basehelper)
  8145. {
  8146. groupSignalled = true;
  8147. }
  8148. virtual bool needsAllocator() const { return true; }
  8149. virtual void onCreate(IHThorArg *_colocalParent)
  8150. {
  8151. CRoxieServerActivity::onCreate(_colocalParent);
  8152. rowDeserializer.setown(rowAllocator->createDiskDeserializer(ctx->queryCodeContext()));
  8153. }
  8154. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8155. {
  8156. groupSignalled = true; // i.e. don't start with a NULL row
  8157. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8158. if (!readTransformer)
  8159. {
  8160. OwnedRoxieString xmlIteratorPath(helper.getXmlIteratorPath());
  8161. readTransformer.setown(createReadRowStream(rowAllocator, rowDeserializer, helper.queryXmlTransformer(), helper.queryCsvTransformer(), xmlIteratorPath, helper.getPipeFlags()));
  8162. }
  8163. OwnedRoxieString pipeProgram(helper.getPipeProgram());
  8164. openPipe(pipeProgram);
  8165. }
  8166. virtual void stop()
  8167. {
  8168. CRoxieServerActivity::stop();
  8169. pipe.clear();
  8170. readTransformer->setStream(NULL);
  8171. }
  8172. virtual const void *nextRow()
  8173. {
  8174. ActivityTimer t(totalCycles, timeActivities);
  8175. while (!waitForPipe())
  8176. {
  8177. if (!pipe)
  8178. return NULL;
  8179. if (helper.getPipeFlags() & TPFgroupeachrow)
  8180. {
  8181. if (!groupSignalled)
  8182. {
  8183. groupSignalled = true;
  8184. return NULL;
  8185. }
  8186. }
  8187. }
  8188. const void *ret = readTransformer->next();
  8189. assertex(ret != NULL); // if ret can ever be NULL then we need to recode this logic
  8190. processed++;
  8191. groupSignalled = false;
  8192. return ret;
  8193. }
  8194. protected:
  8195. bool waitForPipe()
  8196. {
  8197. if (!pipe)
  8198. return false; // done
  8199. if (!readTransformer->eos())
  8200. return true;
  8201. verifyPipe();
  8202. return false;
  8203. }
  8204. void openPipe(char const * cmd)
  8205. {
  8206. pipeCommand.setown(cmd);
  8207. pipe.setown(createPipeProcess());
  8208. if(!pipe->run(NULL, cmd, ".", false, true, true, 0x10000))
  8209. throw MakeStringException(ROXIE_PIPE_ERROR, "Could not run pipe process %s", cmd);
  8210. Owned<ISimpleReadStream> pipeReader = pipe->getOutputStream();
  8211. readTransformer->setStream(pipeReader.get());
  8212. }
  8213. void verifyPipe()
  8214. {
  8215. if (pipe)
  8216. {
  8217. unsigned err = pipe->wait();
  8218. if(err && !(helper.getPipeFlags() & TPFnofail))
  8219. {
  8220. throw createPipeFailureException(pipeCommand.get(), err, pipe);
  8221. }
  8222. pipe.clear();
  8223. }
  8224. }
  8225. };
  8226. class CRoxieServerPipeThroughActivity : public CRoxieServerActivity, implements IRecordPullerCallback
  8227. {
  8228. IHThorPipeThroughArg &helper;
  8229. RecordPullerThread puller;
  8230. Owned<IPipeProcess> pipe;
  8231. StringAttr pipeCommand;
  8232. InterruptableSemaphore pipeVerified;
  8233. InterruptableSemaphore pipeOpened;
  8234. CachedOutputMetaData inputMeta;
  8235. Owned<IOutputRowSerializer> rowSerializer;
  8236. Owned<IOutputRowDeserializer> rowDeserializer;
  8237. Owned<IPipeWriteXformHelper> writeTransformer;
  8238. Owned<IReadRowStream> readTransformer;
  8239. bool firstRead;
  8240. bool recreate;
  8241. bool inputExhausted;
  8242. bool groupSignalled;
  8243. public:
  8244. CRoxieServerPipeThroughActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8245. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorPipeThroughArg &)basehelper), puller(false)
  8246. {
  8247. recreate = helper.recreateEachRow();
  8248. groupSignalled = true;
  8249. firstRead = false;
  8250. inputExhausted = false;
  8251. }
  8252. virtual bool needsAllocator() const { return true; }
  8253. virtual void onCreate(IHThorArg *_colocalParent)
  8254. {
  8255. CRoxieServerActivity::onCreate(_colocalParent);
  8256. rowSerializer.setown(inputMeta.createDiskSerializer(ctx->queryCodeContext(), activityId));
  8257. rowDeserializer.setown(rowAllocator->createDiskDeserializer(ctx->queryCodeContext()));
  8258. writeTransformer.setown(createPipeWriteXformHelper(helper.getPipeFlags(), helper.queryXmlOutput(), helper.queryCsvOutput(), rowSerializer));
  8259. }
  8260. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8261. {
  8262. firstRead = true;
  8263. inputExhausted = false;
  8264. groupSignalled = true; // i.e. don't start with a NULL row
  8265. pipeVerified.reinit();
  8266. pipeOpened.reinit();
  8267. writeTransformer->ready();
  8268. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8269. if (!readTransformer)
  8270. {
  8271. OwnedRoxieString xmlIterator(helper.getXmlIteratorPath());
  8272. readTransformer.setown(createReadRowStream(rowAllocator, rowDeserializer, helper.queryXmlTransformer(), helper.queryCsvTransformer(), xmlIterator, helper.getPipeFlags()));
  8273. }
  8274. if(!recreate)
  8275. {
  8276. OwnedRoxieString pipeProgram(helper.getPipeProgram());
  8277. openPipe(pipeProgram);
  8278. }
  8279. puller.start(parentExtractSize, parentExtract, paused, 0, false, ctx); // Pipe does not support preload presently - locks up
  8280. }
  8281. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  8282. {
  8283. if (idx)
  8284. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  8285. puller.setInput(this, _sourceIdx, _in);
  8286. inputMeta.set(_in->queryOutputMeta());
  8287. }
  8288. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  8289. {
  8290. puller.connectInputStreams(ctx, consumerOrdered);
  8291. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
  8292. }
  8293. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  8294. {
  8295. if (idx==0)
  8296. return puller.queryInput();
  8297. else
  8298. return NULL;
  8299. }
  8300. virtual void stop()
  8301. {
  8302. pipeVerified.interrupt(NULL);
  8303. pipeOpened.interrupt(NULL);
  8304. puller.stop();
  8305. CRoxieServerActivity::stop();
  8306. pipe.clear();
  8307. readTransformer->setStream(NULL);
  8308. }
  8309. virtual void reset()
  8310. {
  8311. puller.reset();
  8312. CRoxieServerActivity::reset();
  8313. }
  8314. virtual const void *nextRow()
  8315. {
  8316. ActivityTimer t(totalCycles, timeActivities);
  8317. while (!waitForPipe())
  8318. {
  8319. if (!pipe)
  8320. return NULL;
  8321. if (helper.getPipeFlags() & TPFgroupeachrow)
  8322. {
  8323. if (!groupSignalled)
  8324. {
  8325. groupSignalled = true;
  8326. return NULL;
  8327. }
  8328. }
  8329. }
  8330. const void *ret = readTransformer->next();
  8331. assertex(ret != NULL); // if ret can ever be NULL then we need to recode this logic
  8332. processed++;
  8333. groupSignalled = false;
  8334. return ret;
  8335. }
  8336. virtual void processRow(const void *row)
  8337. {
  8338. // called from puller thread
  8339. if(recreate)
  8340. openPipe(helper.getNameFromRow(row));
  8341. writeTransformer->writeTranslatedText(row, pipe);
  8342. ReleaseRoxieRow(row);
  8343. if(recreate)
  8344. {
  8345. closePipe();
  8346. pipeVerified.wait();
  8347. }
  8348. }
  8349. virtual void processDone()
  8350. {
  8351. // called from puller thread
  8352. if(recreate)
  8353. {
  8354. inputExhausted = true;
  8355. pipeOpened.signal();
  8356. }
  8357. else
  8358. {
  8359. closePipe();
  8360. pipeVerified.wait();
  8361. }
  8362. }
  8363. virtual void processEOG()
  8364. {
  8365. }
  8366. void processGroup(const ConstPointerArray &)
  8367. {
  8368. throwUnexpected();
  8369. }
  8370. virtual bool fireException(IException *e)
  8371. {
  8372. pipeOpened.interrupt(LINK(e));
  8373. pipeVerified.interrupt(e);
  8374. return true;
  8375. }
  8376. private:
  8377. bool waitForPipe()
  8378. {
  8379. if (firstRead)
  8380. {
  8381. pipeOpened.wait();
  8382. firstRead = false;
  8383. }
  8384. if (!pipe)
  8385. return false; // done
  8386. if (!readTransformer->eos())
  8387. return true;
  8388. verifyPipe();
  8389. if (recreate && !inputExhausted)
  8390. pipeOpened.wait();
  8391. return false;
  8392. }
  8393. void openPipe(char const * cmd)
  8394. {
  8395. pipeCommand.setown(cmd);
  8396. pipe.setown(createPipeProcess());
  8397. if(!pipe->run(NULL, cmd, ".", true, true, true, 0x10000))
  8398. throw MakeStringException(ROXIE_PIPE_ERROR, "Could not run pipe process %s", cmd);
  8399. writeTransformer->writeHeader(pipe);
  8400. Owned<ISimpleReadStream> pipeReader = pipe->getOutputStream();
  8401. readTransformer->setStream(pipeReader.get());
  8402. pipeOpened.signal();
  8403. }
  8404. void closePipe()
  8405. {
  8406. writeTransformer->writeFooter(pipe);
  8407. pipe->closeInput();
  8408. }
  8409. void verifyPipe()
  8410. {
  8411. if (pipe)
  8412. {
  8413. unsigned err = pipe->wait();
  8414. if(err && !(helper.getPipeFlags() & TPFnofail))
  8415. {
  8416. throw createPipeFailureException(pipeCommand.get(), err, pipe);
  8417. }
  8418. pipe.clear();
  8419. pipeVerified.signal();
  8420. }
  8421. }
  8422. };
  8423. class CRoxieServerPipeWriteActivity : public CRoxieServerInternalSinkActivity
  8424. {
  8425. IHThorPipeWriteArg &helper;
  8426. Owned<IPipeProcess> pipe;
  8427. StringAttr pipeCommand;
  8428. CachedOutputMetaData inputMeta;
  8429. Owned<IOutputRowSerializer> rowSerializer;
  8430. Owned<IPipeWriteXformHelper> writeTransformer;
  8431. bool firstRead;
  8432. bool recreate;
  8433. bool inputExhausted;
  8434. public:
  8435. CRoxieServerPipeWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  8436. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _numOutputs), helper((IHThorPipeWriteArg &)basehelper)
  8437. {
  8438. recreate = helper.recreateEachRow();
  8439. firstRead = false;
  8440. inputExhausted = false;
  8441. }
  8442. virtual bool needsAllocator() const { return true; }
  8443. virtual void onCreate(IHThorArg *_colocalParent)
  8444. {
  8445. CRoxieServerActivity::onCreate(_colocalParent);
  8446. inputMeta.set(input->queryOutputMeta());
  8447. rowSerializer.setown(inputMeta.createDiskSerializer(ctx->queryCodeContext(), activityId));
  8448. writeTransformer.setown(createPipeWriteXformHelper(helper.getPipeFlags(), helper.queryXmlOutput(), helper.queryCsvOutput(), rowSerializer));
  8449. }
  8450. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8451. {
  8452. firstRead = true;
  8453. inputExhausted = false;
  8454. writeTransformer->ready();
  8455. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8456. if(!recreate)
  8457. {
  8458. OwnedRoxieString pipeProgram(helper.getPipeProgram());
  8459. openPipe(pipeProgram);
  8460. }
  8461. }
  8462. virtual void stop()
  8463. {
  8464. if (!aborted && helper.getSequence() >= 0)
  8465. {
  8466. WorkunitUpdate wu = ctx->updateWorkUnit();
  8467. if (wu)
  8468. {
  8469. Owned<IWUResult> result = wu->updateResultBySequence(helper.getSequence());
  8470. if (result)
  8471. {
  8472. result->setResultTotalRowCount(processed);
  8473. result->setResultStatus(ResultStatusCalculated);
  8474. }
  8475. }
  8476. }
  8477. CRoxieServerActivity::stop();
  8478. pipe.clear();
  8479. }
  8480. virtual void onExecute()
  8481. {
  8482. loop
  8483. {
  8484. const void *row = inputStream->ungroupedNextRow();
  8485. if (!row)
  8486. break;
  8487. processed++;
  8488. if(recreate)
  8489. openPipe(helper.getNameFromRow(row));
  8490. writeTransformer->writeTranslatedText(row, pipe);
  8491. ReleaseRoxieRow(row);
  8492. if(recreate)
  8493. closePipe();
  8494. }
  8495. closePipe();
  8496. }
  8497. private:
  8498. void openPipe(char const * cmd)
  8499. {
  8500. pipeCommand.setown(cmd);
  8501. pipe.setown(createPipeProcess());
  8502. if(!pipe->run(NULL, cmd, ".", true, false, true, 0x10000))
  8503. throw MakeStringException(ROXIE_PIPE_ERROR, "Could not run pipe process %s", cmd);
  8504. writeTransformer->writeHeader(pipe);
  8505. }
  8506. void closePipe()
  8507. {
  8508. writeTransformer->writeFooter(pipe);
  8509. pipe->closeInput();
  8510. unsigned err = pipe->wait();
  8511. if(err && !(helper.getPipeFlags() & TPFnofail))
  8512. {
  8513. throw createPipeFailureException(pipeCommand.get(), err, pipe);
  8514. }
  8515. pipe.clear();
  8516. }
  8517. };
  8518. class CRoxieServerPipeReadActivityFactory : public CRoxieServerActivityFactory
  8519. {
  8520. public:
  8521. CRoxieServerPipeReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8522. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  8523. {
  8524. }
  8525. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  8526. {
  8527. return new CRoxieServerPipeReadActivity(_ctx, this, _probeManager);
  8528. }
  8529. };
  8530. class CRoxieServerPipeThroughActivityFactory : public CRoxieServerActivityFactory
  8531. {
  8532. public:
  8533. CRoxieServerPipeThroughActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8534. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  8535. {
  8536. }
  8537. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  8538. {
  8539. return new CRoxieServerPipeThroughActivity(_ctx, this, _probeManager);
  8540. }
  8541. };
  8542. class CRoxieServerPipeWriteActivityFactory : public CRoxieServerInternalSinkFactory
  8543. {
  8544. public:
  8545. CRoxieServerPipeWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  8546. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot)
  8547. {
  8548. }
  8549. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  8550. {
  8551. return new CRoxieServerPipeWriteActivity(_ctx, this, _probeManager, usageCount);
  8552. }
  8553. };
  8554. IRoxieServerActivityFactory *createRoxieServerPipeReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8555. {
  8556. return new CRoxieServerPipeReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  8557. }
  8558. IRoxieServerActivityFactory *createRoxieServerPipeThroughActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8559. {
  8560. return new CRoxieServerPipeThroughActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  8561. }
  8562. IRoxieServerActivityFactory *createRoxieServerPipeWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  8563. {
  8564. return new CRoxieServerPipeWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot);
  8565. }
  8566. //=====================================================================================================
  8567. class CRoxieServerStreamedIteratorActivity : public CRoxieServerActivity
  8568. {
  8569. IHThorStreamedIteratorArg &helper;
  8570. Owned<IRowStream> rows;
  8571. public:
  8572. CRoxieServerStreamedIteratorActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8573. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorStreamedIteratorArg &)basehelper)
  8574. {
  8575. }
  8576. ~CRoxieServerStreamedIteratorActivity()
  8577. {
  8578. }
  8579. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8580. {
  8581. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8582. rows.setown(helper.createInput());
  8583. }
  8584. virtual void stop()
  8585. {
  8586. if (rows)
  8587. {
  8588. rows->stop();
  8589. rows.clear();
  8590. }
  8591. CRoxieServerActivity::stop();
  8592. }
  8593. virtual const void *nextRow()
  8594. {
  8595. ActivityTimer t(totalCycles, timeActivities);
  8596. assertex(rows != NULL);
  8597. const void * next = rows->nextRow();
  8598. if (next)
  8599. processed++;
  8600. return next;
  8601. }
  8602. };
  8603. class CRoxieServerStreamedIteratorActivityFactory : public CRoxieServerActivityFactory
  8604. {
  8605. public:
  8606. CRoxieServerStreamedIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8607. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  8608. {
  8609. }
  8610. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  8611. {
  8612. return new CRoxieServerStreamedIteratorActivity(_ctx, this, _probeManager);
  8613. }
  8614. };
  8615. IRoxieServerActivityFactory *createRoxieServerStreamedIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8616. {
  8617. return new CRoxieServerStreamedIteratorActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  8618. }
  8619. //=====================================================================================================
  8620. class CRoxieServerFilterActivity : public CRoxieServerLateStartActivity
  8621. {
  8622. IHThorFilterArg &helper;
  8623. bool anyThisGroup;
  8624. IRangeCompare * stepCompare;
  8625. public:
  8626. CRoxieServerFilterActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8627. : CRoxieServerLateStartActivity(_ctx, _factory, _probeManager), helper((IHThorFilterArg &)basehelper)
  8628. {
  8629. anyThisGroup = false;
  8630. stepCompare = NULL;
  8631. }
  8632. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8633. {
  8634. anyThisGroup = false;
  8635. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  8636. lateStart(parentExtractSize, parentExtract, helper.canMatchAny());
  8637. stepCompare = NULL;
  8638. if (!eof)
  8639. {
  8640. IInputSteppingMeta * stepMeta = input->querySteppingMeta();
  8641. if (stepMeta)
  8642. stepCompare = stepMeta->queryCompare();
  8643. }
  8644. }
  8645. virtual const void * nextRow()
  8646. {
  8647. ActivityTimer t(totalCycles, timeActivities);
  8648. if (eof)
  8649. return NULL;
  8650. loop
  8651. {
  8652. const void * ret = inputStream->nextRow();
  8653. if (!ret)
  8654. {
  8655. //stop returning two NULLs in a row.
  8656. if (anyThisGroup)
  8657. {
  8658. anyThisGroup = false;
  8659. return NULL;
  8660. }
  8661. ret = inputStream->nextRow();
  8662. if (!ret)
  8663. {
  8664. eof = true;
  8665. return NULL; // eof...
  8666. }
  8667. }
  8668. if (helper.isValid(ret))
  8669. {
  8670. anyThisGroup = true;
  8671. processed++;
  8672. return ret;
  8673. }
  8674. ReleaseRoxieRow(ret);
  8675. }
  8676. }
  8677. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  8678. {
  8679. //Could assert that this isn't grouped
  8680. // MORE - will need rethinking once we rethink the nextRowGE interface for global smart-stepping.
  8681. ActivityTimer t(totalCycles, timeActivities);
  8682. if (eof)
  8683. return NULL;
  8684. loop
  8685. {
  8686. const void * ret = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  8687. if (!ret)
  8688. {
  8689. eof = true;
  8690. return NULL;
  8691. }
  8692. if (!wasCompleteMatch)
  8693. {
  8694. anyThisGroup = false; // RKC->GH - is this right??
  8695. return ret;
  8696. }
  8697. if (helper.isValid(ret))
  8698. {
  8699. anyThisGroup = true;
  8700. processed++;
  8701. return ret;
  8702. }
  8703. if (!stepExtra.returnMismatches())
  8704. {
  8705. ReleaseRoxieRow(ret);
  8706. return nextRow();
  8707. }
  8708. //If asked to return mismatches we are only interested in mismatches that will force the stepped
  8709. //condition to advance
  8710. if (stepCompare->docompare(ret, seek, numFields) != 0)
  8711. {
  8712. wasCompleteMatch = false;
  8713. anyThisGroup = false; // WHY?
  8714. return ret;
  8715. }
  8716. ReleaseRoxieRow(ret);
  8717. }
  8718. }
  8719. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  8720. {
  8721. return input->gatherConjunctions(collector);
  8722. }
  8723. virtual void resetEOF()
  8724. {
  8725. eof = prefiltered;
  8726. anyThisGroup = false;
  8727. inputStream->resetEOF();
  8728. }
  8729. IInputSteppingMeta * querySteppingMeta()
  8730. {
  8731. return input->querySteppingMeta();
  8732. }
  8733. };
  8734. class CRoxieServerFilterActivityFactory : public CRoxieServerActivityFactory
  8735. {
  8736. public:
  8737. CRoxieServerFilterActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8738. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  8739. {
  8740. optStableInput = false;
  8741. }
  8742. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  8743. {
  8744. return new CRoxieServerFilterActivity(_ctx, this, _probeManager);
  8745. }
  8746. };
  8747. IRoxieServerActivityFactory *createRoxieServerFilterActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8748. {
  8749. return new CRoxieServerFilterActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  8750. }
  8751. //=====================================================================================================
  8752. class CRoxieServerFilterGroupActivity : public CRoxieServerLateStartActivity
  8753. {
  8754. IHThorFilterGroupArg &helper;
  8755. unsigned curIndex;
  8756. ConstPointerArray gathered;
  8757. IRangeCompare * stepCompare;
  8758. public:
  8759. CRoxieServerFilterGroupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8760. : CRoxieServerLateStartActivity(_ctx, _factory, _probeManager), helper((IHThorFilterGroupArg &)basehelper)
  8761. {
  8762. curIndex = 0;
  8763. stepCompare = NULL;
  8764. }
  8765. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8766. {
  8767. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  8768. lateStart(parentExtractSize, parentExtract, helper.canMatchAny());//sets eof
  8769. assertex(eof == !helper.canMatchAny());
  8770. curIndex = 0;
  8771. stepCompare = NULL;
  8772. if (!eof)
  8773. {
  8774. IInputSteppingMeta * inputStepping = input->querySteppingMeta();
  8775. if (inputStepping)
  8776. stepCompare = inputStepping->queryCompare();
  8777. }
  8778. }
  8779. virtual void reset()
  8780. {
  8781. releaseGathered();
  8782. CRoxieServerLateStartActivity::reset();
  8783. }
  8784. inline void releaseGathered()
  8785. {
  8786. roxiemem::ReleaseRoxieRowRange(gathered.getArray(), curIndex, gathered.ordinality());
  8787. gathered.kill();
  8788. curIndex = 0;
  8789. }
  8790. virtual const void * nextRow()
  8791. {
  8792. ActivityTimer t(totalCycles, timeActivities);
  8793. loop
  8794. {
  8795. if (eof)
  8796. return NULL;
  8797. if (gathered.ordinality())
  8798. {
  8799. if (gathered.isItem(curIndex))
  8800. {
  8801. const void * ret = gathered.item(curIndex++);
  8802. processed++;
  8803. return ret;
  8804. }
  8805. curIndex = 0;
  8806. gathered.kill();
  8807. return NULL;
  8808. }
  8809. const void * ret = inputStream->nextRow();
  8810. while (ret)
  8811. {
  8812. gathered.append(ret);
  8813. ret = inputStream->nextRow();
  8814. }
  8815. unsigned num = gathered.ordinality();
  8816. if (num != 0)
  8817. {
  8818. if (!helper.isValid(num, (const void * *)gathered.getArray()))
  8819. ReleaseRoxieRows(gathered); // read next group
  8820. }
  8821. else
  8822. eof = true;
  8823. }
  8824. }
  8825. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  8826. {
  8827. ActivityTimer t(totalCycles, timeActivities);
  8828. if (eof)
  8829. return NULL;
  8830. if (gathered.ordinality())
  8831. {
  8832. while (gathered.isItem(curIndex))
  8833. {
  8834. const void * ret = gathered.item(curIndex++);
  8835. if (stepCompare->docompare(ret, seek, numFields) >= 0)
  8836. {
  8837. processed++;
  8838. return ret;
  8839. }
  8840. ReleaseRoxieRow(ret);
  8841. }
  8842. curIndex = 0;
  8843. gathered.kill();
  8844. //nextRowGE never returns an end of group marker.
  8845. }
  8846. //Not completely sure about this - it could lead the the start of a group being skipped,
  8847. //so the group filter could potentially work on a different group. If so, we'd need to check the
  8848. //next fields were a subset of the grouping fields - more an issue for the group activity.
  8849. //MORE: What do we do with wasCompleteMatch? something like the following????
  8850. #if 0
  8851. loop
  8852. {
  8853. const void * ret;
  8854. if (stepExtra.returnMismatches())
  8855. {
  8856. bool matchedCompletely = true;
  8857. ret = input->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  8858. if (!wasCompleteMatch)
  8859. return ret;
  8860. }
  8861. else
  8862. ret = input->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  8863. #endif
  8864. const void * ret = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  8865. while (ret)
  8866. {
  8867. gathered.append(ret);
  8868. ret = inputStream->nextRow();
  8869. }
  8870. unsigned num = gathered.ordinality();
  8871. if (num != 0)
  8872. {
  8873. if (!helper.isValid(num, (const void * *)gathered.getArray()))
  8874. ReleaseRoxieRows(gathered); // read next group
  8875. }
  8876. else
  8877. eof = true;
  8878. return IEngineRowStream::ungroupedNextRow();
  8879. }
  8880. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  8881. {
  8882. return input->gatherConjunctions(collector);
  8883. }
  8884. virtual void resetEOF()
  8885. {
  8886. eof = false;
  8887. releaseGathered();
  8888. inputStream->resetEOF();
  8889. }
  8890. IInputSteppingMeta * querySteppingMeta()
  8891. {
  8892. return input->querySteppingMeta();
  8893. }
  8894. };
  8895. class CRoxieServerFilterGroupActivityFactory : public CRoxieServerActivityFactory
  8896. {
  8897. public:
  8898. CRoxieServerFilterGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8899. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  8900. {
  8901. }
  8902. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  8903. {
  8904. return new CRoxieServerFilterGroupActivity(_ctx, this, _probeManager);
  8905. }
  8906. };
  8907. IRoxieServerActivityFactory *createRoxieServerFilterGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8908. {
  8909. return new CRoxieServerFilterGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  8910. }
  8911. //=================================================================================
  8912. class CRoxieServerSideEffectActivity : public CRoxieServerActivity
  8913. {
  8914. IHThorSideEffectArg &helper;
  8915. CriticalSection ecrit;
  8916. Owned<IException> exception;
  8917. bool executed;
  8918. public:
  8919. CRoxieServerSideEffectActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8920. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorSideEffectArg &)basehelper)
  8921. {
  8922. executed = false;
  8923. }
  8924. virtual const void * nextRow()
  8925. {
  8926. ActivityTimer t(totalCycles, timeActivities);
  8927. CriticalBlock b(ecrit);
  8928. if (exception)
  8929. throw(exception.getLink());
  8930. if (!executed)
  8931. {
  8932. try
  8933. {
  8934. executed = true;
  8935. helper.action();
  8936. }
  8937. catch(IException *E)
  8938. {
  8939. exception.set(E);
  8940. throw;
  8941. }
  8942. }
  8943. return NULL;
  8944. }
  8945. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  8946. {
  8947. CriticalBlock b(ecrit);
  8948. if (exception)
  8949. throw(exception.getLink());
  8950. if (!executed)
  8951. {
  8952. try
  8953. {
  8954. ActivityTimer t(totalCycles, timeActivities);
  8955. executed = true;
  8956. start(parentExtractSize, parentExtract, false);
  8957. helper.action();
  8958. stop();
  8959. }
  8960. catch(IException *E)
  8961. {
  8962. ctx->notifyAbort(E);
  8963. abort();
  8964. exception.set(E);
  8965. throw;
  8966. }
  8967. }
  8968. }
  8969. virtual void reset()
  8970. {
  8971. executed = false;
  8972. exception.clear();
  8973. CRoxieServerActivity::reset();
  8974. }
  8975. };
  8976. class CRoxieServerSideEffectActivityFactory : public CRoxieServerActivityFactory
  8977. {
  8978. bool isRoot;
  8979. public:
  8980. CRoxieServerSideEffectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  8981. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  8982. {
  8983. }
  8984. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  8985. {
  8986. return new CRoxieServerSideEffectActivity(_ctx, this, _probeManager);
  8987. }
  8988. virtual bool isSink() const
  8989. {
  8990. return isRoot && !meta.queryOriginal();
  8991. }
  8992. };
  8993. IRoxieServerActivityFactory *createRoxieServerSideEffectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  8994. {
  8995. return new CRoxieServerSideEffectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  8996. }
  8997. //=================================================================================
  8998. class CRoxieServerActionActivity : public CRoxieServerInternalSinkActivity
  8999. {
  9000. IHThorActionArg &helper;
  9001. public:
  9002. CRoxieServerActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  9003. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _numOutputs), helper((IHThorActionArg &)basehelper)
  9004. {
  9005. }
  9006. virtual void onExecute()
  9007. {
  9008. helper.action();
  9009. }
  9010. };
  9011. class CRoxieServerActionActivityFactory : public CRoxieServerInternalSinkFactory
  9012. {
  9013. public:
  9014. CRoxieServerActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  9015. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot)
  9016. {
  9017. }
  9018. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9019. {
  9020. return new CRoxieServerActionActivity(_ctx, this, _probeManager, usageCount);
  9021. }
  9022. };
  9023. IRoxieServerActivityFactory *createRoxieServerActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  9024. {
  9025. return new CRoxieServerActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot);
  9026. }
  9027. //=================================================================================
  9028. class CRoxieServerSampleActivity : public CRoxieServerActivity
  9029. {
  9030. IHThorSampleArg &helper;
  9031. unsigned numSamples;
  9032. unsigned numToSkip;
  9033. unsigned whichSample;
  9034. bool anyThisGroup;
  9035. bool eof;
  9036. public:
  9037. CRoxieServerSampleActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9038. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorSampleArg &)basehelper)
  9039. {
  9040. numSamples = 0;
  9041. numToSkip = 0;
  9042. whichSample = 0;
  9043. anyThisGroup = false;
  9044. eof = false;
  9045. }
  9046. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9047. {
  9048. anyThisGroup = false;
  9049. eof = false;
  9050. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9051. numSamples = helper.getProportion();
  9052. whichSample = helper.getSampleNumber();
  9053. numToSkip = (whichSample ? whichSample-1 : 0);
  9054. }
  9055. virtual const void * nextRow()
  9056. {
  9057. ActivityTimer t(totalCycles, timeActivities);
  9058. if (eof)
  9059. return NULL;
  9060. loop
  9061. {
  9062. const void * ret = inputStream->nextRow();
  9063. if (!ret)
  9064. {
  9065. //this does work with groups - may or may not be useful...
  9066. //reset the sample for each group.... probably best.
  9067. numToSkip = (whichSample ? whichSample-1 : 0);
  9068. if (anyThisGroup)
  9069. {
  9070. anyThisGroup = false;
  9071. return NULL;
  9072. }
  9073. ret = inputStream->nextRow();
  9074. if (!ret)
  9075. {
  9076. eof = true;
  9077. return NULL; // eof...
  9078. }
  9079. }
  9080. if (numToSkip == 0)
  9081. {
  9082. anyThisGroup = true;
  9083. numToSkip = numSamples-1;
  9084. processed++;
  9085. return ret;
  9086. }
  9087. numToSkip--;
  9088. ReleaseRoxieRow(ret);
  9089. }
  9090. }
  9091. };
  9092. class CRoxieServerSampleActivityFactory : public CRoxieServerActivityFactory
  9093. {
  9094. public:
  9095. CRoxieServerSampleActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9096. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  9097. {
  9098. }
  9099. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9100. {
  9101. return new CRoxieServerSampleActivity(_ctx, this, _probeManager);
  9102. }
  9103. };
  9104. IRoxieServerActivityFactory *createRoxieServerSampleActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9105. {
  9106. return new CRoxieServerSampleActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9107. }
  9108. //=================================================================================
  9109. class CRoxieServerChooseSetsActivity : public CRoxieServerActivity
  9110. {
  9111. IHThorChooseSetsArg &helper;
  9112. unsigned numSets;
  9113. unsigned * setCounts;
  9114. bool done;
  9115. public:
  9116. CRoxieServerChooseSetsActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9117. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorChooseSetsArg &)basehelper)
  9118. {
  9119. setCounts = NULL;
  9120. numSets = 0;
  9121. done = false;
  9122. }
  9123. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9124. {
  9125. done = false;
  9126. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9127. numSets = helper.getNumSets();
  9128. setCounts = new unsigned[numSets];
  9129. memset(setCounts, 0, sizeof(unsigned)*numSets);
  9130. helper.setCounts(setCounts);
  9131. }
  9132. virtual void reset()
  9133. {
  9134. delete [] setCounts;
  9135. setCounts = NULL;
  9136. CRoxieServerActivity::reset();
  9137. }
  9138. virtual const void * nextRow()
  9139. {
  9140. ActivityTimer t(totalCycles, timeActivities);
  9141. if (done)
  9142. return NULL;
  9143. loop
  9144. {
  9145. const void * ret = inputStream->ungroupedNextRow();
  9146. if (!ret)
  9147. {
  9148. done = true;
  9149. return NULL;
  9150. }
  9151. processed++;
  9152. switch (helper.getRecordAction(ret))
  9153. {
  9154. case 2:
  9155. done = true;
  9156. return ret;
  9157. case 1:
  9158. return ret;
  9159. }
  9160. ReleaseRoxieRow(ret);
  9161. }
  9162. }
  9163. };
  9164. class CRoxieServerChooseSetsActivityFactory : public CRoxieServerActivityFactory
  9165. {
  9166. public:
  9167. CRoxieServerChooseSetsActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9168. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  9169. {
  9170. }
  9171. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9172. {
  9173. return new CRoxieServerChooseSetsActivity(_ctx, this, _probeManager);
  9174. }
  9175. };
  9176. IRoxieServerActivityFactory *createRoxieServerChooseSetsActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9177. {
  9178. return new CRoxieServerChooseSetsActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9179. }
  9180. //=================================================================================
  9181. class CRoxieServerChooseSetsExActivity : public CRoxieServerActivity
  9182. {
  9183. protected:
  9184. IHThorChooseSetsExArg &helper;
  9185. unsigned numSets;
  9186. unsigned curIndex;
  9187. unsigned * setCounts;
  9188. count_t * limits;
  9189. bool done;
  9190. ConstPointerArray gathered;
  9191. virtual bool includeRow(const void * row) = 0;
  9192. virtual void calculateSelection() = 0;
  9193. public:
  9194. CRoxieServerChooseSetsExActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9195. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorChooseSetsExArg &)basehelper)
  9196. {
  9197. setCounts = NULL;
  9198. limits = NULL;
  9199. done = false;
  9200. curIndex = 0;
  9201. numSets = 0;
  9202. }
  9203. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9204. {
  9205. done = false;
  9206. curIndex = 0;
  9207. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9208. numSets = helper.getNumSets();
  9209. setCounts = new unsigned[numSets];
  9210. memset(setCounts, 0, sizeof(unsigned)*numSets);
  9211. limits = (count_t *)calloc(sizeof(count_t), numSets);
  9212. helper.getLimits(limits);
  9213. }
  9214. virtual void reset()
  9215. {
  9216. delete [] setCounts;
  9217. setCounts = NULL;
  9218. free(limits);
  9219. limits = NULL;
  9220. roxiemem::ReleaseRoxieRowRange(gathered.getArray(), curIndex, gathered.ordinality());
  9221. gathered.kill();
  9222. curIndex = 0;
  9223. CRoxieServerActivity::reset();
  9224. }
  9225. virtual const void * nextRow()
  9226. {
  9227. ActivityTimer t(totalCycles, timeActivities);
  9228. if (gathered.ordinality() == 0)
  9229. {
  9230. curIndex = 0;
  9231. if (!inputStream->nextGroup(gathered))
  9232. {
  9233. done = true;
  9234. return NULL;
  9235. }
  9236. ForEachItemIn(idx1, gathered)
  9237. {
  9238. unsigned category = helper.getCategory(gathered.item(idx1));
  9239. if (category)
  9240. setCounts[category-1]++;
  9241. }
  9242. calculateSelection();
  9243. }
  9244. while (gathered.isItem(curIndex))
  9245. {
  9246. const void * row = gathered.item(curIndex);
  9247. gathered.replace(NULL, curIndex);
  9248. curIndex++;
  9249. if (includeRow(row))
  9250. {
  9251. processed++;
  9252. return row;
  9253. }
  9254. ReleaseRoxieRow(row);
  9255. }
  9256. gathered.kill();
  9257. return NULL;
  9258. }
  9259. };
  9260. class CRoxieServerChooseSetsLastActivity : public CRoxieServerChooseSetsExActivity
  9261. {
  9262. unsigned * numToSkip;
  9263. public:
  9264. CRoxieServerChooseSetsLastActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager) : CRoxieServerChooseSetsExActivity(_ctx, _factory, _probeManager)
  9265. {
  9266. numToSkip = NULL;
  9267. }
  9268. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9269. {
  9270. CRoxieServerChooseSetsExActivity::start(parentExtractSize, parentExtract, paused);
  9271. numToSkip = (unsigned *)calloc(sizeof(unsigned), numSets);
  9272. }
  9273. virtual void reset()
  9274. {
  9275. free(numToSkip);
  9276. numToSkip = NULL;
  9277. CRoxieServerChooseSetsExActivity::reset();
  9278. }
  9279. protected:
  9280. virtual void calculateSelection()
  9281. {
  9282. for (unsigned idx=0; idx < numSets; idx++)
  9283. {
  9284. if (setCounts[idx] < limits[idx])
  9285. numToSkip[idx] = 0;
  9286. else
  9287. numToSkip[idx] = (unsigned)(setCounts[idx] - limits[idx]);
  9288. }
  9289. }
  9290. virtual bool includeRow(const void * row)
  9291. {
  9292. unsigned category = helper.getCategory(row);
  9293. if (category)
  9294. {
  9295. if (numToSkip[category-1] == 0)
  9296. return true;
  9297. numToSkip[category-1]--;
  9298. }
  9299. return false;
  9300. }
  9301. };
  9302. class CRoxieServerChooseSetsEnthActivity : public CRoxieServerChooseSetsExActivity
  9303. {
  9304. count_t * counter;
  9305. public:
  9306. CRoxieServerChooseSetsEnthActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager) : CRoxieServerChooseSetsExActivity(_ctx, _factory, _probeManager)
  9307. {
  9308. counter = NULL;
  9309. }
  9310. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9311. {
  9312. CRoxieServerChooseSetsExActivity::start(parentExtractSize, parentExtract, paused);
  9313. counter = (count_t *)calloc(sizeof(count_t), numSets);
  9314. }
  9315. virtual void reset()
  9316. {
  9317. free(counter);
  9318. counter = NULL;
  9319. CRoxieServerChooseSetsExActivity::reset();
  9320. }
  9321. protected:
  9322. virtual void calculateSelection()
  9323. {
  9324. }
  9325. virtual bool includeRow(const void * row)
  9326. {
  9327. unsigned category = helper.getCategory(row);
  9328. if (category)
  9329. {
  9330. assertex(category <= numSets);
  9331. counter[category-1] += limits[category-1];
  9332. if(counter[category-1] >= setCounts[category-1])
  9333. {
  9334. counter[category-1] -= setCounts[category-1];
  9335. return true;
  9336. }
  9337. }
  9338. return false;
  9339. }
  9340. };
  9341. class CRoxieServerChooseSetsEnthActivityFactory : public CRoxieServerActivityFactory
  9342. {
  9343. public:
  9344. CRoxieServerChooseSetsEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9345. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  9346. {
  9347. }
  9348. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9349. {
  9350. return new CRoxieServerChooseSetsEnthActivity(_ctx, this, _probeManager);
  9351. }
  9352. };
  9353. IRoxieServerActivityFactory *createRoxieServerChooseSetsEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9354. {
  9355. return new CRoxieServerChooseSetsEnthActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9356. }
  9357. class CRoxieServerChooseSetsLastActivityFactory : public CRoxieServerActivityFactory
  9358. {
  9359. public:
  9360. CRoxieServerChooseSetsLastActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9361. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  9362. {
  9363. }
  9364. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9365. {
  9366. return new CRoxieServerChooseSetsLastActivity(_ctx, this, _probeManager);
  9367. }
  9368. };
  9369. IRoxieServerActivityFactory *createRoxieServerChooseSetsLastActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9370. {
  9371. return new CRoxieServerChooseSetsLastActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9372. }
  9373. //=================================================================================
  9374. class CRoxieServerEnthActivity : public CRoxieServerActivity
  9375. {
  9376. IHThorEnthArg &helper;
  9377. unsigned __int64 numerator;
  9378. unsigned __int64 denominator;
  9379. unsigned __int64 counter;
  9380. bool eof;
  9381. public:
  9382. CRoxieServerEnthActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9383. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorEnthArg &)basehelper)
  9384. {
  9385. eof = false;
  9386. numerator = denominator = counter = 0;
  9387. }
  9388. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9389. {
  9390. eof = false;
  9391. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9392. numerator = helper.getProportionNumerator();
  9393. denominator = helper.getProportionDenominator();
  9394. if(denominator == 0) denominator = 1; //MORE: simplest way to avoid disaster in this case
  9395. counter = (helper.getSampleNumber()-1) * greatestCommonDivisor(numerator, denominator);
  9396. if (counter >= denominator)
  9397. counter %= denominator;
  9398. }
  9399. inline bool wanted()
  9400. {
  9401. counter += numerator;
  9402. if(counter >= denominator)
  9403. {
  9404. counter -= denominator;
  9405. return true;
  9406. }
  9407. return false;
  9408. }
  9409. virtual const void * nextRow()
  9410. {
  9411. ActivityTimer t(totalCycles, timeActivities);
  9412. if (eof)
  9413. return NULL;
  9414. const void * ret;
  9415. loop
  9416. {
  9417. ret = inputStream->ungroupedNextRow();
  9418. if (!ret) //eof
  9419. {
  9420. eof = true;
  9421. return ret;
  9422. }
  9423. if (wanted())
  9424. return ret;
  9425. ReleaseRoxieRow(ret);
  9426. }
  9427. }
  9428. };
  9429. class CRoxieServerEnthActivityFactory : public CRoxieServerActivityFactory
  9430. {
  9431. public:
  9432. CRoxieServerEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9433. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  9434. {
  9435. }
  9436. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9437. {
  9438. return new CRoxieServerEnthActivity(_ctx, this, _probeManager);
  9439. }
  9440. };
  9441. IRoxieServerActivityFactory *createRoxieServerEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9442. {
  9443. return new CRoxieServerEnthActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9444. }
  9445. //=================================================================================
  9446. class CRoxieServerAggregateActivity : public CRoxieServerActivity
  9447. {
  9448. IHThorAggregateArg &helper;
  9449. bool eof;
  9450. bool isInputGrouped;
  9451. bool abortEarly;
  9452. public:
  9453. CRoxieServerAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9454. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorAggregateArg &)basehelper)
  9455. {
  9456. eof = false;
  9457. isInputGrouped = false;
  9458. abortEarly = false;
  9459. }
  9460. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9461. {
  9462. eof = false;
  9463. isInputGrouped = input->queryOutputMeta()->isGrouped(); // could be done earlier, in setInput?
  9464. abortEarly = !isInputGrouped && (factory->getKind() == TAKexistsaggregate); // ditto
  9465. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9466. }
  9467. virtual bool needsAllocator() const { return true; }
  9468. virtual const void * nextRow()
  9469. {
  9470. ActivityTimer t(totalCycles, timeActivities);
  9471. if (eof)
  9472. return NULL;
  9473. const void * next = inputStream->nextRow();
  9474. if (!next && isInputGrouped)
  9475. {
  9476. eof = true;
  9477. return NULL;
  9478. }
  9479. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  9480. size32_t finalSize = helper.clearAggregate(rowBuilder);
  9481. if (next)
  9482. {
  9483. finalSize = helper.processFirst(rowBuilder, next);
  9484. ReleaseRoxieRow(next);
  9485. if (!abortEarly)
  9486. {
  9487. loop
  9488. {
  9489. next = inputStream->nextRow();
  9490. if (!next)
  9491. break;
  9492. finalSize = helper.processNext(rowBuilder, next);
  9493. ReleaseRoxieRow(next);
  9494. }
  9495. }
  9496. }
  9497. if (!isInputGrouped) // either read all, or aborted early
  9498. eof = true;
  9499. processed++;
  9500. return rowBuilder.finalizeRowClear(finalSize);
  9501. }
  9502. };
  9503. class CRoxieServerStrandedAggregateActivity : public CRoxieServerStrandedActivity, implements IOrderedCallbackCollection
  9504. {
  9505. class AggregateProcessor : public StrandProcessor, implements IStrandThreaded, implements IOrderedOutputCallback
  9506. {
  9507. protected:
  9508. IHThorAggregateArg &helper;
  9509. OwnedConstRoxieRow result;
  9510. bool eof = false;
  9511. bool isInputGrouped = false;
  9512. bool abortEarly = false;
  9513. public:
  9514. AggregateProcessor(CRoxieServerActivity &_parent, IEngineRowStream *_inputStream, IHThorAggregateArg &_helper, bool _isInputGrouped, bool _abortEarly)
  9515. : StrandProcessor(_parent, _inputStream, true), helper(_helper), isInputGrouped(_isInputGrouped), abortEarly(_abortEarly)
  9516. {
  9517. }
  9518. virtual const void * nextRow() override
  9519. {
  9520. ActivityTimer t(totalCycles, timeActivities);
  9521. if (eof || isAborting())
  9522. return NULL;
  9523. const void * next = inputStream->nextRow();
  9524. if (!next && isInputGrouped)
  9525. {
  9526. eof = true;
  9527. return NULL;
  9528. }
  9529. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  9530. size32_t finalSize = helper.clearAggregate(rowBuilder);
  9531. if (next)
  9532. {
  9533. finalSize = helper.processFirst(rowBuilder, next);
  9534. ReleaseRoxieRow(next);
  9535. if (!abortEarly)
  9536. {
  9537. loop
  9538. {
  9539. next = inputStream->nextRow();
  9540. if (!next)
  9541. break;
  9542. finalSize = helper.processNext(rowBuilder, next);
  9543. ReleaseRoxieRow(next);
  9544. if (isAborting())
  9545. break;
  9546. }
  9547. }
  9548. }
  9549. if (!isInputGrouped) // either read all, or aborted early
  9550. eof = true;
  9551. processed++;
  9552. return rowBuilder.finalizeRowClear(finalSize);
  9553. }
  9554. virtual void main() override
  9555. {
  9556. isInputGrouped = true; // gather no row if there are no input rows.
  9557. result.setown(nextRow());
  9558. queryActivity().noteStrandFinished(inputStream);
  9559. }
  9560. virtual void reset() override
  9561. {
  9562. StrandProcessor::reset();
  9563. result.clear();
  9564. eof = false;
  9565. }
  9566. //interface IOutputOutputCallback
  9567. virtual bool noteEndOfInputChunk() { return true; }
  9568. virtual void noteEndOfInput() {}
  9569. virtual void stopStream()
  9570. {
  9571. inputStream->stop();
  9572. }
  9573. const void * queryResult() const { return result; }
  9574. CRoxieServerStrandedAggregateActivity & queryActivity() { return static_cast<CRoxieServerStrandedAggregateActivity &>(parent); }
  9575. };
  9576. //This class is only used when a single aggregate is being calculated.
  9577. class AggregateCombiner : public CInterfaceOf<IEngineRowStream>
  9578. {
  9579. public:
  9580. explicit AggregateCombiner(CRoxieServerStrandedAggregateActivity & _parent) : parent(_parent)
  9581. {
  9582. }
  9583. virtual const void *nextRow()
  9584. {
  9585. return parent.getCombinedAggregate();
  9586. }
  9587. virtual void stop()
  9588. {
  9589. parent.outputStopped();
  9590. }
  9591. virtual void resetEOF()
  9592. {
  9593. throwUnexpected();
  9594. }
  9595. protected:
  9596. CRoxieServerStrandedAggregateActivity & parent;
  9597. } combiner;
  9598. class NullCallback : implements IOrderedOutputCallback
  9599. {
  9600. public:
  9601. virtual bool noteEndOfInputChunk() { return true; }
  9602. virtual void noteEndOfInput() {}
  9603. } nullCallback;
  9604. public:
  9605. CRoxieServerStrandedAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const StrandOptions &_strandOptions)
  9606. : CRoxieServerStrandedActivity(_ctx, _factory, _probeManager, _strandOptions), helper((IHThorAggregateArg &)basehelper), combiner(*this)
  9607. {
  9608. isInputGrouped = false;
  9609. abortEarly = false;
  9610. }
  9611. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  9612. {
  9613. CRoxieServerStrandedActivity::setInput(idx, _sourceIdx, _in);
  9614. isInputGrouped = input->queryOutputMeta()->isGrouped(); // could be done earlier, in setInput?
  9615. abortEarly = !isInputGrouped && (factory->getKind() == TAKexistsaggregate); // ditto
  9616. //For EXISTS(), and aggregates that rely on the input order, force to execute single threaded
  9617. //MORE: Ordered should be able to process a block at a time and then merge them, similar to disk write processing.
  9618. if (abortEarly || (!isInputGrouped && queryFactory()->isInputOrdered(false, 0)))
  9619. strandOptions.numStrands = 1;
  9620. else if (!isInputGrouped)
  9621. combineStreams = true;
  9622. }
  9623. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  9624. {
  9625. PointerArrayOf<IEngineRowStream> localStreams;
  9626. //If streams are being combined, this class should be notified of end of sections, otherwise grouped aggregates can inform a downstream activity.
  9627. IOrderedCallbackCollection * callbacks = combineStreams ? static_cast<IOrderedCallbackCollection *>(this) : orderedCallbacks;
  9628. Owned<IStrandJunction> outJunction = CRoxieServerStrandedActivity::getOutputStreams(ctx, idx, localStreams, consumerOptions, consumerOrdered, callbacks);
  9629. if (localStreams.ordinality() == 1)
  9630. combineStreams = false; // Select a more efficient/simpler code path
  9631. if (combineStreams)
  9632. {
  9633. assertex(!outJunction); // this needs more thought!
  9634. streams.append(&combiner);
  9635. }
  9636. else
  9637. {
  9638. streams.swapWith(localStreams);
  9639. }
  9640. return outJunction.getClear();
  9641. }
  9642. virtual StrandProcessor *createStrandProcessor(IEngineRowStream *instream)
  9643. {
  9644. DBGLOG("Create aggregate strand processor %u", strandOptions.numStrands);
  9645. return new AggregateProcessor(*this, instream, (IHThorAggregateArg &) basehelper, isInputGrouped && !combineStreams, abortEarly);
  9646. }
  9647. virtual StrandProcessor *createStrandSourceProcessor(bool inputOrdered) { throwUnexpected(); }
  9648. virtual bool needsAllocator() const { return true; }
  9649. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused) override
  9650. {
  9651. CRoxieServerStrandedActivity::start(parentExtractSize, parentExtract, paused);
  9652. if (combineStreams)
  9653. {
  9654. barrier.setown(createStrandBarrier());
  9655. ForEachItemIn(i, strands)
  9656. barrier->startStrand(queryAggregate(i));
  9657. active.store(1);
  9658. }
  9659. else
  9660. active.store(0);
  9661. }
  9662. virtual void reset() override
  9663. {
  9664. CRoxieServerStrandedActivity::reset();
  9665. barrier.clear();
  9666. calculated = false;
  9667. }
  9668. //Helper functions for the single aggregate case
  9669. const void * getCombinedAggregate()
  9670. {
  9671. if (calculated)
  9672. return NULL;
  9673. calculated= true;
  9674. barrier->waitForStrands();
  9675. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  9676. size32_t finalSize = helper.clearAggregate(rowBuilder);
  9677. bool isFirst = true;
  9678. for (unsigned i=0; i < numStrands(); i++)
  9679. {
  9680. const void * next = queryAggregate(i).queryResult();
  9681. if (next)
  9682. {
  9683. if (isFirst)
  9684. {
  9685. finalSize = cloneRow(rowBuilder, next, helper.queryOutputMeta());
  9686. isFirst = false;
  9687. }
  9688. else
  9689. finalSize = helper.mergeAggregate(rowBuilder, next);
  9690. }
  9691. }
  9692. return rowBuilder.finalizeRowClear(finalSize);
  9693. }
  9694. void outputStopped()
  9695. {
  9696. //only called if generating a single result.
  9697. assertex(combineStreams);
  9698. if (barrier)
  9699. {
  9700. requestAbort(); // if strands are still running, abort them
  9701. barrier->waitForStrands();
  9702. }
  9703. else
  9704. {
  9705. ForEachItemIn(i, strands)
  9706. queryAggregate(i).stopStream();
  9707. }
  9708. CRoxieServerStrandedActivity::stop();
  9709. }
  9710. void noteStrandFinished(IRowStream * stream)
  9711. {
  9712. barrier->noteStrandFinished(stream);
  9713. }
  9714. virtual IOrderedOutputCallback * queryCallback(unsigned i)
  9715. {
  9716. //The non-ordered aggregate does not need to process the ordered call back information.
  9717. //If the ordered single aggregate was implemented then it would need to be processed instead of ignored,
  9718. //however it needs some care since the strands are not yet created. So cannot return strand(i).
  9719. return &nullCallback;
  9720. }
  9721. inline AggregateProcessor & queryAggregate(unsigned i)
  9722. {
  9723. return static_cast<AggregateProcessor &>(strands.item(i));
  9724. }
  9725. protected:
  9726. IHThorAggregateArg &helper;
  9727. Owned<IStrandBarrier> barrier;
  9728. IEngineRowStream * combinedStream = nullptr;
  9729. bool isInputGrouped;
  9730. bool abortEarly;
  9731. bool combineStreams = false;
  9732. bool calculated = false;
  9733. };
  9734. class CRoxieServerAggregateActivityFactory : public CRoxieServerActivityFactory
  9735. {
  9736. StrandOptions strandOptions;
  9737. public:
  9738. CRoxieServerAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9739. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), strandOptions(_graphNode)
  9740. {
  9741. Owned<IHThorAggregateArg> helper = (IHThorAggregateArg *) helperFactory();
  9742. if (!(helper->getAggregateFlags() & TAForderedmerge))
  9743. optStableInput = false;
  9744. }
  9745. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9746. {
  9747. return new CRoxieServerStrandedAggregateActivity(_ctx, this, _probeManager, strandOptions);
  9748. }
  9749. };
  9750. IRoxieServerActivityFactory *createRoxieServerAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9751. {
  9752. return new CRoxieServerAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9753. }
  9754. //=================================================================================
  9755. typedef unsigned t_hashPrefix;
  9756. class CRoxieServerHashAggregateActivity : public CRoxieServerActivity
  9757. {
  9758. IHThorHashAggregateArg &helper;
  9759. RowAggregator aggregated;
  9760. bool eof;
  9761. bool gathered;
  9762. bool isGroupedAggregate;
  9763. public:
  9764. CRoxieServerHashAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, bool _isGroupedAggregate, IProbeManager *_probeManager)
  9765. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorHashAggregateArg &)basehelper),
  9766. isGroupedAggregate(_isGroupedAggregate),
  9767. aggregated(helper, helper)
  9768. {
  9769. eof = false;
  9770. gathered = false;
  9771. }
  9772. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9773. {
  9774. eof = false;
  9775. gathered = false;
  9776. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9777. }
  9778. virtual void reset()
  9779. {
  9780. aggregated.reset();
  9781. CRoxieServerActivity::reset();
  9782. }
  9783. virtual bool needsAllocator() const { return true; }
  9784. virtual const void * nextRow()
  9785. {
  9786. ActivityTimer t(totalCycles, timeActivities);
  9787. if (eof)
  9788. return NULL;
  9789. if (!gathered)
  9790. {
  9791. aggregated.start(rowAllocator);
  9792. bool eog = true;
  9793. loop
  9794. {
  9795. const void * next = inputStream->nextRow();
  9796. if (!next)
  9797. {
  9798. if (isGroupedAggregate)
  9799. {
  9800. if (eog)
  9801. eof = true;
  9802. break;
  9803. }
  9804. next = inputStream->nextRow();
  9805. if (!next)
  9806. break;
  9807. }
  9808. eog = false;
  9809. aggregated.addRow(next);
  9810. ReleaseRoxieRow(next);
  9811. }
  9812. gathered = true;
  9813. }
  9814. Owned<AggregateRowBuilder> next = aggregated.nextResult();
  9815. if (next)
  9816. {
  9817. processed++;
  9818. return next->finalizeRowClear();
  9819. }
  9820. if (!isGroupedAggregate)
  9821. eof = true;
  9822. aggregated.reset();
  9823. gathered = false;
  9824. return NULL;
  9825. }
  9826. };
  9827. class CRoxieServerHashAggregateActivityFactory : public CRoxieServerActivityFactory
  9828. {
  9829. public:
  9830. CRoxieServerHashAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9831. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  9832. {
  9833. isGroupedAggregate = _graphNode.getPropBool("att[@name='grouped']/@value");
  9834. }
  9835. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9836. {
  9837. return new CRoxieServerHashAggregateActivity(_ctx, this, isGroupedAggregate, _probeManager);
  9838. }
  9839. protected:
  9840. bool isGroupedAggregate;
  9841. };
  9842. IRoxieServerActivityFactory *createRoxieServerHashAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9843. {
  9844. return new CRoxieServerHashAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9845. }
  9846. //=================================================================================
  9847. class CRoxieServerDegroupActivity : public CRoxieServerActivity
  9848. {
  9849. IHThorDegroupArg &helper;
  9850. bool eof;
  9851. public:
  9852. CRoxieServerDegroupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9853. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorDegroupArg &)basehelper)
  9854. {
  9855. eof = false;
  9856. }
  9857. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9858. {
  9859. eof = false;
  9860. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9861. }
  9862. virtual const void * nextRow()
  9863. {
  9864. ActivityTimer t(totalCycles, timeActivities);
  9865. if (eof)
  9866. return NULL;
  9867. const void * ret = inputStream->ungroupedNextRow();
  9868. if (ret)
  9869. processed++;
  9870. else
  9871. eof = true;
  9872. return ret;
  9873. }
  9874. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  9875. {
  9876. ActivityTimer t(totalCycles, timeActivities);
  9877. if (eof)
  9878. return NULL;
  9879. const void * ret = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  9880. if (ret)
  9881. processed++;
  9882. else
  9883. eof = true;
  9884. return ret;
  9885. }
  9886. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  9887. {
  9888. return input->gatherConjunctions(collector);
  9889. }
  9890. virtual void resetEOF()
  9891. {
  9892. eof = false;
  9893. inputStream->resetEOF();
  9894. }
  9895. IInputSteppingMeta * querySteppingMeta()
  9896. {
  9897. return input->querySteppingMeta();
  9898. }
  9899. };
  9900. class CRoxieServerDegroupActivityFactory : public CRoxieServerActivityFactory
  9901. {
  9902. public:
  9903. CRoxieServerDegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9904. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  9905. {
  9906. }
  9907. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9908. {
  9909. return new CRoxieServerDegroupActivity(_ctx, this, _probeManager);
  9910. }
  9911. };
  9912. IRoxieServerActivityFactory *createRoxieServerDegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9913. {
  9914. return new CRoxieServerDegroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9915. }
  9916. //=================================================================================
  9917. class CRoxieServerSpillReadActivity : public CRoxieServerActivity
  9918. {
  9919. IHThorDiskReadArg &helper;
  9920. bool needTransform;
  9921. bool eof;
  9922. bool anyThisGroup;
  9923. unsigned __int64 rowLimit;
  9924. unsigned __int64 choosenLimit;
  9925. public:
  9926. CRoxieServerSpillReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9927. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorDiskReadArg &)basehelper)
  9928. {
  9929. needTransform = helper.needTransform();
  9930. rowLimit = (unsigned __int64) -1;
  9931. choosenLimit = 0;
  9932. eof = false;
  9933. anyThisGroup = false;
  9934. }
  9935. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9936. {
  9937. anyThisGroup = false;
  9938. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9939. if (helper.canMatchAny())
  9940. eof = false;
  9941. else
  9942. eof = true;
  9943. choosenLimit = helper.getChooseNLimit();
  9944. rowLimit = helper.getRowLimit();
  9945. helper.setCallback(NULL); // members should not be called - change if they are
  9946. }
  9947. virtual bool needsAllocator() const { return true; }
  9948. virtual const void * nextRow()
  9949. {
  9950. ActivityTimer t(totalCycles, timeActivities);
  9951. if (eof)
  9952. return NULL;
  9953. if (processed==choosenLimit)
  9954. {
  9955. eof = true;
  9956. return NULL;
  9957. }
  9958. if (needTransform)
  9959. {
  9960. loop
  9961. {
  9962. const void *in = inputStream->nextRow();
  9963. if (!in)
  9964. {
  9965. if (anyThisGroup)
  9966. {
  9967. anyThisGroup = false;
  9968. return NULL;
  9969. }
  9970. in = inputStream->nextRow();
  9971. if (!in)
  9972. {
  9973. eof = true;
  9974. return NULL; // eof...
  9975. }
  9976. }
  9977. unsigned outSize;
  9978. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  9979. try
  9980. {
  9981. outSize = helper.transform(rowBuilder, in);
  9982. ReleaseRoxieRow(in);
  9983. }
  9984. catch (IException *E)
  9985. {
  9986. throw makeWrappedException(E);
  9987. }
  9988. if (outSize)
  9989. {
  9990. anyThisGroup = true;
  9991. processed++;
  9992. if (processed==rowLimit)
  9993. {
  9994. if (traceLevel > 4)
  9995. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  9996. helper.onLimitExceeded();
  9997. }
  9998. return rowBuilder.finalizeRowClear(outSize);
  9999. }
  10000. }
  10001. }
  10002. else
  10003. {
  10004. const void *ret = inputStream->nextRow();
  10005. if (ret)
  10006. {
  10007. processed++;
  10008. if (processed==rowLimit)
  10009. {
  10010. if (traceLevel > 4)
  10011. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  10012. ReleaseClearRoxieRow(ret);
  10013. helper.onLimitExceeded(); // should not return
  10014. throwUnexpected();
  10015. }
  10016. }
  10017. return ret;
  10018. }
  10019. }
  10020. };
  10021. class CRoxieServerSpillReadActivityFactory : public CRoxieServerActivityFactory
  10022. {
  10023. public:
  10024. CRoxieServerSpillReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  10025. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  10026. {
  10027. }
  10028. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  10029. {
  10030. return new CRoxieServerSpillReadActivity(_ctx, this, _probeManager);
  10031. }
  10032. virtual void addDependency(unsigned source, ThorActivityKind sourceKind, unsigned sourceIdx, int controlId, const char *edgeId)
  10033. {
  10034. if (sourceKind==TAKspill || sourceKind==TAKdiskwrite) // Bit of a hack - codegen probably should differentiate
  10035. setInput(0, source, sourceIdx);
  10036. else
  10037. CRoxieServerActivityFactory::addDependency(source, kind, sourceIdx, controlId, edgeId);
  10038. }
  10039. };
  10040. IRoxieServerActivityFactory *createRoxieServerSpillReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  10041. {
  10042. return new CRoxieServerSpillReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  10043. }
  10044. //=================================================================================
  10045. class CRoxieServerSpillWriteActivity : public CRoxieServerActivity
  10046. {
  10047. public:
  10048. CRoxieServerSpillWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  10049. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  10050. {
  10051. }
  10052. ~CRoxieServerSpillWriteActivity()
  10053. {
  10054. }
  10055. virtual const void *nextRow()
  10056. {
  10057. ActivityTimer t(totalCycles, timeActivities);
  10058. return inputStream->nextRow();
  10059. }
  10060. };
  10061. //==================================================================================
  10062. class CRoxieServerDiskWriteActivity : public CRoxieServerInternalSinkActivity, implements IRoxiePublishCallback
  10063. {
  10064. protected:
  10065. Owned<IExtRowWriter> outSeq;
  10066. Owned<IOutputRowSerializer> rowSerializer;
  10067. Linked<IFileIOStream> diskout;
  10068. bool blockcompressed;
  10069. bool extend;
  10070. bool overwrite;
  10071. bool encrypted;
  10072. bool grouped;
  10073. IHThorDiskWriteArg &helper;
  10074. CachedOutputMetaData diskmeta;
  10075. Owned<IRoxieWriteHandler> writer;
  10076. bool tallycrc;
  10077. unsigned __int64 uncompressedBytesWritten;
  10078. CRC32 crc;
  10079. void updateWorkUnitResult(unsigned __int64 reccount)
  10080. {
  10081. assertex(writer);
  10082. // MORE - a lot of this is common with hthor
  10083. WorkunitUpdate wu = ctx->updateWorkUnit();
  10084. if (wu)
  10085. {
  10086. OwnedRoxieString rawLogicalName = helper.getFileName();
  10087. StringBuffer lfn; // logical filename
  10088. expandLogicalFilename(lfn, rawLogicalName, wu, false, false);
  10089. if (lfn.length())
  10090. {
  10091. unsigned flags = helper.getFlags();
  10092. WUFileKind fileKind;
  10093. if (TDXtemporary & flags)
  10094. fileKind = WUFileTemporary;
  10095. else if(TDXjobtemp & flags)
  10096. fileKind = WUFileJobOwned;
  10097. else if(TDWowned & flags)
  10098. fileKind = WUFileOwned;
  10099. else
  10100. fileKind = WUFileStandard;
  10101. StringArray clusters;
  10102. writer->getClusters(clusters);
  10103. wu->addFile(lfn.str(), &clusters, helper.getTempUsageCount(), fileKind, NULL);
  10104. if (!(flags & TDXtemporary) && helper.getSequence() >= 0)
  10105. {
  10106. Owned<IWUResult> result = wu->updateResultBySequence(helper.getSequence());
  10107. if (result)
  10108. {
  10109. result->setResultTotalRowCount(reccount);
  10110. result->setResultStatus(ResultStatusCalculated);
  10111. if (helper.getFlags() & TDWresult)
  10112. result->setResultFilename(lfn.str());
  10113. else
  10114. result->setResultLogicalName(lfn.str());
  10115. }
  10116. }
  10117. }
  10118. }
  10119. }
  10120. void resolve()
  10121. {
  10122. OwnedRoxieString rawLogicalName = helper.getFileName();
  10123. assertex(rawLogicalName);
  10124. assertex((helper.getFlags() & TDXtemporary) == 0);
  10125. StringArray clusters;
  10126. unsigned clusterIdx = 0;
  10127. while(true)
  10128. {
  10129. OwnedRoxieString cluster(helper.getCluster(clusterIdx));
  10130. if(!cluster)
  10131. break;
  10132. clusters.append(cluster);
  10133. clusterIdx++;
  10134. }
  10135. if (clusters.length())
  10136. {
  10137. if (extend)
  10138. throw MakeStringException(0, "Cannot combine EXTEND and CLUSTER flags on disk write of file %s", rawLogicalName.get());
  10139. }
  10140. else
  10141. {
  10142. if (roxieName.length())
  10143. clusters.append(roxieName.str());
  10144. else
  10145. clusters.append(".");
  10146. }
  10147. writer.setown(ctx->createLFN(rawLogicalName, overwrite, extend, clusters));
  10148. // MORE - need to check somewhere that single part if it's an existing file or an external one...
  10149. }
  10150. public:
  10151. CRoxieServerDiskWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  10152. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, 0), helper((IHThorDiskWriteArg &)basehelper)
  10153. {
  10154. extend = ((helper.getFlags() & TDWextend) != 0);
  10155. overwrite = ((helper.getFlags() & TDWoverwrite) != 0);
  10156. grouped = false; // don't think we need to support it...
  10157. diskmeta.set(helper.queryDiskRecordSize());
  10158. blockcompressed = (((helper.getFlags() & TDWnewcompress) != 0) || (((helper.getFlags() & TDXcompress) != 0) && (diskmeta.getFixedSize() >= MIN_ROWCOMPRESS_RECSIZE))); //always use new compression
  10159. encrypted = false; // set later
  10160. tallycrc = true;
  10161. uncompressedBytesWritten = 0;
  10162. }
  10163. ~CRoxieServerDiskWriteActivity()
  10164. {
  10165. }
  10166. virtual bool needsAllocator() const
  10167. {
  10168. return true;
  10169. }
  10170. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10171. {
  10172. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  10173. resolve();
  10174. Owned<IFileIO> io;
  10175. void *ekey;
  10176. size32_t ekeylen;
  10177. helper.getEncryptKey(ekeylen, ekey);
  10178. Owned<ICompressor> ecomp;
  10179. if (ekeylen!=0)
  10180. {
  10181. ecomp.setown(createAESCompressor256(ekeylen,ekey));
  10182. memset(ekey,0,ekeylen);
  10183. rtlFree(ekey);
  10184. encrypted = true;
  10185. blockcompressed = true;
  10186. }
  10187. if (blockcompressed)
  10188. io.setown(createCompressedFileWriter(writer->queryFile(), (diskmeta.isFixedSize() ? diskmeta.getFixedSize() : 0), extend, true, ecomp));
  10189. else
  10190. io.setown(writer->queryFile()->open(extend ? IFOwrite : IFOcreate));
  10191. if (!io)
  10192. throw MakeStringException(errno, "Failed to create%s file %s for writing", (encrypted ? " encrypted" : (blockcompressed ? " compressed" : "")), writer->queryFile()->queryFilename());
  10193. diskout.setown(createBufferedIOStream(io));
  10194. if (extend)
  10195. diskout->seek(0, IFSend);
  10196. tallycrc = !factory->queryQueryFactory().queryOptions().skipFileFormatCrcCheck && !(helper.getFlags() & TDRnocrccheck) && !blockcompressed;
  10197. Owned<IRowInterfaces> rowIf = createRowInterfaces(input->queryOutputMeta(), activityId, ctx->queryCodeContext());
  10198. rowSerializer.set(rowIf->queryRowSerializer());
  10199. unsigned rwFlags = rw_autoflush;
  10200. if(grouped)
  10201. rwFlags |= rw_grouped;
  10202. if(tallycrc)
  10203. rwFlags |= rw_crc;
  10204. outSeq.setown(createRowWriter(diskout, rowIf, rwFlags));
  10205. }
  10206. virtual void stop()
  10207. {
  10208. if (aborted)
  10209. {
  10210. if (writer)
  10211. writer->finish(false, this);
  10212. }
  10213. else
  10214. {
  10215. if (outSeq)
  10216. outSeq->flush(&crc);
  10217. if (outSeq)
  10218. uncompressedBytesWritten = outSeq->getPosition();
  10219. outSeq.clear();
  10220. diskout.clear(); // Make sure file is properly closed or date may not match published info
  10221. if (writer)
  10222. {
  10223. updateWorkUnitResult(processed);
  10224. writer->finish(true, this);
  10225. }
  10226. }
  10227. writer.clear();
  10228. CRoxieServerActivity::stop();
  10229. }
  10230. virtual void reset()
  10231. {
  10232. CRoxieServerActivity::reset();
  10233. diskout.clear();
  10234. outSeq.clear();
  10235. writer.clear();
  10236. uncompressedBytesWritten = 0;
  10237. crc.reset();
  10238. }
  10239. virtual void onExecute()
  10240. {
  10241. loop
  10242. {
  10243. const void *nextrec = inputStream->ungroupedNextRow();
  10244. if (!nextrec)
  10245. break;
  10246. processed++;
  10247. outSeq->putRow(nextrec);
  10248. }
  10249. }
  10250. virtual void setFileProperties(IFileDescriptor *desc) const
  10251. {
  10252. IPropertyTree &partProps = desc->queryPart(0)->queryProperties(); //properties of the first file part.
  10253. IPropertyTree &fileProps = desc->queryProperties(); // properties of the logical file
  10254. if (blockcompressed)
  10255. {
  10256. // caller has already set @size from file size...
  10257. fileProps.setPropBool("@blockCompressed", true);
  10258. fileProps.setPropInt64("@compressedSize", partProps.getPropInt64("@size", 0));
  10259. partProps.setPropInt64("@compressedSize", partProps.getPropInt64("@size", 0));
  10260. fileProps.setPropInt64("@size", uncompressedBytesWritten);
  10261. partProps.setPropInt64("@size", uncompressedBytesWritten);
  10262. }
  10263. else if (tallycrc && crc.get())
  10264. partProps.setPropInt64("@fileCrc", crc.get());
  10265. if (encrypted)
  10266. fileProps.setPropBool("@encrypted", true);
  10267. fileProps.setPropInt64("@recordCount", processed);
  10268. unsigned flags = helper.getFlags();
  10269. if (flags & TDWpersist)
  10270. fileProps.setPropBool("@persistent", true);
  10271. if (grouped)
  10272. fileProps.setPropBool("@grouped", true);
  10273. if (flags & (TDWowned|TDXjobtemp|TDXtemporary))
  10274. fileProps.setPropBool("@owned", true);
  10275. if (flags & TDWresult)
  10276. fileProps.setPropBool("@result", true);
  10277. IConstWorkUnit *workUnit = ctx->queryWorkUnit();
  10278. if (workUnit)
  10279. {
  10280. fileProps.setProp("@owner", workUnit->queryUser());
  10281. fileProps.setProp("@workunit", workUnit->queryWuid());
  10282. fileProps.setProp("@job", workUnit->queryJobName());
  10283. }
  10284. if (flags & TDWexpires)
  10285. setExpiryTime(fileProps, helper.getExpiryDays());
  10286. if (flags & TDWupdate)
  10287. {
  10288. unsigned eclCRC;
  10289. unsigned __int64 totalCRC;
  10290. helper.getUpdateCRCs(eclCRC, totalCRC);
  10291. fileProps.setPropInt("@eclCRC", eclCRC);
  10292. fileProps.setPropInt64("@totalCRC", totalCRC);
  10293. }
  10294. fileProps.setPropInt("@formatCrc", helper.getFormatCrc());
  10295. IRecordSize * inputMeta = input->queryOutputMeta();
  10296. if ((inputMeta->isFixedSize()) && !isOutputTransformed())
  10297. fileProps.setPropInt("@recordSize", inputMeta->getFixedSize() + (grouped ? 1 : 0));
  10298. const char *recordECL = helper.queryRecordECL();
  10299. if (recordECL && *recordECL)
  10300. fileProps.setProp("ECL", recordECL);
  10301. fileProps.setProp("@kind", "flat"); // default, derivitives may override
  10302. }
  10303. virtual IUserDescriptor *queryUserDescriptor() const
  10304. {
  10305. IConstWorkUnit *workUnit = ctx->queryWorkUnit();
  10306. if (workUnit)
  10307. return workUnit->queryUserDescriptor();
  10308. else
  10309. return NULL;
  10310. }
  10311. virtual bool isOutputTransformed() const { return false; }
  10312. };
  10313. //=================================================================================
  10314. class CRoxieServerCsvWriteActivity : public CRoxieServerDiskWriteActivity
  10315. {
  10316. IHThorCsvWriteArg &csvHelper;
  10317. CSVOutputStream csvOutput;
  10318. public:
  10319. CRoxieServerCsvWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  10320. : CRoxieServerDiskWriteActivity(_ctx, _factory, _probeManager), csvHelper(static_cast<IHThorCsvWriteArg &>(helper))
  10321. {
  10322. csvOutput.init(csvHelper.queryCsvParameters(), false);
  10323. }
  10324. virtual void onExecute()
  10325. {
  10326. OwnedRoxieString header(csvHelper.queryCsvParameters()->getHeader());
  10327. if (header)
  10328. {
  10329. csvOutput.beginLine();
  10330. csvOutput.writeHeaderLn(strlen(header), header);
  10331. diskout->write(csvOutput.length(), csvOutput.str());
  10332. }
  10333. loop
  10334. {
  10335. const void *nextrec = inputStream->ungroupedNextRow();
  10336. if (!nextrec)
  10337. break;
  10338. processed++;
  10339. csvOutput.beginLine();
  10340. csvHelper.writeRow((const byte *)nextrec, &csvOutput);
  10341. csvOutput.endLine();
  10342. diskout->write(csvOutput.length(), csvOutput.str());
  10343. ReleaseRoxieRow(nextrec);
  10344. }
  10345. OwnedRoxieString footer(csvHelper.queryCsvParameters()->getFooter());
  10346. if (footer)
  10347. {
  10348. csvOutput.beginLine();
  10349. csvOutput.writeHeaderLn(strlen(footer), footer);
  10350. diskout->write(csvOutput.length(), csvOutput.str());
  10351. }
  10352. }
  10353. virtual void setFileProperties(IFileDescriptor *desc) const
  10354. {
  10355. CRoxieServerDiskWriteActivity::setFileProperties(desc);
  10356. IPropertyTree &props = desc->queryProperties();
  10357. props.setProp("@format","utf8n");
  10358. ICsvParameters *csvParameters = csvHelper.queryCsvParameters();
  10359. StringBuffer separator;
  10360. OwnedRoxieString rs(csvParameters->getSeparator(0));
  10361. const char *s = rs;
  10362. while (s && *s)
  10363. {
  10364. if (',' == *s)
  10365. separator.append("\\,");
  10366. else
  10367. separator.append(*s);
  10368. ++s;
  10369. }
  10370. props.setProp("@csvSeparate", separator.str());
  10371. props.setProp("@csvQuote", rs.setown(csvParameters->getQuote(0)));
  10372. props.setProp("@csvTerminate", rs.setown(csvParameters->getTerminator(0)));
  10373. props.setProp("@csvEscape", rs.setown(csvParameters->getEscape(0)));
  10374. props.setProp("@kind", "csv");
  10375. }
  10376. virtual bool isOutputTransformed() const { return true; }
  10377. };
  10378. class CRoxieServerXmlWriteActivity : public CRoxieServerDiskWriteActivity
  10379. {
  10380. IHThorXmlWriteArg &xmlHelper;
  10381. StringAttr rowTag;
  10382. ThorActivityKind kind;
  10383. unsigned headerLength;
  10384. unsigned footerLength;
  10385. public:
  10386. CRoxieServerXmlWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, ThorActivityKind _kind)
  10387. : CRoxieServerDiskWriteActivity(_ctx, _factory, _probeManager), xmlHelper(static_cast<IHThorXmlWriteArg &>(helper)), kind(_kind), headerLength(0), footerLength(0)
  10388. {
  10389. }
  10390. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10391. {
  10392. CRoxieServerDiskWriteActivity::start(parentExtractSize, parentExtract, paused);
  10393. OwnedRoxieString xmlpath(xmlHelper.getXmlIteratorPath());
  10394. if (!xmlpath)
  10395. rowTag.set(DEFAULTXMLROWTAG);
  10396. else
  10397. {
  10398. const char *path = xmlpath;
  10399. if (*path == '/') path++;
  10400. if (strchr(path, '/')) UNIMPLEMENTED; // more what do we do with /mydata/row
  10401. rowTag.set(path);
  10402. }
  10403. }
  10404. virtual void onExecute()
  10405. {
  10406. StringBuffer header;
  10407. OwnedRoxieString suppliedHeader(xmlHelper.getHeader());
  10408. if (kind==TAKjsonwrite)
  10409. buildJsonHeader(header, suppliedHeader, rowTag);
  10410. else if (suppliedHeader)
  10411. header.set(suppliedHeader);
  10412. else
  10413. header.append(DEFAULTXMLHEADER).newline();
  10414. headerLength = header.length();
  10415. diskout->write(header.length(), header.str());
  10416. Owned<IXmlWriterExt> writer = createIXmlWriterExt(xmlHelper.getXmlFlags(), 0, NULL, (kind==TAKjsonwrite) ? WTJSON : WTStandard);
  10417. writer->outputBeginArray(rowTag); //need to set this
  10418. writer->clear(); //but not output it
  10419. loop
  10420. {
  10421. OwnedConstRoxieRow nextrec = inputStream->ungroupedNextRow();
  10422. if (!nextrec)
  10423. break;
  10424. processed++;
  10425. writer->clear().outputBeginNested(rowTag, false);
  10426. xmlHelper.toXML((const byte *)nextrec.get(), *writer);
  10427. writer->outputEndNested(rowTag);
  10428. diskout->write(writer->length(), writer->str());
  10429. }
  10430. OwnedRoxieString suppliedFooter(xmlHelper.getFooter());
  10431. StringBuffer footer;
  10432. if (kind==TAKjsonwrite)
  10433. buildJsonFooter(footer.newline(), suppliedFooter, rowTag);
  10434. else if (suppliedFooter)
  10435. footer.append(suppliedFooter);
  10436. else
  10437. footer.append(DEFAULTXMLFOOTER);
  10438. footerLength=footer.length();
  10439. diskout->write(footer.length(), footer);
  10440. }
  10441. virtual void reset()
  10442. {
  10443. CRoxieServerDiskWriteActivity::reset();
  10444. rowTag.clear();
  10445. }
  10446. virtual void setFileProperties(IFileDescriptor *desc) const
  10447. {
  10448. CRoxieServerDiskWriteActivity::setFileProperties(desc);
  10449. desc->queryProperties().setProp("@format","utf8n");
  10450. desc->queryProperties().setProp("@rowTag",rowTag.get());
  10451. desc->queryProperties().setProp("@kind", (kind==TAKjsonwrite) ? "json" : "xml");
  10452. desc->queryProperties().setPropInt(FPheaderLength, headerLength);
  10453. desc->queryProperties().setPropInt(FPfooterLength, footerLength);
  10454. }
  10455. virtual bool isOutputTransformed() const { return true; }
  10456. };
  10457. class CRoxieServerDiskWriteActivityFactory : public CRoxieServerMultiOutputFactory
  10458. {
  10459. bool isRoot;
  10460. bool isTemp;
  10461. public:
  10462. CRoxieServerDiskWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  10463. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  10464. {
  10465. Owned<IHThorDiskWriteArg> helper = (IHThorDiskWriteArg *) helperFactory();
  10466. isTemp = (helper->getFlags() & TDXtemporary) != 0;
  10467. setNumOutputs(helper->getTempUsageCount());
  10468. if (_kind!=TAKdiskwrite)
  10469. assertex(numOutputs == 0);
  10470. }
  10471. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  10472. {
  10473. switch (numOutputs)
  10474. {
  10475. case 0:
  10476. switch (kind)
  10477. {
  10478. case TAKdiskwrite: return new CRoxieServerDiskWriteActivity(_ctx, this, _probeManager);
  10479. case TAKcsvwrite: return new CRoxieServerCsvWriteActivity(_ctx, this, _probeManager);
  10480. case TAKxmlwrite:
  10481. case TAKjsonwrite:
  10482. return new CRoxieServerXmlWriteActivity(_ctx, this, _probeManager, kind);
  10483. };
  10484. throwUnexpected();
  10485. case 1:
  10486. return new CRoxieServerSpillWriteActivity(_ctx, this, _probeManager);
  10487. default:
  10488. return new CRoxieServerThroughSpillActivity(_ctx, this, _probeManager, numOutputs);
  10489. }
  10490. }
  10491. virtual bool isSink() const
  10492. {
  10493. return numOutputs == 0 && !isTemp; // MORE - check with Gavin if this is right if not a temp but reread in same job...
  10494. }
  10495. };
  10496. IRoxieServerActivityFactory *createRoxieServerDiskWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  10497. {
  10498. return new CRoxieServerDiskWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  10499. }
  10500. //=================================================================================
  10501. class CRoxieServerIndexWriteActivity : public CRoxieServerInternalSinkActivity, implements IRoxiePublishCallback
  10502. {
  10503. IHThorIndexWriteArg &helper;
  10504. bool overwrite;
  10505. Owned<ClusterWriteHandler> clusterHandler;
  10506. Owned<IRoxieWriteHandler> writer;
  10507. unsigned __int64 reccount;
  10508. unsigned int fileCrc;
  10509. StringBuffer filename;
  10510. void updateWorkUnitResult()
  10511. {
  10512. // MORE - a lot of this is common with hthor
  10513. WorkunitUpdate wu = ctx->updateWorkUnit();
  10514. if (wu)
  10515. {
  10516. OwnedRoxieString rawLogicalName = helper.getFileName();
  10517. StringBuffer lfn; // logical filename
  10518. expandLogicalFilename(lfn, rawLogicalName, wu, false, false);
  10519. if (lfn.length())
  10520. {
  10521. if (helper.getSequence() >= 0)
  10522. {
  10523. Owned<IWUResult> result = wu->updateResultBySequence(helper.getSequence());
  10524. if (result)
  10525. {
  10526. result->setResultTotalRowCount(reccount);
  10527. result->setResultStatus(ResultStatusCalculated);
  10528. result->setResultLogicalName(lfn.str());
  10529. }
  10530. }
  10531. if(clusterHandler)
  10532. clusterHandler->finish(writer->queryFile());
  10533. CTXLOG("Created roxie index file %s", lfn.str());
  10534. }
  10535. }
  10536. }
  10537. virtual void resolve()
  10538. {
  10539. StringArray clusters;
  10540. unsigned clusterIdx = 0;
  10541. while(true)
  10542. {
  10543. OwnedRoxieString cluster(helper.getCluster(clusterIdx));
  10544. if(!cluster)
  10545. break;
  10546. clusters.append(cluster);
  10547. clusterIdx++;
  10548. }
  10549. if (roxieName.length())
  10550. clusters.append(roxieName.str());
  10551. else
  10552. clusters.append(".");
  10553. OwnedRoxieString fname(helper.getFileName());
  10554. writer.setown(ctx->createLFN(fname, overwrite, false, clusters)); // MORE - if there's a workunit, use if for scope.
  10555. filename.set(writer->queryFile()->queryFilename());
  10556. if (writer->queryFile()->exists())
  10557. {
  10558. if (overwrite)
  10559. {
  10560. CTXLOG("Removing existing %s from DFS",filename.str());
  10561. writer->queryFile()->remove();
  10562. }
  10563. else
  10564. throw MakeStringException(99, "Cannot write index file %s, file already exists (missing OVERWRITE attribute?)", filename.str());
  10565. }
  10566. }
  10567. void buildUserMetadata(Owned<IPropertyTree> & metadata)
  10568. {
  10569. size32_t nameLen;
  10570. char * nameBuff;
  10571. size32_t valueLen;
  10572. char * valueBuff;
  10573. unsigned idx = 0;
  10574. while(helper.getIndexMeta(nameLen, nameBuff, valueLen, valueBuff, idx++))
  10575. {
  10576. StringBuffer name(nameLen, nameBuff);
  10577. StringBuffer value(valueLen, valueBuff);
  10578. if(*nameBuff == '_' && strcmp(name, "_nodeSize") != 0)
  10579. {
  10580. OwnedRoxieString fname(helper.getFileName());
  10581. throw MakeStringException(0, "Invalid name %s in user metadata for index %s (names beginning with underscore are reserved)", name.str(), fname.get());
  10582. }
  10583. if(!validateXMLTag(name.str()))
  10584. {
  10585. OwnedRoxieString fname(helper.getFileName());
  10586. throw MakeStringException(0, "Invalid name %s in user metadata for index %s (not legal XML element name)", name.str(), fname.get());
  10587. }
  10588. if(!metadata)
  10589. metadata.setown(createPTree("metadata"));
  10590. metadata->setProp(name.str(), value.str());
  10591. }
  10592. }
  10593. void buildLayoutMetadata(Owned<IPropertyTree> & metadata)
  10594. {
  10595. if(!metadata)
  10596. metadata.setown(createPTree("metadata"));
  10597. metadata->setProp("_record_ECL", helper.queryRecordECL());
  10598. void * layoutMetaBuff;
  10599. size32_t layoutMetaSize;
  10600. if(helper.getIndexLayout(layoutMetaSize, layoutMetaBuff))
  10601. {
  10602. metadata->setPropBin("_record_layout", layoutMetaSize, layoutMetaBuff);
  10603. rtlFree(layoutMetaBuff);
  10604. }
  10605. }
  10606. public:
  10607. CRoxieServerIndexWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  10608. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, 0), helper(static_cast<IHThorIndexWriteArg &>(basehelper))
  10609. {
  10610. overwrite = ((helper.getFlags() & TIWoverwrite) != 0);
  10611. reccount = 0;
  10612. fileCrc = 0;
  10613. }
  10614. ~CRoxieServerIndexWriteActivity()
  10615. {
  10616. }
  10617. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10618. {
  10619. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  10620. resolve();
  10621. }
  10622. virtual void onExecute()
  10623. {
  10624. bool isVariable = helper.queryDiskRecordSize()->isVariableSize();
  10625. size32_t maxDiskRecordSize;
  10626. if (isVariable)
  10627. {
  10628. if (helper.getFlags() & TIWmaxlength)
  10629. maxDiskRecordSize = helper.getMaxKeySize();
  10630. else
  10631. maxDiskRecordSize = KEYBUILD_MAXLENGTH; // Current default behaviour, could be improved in the future
  10632. }
  10633. else
  10634. maxDiskRecordSize = helper.queryDiskRecordSize()->getFixedSize();
  10635. if (maxDiskRecordSize > KEYBUILD_MAXLENGTH)
  10636. throw MakeStringException(99, "Index maximum record length (%d) exceeds 32k internal limit", maxDiskRecordSize);
  10637. OwnedMalloc<char> rowBuffer(maxDiskRecordSize, true);
  10638. fileCrc = -1;
  10639. {
  10640. Owned<IFileIO> io;
  10641. try
  10642. {
  10643. io.setown(writer->queryFile()->open(IFOcreate));
  10644. }
  10645. catch(IException * e)
  10646. {
  10647. e->Release();
  10648. clearKeyStoreCache(false);
  10649. io.setown(writer->queryFile()->open(IFOcreate));
  10650. }
  10651. if(!io)
  10652. throw MakeStringException(errno, "Failed to create file %s for writing", filename.str());
  10653. Owned<IFileIOStream> out = createIOStream(io);
  10654. unsigned flags = COL_PREFIX | HTREE_FULLSORT_KEY;
  10655. if (helper.getFlags() & TIWrowcompress)
  10656. flags |= HTREE_COMPRESSED_KEY|HTREE_QUICK_COMPRESSED_KEY;
  10657. else if (!(helper.getFlags() & TIWnolzwcompress))
  10658. flags |= HTREE_COMPRESSED_KEY;
  10659. if (isVariable)
  10660. flags |= HTREE_VARSIZE;
  10661. Owned<IPropertyTree> metadata;
  10662. buildUserMetadata(metadata);
  10663. buildLayoutMetadata(metadata);
  10664. unsigned nodeSize = metadata ? metadata->getPropInt("_nodeSize", NODESIZE) : NODESIZE;
  10665. Owned<IKeyBuilder> builder = createKeyBuilder(out, flags, maxDiskRecordSize, nodeSize, helper.getKeyedSize(), 0);
  10666. class BcWrapper : implements IBlobCreator
  10667. {
  10668. IKeyBuilder *builder;
  10669. public:
  10670. BcWrapper(IKeyBuilder *_builder) : builder(_builder) {}
  10671. virtual unsigned __int64 createBlob(size32_t size, const void * ptr)
  10672. {
  10673. return builder->createBlob(size, (const char *) ptr);
  10674. }
  10675. } bc(builder);
  10676. // Loop thru the results
  10677. loop
  10678. {
  10679. OwnedConstRoxieRow nextrec(inputStream->ungroupedNextRow());
  10680. if (!nextrec)
  10681. break;
  10682. try
  10683. {
  10684. unsigned __int64 fpos=0;
  10685. RtlStaticRowBuilder rowBuilder(rowBuffer, maxDiskRecordSize);
  10686. size32_t thisSize = helper.transform(rowBuilder, nextrec, &bc, fpos);
  10687. builder->processKeyData(rowBuffer, fpos, thisSize);
  10688. }
  10689. catch(IException * e)
  10690. {
  10691. throw makeWrappedException(e);
  10692. }
  10693. reccount++;
  10694. }
  10695. if(metadata)
  10696. builder->finish(metadata,&fileCrc);
  10697. else
  10698. builder->finish(&fileCrc);
  10699. }
  10700. }
  10701. virtual void stop()
  10702. {
  10703. if (writer)
  10704. {
  10705. if (!aborted)
  10706. updateWorkUnitResult();
  10707. writer->finish(!aborted, this);
  10708. writer.clear();
  10709. }
  10710. CRoxieServerActivity::stop();
  10711. }
  10712. virtual void reset()
  10713. {
  10714. CRoxieServerActivity::reset();
  10715. writer.clear();
  10716. }
  10717. //interface IRoxiePublishCallback
  10718. virtual void setFileProperties(IFileDescriptor *desc) const
  10719. {
  10720. IPropertyTree &partProps = desc->queryPart(0)->queryProperties(); //properties of the first file part.
  10721. IPropertyTree &fileProps = desc->queryProperties(); // properties of the logical file
  10722. // Now publish to name services
  10723. StringBuffer dir,base;
  10724. offset_t indexFileSize = writer->queryFile()->size();
  10725. if(clusterHandler)
  10726. clusterHandler->splitPhysicalFilename(dir, base);
  10727. else
  10728. splitFilename(filename.str(), &dir, &dir, &base, &base);
  10729. desc->setDefaultDir(dir.str());
  10730. //properties of the first file part.
  10731. Owned<IPropertyTree> attrs;
  10732. if(clusterHandler)
  10733. attrs.setown(createPTree("Part")); // clusterHandler is going to set attributes
  10734. else
  10735. {
  10736. // add cluster
  10737. StringBuffer mygroupname;
  10738. desc->setNumParts(1);
  10739. desc->setPartMask(base.str());
  10740. attrs.set(&desc->queryPart(0)->queryProperties());
  10741. }
  10742. attrs->setPropInt64("@size", indexFileSize);
  10743. CDateTime createTime, modifiedTime, accessedTime;
  10744. writer->queryFile()->getTime(&createTime, &modifiedTime, &accessedTime);
  10745. // round file time down to nearest sec. Nanosec accurancy is not preserved elsewhere and can lead to mismatch later.
  10746. unsigned hour, min, sec, nanosec;
  10747. modifiedTime.getTime(hour, min, sec, nanosec);
  10748. modifiedTime.setTime(hour, min, sec, 0);
  10749. StringBuffer timestr;
  10750. modifiedTime.getString(timestr);
  10751. if(timestr.length())
  10752. attrs->setProp("@modified", timestr.str());
  10753. if(clusterHandler)
  10754. clusterHandler->setDescriptorParts(desc, base.str(), attrs);
  10755. // properties of the logical file
  10756. IPropertyTree & properties = desc->queryProperties();
  10757. properties.setProp("@kind", "key");
  10758. properties.setPropInt64("@size", indexFileSize);
  10759. properties.setPropInt64("@recordCount", reccount);
  10760. WorkunitUpdate workUnit = ctx->updateWorkUnit();
  10761. if (workUnit)
  10762. {
  10763. properties.setProp("@owner", workUnit->queryUser());
  10764. properties.setProp("@workunit", workUnit->queryWuid());
  10765. properties.setProp("@job", workUnit->queryJobName());
  10766. }
  10767. char const * rececl = helper.queryRecordECL();
  10768. if(rececl && *rececl)
  10769. properties.setProp("ECL", rececl);
  10770. if (helper.getFlags() & TIWexpires)
  10771. setExpiryTime(properties, helper.getExpiryDays());
  10772. if (helper.getFlags() & TIWupdate)
  10773. {
  10774. unsigned eclCRC;
  10775. unsigned __int64 totalCRC;
  10776. helper.getUpdateCRCs(eclCRC, totalCRC);
  10777. properties.setPropInt("@eclCRC", eclCRC);
  10778. properties.setPropInt64("@totalCRC", totalCRC);
  10779. }
  10780. properties.setPropInt("@fileCrc", fileCrc);
  10781. properties.setPropInt("@formatCrc", helper.getFormatCrc());
  10782. void * layoutMetaBuff;
  10783. size32_t layoutMetaSize;
  10784. if(helper.getIndexLayout(layoutMetaSize, layoutMetaBuff))
  10785. {
  10786. properties.setPropBin("_record_layout", layoutMetaSize, layoutMetaBuff);
  10787. rtlFree(layoutMetaBuff);
  10788. }
  10789. }
  10790. IUserDescriptor *queryUserDescriptor() const
  10791. {
  10792. IConstWorkUnit *workUnit = ctx->queryWorkUnit();
  10793. if (workUnit)
  10794. return workUnit->queryUserDescriptor();
  10795. else
  10796. return NULL;
  10797. }
  10798. };
  10799. //=================================================================================
  10800. class CRoxieServerIndexWriteActivityFactory : public CRoxieServerMultiOutputFactory
  10801. {
  10802. public:
  10803. CRoxieServerIndexWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  10804. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  10805. {
  10806. setNumOutputs(0);
  10807. }
  10808. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  10809. {
  10810. return new CRoxieServerIndexWriteActivity(_ctx, this, _probeManager);
  10811. }
  10812. virtual bool isSink() const
  10813. {
  10814. return true;
  10815. }
  10816. };
  10817. IRoxieServerActivityFactory *createRoxieServerIndexWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  10818. {
  10819. return new CRoxieServerIndexWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  10820. }
  10821. //=================================================================================
  10822. static inline void getLimitType(unsigned flags, bool & limitFail, bool & limitOnFail)
  10823. {
  10824. if((flags & JFmatchAbortLimitSkips) != 0)
  10825. {
  10826. limitFail = false;
  10827. limitOnFail = false;
  10828. }
  10829. else
  10830. {
  10831. limitOnFail = ((flags & JFonfail) != 0);
  10832. limitFail = !limitOnFail;
  10833. }
  10834. }
  10835. class CRoxieServerJoinActivity : public CRoxieServerTwoInputActivity
  10836. {
  10837. enum { JSfill, JSfillleft, JSfillright, JScollate, JScompare, JSleftonly, JSrightonly } state;
  10838. IHThorJoinArg &helper;
  10839. ICompare * collate;
  10840. ICompare * collateupper;
  10841. ThorActivityKind activityKind;
  10842. bool leftOuterJoin;
  10843. bool rightOuterJoin;
  10844. bool exclude;
  10845. bool limitFail;
  10846. bool limitOnFail;
  10847. bool forceSpill;
  10848. unsigned keepLimit;
  10849. unsigned joinLimit;
  10850. unsigned atmostLimit;
  10851. unsigned abortLimit;
  10852. unsigned atmostsTriggered;
  10853. bool betweenjoin;
  10854. OwnedRowArray right;
  10855. const void * left;
  10856. const void * pendingRight;
  10857. unsigned rightIndex;
  10858. unsigned joinCounter;
  10859. BoolArray matchedRight;
  10860. bool matchedLeft;
  10861. Owned<IException> failingLimit;
  10862. ConstPointerArray filteredRight;
  10863. Owned<IRHLimitedCompareHelper> limitedhelper;
  10864. OwnedConstRoxieRow defaultLeft;
  10865. OwnedConstRoxieRow defaultRight;
  10866. Owned<IEngineRowAllocator> defaultLeftAllocator;
  10867. Owned<IEngineRowAllocator> defaultRightAllocator;
  10868. Owned<IGroupedInput> sortedLeft;
  10869. Owned<IGroupedInput> groupedSortedRight;
  10870. bool cloneLeft;
  10871. void createDefaultLeft()
  10872. {
  10873. if (!defaultLeft)
  10874. {
  10875. if (!defaultLeftAllocator)
  10876. defaultLeftAllocator.setown(ctx->queryCodeContext()->getRowAllocator(input->queryOutputMeta(), activityId));
  10877. RtlDynamicRowBuilder rowBuilder(defaultLeftAllocator);
  10878. size32_t thisSize = helper.createDefaultLeft(rowBuilder);
  10879. defaultLeft.setown(rowBuilder.finalizeRowClear(thisSize));
  10880. }
  10881. }
  10882. void createDefaultRight()
  10883. {
  10884. if (!defaultRight)
  10885. {
  10886. if (!defaultRightAllocator)
  10887. defaultRightAllocator.setown(ctx->queryCodeContext()->getRowAllocator(input1->queryOutputMeta(), activityId));
  10888. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  10889. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  10890. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  10891. }
  10892. }
  10893. public:
  10894. CRoxieServerJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _forceSpill)
  10895. : CRoxieServerTwoInputActivity(_ctx, _factory, _probeManager), helper((IHThorJoinArg &)basehelper), forceSpill(_forceSpill)
  10896. {
  10897. // MORE - some of this should be done in factory
  10898. unsigned joinFlags = helper.getJoinFlags();
  10899. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  10900. rightOuterJoin = (joinFlags & JFrightouter) != 0;
  10901. exclude = (joinFlags & JFexclude) != 0;
  10902. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  10903. getLimitType(joinFlags, limitFail, limitOnFail);
  10904. if (joinFlags & JFslidingmatch)
  10905. {
  10906. betweenjoin = true;
  10907. collate = helper.queryCompareLeftRightLower();
  10908. collateupper = helper.queryCompareLeftRightUpper();
  10909. }
  10910. else
  10911. {
  10912. betweenjoin = false;
  10913. collate = collateupper = helper.queryCompareLeftRight();
  10914. }
  10915. rightIndex = 0;
  10916. joinCounter = 0;
  10917. state = JSfill;
  10918. matchedLeft = false;
  10919. joinLimit = 0;
  10920. keepLimit = 0; // wait until ctx available
  10921. atmostLimit = 0; // wait until ctx available
  10922. abortLimit = 0; // wait until ctx available
  10923. atmostsTriggered = 0;
  10924. assertex((joinFlags & (JFfirst | JFfirstleft | JFfirstright)) == 0);
  10925. left = NULL;
  10926. pendingRight = NULL;
  10927. activityKind = _factory->getKind();
  10928. }
  10929. virtual bool needsAllocator() const { return true; }
  10930. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10931. {
  10932. left = NULL;
  10933. rightIndex = 0;
  10934. joinCounter = 0;
  10935. state = JSfill;
  10936. matchedLeft = false;
  10937. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  10938. keepLimit = helper.getKeepLimit();
  10939. if (keepLimit == 0)
  10940. keepLimit = (unsigned)-1;
  10941. atmostsTriggered = 0;
  10942. atmostLimit = helper.getJoinLimit();
  10943. if(atmostLimit == 0)
  10944. atmostLimit = (unsigned)-1;
  10945. else
  10946. assertex(!rightOuterJoin && !betweenjoin);
  10947. abortLimit = helper.getMatchAbortLimit();
  10948. if (abortLimit == 0)
  10949. abortLimit = (unsigned)-1;
  10950. if (rightOuterJoin)
  10951. createDefaultLeft();
  10952. if ((leftOuterJoin && (activityKind==TAKjoin || activityKind==TAKjoinlight || activityKind==TAKdenormalizegroup)) || limitOnFail)
  10953. createDefaultRight();
  10954. bool isStable = (helper.getJoinFlags() & JFunstable) == 0;
  10955. RoxieSortAlgorithm sortAlgorithm;
  10956. if (forceSpill)
  10957. sortAlgorithm = isStable ? stableSpillingQuickSortAlgorithm : spillingQuickSortAlgorithm;
  10958. else
  10959. sortAlgorithm = isStable ? stableQuickSortAlgorithm : quickSortAlgorithm;
  10960. if (helper.isLeftAlreadySorted())
  10961. sortedLeft.setown(createDegroupedInputReader(inputStream));
  10962. else
  10963. sortedLeft.setown(createSortedInputReader(inputStream, createSortAlgorithm(sortAlgorithm, helper.queryCompareLeft(), ctx->queryRowManager(), input->queryOutputMeta(), ctx->queryCodeContext(), tempDirectory, activityId)));
  10964. ICompare *compareRight = helper.queryCompareRight();
  10965. if (helper.isRightAlreadySorted())
  10966. groupedSortedRight.setown(createGroupedInputReader(inputStream1, compareRight));
  10967. else
  10968. groupedSortedRight.setown(createSortedGroupedInputReader(inputStream1, compareRight, createSortAlgorithm(sortAlgorithm, compareRight, ctx->queryRowManager(), input1->queryOutputMeta(), ctx->queryCodeContext(), tempDirectory, activityId)));
  10969. if ((helper.getJoinFlags() & JFlimitedprefixjoin) && helper.getJoinLimit())
  10970. { //limited match join (s[1..n])
  10971. limitedhelper.setown(createRHLimitedCompareHelper());
  10972. limitedhelper->init( helper.getJoinLimit(), groupedSortedRight, collate, helper.queryPrefixCompare() );
  10973. }
  10974. }
  10975. virtual void reset()
  10976. {
  10977. if (atmostsTriggered)
  10978. noteStatistic(StNumAtmostTriggered, atmostsTriggered);
  10979. right.clear();
  10980. ReleaseClearRoxieRow(left);
  10981. ReleaseClearRoxieRow(pendingRight);
  10982. defaultRight.clear();
  10983. defaultLeft.clear();
  10984. sortedLeft.clear();
  10985. groupedSortedRight.clear();
  10986. CRoxieServerTwoInputActivity::reset();
  10987. }
  10988. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  10989. {
  10990. if (!idx && (helper.getJoinFlags() & JFparallel) != 0)
  10991. {
  10992. puller.setown(new CRoxieServerReadAheadInput(ctx, ctx->queryOptions().parallelJoinPreload));
  10993. puller->setInput(0, _sourceIdx, _in);
  10994. _in = puller;
  10995. _sourceIdx = 0;
  10996. }
  10997. CRoxieServerTwoInputActivity::setInput(idx, _sourceIdx, _in);
  10998. }
  10999. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  11000. {
  11001. if (idx==(unsigned)-1)
  11002. idx = 0;
  11003. return idx ? NULL : this;
  11004. }
  11005. void fillLeft()
  11006. {
  11007. matchedLeft = false;
  11008. left = sortedLeft->nextRow(); // NOTE: already degrouped by the IGroupedInput we attached
  11009. if (betweenjoin && left && pendingRight && (collate->docompare(left, pendingRight) >= 0))
  11010. fillRight();
  11011. if (limitedhelper && 0==rightIndex)
  11012. {
  11013. rightIndex = 0;
  11014. joinCounter = 0;
  11015. right.clear();
  11016. matchedRight.kill();
  11017. if (left)
  11018. {
  11019. limitedhelper->getGroup(right,left);
  11020. ForEachItemIn(idx, right)
  11021. matchedRight.append(false);
  11022. }
  11023. }
  11024. }
  11025. void fillRight()
  11026. {
  11027. if (limitedhelper)
  11028. return;
  11029. failingLimit.clear();
  11030. if(betweenjoin && left)
  11031. {
  11032. aindex_t start = 0;
  11033. while(right.isItem(start) && (collateupper->docompare(left, right.item(start)) > 0))
  11034. start++;
  11035. if(start>0)
  11036. right.clearPart(0, start);
  11037. }
  11038. else
  11039. right.clear();
  11040. rightIndex = 0;
  11041. joinCounter = 0;
  11042. unsigned groupCount = 0;
  11043. const void * next;
  11044. while(true)
  11045. {
  11046. if(pendingRight)
  11047. {
  11048. next = pendingRight;
  11049. pendingRight = NULL;
  11050. }
  11051. else
  11052. {
  11053. next = groupedSortedRight->nextRow();
  11054. }
  11055. if(!rightOuterJoin && next && (!left || (collateupper->docompare(left, next) > 0))) // if right is less than left, and not right outer, can skip group
  11056. {
  11057. while(next)
  11058. {
  11059. ReleaseClearRoxieRow(next);
  11060. next = groupedSortedRight->nextRow();
  11061. }
  11062. continue;
  11063. }
  11064. while(next)
  11065. {
  11066. if(groupCount==abortLimit)
  11067. {
  11068. if(limitFail)
  11069. failLimit();
  11070. if (ctx->queryDebugContext())
  11071. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  11072. if(limitOnFail)
  11073. {
  11074. assertex(!failingLimit);
  11075. try
  11076. {
  11077. failLimit();
  11078. }
  11079. catch(IException * except)
  11080. {
  11081. failingLimit.setown(except);
  11082. }
  11083. assertex(failingLimit != NULL);
  11084. }
  11085. right.append(next);
  11086. do
  11087. {
  11088. next = groupedSortedRight->nextRow();
  11089. ReleaseRoxieRow(next);
  11090. } while(next);
  11091. break;
  11092. }
  11093. else if(groupCount==atmostLimit)
  11094. {
  11095. atmostsTriggered++;
  11096. right.clear();
  11097. groupCount = 0;
  11098. while(next)
  11099. {
  11100. ReleaseRoxieRow(next);
  11101. next = groupedSortedRight->nextRow();
  11102. }
  11103. }
  11104. else
  11105. {
  11106. right.append(next);
  11107. groupCount++;
  11108. }
  11109. next = groupedSortedRight->nextRow();
  11110. }
  11111. // 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
  11112. if(betweenjoin && left)
  11113. {
  11114. pendingRight = groupedSortedRight->nextRow();
  11115. if(!pendingRight || (collate->docompare(left, pendingRight) < 0))
  11116. break;
  11117. }
  11118. else
  11119. break;
  11120. }
  11121. matchedRight.kill();
  11122. ForEachItemIn(idx, right)
  11123. matchedRight.append(false);
  11124. }
  11125. const void * joinRecords(const void * curLeft, const void * curRight, unsigned counter)
  11126. {
  11127. if (cloneLeft)
  11128. {
  11129. LinkRoxieRow(curLeft);
  11130. return curLeft;
  11131. }
  11132. try
  11133. {
  11134. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11135. size32_t thisSize = helper.transform(rowBuilder, curLeft, curRight, counter);
  11136. if (thisSize)
  11137. return rowBuilder.finalizeRowClear(thisSize);
  11138. else
  11139. return NULL;
  11140. }
  11141. catch (IException *E)
  11142. {
  11143. throw makeWrappedException(E);
  11144. }
  11145. }
  11146. const void * denormalizeRecords(const void * curLeft, ConstPointerArray & rows)
  11147. {
  11148. try
  11149. {
  11150. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11151. unsigned numRows = rows.ordinality();
  11152. const void * right = numRows ? rows.item(0) : defaultRight.get();
  11153. size32_t thisSize = helper.transform(rowBuilder, curLeft, right, numRows, (const void * *)rows.getArray());
  11154. if (thisSize)
  11155. return rowBuilder.finalizeRowClear(thisSize);
  11156. else
  11157. return NULL;
  11158. }
  11159. catch (IException *E)
  11160. {
  11161. throw makeWrappedException(E);
  11162. }
  11163. }
  11164. const void * joinException(const void * curLeft, IException * except)
  11165. {
  11166. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11167. size32_t thisSize = helper.onFailTransform(rowBuilder, curLeft, defaultRight, except);
  11168. return rowBuilder.finalizeRowClear(thisSize);
  11169. }
  11170. void failLimit()
  11171. {
  11172. helper.onMatchAbortLimitExceeded();
  11173. CommonXmlWriter xmlwrite(0);
  11174. if (input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  11175. {
  11176. input->queryOutputMeta()->toXML((byte *) left, xmlwrite);
  11177. }
  11178. throw MakeStringException(ROXIE_TOO_MANY_RESULTS, "More than %d match candidates in join %d for row %s", abortLimit, queryId(), xmlwrite.str());
  11179. }
  11180. virtual const void * nextRow()
  11181. {
  11182. ActivityTimer t(totalCycles, timeActivities);
  11183. loop
  11184. {
  11185. switch (state)
  11186. {
  11187. case JSfill:
  11188. fillLeft();
  11189. state = JSfillright;
  11190. break;
  11191. case JSfillright:
  11192. fillRight();
  11193. state = JScollate;
  11194. break;
  11195. case JSfillleft:
  11196. fillLeft();
  11197. state = JScollate;
  11198. break;
  11199. case JScollate:
  11200. if (right.ordinality() == 0)
  11201. {
  11202. if (left == NULL)
  11203. return NULL;
  11204. state = JSleftonly;
  11205. }
  11206. else
  11207. {
  11208. if (!left)
  11209. state = JSrightonly;
  11210. else
  11211. {
  11212. int diff;
  11213. if(betweenjoin)
  11214. diff = ((collate->docompare(left, right.item(0)) < 0) ? -1 : ((collateupper->docompare(left, right.item(right.ordinality()-1)) > 0) ? +1 : 0));
  11215. else
  11216. diff = collate->docompare(left, right.item(0));
  11217. bool limitExceeded = right.ordinality()>abortLimit;
  11218. if (diff == 0)
  11219. {
  11220. if (limitExceeded)
  11221. {
  11222. const void * ret = NULL;
  11223. if(failingLimit)
  11224. ret = joinException(left, failingLimit);
  11225. ReleaseRoxieRow(left);
  11226. left = NULL;
  11227. state = JSfillleft;
  11228. ForEachItemIn(idx, right)
  11229. matchedRight.replace(true, idx);
  11230. if(ret)
  11231. {
  11232. processed++;
  11233. return ret;
  11234. }
  11235. }
  11236. else
  11237. {
  11238. state = JScompare;
  11239. joinLimit = keepLimit;
  11240. }
  11241. }
  11242. else if (diff < 0)
  11243. state = JSleftonly;
  11244. else if (limitExceeded)
  11245. {
  11246. // MORE - Roxie code seems to think there should be a destroyRowset(right) here....
  11247. state = JSfillright;
  11248. }
  11249. else
  11250. state = JSrightonly;
  11251. }
  11252. }
  11253. break;
  11254. case JSrightonly:
  11255. if (rightOuterJoin)
  11256. {
  11257. switch (activityKind)
  11258. {
  11259. case TAKjoin:
  11260. {
  11261. while (right.isItem(rightIndex))
  11262. {
  11263. if (!matchedRight.item(rightIndex))
  11264. {
  11265. const void * rhs = right.item(rightIndex++);
  11266. const void *ret = joinRecords(defaultLeft, rhs, 0);
  11267. if (ret)
  11268. {
  11269. processed++;
  11270. return ret;
  11271. }
  11272. }
  11273. else
  11274. rightIndex++;
  11275. }
  11276. break;
  11277. }
  11278. //Probably excessive to implement the following, but possibly useful
  11279. case TAKdenormalize:
  11280. {
  11281. OwnedConstRoxieRow newLeft;
  11282. newLeft.set(defaultLeft);
  11283. unsigned rowSize = 0;
  11284. unsigned leftCount = 0;
  11285. while (right.isItem(rightIndex))
  11286. {
  11287. if (!matchedRight.item(rightIndex))
  11288. {
  11289. const void * rhs = right.item(rightIndex);
  11290. try
  11291. {
  11292. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11293. unsigned thisSize = helper.transform(rowBuilder, newLeft, rhs, ++leftCount);
  11294. if (thisSize)
  11295. {
  11296. rowSize = thisSize;
  11297. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  11298. }
  11299. }
  11300. catch (IException *E)
  11301. {
  11302. throw makeWrappedException(E);
  11303. }
  11304. }
  11305. rightIndex++;
  11306. }
  11307. state = JSfillright;
  11308. if (rowSize)
  11309. {
  11310. processed++;
  11311. return newLeft.getClear();
  11312. }
  11313. break;
  11314. }
  11315. case TAKdenormalizegroup:
  11316. {
  11317. filteredRight.kill();
  11318. while (right.isItem(rightIndex))
  11319. {
  11320. if (!matchedRight.item(rightIndex))
  11321. filteredRight.append(right.item(rightIndex));
  11322. rightIndex++;
  11323. }
  11324. state = JSfillright;
  11325. if (filteredRight.ordinality())
  11326. {
  11327. const void * ret = denormalizeRecords(defaultLeft, filteredRight);
  11328. filteredRight.kill();
  11329. if (ret)
  11330. {
  11331. processed++;
  11332. return ret;
  11333. }
  11334. }
  11335. break;
  11336. }
  11337. }
  11338. }
  11339. state = JSfillright;
  11340. break;
  11341. case JSleftonly:
  11342. {
  11343. const void * ret = NULL;
  11344. if (!matchedLeft && leftOuterJoin)
  11345. {
  11346. switch (activityKind)
  11347. {
  11348. case TAKjoin:
  11349. ret = joinRecords(left, defaultRight, 0);
  11350. break;
  11351. case TAKdenormalize:
  11352. ret = left;
  11353. left = NULL;
  11354. break;
  11355. case TAKdenormalizegroup:
  11356. filteredRight.kill();
  11357. ret = denormalizeRecords(left, filteredRight);
  11358. break;
  11359. }
  11360. }
  11361. ReleaseRoxieRow(left);
  11362. left = NULL;
  11363. state = JSfillleft;
  11364. if (ret)
  11365. {
  11366. processed++;
  11367. return ret;
  11368. }
  11369. break;
  11370. }
  11371. case JScompare:
  11372. if (joinLimit != 0)
  11373. {
  11374. switch (activityKind)
  11375. {
  11376. case TAKjoin:
  11377. {
  11378. while (right.isItem(rightIndex))
  11379. {
  11380. const void * rhs = right.item(rightIndex++);
  11381. if (helper.match(left, rhs))
  11382. {
  11383. matchedRight.replace(true, rightIndex-1);
  11384. matchedLeft = true;
  11385. if (!exclude)
  11386. {
  11387. const void *ret = joinRecords(left, rhs, ++joinCounter);
  11388. if (ret)
  11389. {
  11390. processed++;
  11391. joinLimit--;
  11392. return ret;
  11393. }
  11394. }
  11395. }
  11396. }
  11397. break;
  11398. }
  11399. case TAKdenormalize:
  11400. {
  11401. OwnedConstRoxieRow newLeft;
  11402. newLeft.set(left);
  11403. unsigned rowSize = 0;
  11404. unsigned leftCount = 0;
  11405. while (right.isItem(rightIndex) && joinLimit)
  11406. {
  11407. try
  11408. {
  11409. const void * rhs = right.item(rightIndex++);
  11410. if (helper.match(left, rhs))
  11411. {
  11412. matchedRight.replace(true, rightIndex-1);
  11413. matchedLeft = true;
  11414. if (!exclude)
  11415. {
  11416. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11417. unsigned thisSize = helper.transform(rowBuilder, newLeft, rhs, ++leftCount);
  11418. if (thisSize)
  11419. {
  11420. rowSize = thisSize;
  11421. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  11422. joinLimit--;
  11423. }
  11424. }
  11425. }
  11426. }
  11427. catch (IException *E)
  11428. {
  11429. throw makeWrappedException(E);
  11430. }
  11431. }
  11432. state = JSleftonly;
  11433. rightIndex = 0;
  11434. if (rowSize)
  11435. {
  11436. processed++;
  11437. return newLeft.getClear();
  11438. }
  11439. break;
  11440. }
  11441. case TAKdenormalizegroup:
  11442. {
  11443. filteredRight.kill();
  11444. while (right.isItem(rightIndex))
  11445. {
  11446. const void * rhs = right.item(rightIndex++);
  11447. if (helper.match(left, rhs))
  11448. {
  11449. matchedRight.replace(true, rightIndex-1);
  11450. filteredRight.append(rhs);
  11451. matchedLeft = true;
  11452. if (filteredRight.ordinality()==joinLimit)
  11453. break;
  11454. }
  11455. }
  11456. state = JSleftonly;
  11457. rightIndex = 0;
  11458. if (!exclude && filteredRight.ordinality())
  11459. {
  11460. const void * ret = denormalizeRecords(left, filteredRight);
  11461. filteredRight.kill();
  11462. if (ret)
  11463. {
  11464. processed++;
  11465. return ret;
  11466. }
  11467. }
  11468. break;
  11469. }
  11470. }
  11471. }
  11472. state = JSleftonly;
  11473. rightIndex = 0;
  11474. joinCounter = 0;
  11475. break;
  11476. }
  11477. }
  11478. }
  11479. };
  11480. class CRoxieServerJoinActivityFactory : public CRoxieServerActivityFactory
  11481. {
  11482. unsigned input2;
  11483. unsigned input2idx;
  11484. bool forceSpill;
  11485. public:
  11486. CRoxieServerJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  11487. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  11488. {
  11489. forceSpill = _graphNode.getPropBool("hint[@name='spill']/@value", _queryFactory.queryOptions().allSortsMaySpill);
  11490. input2 = 0;
  11491. input2idx = 0;
  11492. }
  11493. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  11494. {
  11495. return new CRoxieServerJoinActivity(_ctx, this, _probeManager, forceSpill);
  11496. }
  11497. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  11498. {
  11499. if (idx==1)
  11500. {
  11501. input2 = source;
  11502. input2idx = sourceidx;
  11503. }
  11504. else
  11505. CRoxieServerActivityFactory::setInput(idx, source, sourceidx);
  11506. }
  11507. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  11508. {
  11509. switch (idx)
  11510. {
  11511. case 1:
  11512. sourceidx = input2idx;
  11513. return input2;
  11514. case 0:
  11515. return CRoxieServerActivityFactory::getInput(idx, sourceidx);
  11516. default:
  11517. return (unsigned) -1;
  11518. }
  11519. }
  11520. virtual unsigned numInputs() const { return 2; }
  11521. virtual const StatisticsMapping &queryStatsMapping() const
  11522. {
  11523. return joinStatistics;
  11524. }
  11525. };
  11526. IRoxieServerActivityFactory *createRoxieServerJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  11527. {
  11528. return new CRoxieServerJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  11529. }
  11530. //=================================================================================
  11531. #define CONCAT_READAHEAD 1000
  11532. class CRoxieThreadedConcatReader : public CInterface, implements IRecordPullerCallback
  11533. {
  11534. public:
  11535. IMPLEMENT_IINTERFACE;
  11536. CRoxieThreadedConcatReader(InterruptableSemaphore &_ready, bool _grouped)
  11537. : puller(false), grouped(_grouped), atEog(true), ready(_ready), eof(false)
  11538. {
  11539. }
  11540. void start(unsigned parentExtractSize, const byte *parentExtract, bool paused, IRoxieSlaveContext *ctx)
  11541. {
  11542. space.reinit(CONCAT_READAHEAD);
  11543. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().concatPreload, false, ctx);
  11544. }
  11545. void stop()
  11546. {
  11547. space.interrupt();
  11548. puller.stop();
  11549. }
  11550. IFinalRoxieInput *queryInput() const
  11551. {
  11552. return puller.queryInput();
  11553. }
  11554. void reset()
  11555. {
  11556. puller.reset();
  11557. ForEachItemIn(idx, buffer)
  11558. ReleaseRoxieRow(buffer.item(idx));
  11559. buffer.clear();
  11560. eof = false;
  11561. atEog = true;
  11562. }
  11563. void setInput(unsigned _sourceIdx, IFinalRoxieInput *_in)
  11564. {
  11565. puller.setInput(this, _sourceIdx, _in);
  11566. }
  11567. void connectInputStreams(IRoxieSlaveContext *ctx, bool consumerOrdered)
  11568. {
  11569. puller.connectInputStreams(ctx, consumerOrdered);
  11570. }
  11571. virtual void processRow(const void *row)
  11572. {
  11573. buffer.enqueue(row);
  11574. ready.signal();
  11575. space.wait();
  11576. }
  11577. virtual void processGroup(const ConstPointerArray &rows)
  11578. {
  11579. // We use record-by-record input mode of the puller thread even in grouped mode.
  11580. throwUnexpected();
  11581. }
  11582. virtual void processEOG()
  11583. {
  11584. if (grouped)
  11585. processRow(NULL);
  11586. }
  11587. virtual void processDone()
  11588. {
  11589. processRow(NULL);
  11590. }
  11591. virtual bool fireException(IException *e)
  11592. {
  11593. // called from puller thread on failure
  11594. ready.interrupt(LINK(e));
  11595. space.interrupt(e);
  11596. return true;
  11597. }
  11598. bool peek(const void * &row, bool &anyActive)
  11599. {
  11600. if (!eof)
  11601. {
  11602. if (buffer.ordinality())
  11603. {
  11604. space.signal();
  11605. row = buffer.dequeue();
  11606. if (row==NULL)
  11607. {
  11608. if (atEog)
  11609. {
  11610. eof = true;
  11611. return false;
  11612. }
  11613. else
  11614. atEog = true;
  11615. }
  11616. else if (grouped)
  11617. atEog = false;
  11618. return true;
  11619. }
  11620. anyActive = true;
  11621. }
  11622. return false;
  11623. }
  11624. protected:
  11625. RecordPullerThread puller;
  11626. InterruptableSemaphore space;
  11627. InterruptableSemaphore &ready;
  11628. SafeQueueOf<const void, true> buffer;
  11629. bool atEog;
  11630. bool eof;
  11631. bool grouped;
  11632. };
  11633. typedef CopyReferenceArrayOf<CRoxieThreadedConcatReader> ReaderArray;
  11634. class CRoxieServerThreadedConcatActivity : public CRoxieServerActivity
  11635. {
  11636. InterruptableSemaphore ready;
  11637. ReaderArray pullers;
  11638. unsigned numInputs;
  11639. unsigned nextPuller; // for round robin
  11640. unsigned readyPending;
  11641. bool eof;
  11642. bool inGroup;
  11643. bool grouped;
  11644. public:
  11645. CRoxieServerThreadedConcatActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _grouped, unsigned _numInputs)
  11646. : CRoxieServerActivity(_ctx, _factory, _probeManager), grouped(_grouped)
  11647. {
  11648. numInputs = _numInputs;
  11649. eof = (numInputs==0);
  11650. inGroup = false;
  11651. nextPuller = 0;
  11652. readyPending = 0;
  11653. for (unsigned i = 0; i < numInputs; i++)
  11654. pullers.append(*new CRoxieThreadedConcatReader(ready, _grouped));
  11655. }
  11656. ~CRoxieServerThreadedConcatActivity()
  11657. {
  11658. ForEachItemIn(idx, pullers)
  11659. delete &pullers.item(idx);
  11660. }
  11661. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11662. {
  11663. eof = (numInputs==0);
  11664. inGroup = false;
  11665. nextPuller = 0;
  11666. readyPending = 0;
  11667. ready.reinit();
  11668. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  11669. ForEachItemIn(idx, pullers)
  11670. {
  11671. pullers.item(idx).start(parentExtractSize, parentExtract, paused, ctx);
  11672. // NOTE - it is ok to start the thread running while parts of the subgraph are still being started, since everything
  11673. // in the part of the subgraph that the thread uses has been started.
  11674. // Note that splitters are supposed to cope with being used when only some outputs have been started.
  11675. }
  11676. }
  11677. virtual void stop()
  11678. {
  11679. ready.interrupt();
  11680. ForEachItemIn(idx, pullers)
  11681. pullers.item(idx).stop();
  11682. CRoxieServerActivity::stop();
  11683. }
  11684. virtual unsigned __int64 queryLocalCycles() const
  11685. {
  11686. return 0;
  11687. }
  11688. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  11689. {
  11690. if (pullers.isItem(idx))
  11691. return pullers.item(idx).queryInput();
  11692. else
  11693. return NULL;
  11694. }
  11695. virtual void reset()
  11696. {
  11697. CRoxieServerActivity::reset();
  11698. ForEachItemIn(idx, pullers)
  11699. pullers.item(idx).reset();
  11700. eof = false;
  11701. inGroup = false;
  11702. nextPuller = 0;
  11703. readyPending = 0;
  11704. }
  11705. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  11706. {
  11707. if (pullers.isItem(idx))
  11708. pullers.item(idx).setInput(_sourceIdx, _in);
  11709. else
  11710. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  11711. }
  11712. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  11713. {
  11714. ForEachItemIn(i, pullers)
  11715. pullers.item(i).connectInputStreams(ctx, consumerOrdered);
  11716. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, nullptr, consumerOrdered, nullptr); // No input actually connected
  11717. }
  11718. virtual const void * nextRow()
  11719. {
  11720. ActivityTimer t(totalCycles, timeActivities);
  11721. if (eof)
  11722. return NULL;
  11723. loop
  11724. {
  11725. if (readyPending && !inGroup)
  11726. {
  11727. if (readyPending > 1)
  11728. ready.signal(readyPending-1);
  11729. readyPending = 0;
  11730. }
  11731. else
  11732. ready.wait();
  11733. bool anyActive = false;
  11734. ForEachItemIn(unused_index, pullers)
  11735. {
  11736. // NOTE - we round robin not just because it's more efficient, but because it ensures the preservation of grouping information
  11737. const void *ret;
  11738. bool fetched = pullers.item(nextPuller).peek(ret, anyActive);
  11739. if (fetched)
  11740. {
  11741. inGroup = (ret != NULL);
  11742. return ret;
  11743. }
  11744. if (inGroup && grouped)
  11745. {
  11746. // Some other puller has data, but we can't consume it until the group we are reading is complete.
  11747. readyPending++;
  11748. anyActive = true;
  11749. break;
  11750. }
  11751. nextPuller++;
  11752. if (nextPuller==pullers.ordinality())
  11753. nextPuller = 0;
  11754. }
  11755. if (!anyActive)
  11756. break;
  11757. // A ready signal without anything being ready means someone reached end-of-file.
  11758. }
  11759. eof = true;
  11760. return NULL;
  11761. }
  11762. };
  11763. class CRoxieServerOrderedConcatActivity : public CRoxieServerMultiInputActivity
  11764. {
  11765. IEngineRowStream *curStream;
  11766. bool eogSeen;
  11767. bool anyThisGroup;
  11768. bool grouped;
  11769. unsigned streamIdx;
  11770. public:
  11771. CRoxieServerOrderedConcatActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _grouped, unsigned _numInputs)
  11772. : CRoxieServerMultiInputActivity(_ctx, _factory, _probeManager, _numInputs)
  11773. {
  11774. eogSeen = false;
  11775. anyThisGroup = false;
  11776. grouped = _grouped;
  11777. streamIdx = 0;
  11778. curStream = NULL;
  11779. }
  11780. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11781. {
  11782. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  11783. streamIdx = 0;
  11784. curStream = streamArray[streamIdx];
  11785. eogSeen = false;
  11786. anyThisGroup = false;
  11787. }
  11788. virtual const void * nextRow()
  11789. {
  11790. ActivityTimer t(totalCycles, timeActivities);
  11791. if (!curStream)
  11792. return NULL; // eof
  11793. const void * next = curStream->nextRow();
  11794. if (next)
  11795. {
  11796. anyThisGroup = true;
  11797. eogSeen = false;
  11798. processed++;
  11799. return next;
  11800. }
  11801. else if (!eogSeen)
  11802. {
  11803. eogSeen = true;
  11804. if (grouped)
  11805. {
  11806. if (anyThisGroup)
  11807. {
  11808. anyThisGroup = false;
  11809. return NULL;
  11810. }
  11811. else
  11812. return nextRow();
  11813. }
  11814. else
  11815. return nextRow();
  11816. }
  11817. else if (streamIdx < numStreams-1)
  11818. {
  11819. streamIdx++;
  11820. curStream = streamArray[streamIdx];
  11821. eogSeen = false;
  11822. return nextRow();
  11823. }
  11824. else
  11825. {
  11826. curStream = NULL;
  11827. return NULL;
  11828. }
  11829. }
  11830. };
  11831. class CRoxieServerConcatActivityFactory : public CRoxieServerMultiInputFactory
  11832. {
  11833. bool ordered;
  11834. bool grouped;
  11835. public:
  11836. CRoxieServerConcatActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  11837. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  11838. {
  11839. Owned <IHThorFunnelArg> helper = (IHThorFunnelArg *) helperFactory();
  11840. ordered = helper->isOrdered();
  11841. grouped = helper->queryOutputMeta()->isGrouped();
  11842. }
  11843. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  11844. {
  11845. if (ordered || (_probeManager && _probeManager->queryDebugManager()))
  11846. return new CRoxieServerOrderedConcatActivity(_ctx, this, _probeManager, grouped, numInputs());
  11847. else
  11848. return new CRoxieServerThreadedConcatActivity(_ctx, this, _probeManager, grouped, numInputs());
  11849. }
  11850. };
  11851. IRoxieServerActivityFactory *createRoxieServerConcatActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  11852. {
  11853. return new CRoxieServerConcatActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  11854. }
  11855. //=================================================================================
  11856. class CRoxieServerNonEmptyActivity : public CRoxieServerMultiInputBaseActivity
  11857. {
  11858. IEngineRowStream* selectedStream;
  11859. unsigned savedParentExtractSize;
  11860. const byte * savedParentExtract;
  11861. bool foundInput;
  11862. public:
  11863. CRoxieServerNonEmptyActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  11864. : CRoxieServerMultiInputBaseActivity(_ctx, _factory, _probeManager, _numInputs)
  11865. {
  11866. foundInput = false;
  11867. selectedStream = NULL;
  11868. savedParentExtractSize = 0;;
  11869. savedParentExtract = NULL;
  11870. }
  11871. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11872. {
  11873. //Don't start the inputs yet so we can short-circuit...
  11874. CRoxieServerMultiInputBaseActivity::start(parentExtractSize, parentExtract, paused);
  11875. savedParentExtractSize = parentExtractSize;
  11876. savedParentExtract = parentExtract;
  11877. }
  11878. virtual void stop()
  11879. {
  11880. if (foundInput)
  11881. {
  11882. if (selectedStream)
  11883. selectedStream->stop();
  11884. }
  11885. else
  11886. {
  11887. for (unsigned i = 0; i < numStreams; i++)
  11888. streamArray[i]->stop();
  11889. }
  11890. CRoxieServerMultiInputBaseActivity::stop();
  11891. }
  11892. virtual void reset()
  11893. {
  11894. CRoxieServerMultiInputBaseActivity::reset();
  11895. foundInput = false;
  11896. selectedStream = NULL;
  11897. }
  11898. virtual unsigned __int64 queryLocalCycles() const
  11899. {
  11900. return 0; // Can't easily calculate anything reliable but local processing is negligible
  11901. }
  11902. virtual const void * nextRow()
  11903. {
  11904. ActivityTimer t(totalCycles, timeActivities);
  11905. if (!foundInput)
  11906. {
  11907. foundInput = true;
  11908. assertex(numInputs == numStreams); // If this ceases to be true we will need to rethink some of this
  11909. //If we get an exception in this loop then stop() will stop any started inputs
  11910. for (unsigned i=0; i < numStreams; i++)
  11911. {
  11912. selectedStream = streamArray[i];
  11913. inputArray[i]->start(savedParentExtractSize, savedParentExtract, false); // Assumes 1:1 mapping streams to inputs
  11914. startJunction(junctionArray[i]);
  11915. const void * next = selectedStream->nextRow();
  11916. if (next)
  11917. {
  11918. //Found a row so stop remaining
  11919. for (unsigned j=i+1; j < numInputs; j++)
  11920. streamArray[j]->stop();
  11921. processed++;
  11922. return next;
  11923. }
  11924. selectedStream->stop();
  11925. }
  11926. selectedStream = NULL;
  11927. return NULL;
  11928. }
  11929. if (!selectedStream)
  11930. return NULL;
  11931. const void * next = selectedStream->nextRow();
  11932. if (next)
  11933. processed++;
  11934. return next;
  11935. }
  11936. };
  11937. class CRoxieServerNonEmptyActivityFactory : public CRoxieServerMultiInputFactory
  11938. {
  11939. public:
  11940. CRoxieServerNonEmptyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  11941. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  11942. {
  11943. }
  11944. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  11945. {
  11946. return new CRoxieServerNonEmptyActivity(_ctx, this, _probeManager, numInputs());
  11947. }
  11948. };
  11949. IRoxieServerActivityFactory *createRoxieServerNonEmptyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  11950. {
  11951. return new CRoxieServerNonEmptyActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  11952. }
  11953. //=================================================================================
  11954. class CRoxieServerMergeActivity : public CRoxieServerMultiInputActivity
  11955. {
  11956. IHThorMergeArg &helper;
  11957. unsigned *mergeheap;
  11958. unsigned activeInputs;
  11959. const void **pending;
  11960. bool first;
  11961. ICompare *compare;
  11962. bool dedup;
  11963. void permute()
  11964. {
  11965. assertex(activeInputs == 0);
  11966. for(unsigned i = 0; i < numStreams; i++)
  11967. if(pullInput(i))
  11968. mergeheap[activeInputs++] = i;
  11969. // the tree structure: element p has children p*2+1 and p*2+2, or element c has parent (unsigned)(c-1)/2
  11970. // the heap property: no element should be smaller than its parent
  11971. // the dedup variant: if(dedup), the top of the heap should also not be equal to either child
  11972. // 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
  11973. if (activeInputs >= 2)
  11974. for(unsigned p = (activeInputs-2)/2; p > 0; --p)
  11975. siftDown(p);
  11976. if(dedup)
  11977. siftDownDedupTop();
  11978. else
  11979. siftDown(0);
  11980. }
  11981. void readNext()
  11982. {
  11983. if(!pullInput(mergeheap[0]))
  11984. if(!promote(0))
  11985. return;
  11986. // we have changed the element at the top of the heap, so need to sift it down to maintain the heap property
  11987. if(dedup)
  11988. siftDownDedupTop();
  11989. else
  11990. siftDown(0);
  11991. }
  11992. bool pullInput(unsigned i)
  11993. {
  11994. const void *next = streamArray[i]->ungroupedNextRow();
  11995. pending[i] = next;
  11996. return (next != NULL);
  11997. }
  11998. bool promote(unsigned p)
  11999. {
  12000. activeInputs--;
  12001. if(activeInputs == p)
  12002. return false;
  12003. mergeheap[p] = mergeheap[activeInputs];
  12004. return true;
  12005. }
  12006. bool siftDown(unsigned p)
  12007. {
  12008. // assuming that all descendants of p form a heap, sift p down to its correct position, and so include it in the heap
  12009. bool nochange = true;
  12010. while(1)
  12011. {
  12012. unsigned c = p*2 + 1;
  12013. if(c >= activeInputs)
  12014. return nochange;
  12015. if(c+1 < activeInputs)
  12016. {
  12017. int childcmp = BuffCompare(c+1, c);
  12018. if((childcmp < 0) || ((childcmp == 0) && (mergeheap[c+1] < mergeheap[c])))
  12019. ++c;
  12020. }
  12021. int cmp = BuffCompare(c, p);
  12022. if((cmp > 0) || ((cmp == 0) && (mergeheap[c] > mergeheap[p])))
  12023. return nochange;
  12024. nochange = false;
  12025. unsigned r = mergeheap[c];
  12026. mergeheap[c] = mergeheap[p];
  12027. mergeheap[p] = r;
  12028. p = c;
  12029. }
  12030. }
  12031. void siftDownDedupTop()
  12032. {
  12033. // same as siftDown(0), except that it also ensures that the top of the heap is not equal to either of its children
  12034. if(activeInputs < 2)
  12035. return;
  12036. unsigned c = 1;
  12037. int childcmp = 1;
  12038. if(activeInputs >= 3)
  12039. {
  12040. childcmp = BuffCompare(2, 1);
  12041. if(childcmp < 0)
  12042. c = 2;
  12043. }
  12044. int cmp = BuffCompare(c, 0);
  12045. if(cmp > 0)
  12046. return;
  12047. // the following loop ensures the correct property holds on the smaller branch, and that childcmp==0 iff the top matches the other branch
  12048. while(cmp <= 0)
  12049. {
  12050. if(cmp == 0)
  12051. {
  12052. if(mergeheap[c] < mergeheap[0])
  12053. {
  12054. unsigned r = mergeheap[c];
  12055. mergeheap[c] = mergeheap[0];
  12056. mergeheap[0] = r;
  12057. }
  12058. ReleaseClearRoxieRow(pending[mergeheap[c]]);
  12059. if(!pullInput(mergeheap[c]))
  12060. if(!promote(c))
  12061. break;
  12062. siftDown(c);
  12063. }
  12064. else
  12065. {
  12066. unsigned r = mergeheap[c];
  12067. mergeheap[c] = mergeheap[0];
  12068. mergeheap[0] = r;
  12069. if(siftDown(c))
  12070. break;
  12071. }
  12072. cmp = BuffCompare(c, 0);
  12073. }
  12074. // the following loop ensures the uniqueness property holds on the other branch too
  12075. c = 3-c;
  12076. if(activeInputs <= c)
  12077. return;
  12078. while(childcmp == 0)
  12079. {
  12080. if(mergeheap[c] < mergeheap[0])
  12081. {
  12082. unsigned r = mergeheap[c];
  12083. mergeheap[c] = mergeheap[0];
  12084. mergeheap[0] = r;
  12085. }
  12086. ReleaseClearRoxieRow(pending[mergeheap[c]]);
  12087. if(!pullInput(mergeheap[c]))
  12088. if(!promote(c))
  12089. break;
  12090. siftDown(c);
  12091. childcmp = BuffCompare(c, 0);
  12092. }
  12093. }
  12094. inline int BuffCompare(unsigned a, unsigned b)
  12095. {
  12096. return compare->docompare(pending[mergeheap[a]], pending[mergeheap[b]]);
  12097. }
  12098. public:
  12099. CRoxieServerMergeActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  12100. : CRoxieServerMultiInputActivity(_ctx, _factory, _probeManager, _numInputs), helper((IHThorMergeArg &)basehelper)
  12101. {
  12102. activeInputs = 0;
  12103. first = true;
  12104. mergeheap = new unsigned[numInputs];
  12105. pending = new const void *[numStreams];
  12106. compare = helper.queryCompare();
  12107. dedup = helper.dedup();
  12108. for (unsigned i = 0; i < numStreams; i++)
  12109. pending[i] = NULL;
  12110. }
  12111. ~CRoxieServerMergeActivity()
  12112. {
  12113. delete [] mergeheap;
  12114. delete [] pending;
  12115. }
  12116. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12117. {
  12118. activeInputs = 0;
  12119. first = true;
  12120. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  12121. }
  12122. virtual void reset()
  12123. {
  12124. for (unsigned i = 0; i < numStreams; i++)
  12125. ReleaseClearRoxieRow(pending[i]);
  12126. CRoxieServerMultiInputActivity::reset();
  12127. }
  12128. virtual const void * nextRow()
  12129. {
  12130. ActivityTimer t(totalCycles, timeActivities);
  12131. if (first)
  12132. {
  12133. permute();
  12134. first = false;
  12135. }
  12136. if (activeInputs)
  12137. {
  12138. const void *next = pending[mergeheap[0]];
  12139. readNext();
  12140. if (next)
  12141. processed++;
  12142. return next;
  12143. }
  12144. else
  12145. return NULL;
  12146. }
  12147. };
  12148. class CRoxieServerMergeActivityFactory : public CRoxieServerMultiInputFactory
  12149. {
  12150. public:
  12151. CRoxieServerMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12152. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12153. {
  12154. }
  12155. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12156. {
  12157. return new CRoxieServerMergeActivity(_ctx, this, _probeManager, numInputs());
  12158. }
  12159. };
  12160. IRoxieServerActivityFactory *createRoxieServerMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12161. {
  12162. return new CRoxieServerMergeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12163. }
  12164. //=================================================================================
  12165. class CRoxieServerRegroupActivity : public CRoxieServerMultiInputActivity
  12166. {
  12167. IHThorRegroupArg &helper;
  12168. unsigned streamIndex;
  12169. bool eof;
  12170. unsigned __int64 numProcessedLastGroup;
  12171. public:
  12172. CRoxieServerRegroupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  12173. : CRoxieServerMultiInputActivity(_ctx, _factory, _probeManager, _numInputs), helper((IHThorRegroupArg &)basehelper)
  12174. {
  12175. streamIndex = 0;
  12176. eof = false;
  12177. numProcessedLastGroup = 0;
  12178. }
  12179. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12180. {
  12181. streamIndex = 0;
  12182. eof = false;
  12183. numProcessedLastGroup = processed;
  12184. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  12185. }
  12186. const void * nextFromInputs()
  12187. {
  12188. unsigned initialStream = streamIndex;
  12189. while (streamIndex < numStreams)
  12190. {
  12191. const void * next = streamArray[streamIndex]->nextRow();
  12192. if (next)
  12193. {
  12194. if ((streamIndex != initialStream) && (streamIndex != initialStream+1))
  12195. {
  12196. ReleaseRoxieRow(next);
  12197. throw MakeStringException(ROXIE_MISMATCH_GROUP_ERROR, "Mismatched groups supplied to Regroup (%d)", factory->queryId());
  12198. }
  12199. return next;
  12200. }
  12201. streamIndex++;
  12202. }
  12203. if ((initialStream != 0) && (initialStream+1 != numStreams))
  12204. throw MakeStringException(ROXIE_MISMATCH_GROUP_ERROR, "Mismatched groups supplied to Regroup (%d)", factory->queryId());
  12205. streamIndex = 0;
  12206. return NULL;
  12207. }
  12208. virtual const void * nextRow()
  12209. {
  12210. ActivityTimer t(totalCycles, timeActivities);
  12211. if (eof)
  12212. return NULL;
  12213. const void * ret = nextFromInputs();
  12214. if (ret)
  12215. {
  12216. processed++;
  12217. return ret;
  12218. }
  12219. if (numProcessedLastGroup != processed)
  12220. {
  12221. numProcessedLastGroup = processed;
  12222. return NULL;
  12223. }
  12224. eof = true;
  12225. return NULL;
  12226. }
  12227. };
  12228. class CRoxieServerRegroupActivityFactory : public CRoxieServerMultiInputFactory
  12229. {
  12230. public:
  12231. CRoxieServerRegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12232. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12233. {
  12234. }
  12235. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12236. {
  12237. return new CRoxieServerRegroupActivity(_ctx, this, _probeManager, numInputs());
  12238. }
  12239. };
  12240. IRoxieServerActivityFactory *createRoxieServerRegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12241. {
  12242. return new CRoxieServerRegroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12243. }
  12244. //=================================================================================
  12245. class CRoxieServerCombineActivity : public CRoxieServerMultiInputActivity
  12246. {
  12247. IHThorCombineArg &helper;
  12248. unsigned __int64 numProcessedLastGroup;
  12249. public:
  12250. CRoxieServerCombineActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  12251. : CRoxieServerMultiInputActivity(_ctx, _factory, _probeManager, _numInputs), helper((IHThorCombineArg &)basehelper)
  12252. {
  12253. numProcessedLastGroup = 0;
  12254. }
  12255. ~CRoxieServerCombineActivity()
  12256. {
  12257. }
  12258. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12259. {
  12260. numProcessedLastGroup = processed;
  12261. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  12262. }
  12263. void nextInputs(ConstPointerArray & out)
  12264. {
  12265. for (unsigned i=0; i < numStreams; i++)
  12266. {
  12267. const void * next = streamArray[i]->nextRow();
  12268. if (next)
  12269. out.append(next);
  12270. }
  12271. }
  12272. virtual bool needsAllocator() const { return true; }
  12273. virtual const void * nextRow()
  12274. {
  12275. ActivityTimer t(totalCycles, timeActivities);
  12276. loop
  12277. {
  12278. ConstPointerArray group;
  12279. nextInputs(group);
  12280. if ((group.ordinality() == 0) && (numProcessedLastGroup == processed))
  12281. nextInputs(group);
  12282. if (group.ordinality() == 0)
  12283. {
  12284. numProcessedLastGroup = processed;
  12285. return NULL;
  12286. }
  12287. else if (group.ordinality() != numInputs)
  12288. {
  12289. ReleaseRoxieRows(group);
  12290. throw MakeStringException(ROXIE_MISMATCH_GROUP_ERROR, "Mismatched group input for Combine Activity(%d)", factory->queryId());
  12291. }
  12292. try
  12293. {
  12294. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12295. size32_t outSize = helper.transform(rowBuilder, group.ordinality(), group.getArray());
  12296. ReleaseRoxieRows(group);
  12297. if (outSize)
  12298. {
  12299. processed++;
  12300. return rowBuilder.finalizeRowClear(outSize);
  12301. }
  12302. }
  12303. catch (IException *E)
  12304. {
  12305. ReleaseRoxieRows(group);
  12306. throw makeWrappedException(E);
  12307. }
  12308. }
  12309. }
  12310. };
  12311. class CRoxieServerCombineActivityFactory : public CRoxieServerMultiInputFactory
  12312. {
  12313. public:
  12314. CRoxieServerCombineActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12315. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12316. {
  12317. }
  12318. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12319. {
  12320. return new CRoxieServerCombineActivity(_ctx, this, _probeManager, numInputs());
  12321. }
  12322. };
  12323. IRoxieServerActivityFactory *createRoxieServerCombineActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12324. {
  12325. return new CRoxieServerCombineActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12326. }
  12327. //=================================================================================
  12328. class CRoxieServerCombineGroupActivity : public CRoxieServerTwoInputActivity
  12329. {
  12330. IHThorCombineGroupArg &helper;
  12331. unsigned __int64 numProcessedLastGroup;
  12332. public:
  12333. CRoxieServerCombineGroupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  12334. : CRoxieServerTwoInputActivity(_ctx, _factory, _probeManager), helper((IHThorCombineGroupArg &)basehelper)
  12335. {
  12336. numProcessedLastGroup = 0;
  12337. }
  12338. ~CRoxieServerCombineGroupActivity()
  12339. {
  12340. }
  12341. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12342. {
  12343. numProcessedLastGroup = processed;
  12344. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  12345. }
  12346. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  12347. {
  12348. if (idx==(unsigned)-1)
  12349. idx = 0;
  12350. return idx ? NULL : this;
  12351. }
  12352. virtual bool needsAllocator() const { return true; }
  12353. virtual const void * nextRow()
  12354. {
  12355. ActivityTimer t(totalCycles, timeActivities);
  12356. loop
  12357. {
  12358. const void * left = inputStream->nextRow();
  12359. if (!left && (numProcessedLastGroup == processed))
  12360. left = inputStream->nextRow();
  12361. if (!left)
  12362. {
  12363. if (numProcessedLastGroup == processed)
  12364. {
  12365. const void * nextRight = inputStream1->nextRow();
  12366. if (nextRight)
  12367. {
  12368. ReleaseRoxieRow(nextRight);
  12369. throw MakeStringException(ROXIE_MISSING_GROUP_ERROR, "Missing LEFT record for Combine Group (%d)", factory->queryId());
  12370. }
  12371. }
  12372. else
  12373. numProcessedLastGroup = processed;
  12374. return NULL;
  12375. }
  12376. ConstPointerArray group;
  12377. loop
  12378. {
  12379. const void * in = inputStream1->nextRow();
  12380. if (!in)
  12381. break;
  12382. group.append(in);
  12383. }
  12384. if (group.ordinality() == 0)
  12385. {
  12386. ReleaseRoxieRow(left);
  12387. ReleaseRoxieRows(group);
  12388. throw MakeStringException(ROXIE_MISSING_GROUP_ERROR, "Missing RIGHT group for Combine Group (%d)", factory->queryId());
  12389. }
  12390. try
  12391. {
  12392. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12393. size32_t outSize = helper.transform(rowBuilder, left, group.ordinality(), (const void * *)group.getArray());
  12394. ReleaseRoxieRow(left);
  12395. ReleaseRoxieRows(group);
  12396. if (outSize)
  12397. {
  12398. processed++;
  12399. return rowBuilder.finalizeRowClear(outSize);
  12400. }
  12401. }
  12402. catch (IException *E)
  12403. {
  12404. ReleaseRoxieRow(left);
  12405. ReleaseRoxieRows(group);
  12406. throw makeWrappedException(E);
  12407. }
  12408. }
  12409. }
  12410. };
  12411. class CRoxieServerCombineGroupActivityFactory : public CRoxieServerActivityFactory
  12412. {
  12413. unsigned input2;
  12414. unsigned input2idx;
  12415. public:
  12416. CRoxieServerCombineGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12417. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12418. {
  12419. input2 = 0;
  12420. input2idx = 0;
  12421. }
  12422. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12423. {
  12424. return new CRoxieServerCombineGroupActivity(_ctx, this, _probeManager);
  12425. }
  12426. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  12427. {
  12428. if (idx==1)
  12429. {
  12430. input2 = source;
  12431. input2idx = sourceidx;
  12432. }
  12433. else
  12434. CRoxieServerActivityFactory::setInput(idx, source, sourceidx);
  12435. }
  12436. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  12437. {
  12438. switch (idx)
  12439. {
  12440. case 1:
  12441. sourceidx = input2idx;
  12442. return input2;
  12443. case 0:
  12444. return CRoxieServerActivityFactory::getInput(idx, sourceidx);
  12445. default:
  12446. return (unsigned) -1;
  12447. }
  12448. }
  12449. virtual unsigned numInputs() const { return 2; }
  12450. };
  12451. IRoxieServerActivityFactory *createRoxieServerCombineGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12452. {
  12453. return new CRoxieServerCombineGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12454. }
  12455. //=================================================================================
  12456. class CRoxieServerRollupGroupActivity : public CRoxieServerActivity
  12457. {
  12458. IHThorRollupGroupArg &helper;
  12459. bool eof;
  12460. public:
  12461. CRoxieServerRollupGroupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  12462. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  12463. helper((IHThorRollupGroupArg &)basehelper)
  12464. {
  12465. eof = false;
  12466. }
  12467. ~CRoxieServerRollupGroupActivity()
  12468. {
  12469. }
  12470. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12471. {
  12472. eof = false;
  12473. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  12474. }
  12475. virtual bool needsAllocator() const { return true; }
  12476. virtual const void * nextRow()
  12477. {
  12478. ActivityTimer t(totalCycles, timeActivities);
  12479. if (eof)
  12480. return NULL;
  12481. loop
  12482. {
  12483. ConstPointerArray group;
  12484. loop
  12485. {
  12486. const void * in = inputStream->nextRow();
  12487. if (!in)
  12488. break;
  12489. group.append(in);
  12490. }
  12491. if (group.ordinality() == 0)
  12492. {
  12493. eof = true;
  12494. return NULL;
  12495. }
  12496. try
  12497. {
  12498. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12499. size32_t outSize = helper.transform(rowBuilder, group.ordinality(), (const void * *)group.getArray());
  12500. ReleaseRoxieRows(group);
  12501. if (outSize)
  12502. {
  12503. processed++;
  12504. return rowBuilder.finalizeRowClear(outSize);
  12505. }
  12506. }
  12507. catch (IException * E)
  12508. {
  12509. ReleaseRoxieRows(group);
  12510. throw makeWrappedException(E);
  12511. }
  12512. }
  12513. }
  12514. };
  12515. class CRoxieServerRollupGroupActivityFactory : public CRoxieServerActivityFactory
  12516. {
  12517. public:
  12518. CRoxieServerRollupGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12519. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12520. {
  12521. }
  12522. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12523. {
  12524. return new CRoxieServerRollupGroupActivity(_ctx, this, _probeManager);
  12525. }
  12526. };
  12527. IRoxieServerActivityFactory *createRoxieServerRollupGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12528. {
  12529. return new CRoxieServerRollupGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12530. }
  12531. //=================================================================================
  12532. class CRoxieServerFilterProjectActivity : public CRoxieServerLateStartActivity
  12533. {
  12534. IHThorFilterProjectArg &helper;
  12535. unsigned numProcessedLastGroup;
  12536. unsigned __int64 recordCount;
  12537. public:
  12538. CRoxieServerFilterProjectActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  12539. : CRoxieServerLateStartActivity(_ctx, _factory, _probeManager), helper((IHThorFilterProjectArg &)basehelper)
  12540. {
  12541. numProcessedLastGroup = 0;
  12542. recordCount = 0;
  12543. }
  12544. ~CRoxieServerFilterProjectActivity()
  12545. {
  12546. }
  12547. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12548. {
  12549. numProcessedLastGroup = 0;
  12550. recordCount = 0;
  12551. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  12552. lateStart(parentExtractSize, parentExtract, helper.canMatchAny()); //sets eof
  12553. }
  12554. virtual bool needsAllocator() const { return true; }
  12555. virtual const void * nextRow()
  12556. {
  12557. ActivityTimer t(totalCycles, timeActivities);
  12558. if (eof)
  12559. return NULL;
  12560. loop
  12561. {
  12562. const void * in = inputStream->nextRow();
  12563. if (!in)
  12564. {
  12565. recordCount = 0;
  12566. if (numProcessedLastGroup == processed)
  12567. in = inputStream->nextRow();
  12568. if (!in)
  12569. {
  12570. numProcessedLastGroup = processed;
  12571. return NULL;
  12572. }
  12573. }
  12574. try
  12575. {
  12576. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12577. size32_t outSize = helper.transform(rowBuilder, in, ++recordCount);
  12578. ReleaseRoxieRow(in);
  12579. if (outSize)
  12580. {
  12581. processed++;
  12582. return rowBuilder.finalizeRowClear(outSize);
  12583. }
  12584. }
  12585. catch (IException *E)
  12586. {
  12587. throw makeWrappedException(E);
  12588. }
  12589. }
  12590. }
  12591. };
  12592. class CRoxieServerFilterProjectActivityFactory : public CRoxieServerActivityFactory
  12593. {
  12594. public:
  12595. CRoxieServerFilterProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12596. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12597. {
  12598. //MORE: Code generator needs to indicate if the count is used.
  12599. //optStableInput = false;
  12600. }
  12601. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12602. {
  12603. return new CRoxieServerFilterProjectActivity(_ctx, this, _probeManager);
  12604. }
  12605. };
  12606. IRoxieServerActivityFactory *createRoxieServerFilterProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12607. {
  12608. return new CRoxieServerFilterProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12609. }
  12610. //=====================================================
  12611. class CRoxieServerStrandedProjectActivity : public CRoxieServerStrandedActivity
  12612. {
  12613. class ProjectProcessor : public StrandProcessor
  12614. {
  12615. protected:
  12616. IHThorProjectArg &helper;
  12617. public:
  12618. ProjectProcessor(CRoxieServerActivity &_parent, IEngineRowStream *_inputStream, IHThorProjectArg &_helper)
  12619. : StrandProcessor(_parent, _inputStream, true), helper(_helper)
  12620. {
  12621. }
  12622. virtual const void * nextRow()
  12623. {
  12624. ActivityTimer t(totalCycles, timeActivities);
  12625. loop
  12626. {
  12627. OwnedConstRoxieRow in = inputStream->nextRow();
  12628. if (!in)
  12629. {
  12630. if (numProcessedLastGroup == processed)
  12631. in.setown(inputStream->nextRow());
  12632. if (!in)
  12633. {
  12634. numProcessedLastGroup = processed;
  12635. return NULL;
  12636. }
  12637. }
  12638. try
  12639. {
  12640. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12641. size32_t outSize;
  12642. outSize = helper.transform(rowBuilder, in);
  12643. if (outSize)
  12644. {
  12645. processed++;
  12646. return rowBuilder.finalizeRowClear(outSize);
  12647. }
  12648. }
  12649. catch (IException *E)
  12650. {
  12651. throw parent.makeWrappedException(E);
  12652. }
  12653. }
  12654. }
  12655. };
  12656. public:
  12657. CRoxieServerStrandedProjectActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const StrandOptions &_strandOptions)
  12658. : CRoxieServerStrandedActivity(_ctx, _factory, _probeManager, _strandOptions)
  12659. {
  12660. }
  12661. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12662. {
  12663. CRoxieServerStrandedActivity::start(parentExtractSize, parentExtract, paused);
  12664. onStartStrands();
  12665. }
  12666. virtual StrandProcessor *createStrandProcessor(IEngineRowStream *instream)
  12667. {
  12668. return new ProjectProcessor(*this, instream, (IHThorProjectArg &) basehelper);
  12669. }
  12670. virtual StrandProcessor *createStrandSourceProcessor(bool inputOrdered) { throwUnexpected(); }
  12671. };
  12672. class CRoxieServerProjectActivity : public CRoxieServerActivity
  12673. {
  12674. unsigned numProcessedLastGroup;
  12675. unsigned __int64 recordCount;
  12676. bool count;
  12677. public:
  12678. CRoxieServerProjectActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _count)
  12679. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  12680. count(_count)
  12681. {
  12682. numProcessedLastGroup = 0;
  12683. recordCount = 0;
  12684. }
  12685. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12686. {
  12687. numProcessedLastGroup = 0;
  12688. recordCount = 0;
  12689. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  12690. }
  12691. virtual bool needsAllocator() const { return true; }
  12692. virtual const void * nextRow()
  12693. {
  12694. ActivityTimer t(totalCycles, timeActivities);
  12695. loop
  12696. {
  12697. OwnedConstRoxieRow in = inputStream->nextRow();
  12698. if (!in)
  12699. {
  12700. recordCount = 0;
  12701. if (numProcessedLastGroup == processed)
  12702. in.setown(inputStream->nextRow());
  12703. if (!in)
  12704. {
  12705. numProcessedLastGroup = processed;
  12706. return NULL;
  12707. }
  12708. }
  12709. try
  12710. {
  12711. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12712. size32_t outSize;
  12713. if (count)
  12714. outSize = ((IHThorCountProjectArg &) basehelper).transform(rowBuilder, in, ++recordCount);
  12715. else
  12716. outSize = ((IHThorProjectArg &) basehelper).transform(rowBuilder, in);
  12717. if (outSize)
  12718. {
  12719. processed++;
  12720. return rowBuilder.finalizeRowClear(outSize);
  12721. }
  12722. }
  12723. catch (IException *E)
  12724. {
  12725. throw makeWrappedException(E);
  12726. }
  12727. }
  12728. }
  12729. };
  12730. class CRoxieServerProjectActivityFactory : public CRoxieServerActivityFactory
  12731. {
  12732. protected:
  12733. StrandOptions strandOptions;
  12734. bool count;
  12735. public:
  12736. CRoxieServerProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12737. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), strandOptions(_graphNode)
  12738. {
  12739. count = (kind==TAKcountproject || kind==TAKprefetchcountproject);
  12740. optStableInput = count;
  12741. }
  12742. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12743. {
  12744. // 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.
  12745. if (kind == TAKproject) // Not supported on prefetch or count projects
  12746. return new CRoxieServerStrandedProjectActivity(_ctx, this, _probeManager, strandOptions);
  12747. else
  12748. return new CRoxieServerProjectActivity(_ctx, this, _probeManager, count);
  12749. }
  12750. };
  12751. IRoxieServerActivityFactory *createRoxieServerProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12752. {
  12753. return new CRoxieServerProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12754. }
  12755. //=================================================================================
  12756. class CRoxieServerPrefetchProjectActivity : public CRoxieServerActivity, implements IRecordPullerCallback
  12757. {
  12758. unsigned numProcessedLastGroup;
  12759. bool count;
  12760. bool eof;
  12761. bool allPulled;
  12762. bool isThreaded;
  12763. unsigned preload;
  12764. unsigned __int64 recordCount;
  12765. IHThorPrefetchProjectArg &helper;
  12766. RecordPullerThread puller;
  12767. InterruptableSemaphore ready;
  12768. InterruptableSemaphore space;
  12769. class PrefetchInfo : public CInterface
  12770. {
  12771. public:
  12772. inline PrefetchInfo(IHThorPrefetchProjectArg &helper, const void *_in, unsigned __int64 _recordCount)
  12773. {
  12774. if (helper.preTransform(extract, _in, _recordCount))
  12775. {
  12776. in.setown(_in);
  12777. recordCount = _recordCount;
  12778. }
  12779. else
  12780. ReleaseRoxieRow(_in);
  12781. }
  12782. OwnedConstRoxieRow in;
  12783. unsigned __int64 recordCount;
  12784. rtlRowBuilder extract;
  12785. };
  12786. QueueOf<PrefetchInfo, true> pulled;
  12787. CriticalSection pulledCrit;
  12788. public:
  12789. CRoxieServerPrefetchProjectActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _count)
  12790. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  12791. helper((IHThorPrefetchProjectArg &) basehelper),
  12792. puller(false),
  12793. count(_count)
  12794. {
  12795. numProcessedLastGroup = 0;
  12796. recordCount = 0;
  12797. eof = false;
  12798. allPulled = false;
  12799. isThreaded = (helper.getFlags() & PPFparallel) != 0;
  12800. preload = 0;
  12801. }
  12802. ~CRoxieServerPrefetchProjectActivity()
  12803. {
  12804. while (pulled.ordinality())
  12805. ::Release(pulled.dequeue());
  12806. }
  12807. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  12808. {
  12809. if (idx)
  12810. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  12811. puller.setInput(this, _sourceIdx, _in);
  12812. }
  12813. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  12814. {
  12815. puller.connectInputStreams(ctx, consumerOrdered);
  12816. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
  12817. }
  12818. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  12819. {
  12820. if (idx==0)
  12821. return puller.queryInput();
  12822. else
  12823. return NULL;
  12824. }
  12825. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12826. {
  12827. numProcessedLastGroup = 0;
  12828. recordCount = 0;
  12829. eof = false;
  12830. allPulled = false;
  12831. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  12832. preload = helper.getLookahead();
  12833. if (!preload)
  12834. preload = ctx->queryOptions().prefetchProjectPreload;
  12835. space.reinit(preload);
  12836. ready.reinit();
  12837. puller.start(parentExtractSize, parentExtract, paused, preload, !isThreaded, ctx);
  12838. }
  12839. virtual void stop()
  12840. {
  12841. space.interrupt();
  12842. ready.interrupt();
  12843. CRoxieServerActivity::stop();
  12844. puller.stop();
  12845. }
  12846. virtual void reset()
  12847. {
  12848. CRoxieServerActivity::reset();
  12849. puller.reset();
  12850. allPulled = false;
  12851. while (pulled.ordinality())
  12852. ::Release(pulled.dequeue());
  12853. }
  12854. virtual PrefetchInfo *readNextRecord()
  12855. {
  12856. if (!isThreaded)
  12857. {
  12858. if (!allPulled) // This looks like it's thread unsafe but we are inside the if(!isThreaded) so should be ok
  12859. puller.pullRecords(1);
  12860. }
  12861. else
  12862. ready.wait();
  12863. CriticalBlock b(pulledCrit);
  12864. PrefetchInfo *ret = pulled.ordinality() ? pulled.dequeue() : NULL;
  12865. space.signal();
  12866. return ret;
  12867. }
  12868. virtual bool needsAllocator() const { return true; }
  12869. virtual const void * nextRow()
  12870. {
  12871. ActivityTimer t(totalCycles, timeActivities);
  12872. if (eof)
  12873. return NULL;
  12874. loop
  12875. {
  12876. Owned<PrefetchInfo> in = readNextRecord();
  12877. if (!in)
  12878. {
  12879. recordCount = 0;
  12880. if (numProcessedLastGroup == processed)
  12881. in.setown(readNextRecord());
  12882. if (!in)
  12883. {
  12884. numProcessedLastGroup = processed;
  12885. eof = true;
  12886. return NULL;
  12887. }
  12888. }
  12889. try
  12890. {
  12891. if (in->in)
  12892. {
  12893. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12894. size32_t outSize;
  12895. IThorChildGraph *child = helper.queryChild();
  12896. Owned<IEclGraphResults> results;
  12897. if (child)
  12898. results.setown(child->evaluate(in->extract.size(), in->extract.getbytes()));
  12899. outSize = helper.transform(rowBuilder, in->in, results, in->recordCount);
  12900. if (outSize)
  12901. {
  12902. processed++;
  12903. return rowBuilder.finalizeRowClear(outSize);
  12904. }
  12905. }
  12906. }
  12907. catch (IException *E)
  12908. {
  12909. throw makeWrappedException(E);
  12910. }
  12911. }
  12912. }
  12913. // interface IExceptionHandler
  12914. virtual bool fireException(IException *e)
  12915. {
  12916. // called from puller thread on failure
  12917. ready.interrupt(LINK(e));
  12918. space.interrupt(e);
  12919. return true;
  12920. }
  12921. // interface IRecordPullerCallback
  12922. virtual void processRow(const void *row)
  12923. {
  12924. {
  12925. CriticalBlock b(pulledCrit);
  12926. pulled.enqueue(new PrefetchInfo(helper, row, ++recordCount));
  12927. }
  12928. if (isThreaded)
  12929. {
  12930. ready.signal();
  12931. space.wait();
  12932. }
  12933. }
  12934. virtual void processEOG()
  12935. {
  12936. {
  12937. CriticalBlock b(pulledCrit);
  12938. pulled.enqueue(NULL);
  12939. }
  12940. if (isThreaded)
  12941. {
  12942. ready.signal();
  12943. space.wait();
  12944. }
  12945. }
  12946. virtual void processGroup(const ConstPointerArray &rows)
  12947. {
  12948. throwUnexpected();
  12949. }
  12950. virtual void processDone()
  12951. {
  12952. CriticalBlock b(pulledCrit);
  12953. allPulled = true;
  12954. if (isThreaded)
  12955. ready.signal();
  12956. }
  12957. };
  12958. class CRoxieServerPrefetchProjectActivityFactory : public CRoxieServerProjectActivityFactory
  12959. {
  12960. public:
  12961. CRoxieServerPrefetchProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12962. : CRoxieServerProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12963. {
  12964. }
  12965. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12966. {
  12967. return new CRoxieServerPrefetchProjectActivity(_ctx, this, _probeManager, count);
  12968. }
  12969. };
  12970. extern IRoxieServerActivityFactory *createRoxieServerPrefetchProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12971. {
  12972. return new CRoxieServerPrefetchProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12973. }
  12974. //=================================================================================
  12975. class CPointerArrayRoxieInput : public CPseudoRoxieInput
  12976. {
  12977. public:
  12978. CPointerArrayRoxieInput()
  12979. {
  12980. rowset = NULL;
  12981. rowcount = 0;
  12982. curRow = 0;
  12983. }
  12984. void init(size32_t _rowcount, byte **_rowset)
  12985. {
  12986. rowset = _rowset;
  12987. rowcount = _rowcount;
  12988. curRow = 0;
  12989. }
  12990. virtual const void * nextRow()
  12991. {
  12992. if (curRow < rowcount)
  12993. {
  12994. const void * ret = rowset[curRow];
  12995. if (ret)
  12996. LinkRoxieRow(ret);
  12997. curRow++;
  12998. return ret;
  12999. }
  13000. return NULL;
  13001. }
  13002. protected:
  13003. byte **rowset;
  13004. size32_t rowcount;
  13005. size32_t curRow;
  13006. };
  13007. class CRoxieServerLoopActivity : public CRoxieServerActivity
  13008. {
  13009. protected:
  13010. IHThorLoopArg &helper;
  13011. ThorActivityKind activityKind;
  13012. unsigned maxIterations;
  13013. bool finishedLooping;
  13014. unsigned flags;
  13015. bool eof;
  13016. rtlRowBuilder loopExtractBuilder;
  13017. unsigned loopGraphId;
  13018. Linked<IOutputMetaData> counterMeta;
  13019. public:
  13020. CRoxieServerLoopActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _loopGraphId, IOutputMetaData * _counterMeta)
  13021. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  13022. helper((IHThorLoopArg &)basehelper), loopGraphId(_loopGraphId), counterMeta(_counterMeta)
  13023. {
  13024. eof = false;
  13025. finishedLooping = false;
  13026. activityKind = factory->getKind();
  13027. flags = helper.getFlags();
  13028. maxIterations = 0;
  13029. }
  13030. virtual bool needsAllocator() const { return true; }
  13031. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13032. {
  13033. eof = false;
  13034. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  13035. int iterations = (int) helper.numIterations();
  13036. maxIterations = (iterations >= 0) ? iterations : 0;
  13037. finishedLooping = ((activityKind == TAKloopcount) && (maxIterations == 0));
  13038. if ((flags & IHThorLoopArg::LFnewloopagain) && !helper.loopFirstTime())
  13039. finishedLooping = true;
  13040. loopExtractBuilder.clear();
  13041. helper.createParentExtract(loopExtractBuilder); // could possibly delay this until execution actually happens
  13042. }
  13043. virtual void stop()
  13044. {
  13045. CRoxieServerActivity::stop();
  13046. loopExtractBuilder.clear();
  13047. }
  13048. void createCounterResult(IRoxieServerChildGraph * graph, unsigned counter)
  13049. {
  13050. if (flags & IHThorLoopArg::LFcounter)
  13051. {
  13052. void * counterRow = ctx->queryRowManager().allocate(sizeof(thor_loop_counter_t), activityId);
  13053. *((thor_loop_counter_t *)counterRow) = counter;
  13054. RtlLinkedDatasetBuilder builder(rowAllocator);
  13055. builder.appendOwn(counterRow);
  13056. Owned<CGraphResult> counterResult = new CGraphResult(builder.getcount(), builder.linkrows());
  13057. graph->setInputResult(2, counterResult);
  13058. }
  13059. }
  13060. };
  13061. //=================================================================================
  13062. class CRoxieServerSequentialLoopActivity : public CRoxieServerLoopActivity
  13063. {
  13064. Owned<IActivityGraph> loopQuery;
  13065. Owned<IRoxieServerChildGraph> loopGraph;
  13066. IEngineRowStream * curStream;
  13067. RtlLinkedDatasetBuilder *loopInputBuilder;
  13068. CPointerArrayRoxieInput arrayInput;
  13069. Linked<IEngineRowStream> resultStream;
  13070. unsigned loopCounter;
  13071. public:
  13072. CRoxieServerSequentialLoopActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _loopGraphId, IOutputMetaData * _counterMeta)
  13073. : CRoxieServerLoopActivity(_ctx, _factory, _probeManager, _loopGraphId, _counterMeta)
  13074. {
  13075. curStream = NULL;
  13076. loopCounter = 0;
  13077. loopInputBuilder = NULL;
  13078. }
  13079. virtual bool needsAllocator() const { return true; }
  13080. virtual void onCreate(IHThorArg *_colocalParent)
  13081. {
  13082. CRoxieServerLoopActivity::onCreate(_colocalParent);
  13083. loopQuery.set(ctx->queryChildGraph(loopGraphId));
  13084. }
  13085. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13086. {
  13087. curStream = inputStream;
  13088. loopCounter = 1;
  13089. CRoxieServerLoopActivity::start(parentExtractSize, parentExtract, paused);
  13090. //MORE: Not sure about this, should IRoxieServerChildGraph be combined with IActivityGraph?
  13091. loopGraph.set(loopQuery->queryLoopGraph());
  13092. loopInputBuilder = new RtlLinkedDatasetBuilder(rowAllocator);
  13093. }
  13094. virtual void stop()
  13095. {
  13096. delete loopInputBuilder;
  13097. loopInputBuilder = NULL;
  13098. CRoxieServerLoopActivity::stop();
  13099. }
  13100. virtual const void * nextRow()
  13101. {
  13102. ActivityTimer t(totalCycles, timeActivities);
  13103. if (eof)
  13104. return NULL;
  13105. unsigned emptyIterations = 0;
  13106. loop
  13107. {
  13108. loop
  13109. {
  13110. const void * ret = curStream->nextRow();
  13111. if (!ret)
  13112. {
  13113. ret = curStream->nextRow(); // more cope with groups somehow....
  13114. if (!ret)
  13115. {
  13116. if (finishedLooping)
  13117. {
  13118. eof = true;
  13119. return NULL;
  13120. }
  13121. break;
  13122. }
  13123. }
  13124. if (finishedLooping ||
  13125. ((flags & IHThorLoopArg::LFfiltered) && !helper.sendToLoop(loopCounter, ret)))
  13126. {
  13127. processed++;
  13128. return ret;
  13129. }
  13130. loopInputBuilder->appendOwn(ret);
  13131. }
  13132. switch (activityKind)
  13133. {
  13134. case TAKloopdataset:
  13135. {
  13136. if (!(flags & IHThorLoopArg::LFnewloopagain))
  13137. {
  13138. if (!helper.loopAgain(loopCounter, loopInputBuilder->getcount(), (const void**) loopInputBuilder->queryrows()))
  13139. {
  13140. if (loopInputBuilder->getcount() == 0)
  13141. {
  13142. eof = true;
  13143. return NULL;
  13144. }
  13145. arrayInput.init(loopInputBuilder->getcount(), loopInputBuilder->linkrows());
  13146. // MORE - should builder be cleared here?
  13147. curStream = &arrayInput;
  13148. finishedLooping = true;
  13149. continue; // back to the input loop again
  13150. }
  13151. }
  13152. break;
  13153. }
  13154. case TAKlooprow:
  13155. if (!loopInputBuilder->getcount())
  13156. {
  13157. finishedLooping = true;
  13158. eof = true;
  13159. return NULL;
  13160. }
  13161. break;
  13162. }
  13163. if (loopInputBuilder->getcount())
  13164. emptyIterations = 0;
  13165. else
  13166. {
  13167. //note: any outputs which didn't go around the loop again, would return the record, reinitializing emptyIterations
  13168. emptyIterations++;
  13169. if (emptyIterations > maxEmptyLoopIterations)
  13170. throw MakeStringException(ROXIE_TOO_MANY_EMPTY_LOOP, "Executed LOOP with empty input and output %u times", emptyIterations);
  13171. if (emptyIterations % 32 == 0)
  13172. CTXLOG("Executing LOOP with empty input and output %u times", emptyIterations);
  13173. }
  13174. checkAbort();
  13175. try
  13176. {
  13177. Owned<IRoxieGraphResults> results = executeIteration(loopExtractBuilder.size(), loopExtractBuilder.getbytes(), loopCounter);
  13178. resultStream.setown(results->createIterator(0));
  13179. if (flags & IHThorLoopArg::LFnewloopagain)
  13180. {
  13181. Owned<IEngineRowStream> againResult = results->createIterator(helper.loopAgainResult());
  13182. OwnedConstRoxieRow row = againResult->nextRow();
  13183. assertex(row);
  13184. //Result is a row which contains a single boolean field.
  13185. if (!((const bool *)row.get())[0])
  13186. finishedLooping = true;
  13187. }
  13188. }
  13189. catch (IException *E)
  13190. {
  13191. throw makeWrappedException(E);
  13192. }
  13193. curStream = resultStream.get();
  13194. loopCounter++;
  13195. if ((activityKind == TAKloopcount) && (loopCounter > maxIterations))
  13196. finishedLooping = true;
  13197. }
  13198. }
  13199. IRoxieGraphResults * executeIteration(unsigned parentExtractSize, const byte *parentExtract, unsigned counter)
  13200. {
  13201. try
  13202. {
  13203. loopGraph->beforeExecute();
  13204. Owned<IGraphResult> inputRowsResult = new CGraphResult(loopInputBuilder->getcount(), loopInputBuilder->linkrows());
  13205. loopInputBuilder->clear();
  13206. loopGraph->setInputResult(1, inputRowsResult);
  13207. createCounterResult(loopGraph, counter);
  13208. Owned<IRoxieGraphResults> ret = loopGraph->execute(parentExtractSize, parentExtract);
  13209. loopGraph->afterExecute();
  13210. return ret.getClear();
  13211. }
  13212. catch (...)
  13213. {
  13214. CTXLOG("Exception thrown in loop body - cleaning up");
  13215. loopGraph->afterExecute();
  13216. throw;
  13217. }
  13218. }
  13219. };
  13220. //=================================================================================
  13221. typedef SafeQueueOf<const void, true> SafeRowQueue;
  13222. class CRowQueuePseudoInput : public CPseudoRoxieInput
  13223. {
  13224. public:
  13225. CRowQueuePseudoInput(SafeRowQueue & _input, IOutputMetaData * _meta)
  13226. : meta(_meta), input(_input)
  13227. {
  13228. eof = false;
  13229. }
  13230. virtual const void * nextRow()
  13231. {
  13232. if (eof)
  13233. return NULL;
  13234. const void * ret = input.dequeue();
  13235. if (!ret)
  13236. eof = true;
  13237. return ret;
  13238. }
  13239. virtual IOutputMetaData * queryOutputMeta() const { return meta; }
  13240. protected:
  13241. SafeRowQueue & input;
  13242. IOutputMetaData * meta;
  13243. bool eof;
  13244. };
  13245. class CRoxieServerParallelLoopActivity;
  13246. class LoopFilterPseudoInput : public CIndirectRoxieInput
  13247. {
  13248. public:
  13249. LoopFilterPseudoInput(CRoxieServerParallelLoopActivity * _activity, unsigned _counter) :
  13250. activity(_activity), counter(_counter)
  13251. {
  13252. }
  13253. virtual const void * nextRow();
  13254. protected:
  13255. CRoxieServerParallelLoopActivity * activity;
  13256. unsigned counter;
  13257. };
  13258. class LoopExecutorThread : public RestartableThread
  13259. {
  13260. protected:
  13261. Owned<CSafeRoxieInput> safeInput;
  13262. CRoxieServerParallelLoopActivity * activity;
  13263. bool eof;
  13264. CriticalSection crit;
  13265. unsigned flags;
  13266. SafeRowQueue tempResults[2];
  13267. unsigned savedParentExtractSize;
  13268. const byte * savedParentExtract;
  13269. IArrayOf<IActivityGraph> cachedGraphs;
  13270. IRoxieSlaveContext *ctx;
  13271. public:
  13272. LoopExecutorThread()
  13273. : RestartableThread("LoopExecutorThread")
  13274. {
  13275. activity = NULL;
  13276. eof = false;
  13277. flags = 0;
  13278. ctx = NULL;
  13279. savedParentExtract = NULL;
  13280. savedParentExtractSize = 0;
  13281. }
  13282. void setInput(CRoxieServerParallelLoopActivity * _activity, unsigned _sourceIdx, IFinalRoxieInput *_input, unsigned _flags)
  13283. {
  13284. activity = _activity;
  13285. flags = _flags;
  13286. // 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.
  13287. safeInput.setown(new CSafeRoxieInput(_sourceIdx, _input));
  13288. }
  13289. void connectInputStreams(bool consumerOrdered)
  13290. {
  13291. safeInput->connectInputStreams(ctx, consumerOrdered);
  13292. }
  13293. IFinalRoxieInput *queryInput() const
  13294. {
  13295. return safeInput;
  13296. }
  13297. void onCreate(IRoxieSlaveContext * _ctx);
  13298. void start(unsigned parentExtractSize, const byte *parentExtract, bool paused);
  13299. void stop();
  13300. void reset();
  13301. virtual int run();
  13302. protected:
  13303. void executeLoop();
  13304. void executeLoopInstance(unsigned counter, unsigned numIterations, unsigned inputIdx, IFinalRoxieInput * input, SafeRowQueue * spillOutput);
  13305. IFinalRoxieInput * createLoopIterationGraph(unsigned i, unsigned inputIdx, IFinalRoxieInput * input, unsigned counter);
  13306. };
  13307. class CRoxieServerParallelLoopActivity : public CRoxieServerLoopActivity
  13308. {
  13309. friend class LoopFilterPseudoInput;
  13310. friend class LoopExecutorThread;
  13311. QueueOf<const void, true> ready;
  13312. CriticalSection helperCS;
  13313. CriticalSection cs;
  13314. unsigned defaultNumParallel;
  13315. LoopExecutorThread executor;
  13316. IProbeManager* probeManager;
  13317. CriticalSection canAccess;
  13318. CriticalSection scrit;
  13319. InterruptableSemaphore readySpace;
  13320. InterruptableSemaphore recordsReady;
  13321. protected:
  13322. bool includeInLoop(unsigned counter, const void * row)
  13323. {
  13324. CriticalBlock b(helperCS);
  13325. return helper.sendToLoop(counter, row);
  13326. }
  13327. public:
  13328. CRoxieServerParallelLoopActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _loopGraphId, IOutputMetaData * _counterMeta)
  13329. : CRoxieServerLoopActivity(_ctx, _factory, _probeManager, _loopGraphId, _counterMeta),
  13330. readySpace(parallelLoopFlowLimit)
  13331. {
  13332. probeManager = _probeManager;
  13333. defaultNumParallel = 0;
  13334. }
  13335. virtual void onCreate(IHThorArg *_colocalParent)
  13336. {
  13337. CRoxieServerActivity::onCreate(_colocalParent);
  13338. executor.onCreate(ctx);
  13339. }
  13340. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13341. {
  13342. CriticalBlock b(scrit); // can stop while still starting, if unlucky...
  13343. readySpace.reinit(parallelLoopFlowLimit);
  13344. recordsReady.reinit();
  13345. CRoxieServerLoopActivity::start(parentExtractSize, parentExtract, paused);
  13346. defaultNumParallel = helper.defaultParallelIterations();
  13347. if (!defaultNumParallel)
  13348. defaultNumParallel = DEFAULT_PARALLEL_LOOP_THREADS;
  13349. //MORE: If numIterations <= number of parallel iterations[1],
  13350. //then we don't need to create a separate thread to do the processing, and the results will also avoid
  13351. //being transferred via a queue
  13352. executor.start(parentExtractSize, parentExtract, paused);
  13353. }
  13354. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  13355. {
  13356. if (idx)
  13357. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  13358. executor.setInput(this, _sourceIdx, _in, flags);
  13359. }
  13360. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  13361. {
  13362. executor.connectInputStreams(consumerOrdered);
  13363. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, nullptr, consumerOrdered, nullptr);
  13364. }
  13365. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  13366. {
  13367. if (idx==0)
  13368. return executor.queryInput();
  13369. else
  13370. return NULL;
  13371. }
  13372. virtual void stop()
  13373. {
  13374. CriticalBlock b(scrit); // can stop while still starting, if unlucky...
  13375. readySpace.interrupt();
  13376. recordsReady.interrupt();
  13377. executor.join(); // MORE - may not be needed given stop/reset split
  13378. CRoxieServerLoopActivity::stop();
  13379. }
  13380. virtual void reset()
  13381. {
  13382. while (ready.ordinality())
  13383. ReleaseRoxieRow(ready.dequeue());
  13384. executor.reset();
  13385. CRoxieServerActivity::reset();
  13386. }
  13387. virtual const void * nextRow()
  13388. {
  13389. ActivityTimer t(totalCycles, timeActivities);
  13390. loop
  13391. {
  13392. if (eof)
  13393. return NULL;
  13394. recordsReady.wait();
  13395. CriticalBlock procedure(canAccess);
  13396. if (ready.ordinality())
  13397. {
  13398. const void *result = ready.dequeue();
  13399. readySpace.signal();
  13400. if (result)
  13401. processed++;
  13402. return result;
  13403. }
  13404. else
  13405. eof = true;
  13406. }
  13407. }
  13408. unsigned getNumParallel(unsigned iter)
  13409. {
  13410. return defaultNumParallel;
  13411. }
  13412. inline void enqueueResult(const void * row)
  13413. {
  13414. try
  13415. {
  13416. while(!readySpace.wait(1000))
  13417. {
  13418. CTXLOG("Blocked waiting for space in loop %p activity id: %d output queue: %d records in queue", this, queryId(), ready.ordinality());
  13419. }
  13420. }
  13421. catch (...)
  13422. {
  13423. ReleaseRoxieRow(row);
  13424. throw;
  13425. }
  13426. CriticalBlock b2(canAccess);
  13427. ready.enqueue(row);
  13428. recordsReady.signal();
  13429. }
  13430. inline void finishResults()
  13431. {
  13432. recordsReady.signal();
  13433. }
  13434. virtual bool fireException(IException *e)
  13435. {
  13436. readySpace.interrupt(LINK(e));
  13437. recordsReady.interrupt(e);
  13438. return true;
  13439. }
  13440. IActivityGraph * createChildGraphInstance()
  13441. {
  13442. return factory->createChildGraph(ctx, &helper, loopGraphId, this, probeManager, *this);
  13443. }
  13444. IActivityGraph * queryChildGraph()
  13445. {
  13446. return ctx->queryChildGraph(loopGraphId);
  13447. }
  13448. };
  13449. //=================================================================================
  13450. const void * LoopFilterPseudoInput::nextRow()
  13451. {
  13452. loop
  13453. {
  13454. const void * next = stream->nextRow();
  13455. if (!next || activity->includeInLoop(counter, next))
  13456. return next;
  13457. activity->enqueueResult(next);
  13458. }
  13459. }
  13460. void LoopExecutorThread::onCreate(IRoxieSlaveContext * _ctx)
  13461. {
  13462. //Initialise the cached graph list with the child instance that will always be created. Other iterations will be created on demand.
  13463. ctx = _ctx;
  13464. cachedGraphs.append(*LINK(activity->queryChildGraph()));
  13465. }
  13466. void LoopExecutorThread::start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13467. {
  13468. savedParentExtractSize = parentExtractSize;
  13469. savedParentExtract = parentExtract;
  13470. eof = false;
  13471. StringBuffer logPrefix("[");
  13472. ctx->getLogPrefix(logPrefix).append("] ");
  13473. RestartableThread::start(logPrefix);
  13474. }
  13475. int LoopExecutorThread::run()
  13476. {
  13477. try
  13478. {
  13479. executeLoop();
  13480. }
  13481. catch (IException *e)
  13482. {
  13483. activity->fireException(e);
  13484. }
  13485. catch (...)
  13486. {
  13487. activity->fireException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unexpected exception caught in LoopExecutorThread::run"));
  13488. }
  13489. return 0;
  13490. }
  13491. void LoopExecutorThread::stop()
  13492. {
  13493. safeInput->stop();
  13494. RestartableThread::join();
  13495. }
  13496. void LoopExecutorThread::reset()
  13497. {
  13498. safeInput->reset();
  13499. }
  13500. void LoopExecutorThread::executeLoop()
  13501. {
  13502. unsigned iterations = 0;
  13503. unsigned counter = 0;
  13504. unsigned outputIndex = 0;
  13505. //Note, activities don't link inputs, so need to be careful that special inputs remain linked while the activity is executing.
  13506. loop
  13507. {
  13508. if (activity->activityKind == TAKloopcount)
  13509. {
  13510. if (counter == activity->maxIterations)
  13511. break;
  13512. }
  13513. else
  13514. {
  13515. //This condition isn't quite right because it needs to be whether the filtered
  13516. //input is empty. May be ok if we include that in the semantics,
  13517. if (tempResults[1-outputIndex].ordinality() == 0)
  13518. break;
  13519. }
  13520. unsigned numParallel = activity->getNumParallel(iterations);
  13521. Linked<IFinalRoxieInput> curInput;
  13522. if (iterations == 0)
  13523. curInput.set(safeInput);
  13524. else
  13525. {
  13526. SafeRowQueue & inputQueue = tempResults[1-outputIndex];
  13527. inputQueue.enqueue(NULL);
  13528. curInput.setown(new CRowQueuePseudoInput(inputQueue, activity->queryOutputMeta()));
  13529. }
  13530. SafeRowQueue * curOutput = NULL;
  13531. if (counter+numParallel > activity->maxIterations)
  13532. numParallel = activity->maxIterations - counter;
  13533. else if (counter+numParallel < activity->maxIterations)
  13534. curOutput = &tempResults[outputIndex];
  13535. executeLoopInstance(counter, numParallel, 0, curInput, curOutput); // CurInput is always SOME sort of proxy so idx always 0
  13536. outputIndex = 1-outputIndex;
  13537. counter += numParallel;
  13538. iterations++;
  13539. }
  13540. //Check for TAKlooprow, where end of loop couldn't be determined ahead of time
  13541. SafeRowQueue & inputQueue = tempResults[1-outputIndex];
  13542. while (inputQueue.ordinality())
  13543. {
  13544. const void * next = inputQueue.dequeue();
  13545. activity->enqueueResult(next);
  13546. }
  13547. activity->finishResults();
  13548. }
  13549. void LoopExecutorThread::executeLoopInstance(unsigned counter, unsigned numIterations, unsigned inputIdx, IFinalRoxieInput * input, SafeRowQueue * spillOutput)
  13550. {
  13551. IArrayOf<IFinalRoxieInput> savedInputs; // activities don't link their inputs, so this list keeps filters alive.
  13552. Linked<IFinalRoxieInput> curInput = input;
  13553. unsigned i;
  13554. for (i= 0; i != numIterations; i++)
  13555. {
  13556. unsigned thisCounter = counter+i+1;
  13557. IFinalRoxieInput * filtered = curInput;
  13558. if (flags & IHThorLoopArg::LFfiltered)
  13559. {
  13560. LoopFilterPseudoInput *newFiltered = new LoopFilterPseudoInput(activity, thisCounter);
  13561. newFiltered->setInput(inputIdx, curInput);
  13562. filtered = newFiltered;
  13563. savedInputs.append(*filtered);
  13564. inputIdx = 0;
  13565. }
  13566. //graph is kept, so new curInput will be guaranteed to exist
  13567. curInput.setown(createLoopIterationGraph(i, inputIdx, filtered, thisCounter));
  13568. inputIdx = 0;
  13569. }
  13570. Owned<IStrandJunction> curJunction;
  13571. IEngineRowStream *curStream = connectSingleStream(ctx, curInput, inputIdx, curJunction, true);
  13572. try
  13573. {
  13574. curInput->start(savedParentExtractSize, savedParentExtract, false);
  13575. if (spillOutput)
  13576. {
  13577. loop
  13578. {
  13579. const void * next = curStream->nextRow();
  13580. if (!next)
  13581. break;
  13582. spillOutput->enqueue(next);
  13583. }
  13584. }
  13585. else
  13586. {
  13587. loop
  13588. {
  13589. const void * next = curStream->nextRow();
  13590. if (!next)
  13591. break;
  13592. activity->enqueueResult(next);
  13593. }
  13594. }
  13595. }
  13596. catch (IException *E)
  13597. {
  13598. ctx->notifyAbort(E);
  13599. for (i= 0; i != numIterations; i++)
  13600. {
  13601. cachedGraphs.item(i).queryLoopGraph()->afterExecute();
  13602. }
  13603. curStream->stop();
  13604. curInput->reset();
  13605. throw;
  13606. }
  13607. for (i= 0; i != numIterations; i++)
  13608. {
  13609. cachedGraphs.item(i).queryLoopGraph()->afterExecute();
  13610. }
  13611. curStream->stop();
  13612. curInput->reset();
  13613. }
  13614. IFinalRoxieInput * LoopExecutorThread::createLoopIterationGraph(unsigned i, unsigned inputIdx, IFinalRoxieInput * input, unsigned counter)
  13615. {
  13616. if (!cachedGraphs.isItem(i))
  13617. cachedGraphs.append(*activity->createChildGraphInstance());
  13618. Linked<IRoxieServerChildGraph> loopGraph = cachedGraphs.item(i).queryLoopGraph();
  13619. loopGraph->beforeExecute();
  13620. if (!loopGraph->querySetInputResult(1, inputIdx, input))
  13621. throwUnexpected(); // a loop which doesn't use the value from the previous iteration. Should probably handle even if daft.
  13622. activity->createCounterResult(loopGraph, counter);
  13623. return loopGraph->selectOutput(0);
  13624. }
  13625. //=================================================================================
  13626. class CCounterRowMetaData : public CInterface, implements IOutputMetaData
  13627. {
  13628. public:
  13629. IMPLEMENT_IINTERFACE
  13630. virtual size32_t getRecordSize(const void *) { return sizeof(thor_loop_counter_t); }
  13631. virtual size32_t getMinRecordSize() const { return sizeof(thor_loop_counter_t); }
  13632. virtual size32_t getFixedSize() const { return sizeof(thor_loop_counter_t); }
  13633. virtual void toXML(const byte * self, IXmlWriter & out) { }
  13634. virtual unsigned getVersion() const { return OUTPUTMETADATA_VERSION; }
  13635. virtual unsigned getMetaFlags() { return 0; }
  13636. virtual void destruct(byte * self) {}
  13637. virtual IOutputRowSerializer * createDiskSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  13638. virtual IOutputRowDeserializer * createDiskDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  13639. virtual ISourceRowPrefetcher * createDiskPrefetcher(ICodeContext * ctx, unsigned activityId) { return NULL; }
  13640. virtual IOutputMetaData * querySerializedDiskMeta() { return this; }
  13641. virtual IOutputRowSerializer * createInternalSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  13642. virtual IOutputRowDeserializer * createInternalDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  13643. virtual void walkIndirectMembers(const byte * self, IIndirectMemberVisitor & visitor) {}
  13644. virtual IOutputMetaData * queryChildMeta(unsigned i) { return NULL; }
  13645. };
  13646. class CRoxieServerLoopActivityFactory : public CRoxieServerActivityFactory
  13647. {
  13648. unsigned loopGraphId;
  13649. unsigned flags;
  13650. Linked<IOutputMetaData> counterMeta;
  13651. public:
  13652. CRoxieServerLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _loopGraphId)
  13653. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), loopGraphId(_loopGraphId)
  13654. {
  13655. Owned<IHThorLoopArg> helper = (IHThorLoopArg *) helperFactory();
  13656. flags = helper->getFlags();
  13657. counterMeta.setown(new CCounterRowMetaData);
  13658. }
  13659. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  13660. {
  13661. if (flags & IHThorLoopArg::LFparallel)
  13662. return new CRoxieServerParallelLoopActivity(_ctx, this, _probeManager, loopGraphId, counterMeta);
  13663. else
  13664. return new CRoxieServerSequentialLoopActivity(_ctx, this, _probeManager, loopGraphId, counterMeta);
  13665. }
  13666. };
  13667. IRoxieServerActivityFactory *createRoxieServerLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _loopGraphId)
  13668. {
  13669. return new CRoxieServerLoopActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _loopGraphId);
  13670. }
  13671. //=================================================================================
  13672. class CRoxieServerGraphLoopActivity : public CRoxieServerActivity
  13673. {
  13674. protected:
  13675. IHThorGraphLoopArg &helper;
  13676. unsigned maxIterations;
  13677. unsigned flags;
  13678. rtlRowBuilder GraphExtractBuilder;
  13679. unsigned loopGraphId;
  13680. Linked<IOutputMetaData> counterMeta;
  13681. public:
  13682. CRoxieServerGraphLoopActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _GraphGraphId, IOutputMetaData * _counterMeta)
  13683. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  13684. helper((IHThorGraphLoopArg &)basehelper), loopGraphId(_GraphGraphId), counterMeta(_counterMeta)
  13685. {
  13686. flags = helper.getFlags();
  13687. maxIterations = 0;
  13688. }
  13689. virtual bool needsAllocator() const { return true; }
  13690. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13691. {
  13692. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  13693. int iterations = (int) helper.numIterations();
  13694. maxIterations = (iterations >= 0) ? iterations : 0;
  13695. if (maxIterations > maxGraphLoopIterations)
  13696. throw MakeStringException(ROXIE_TOO_MANY_GRAPH_LOOP, "Attempt to execute graph %u times", maxIterations);
  13697. if (maxIterations != 0)
  13698. {
  13699. GraphExtractBuilder.clear();
  13700. helper.createParentExtract(GraphExtractBuilder);
  13701. }
  13702. }
  13703. virtual void stop()
  13704. {
  13705. CRoxieServerActivity::stop();
  13706. GraphExtractBuilder.clear();
  13707. }
  13708. void createCounterResult(IRoxieServerChildGraph * graph, unsigned counter)
  13709. {
  13710. if (flags & IHThorGraphLoopArg::GLFcounter)
  13711. {
  13712. void * counterRow = ctx->queryRowManager().allocate(sizeof(thor_loop_counter_t), activityId);
  13713. *((thor_loop_counter_t *)counterRow) = counter;
  13714. RtlLinkedDatasetBuilder builder(rowAllocator);
  13715. builder.appendOwn(counterRow);
  13716. Owned<CGraphResult> counterResult = new CGraphResult(builder.getcount(), builder.linkrows());
  13717. graph->setInputResult(0, counterResult);
  13718. }
  13719. }
  13720. };
  13721. //=================================================================================
  13722. class CRoxieServerSequentialGraphLoopActivity : public CRoxieServerGraphLoopActivity
  13723. {
  13724. Owned<IActivityGraph> GraphQuery;
  13725. Owned<IRoxieServerChildGraph> loopGraph;
  13726. Linked<IEngineRowStream> resultStream;
  13727. bool evaluated;
  13728. public:
  13729. CRoxieServerSequentialGraphLoopActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _GraphGraphId, IOutputMetaData * _counterMeta)
  13730. : CRoxieServerGraphLoopActivity(_ctx, _factory, _probeManager, _GraphGraphId, _counterMeta)
  13731. {
  13732. evaluated = false;
  13733. }
  13734. virtual void onCreate(IHThorArg *_colocalParent)
  13735. {
  13736. CRoxieServerGraphLoopActivity::onCreate(_colocalParent);
  13737. GraphQuery.set(ctx->queryChildGraph(loopGraphId));
  13738. }
  13739. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13740. {
  13741. CRoxieServerGraphLoopActivity::start(parentExtractSize, parentExtract, paused);
  13742. //MORE: Not sure about this, should IRoxieServerChildGraph be combined with IActivityGraph?
  13743. loopGraph.set(GraphQuery->queryLoopGraph());
  13744. evaluated = false;
  13745. }
  13746. virtual void stop()
  13747. {
  13748. if (loopGraph)
  13749. loopGraph->clearGraphLoopResults();
  13750. CRoxieServerGraphLoopActivity::stop();
  13751. }
  13752. virtual const void * nextRow()
  13753. {
  13754. ActivityTimer t(totalCycles, timeActivities);
  13755. if (!evaluated)
  13756. {
  13757. executeEntireGraph();
  13758. evaluated = true;
  13759. }
  13760. const void * ret = resultStream->nextRow();
  13761. if (ret)
  13762. processed++;
  13763. return ret;
  13764. }
  13765. void executeIteration(unsigned parentExtractSize, const byte *parentExtract, unsigned counter)
  13766. {
  13767. try
  13768. {
  13769. loopGraph->beforeExecute();
  13770. createCounterResult(loopGraph, counter);
  13771. loopGraph->executeGraphLoop(parentExtractSize, parentExtract);
  13772. loopGraph->afterExecute();
  13773. }
  13774. catch (...)
  13775. {
  13776. CTXLOG("Exception thrown in graph body - cleaning up");
  13777. loopGraph->afterExecute();
  13778. throw;
  13779. }
  13780. }
  13781. void createInitialGraphInput()
  13782. {
  13783. loopGraph->clearGraphLoopResults();
  13784. RtlLinkedDatasetBuilder builder(rowAllocator);
  13785. inputStream->readAll(builder);
  13786. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  13787. loopGraph->setGraphLoopResult(0, result);
  13788. }
  13789. void executeEntireGraph()
  13790. {
  13791. createInitialGraphInput();
  13792. for (unsigned loopCounter=1; loopCounter <= maxIterations; loopCounter++)
  13793. {
  13794. executeIteration(GraphExtractBuilder.size(), GraphExtractBuilder.getbytes(), loopCounter);
  13795. }
  13796. resultStream.setown(loopGraph->getGraphLoopResult(maxIterations));
  13797. }
  13798. };
  13799. //=================================================================================
  13800. struct GraphOutputSplitterArg : public ccdserver_hqlhelper::CThorSplitArg
  13801. {
  13802. public:
  13803. virtual unsigned numBranches()
  13804. {
  13805. return 0;
  13806. }
  13807. virtual IOutputMetaData * queryOutputMeta()
  13808. {
  13809. return NULL;// get it from the parent..
  13810. }
  13811. };
  13812. extern "C" IHThorArg * createGraphOutputSplitter() { return new GraphOutputSplitterArg; }
  13813. class CGraphIterationInfo : public CInterface
  13814. {
  13815. private:
  13816. Owned<IRoxieServerActivityFactory> factory; // Note - before sourceAct, so destroyed last
  13817. unsigned sourceIdx;
  13818. Linked<IRoxieServerActivity> sourceAct;
  13819. Linked<IFinalRoxieInput> sourceInput;
  13820. unsigned numUses;
  13821. unsigned iteration;
  13822. public:
  13823. CGraphIterationInfo(IRoxieServerActivity * _sourceAct, IFinalRoxieInput *_input, unsigned _sourceIdx, unsigned _iteration)
  13824. : sourceAct(_sourceAct), sourceInput(_input), sourceIdx(_sourceIdx), iteration(_iteration)
  13825. {
  13826. numUses = 0;
  13827. }
  13828. inline void noteUsed()
  13829. {
  13830. numUses++;
  13831. }
  13832. void createSplitter(IRoxieSlaveContext *ctx, IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes)
  13833. {
  13834. if (numUses > 1)
  13835. {
  13836. Owned<IPropertyTree> splitterNode = createPTree();
  13837. factory.setown(createRoxieServerThroughSpillActivityFactory(sourceAct->queryFactory()->queryQueryFactory(), createGraphOutputSplitter, numUses, *splitterNode));
  13838. IRoxieServerActivity *splitter = factory->createActivity(ctx, NULL);
  13839. splitter->onCreate(NULL);
  13840. IFinalRoxieInput *input = sourceAct->queryOutput(sourceIdx);
  13841. if (probeManager)
  13842. {
  13843. IRoxieProbe * inputProbe = probeManager->createProbe(static_cast<IInputBase*>(input), sourceAct, splitter, sourceIdx, 0, iteration);
  13844. probes.append(*LINK(inputProbe));
  13845. input = &dynamic_cast<IFinalRoxieInput &>(inputProbe->queryInput());
  13846. sourceIdx = 0;
  13847. }
  13848. sourceAct.setown(splitter);
  13849. sourceAct->setInput(0, sourceIdx, input);
  13850. sourceIdx = 0;
  13851. sourceInput.clear();
  13852. }
  13853. }
  13854. IFinalRoxieInput *connectOutput(IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes, IRoxieServerActivity *targetAct, unsigned targetIdx)
  13855. {
  13856. // MORE - not really necessary to create splitters in separate pass, is it?
  13857. if (factory) // we created a splitter....
  13858. sourceInput.set(sourceAct->queryOutput(sourceIdx));
  13859. IFinalRoxieInput *ret = sourceInput;
  13860. if (probeManager)
  13861. {
  13862. IRoxieProbe * inputProbe = probeManager->createProbe(sourceInput, sourceAct, targetAct, sourceIdx, targetIdx, iteration);
  13863. probes.append(*LINK(inputProbe));
  13864. ret = &dynamic_cast<IFinalRoxieInput &>(inputProbe->queryInput());
  13865. // MORE - do we need to connect the stream in the probe?
  13866. }
  13867. if (factory) // we created a splitter....
  13868. sourceIdx++;
  13869. return ret;
  13870. }
  13871. };
  13872. class CRoxieServerParallelGraphLoopActivity : public CRoxieServerGraphLoopActivity, implements IRoxieServerLoopResultProcessor
  13873. {
  13874. Owned<IActivityGraph> childGraph;
  13875. IFinalRoxieInput * resultInput;
  13876. IEngineRowStream * resultStream;
  13877. Owned<IStrandJunction> resultJunction;
  13878. CIArrayOf<CGraphIterationInfo> outputs;
  13879. IArrayOf<IRoxieServerChildGraph> iterationGraphs;
  13880. Owned<CExtractMapperInput> inputExtractMapper;
  13881. IProbeManager *probeManager;
  13882. unsigned createLoopCounter;
  13883. IArrayOf<IRoxieProbe> probes;
  13884. public:
  13885. CRoxieServerParallelGraphLoopActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _GraphGraphId, IOutputMetaData * _counterMeta)
  13886. : CRoxieServerGraphLoopActivity(_ctx, _factory, _probeManager, _GraphGraphId, _counterMeta), probeManager(_probeManager)
  13887. {
  13888. inputExtractMapper.setown(new CExtractMapperInput);
  13889. resultInput = NULL;
  13890. resultStream = NULL;
  13891. createLoopCounter = 0;
  13892. }
  13893. virtual void onCreate(IHThorArg *_colocalParent)
  13894. {
  13895. CRoxieServerGraphLoopActivity::onCreate(_colocalParent);
  13896. childGraph.set(ctx->queryChildGraph(loopGraphId));
  13897. }
  13898. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  13899. {
  13900. //Input needs to be handled very carefully.....
  13901. //We don't want to call onStart on the input unless it is actually used, so don't use the base CRoxieServerActivity implementation.
  13902. //This activity's input needs to be started with (parentExtractSize, parentExtract), but the elements in the graph need to be started with the
  13903. //GraphExtractBuilder parent extract. So we need to wrap the input in a pseudo-input (inputExtractMapper) that passes through a different
  13904. //parentExtract. Something very similar will be needed for query library calls with streaming inputs when they are implemented.
  13905. assertex(idx == 0);
  13906. inputExtractMapper->setInput(_sourceIdx, _in);
  13907. }
  13908. virtual void connectInputStreams(bool consumerOrdered)
  13909. {
  13910. //NB: inputExtractMapper is not connected at this point - only if/when it is used from within the graph
  13911. CRoxieServerActivity::connectInputStreams(consumerOrdered);
  13912. }
  13913. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  13914. {
  13915. if (idx==0)
  13916. return inputExtractMapper->queryInput();
  13917. else
  13918. return NULL;
  13919. }
  13920. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13921. {
  13922. CRoxieServerGraphLoopActivity::start(parentExtractSize, parentExtract, paused); // initialises GraphExtractBuilder
  13923. inputExtractMapper->setParentExtract(parentExtractSize, parentExtract);
  13924. createExpandedGraph(GraphExtractBuilder.size(), GraphExtractBuilder.getbytes(), probeManager);
  13925. resultInput->start(GraphExtractBuilder.size(), GraphExtractBuilder.getbytes(), paused);
  13926. startJunction(resultJunction);
  13927. }
  13928. virtual void stop()
  13929. {
  13930. if (resultStream)
  13931. resultStream->stop();
  13932. CRoxieServerGraphLoopActivity::stop();
  13933. }
  13934. virtual void reset()
  13935. {
  13936. if (resultInput)
  13937. resultInput->reset();
  13938. resetJunction(resultJunction);
  13939. resultInput = NULL;
  13940. resultStream = NULL;
  13941. resultJunction.clear();
  13942. outputs.kill();
  13943. iterationGraphs.kill(); // must be done after all activities killed
  13944. if (probeManager)
  13945. {
  13946. probeManager->deleteGraph(NULL, (IArrayOf<IInputBase>*)&probes);
  13947. probes.kill();
  13948. }
  13949. CRoxieServerGraphLoopActivity::reset();
  13950. }
  13951. virtual const void * nextRow()
  13952. {
  13953. ActivityTimer t(totalCycles, timeActivities);
  13954. const void * ret = resultStream->nextRow();
  13955. if (ret)
  13956. processed++;
  13957. return ret;
  13958. }
  13959. void createExpandedGraph(unsigned parentExtractSize, const byte *parentExtract, IProbeManager *probeManager)
  13960. {
  13961. //result(0) is the input to the graph.
  13962. resultInput = inputExtractMapper;
  13963. outputs.append(* new CGraphIterationInfo(resultInput->queryActivity(), resultInput, 0, 1));
  13964. for (createLoopCounter=1; createLoopCounter <= maxIterations; createLoopCounter++)
  13965. {
  13966. IRoxieServerChildGraph * graph = childGraph->createGraphLoopInstance(ctx, createLoopCounter, parentExtractSize, parentExtract, *this);
  13967. graph->beforeExecute();
  13968. iterationGraphs.append(*graph);
  13969. graph->gatherIterationUsage(*this);
  13970. CGraphIterationInfo *iteration = graph->selectGraphLoopOutput();
  13971. outputs.append(*iteration);
  13972. }
  13973. createLoopCounter = 0;
  13974. createSplitters(probeManager, probes);
  13975. ForEachItemIn(i2, iterationGraphs)
  13976. iterationGraphs.item(i2).associateIterationOutputs(*this);
  13977. resultInput = outputs.tos().connectOutput(probeManager, probes, this, 0);
  13978. resultStream = connectSingleStream(ctx, resultInput, 0, resultJunction, true);
  13979. }
  13980. void createSplitters(IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes)
  13981. {
  13982. ForEachItemIn(i, outputs)
  13983. {
  13984. CGraphIterationInfo & next = outputs.item(i);
  13985. next.createSplitter(ctx, probeManager, probes);
  13986. }
  13987. }
  13988. //IRoxieServerLoopResultProcessor
  13989. virtual void noteUseIteration(unsigned _whichIteration)
  13990. {
  13991. int whichIteration = (int) _whichIteration; // May go negative - API is unsigned for historical reasons
  13992. if (whichIteration >= 0)
  13993. {
  13994. if (!outputs.isItem(whichIteration))
  13995. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Error reading graph result %d from iteration %d", whichIteration, createLoopCounter);
  13996. outputs.item(whichIteration).noteUsed();
  13997. }
  13998. }
  13999. virtual IFinalRoxieInput* connectIterationOutput(unsigned whichIteration, IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes, IRoxieServerActivity *targetAct, unsigned targetIdx)
  14000. {
  14001. if (outputs.isItem(whichIteration))
  14002. {
  14003. CGraphIterationInfo & next = outputs.item(whichIteration);
  14004. return next.connectOutput(probeManager, probes, targetAct, targetIdx);
  14005. }
  14006. return NULL;
  14007. }
  14008. };
  14009. //=================================================================================
  14010. class CRoxieServerGraphLoopActivityFactory : public CRoxieServerActivityFactory
  14011. {
  14012. unsigned loopGraphId;
  14013. unsigned flags;
  14014. Linked<IOutputMetaData> counterMeta;
  14015. public:
  14016. CRoxieServerGraphLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _loopGraphId)
  14017. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), loopGraphId(_loopGraphId)
  14018. {
  14019. Owned<IHThorGraphLoopArg> helper = (IHThorGraphLoopArg *) helperFactory();
  14020. flags = helper->getFlags();
  14021. counterMeta.setown(new CCounterRowMetaData);
  14022. }
  14023. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  14024. {
  14025. if (kind == TAKparallelgraphloop)
  14026. return new CRoxieServerParallelGraphLoopActivity(_ctx, this, _probeManager, loopGraphId, counterMeta);
  14027. else
  14028. return new CRoxieServerSequentialGraphLoopActivity(_ctx, this, _probeManager, loopGraphId, counterMeta);
  14029. }
  14030. };
  14031. IRoxieServerActivityFactory *createRoxieServerGraphLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _loopGraphId)
  14032. {
  14033. return new CRoxieServerGraphLoopActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _loopGraphId);
  14034. }
  14035. //=====================================================================================================
  14036. class CRoxieServerLibraryCallActivity : public CRoxieServerActivity
  14037. {
  14038. class OutputAdaptor : public CExtractMapperInput
  14039. {
  14040. bool stopped;
  14041. public:
  14042. CRoxieServerLibraryCallActivity *parent;
  14043. IOutputMetaData * meta = nullptr;
  14044. unsigned oid;
  14045. unsigned processed;
  14046. public:
  14047. IMPLEMENT_IINTERFACE;
  14048. OutputAdaptor()
  14049. {
  14050. parent = NULL;
  14051. oid = 0;
  14052. init();
  14053. }
  14054. ~OutputAdaptor()
  14055. {
  14056. if (traceStartStop)
  14057. DBGLOG("%p ~OutputAdaptor %d", this, oid);
  14058. if (processed && parent && parent->factory)
  14059. {
  14060. parent->factory->noteProcessed(oid, processed);
  14061. if (parent->ctx)
  14062. parent->ctx->noteProcessed(parent->querySubgraphId(), parent->activityId, oid, processed, 0);
  14063. }
  14064. }
  14065. void setParent(CRoxieServerLibraryCallActivity * _parent, IOutputMetaData * _meta, unsigned _oid)
  14066. {
  14067. parent = _parent;
  14068. meta = _meta;
  14069. oid = _oid;
  14070. }
  14071. void init()
  14072. {
  14073. processed = 0;
  14074. stopped = false;
  14075. }
  14076. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14077. {
  14078. parent->start(oid, parentExtractSize, parentExtract, paused);
  14079. CExtractMapperInput::start(parentExtractSize, parentExtract, paused);
  14080. }
  14081. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  14082. {
  14083. //MORE value of consumerOrdered depends on whether this activity is marked as ordered.
  14084. if (!oid) // Only need to set up once
  14085. {
  14086. parent->connectInputStreams(true); // To handle dependencies etc
  14087. }
  14088. return CExtractMapperInput::getOutputStreams(ctx, 0, streams, nullptr, true, nullptr);
  14089. }
  14090. //This override should not really be needed, but input is set up too late for the call to connect strands
  14091. virtual IOutputMetaData * queryOutputMeta() const
  14092. {
  14093. return meta;
  14094. }
  14095. virtual void stop()
  14096. {
  14097. if (!stopped)
  14098. {
  14099. stopped = true;
  14100. parent->stop(oid); // parent code relies on stop being called exactly once per adaptor, so make sure it is!
  14101. CExtractMapperInput::stop();
  14102. }
  14103. };
  14104. virtual void reset()
  14105. {
  14106. parent->reset(oid);
  14107. CExtractMapperInput::reset();
  14108. init();
  14109. };
  14110. virtual void checkAbort()
  14111. {
  14112. parent->checkAbort();
  14113. }
  14114. };
  14115. IHThorLibraryCallArg &helper;
  14116. unsigned numInputs;
  14117. unsigned numOutputs;
  14118. unsigned numActiveOutputs;
  14119. bool started;
  14120. OutputAdaptor* outputAdaptors;
  14121. CExtractMapperInput * * inputAdaptors;
  14122. bool * inputUsed;
  14123. bool * outputUsed;
  14124. Owned<IException> error;
  14125. CriticalSection crit;
  14126. rtlRowBuilder libraryExtractBuilder;
  14127. Owned<IActivityGraph> libraryGraph;
  14128. const LibraryCallFactoryExtra & extra;
  14129. public:
  14130. CRoxieServerLibraryCallActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs, unsigned _numOutputs, const LibraryCallFactoryExtra & _extra)
  14131. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  14132. helper((IHThorLibraryCallArg &)basehelper), extra(_extra)
  14133. {
  14134. numInputs = _numInputs;
  14135. numOutputs = _numOutputs;
  14136. numActiveOutputs = numOutputs;
  14137. inputAdaptors = new CExtractMapperInput*[numInputs];
  14138. inputUsed = new bool[numInputs];
  14139. for (unsigned i1 = 0; i1 < numInputs; i1++)
  14140. {
  14141. inputAdaptors[i1] = new CExtractMapperInput;
  14142. inputUsed[i1] = false;
  14143. }
  14144. outputAdaptors = new OutputAdaptor[numOutputs];
  14145. outputUsed = new bool[numOutputs];
  14146. for (unsigned i2 = 0; i2 < numOutputs; i2++)
  14147. {
  14148. outputAdaptors[i2].setParent(this, helper.queryOutputMeta(i2), i2);
  14149. outputUsed[i2] = false;
  14150. }
  14151. started = false;
  14152. }
  14153. ~CRoxieServerLibraryCallActivity()
  14154. {
  14155. for (unsigned i1 = 0; i1 < numInputs; i1++)
  14156. ::Release(inputAdaptors[i1]);
  14157. delete [] inputAdaptors;
  14158. delete [] inputUsed;
  14159. delete [] outputAdaptors;
  14160. delete [] outputUsed;
  14161. }
  14162. virtual void onCreate(IHThorArg *_colocalParent)
  14163. {
  14164. CRoxieServerActivity::onCreate(_colocalParent);
  14165. libraryGraph.setown(ctx->getLibraryGraph(extra, this));
  14166. libraryGraph->onCreate(_colocalParent);
  14167. //Now map the inputs and outputs to the adapters
  14168. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  14169. for (unsigned i1=0; i1<numInputs; i1++)
  14170. inputUsed[i1] = graph->querySetInputResult(i1, 0, inputAdaptors[i1]);
  14171. for (unsigned i2=0; i2<numOutputs; i2++)
  14172. {
  14173. unsigned outputIndex = extra.outputs.item(i2);
  14174. Owned<IFinalRoxieInput> output = graph->selectOutput(numInputs+outputIndex);
  14175. outputAdaptors[i2].setInput(0, output); // MORE - no idea if this 0 is right??
  14176. outputAdaptors[i2].connectInputStreams(ctx, true);
  14177. }
  14178. }
  14179. virtual void start(unsigned oid, unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14180. {
  14181. CriticalBlock b(crit);
  14182. if (error)
  14183. throw error.getLink();
  14184. if (factory)
  14185. factory->noteStarted(oid);
  14186. if (!started)
  14187. {
  14188. // even though it is not complete, we don't want to run this again if it fails.
  14189. started = true;
  14190. //see notes on splitter above
  14191. try
  14192. {
  14193. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14194. }
  14195. catch (IException *E)
  14196. {
  14197. #ifdef TRACE_SPLIT
  14198. CTXLOG("spill %d caught exception in start", activityId);
  14199. #endif
  14200. error.set(E);
  14201. throw;
  14202. }
  14203. catch (...)
  14204. {
  14205. IException *E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught in CRoxieServerLibraryCallActivity::start");
  14206. error.set(E);
  14207. throw E;
  14208. }
  14209. //recreate the parent extract, and use it to reinitialize the graphs...
  14210. libraryExtractBuilder.clear();
  14211. helper.createParentExtract(libraryExtractBuilder);
  14212. // 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
  14213. // some inputs before we see start on others.
  14214. for (unsigned i1 = 0; i1 < numInputs; i1++)
  14215. {
  14216. if (inputUsed[i1])
  14217. inputAdaptors[i1]->setParentExtract(parentExtractSize, parentExtract);
  14218. else
  14219. inputAdaptors[i1]->stop();
  14220. }
  14221. for (unsigned i2 = 0; i2 < numOutputs; i2++)
  14222. outputAdaptors[i2].setParentExtract(libraryExtractBuilder.size(), libraryExtractBuilder.getbytes());
  14223. //call stop on all the unused inputs.
  14224. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  14225. graph->beforeExecute();
  14226. ForEachItemIn(i3, extra.unusedOutputs)
  14227. {
  14228. Owned<IFinalRoxieInput> output = graph->selectOutput(numInputs+extra.unusedOutputs.item(i3));
  14229. // output->queryStream().stop(); Is this needed??
  14230. }
  14231. }
  14232. }
  14233. virtual void stop(unsigned oid)
  14234. {
  14235. CriticalBlock b(crit);
  14236. if (--numActiveOutputs == 0)
  14237. {
  14238. //call stop on all the unused inputs.
  14239. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  14240. graph->beforeExecute();
  14241. ForEachItemIn(i3, extra.unusedOutputs)
  14242. {
  14243. Owned<IFinalRoxieInput> output = graph->selectOutput(numInputs+extra.unusedOutputs.item(i3));
  14244. // Is this needed ?? output->queryStream().stop();
  14245. }
  14246. CRoxieServerActivity::stop();
  14247. }
  14248. }
  14249. void reset(unsigned oid)
  14250. {
  14251. started = false;
  14252. error.clear();
  14253. numActiveOutputs = numOutputs;
  14254. if (state != STATEreset) // make sure input is only reset once
  14255. {
  14256. CRoxieServerActivity::reset();
  14257. libraryGraph->reset();
  14258. //Call reset on all unused inputs/outputs from the graph - no one else will.
  14259. for (unsigned i1 = 0; i1 < numInputs; i1++)
  14260. {
  14261. if (!inputUsed[i1])
  14262. inputAdaptors[i1]->reset();
  14263. }
  14264. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  14265. ForEachItemIn(i3, extra.unusedOutputs)
  14266. {
  14267. Owned<IFinalRoxieInput> output = graph->selectOutput(numInputs+extra.unusedOutputs.item(i3));
  14268. output->reset();
  14269. }
  14270. }
  14271. };
  14272. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  14273. {
  14274. inputAdaptors[idx]->setInput(_sourceIdx, _in);
  14275. }
  14276. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  14277. {
  14278. if (idx < numInputs && inputAdaptors[idx])
  14279. return inputAdaptors[idx]->queryInput();
  14280. else
  14281. return NULL;
  14282. }
  14283. public:
  14284. virtual const void *nextRow()
  14285. {
  14286. throwUnexpected(); // Internal logic error - we are not anybody's input
  14287. }
  14288. virtual IOutputMetaData * queryOutputMeta() const
  14289. {
  14290. throwUnexpected(); // should be called on outputs instead
  14291. }
  14292. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  14293. {
  14294. assertex(idx!=(unsigned)-1);
  14295. assertex(!outputUsed[idx]);
  14296. outputUsed[idx] = true;
  14297. return &outputAdaptors[idx];
  14298. }
  14299. };
  14300. void LibraryCallFactoryExtra::set(const LibraryCallFactoryExtra & _other)
  14301. {
  14302. ForEachItemIn(i1, _other.outputs)
  14303. outputs.append(_other.outputs.item(i1));
  14304. ForEachItemIn(i2, _other.unusedOutputs)
  14305. unusedOutputs.append(_other.unusedOutputs.item(i2));
  14306. maxOutputs = _other.maxOutputs;
  14307. graphid = _other.graphid;
  14308. libraryName.set(_other.libraryName);
  14309. embeddedGraphName.set(_other.embeddedGraphName);
  14310. interfaceHash = _other.interfaceHash;
  14311. embedded = _other.embedded;
  14312. }
  14313. void LibraryCallFactoryExtra::calcUnused()
  14314. {
  14315. for (unsigned i=0; i < maxOutputs; i++)
  14316. if (!outputs.contains(i))
  14317. unusedOutputs.append(i);
  14318. }
  14319. class CRoxieServerLibraryCallActivityFactory : public CRoxieServerMultiOutputFactory
  14320. {
  14321. private:
  14322. CRoxieServerMultiInputInfo inputs;
  14323. LibraryCallFactoryExtra extra;
  14324. public:
  14325. CRoxieServerLibraryCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, LibraryCallFactoryExtra & _extra)
  14326. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  14327. {
  14328. extra.set(_extra);
  14329. extra.calcUnused();
  14330. setNumOutputs(extra.outputs.ordinality());
  14331. }
  14332. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  14333. {
  14334. return new CRoxieServerLibraryCallActivity(_ctx, this, _probeManager, numInputs(), numOutputs, extra);
  14335. }
  14336. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  14337. {
  14338. inputs.set(idx, source, sourceidx);
  14339. }
  14340. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  14341. {
  14342. return inputs.get(idx, sourceidx);
  14343. }
  14344. virtual unsigned numInputs() const { return inputs.ordinality(); }
  14345. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  14346. {
  14347. addXrefLibraryInfo(reply, extra.libraryName);
  14348. }
  14349. };
  14350. IRoxieServerActivityFactory *createRoxieServerLibraryCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, LibraryCallFactoryExtra & _extra)
  14351. {
  14352. return new CRoxieServerLibraryCallActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _extra);
  14353. }
  14354. //=====================================================================================================
  14355. // CRoxieServerNWayInputActivity is a multi-input, multi-output activity, where the outputs are a subset of the inputs
  14356. // Used to implement RANGE(<rowset-expression>, [set-of-indices])
  14357. class CRoxieServerNWayInputBaseActivity : public CRoxieServerMultiInputBaseActivity
  14358. {
  14359. protected:
  14360. PointerArrayOf<IFinalRoxieInput> selectedInputs;
  14361. PointerArrayOf<IEngineRowStream> selectedStreams;
  14362. public:
  14363. CRoxieServerNWayInputBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14364. : CRoxieServerMultiInputBaseActivity(_ctx, _factory, _probeManager, _numInputs)
  14365. {
  14366. }
  14367. virtual void stop()
  14368. {
  14369. ForEachItemIn(i2, selectedStreams)
  14370. selectedStreams.item(i2)->stop();
  14371. CRoxieServerMultiInputBaseActivity::stop();
  14372. }
  14373. virtual unsigned __int64 queryLocalCycles() const
  14374. {
  14375. __int64 localCycles = totalCycles.totalCycles;
  14376. ForEachItemIn(i, selectedInputs)
  14377. {
  14378. localCycles -= selectedInputs.item(i)->queryTotalCycles();
  14379. }
  14380. if (localCycles < 0)
  14381. localCycles = 0;
  14382. return localCycles;
  14383. }
  14384. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  14385. {
  14386. if (selectedInputs.isItem(idx))
  14387. return selectedInputs.item(idx);
  14388. else
  14389. return NULL;
  14390. }
  14391. virtual void reset()
  14392. {
  14393. ForEachItemIn(i, selectedInputs)
  14394. selectedInputs.item(i)->reset();
  14395. selectedInputs.kill();
  14396. selectedStreams.kill();
  14397. CRoxieServerMultiInputBaseActivity::reset();
  14398. }
  14399. virtual const void * nextRow()
  14400. {
  14401. throwUnexpected();
  14402. }
  14403. virtual unsigned numConcreteOutputs() const
  14404. {
  14405. return selectedInputs.ordinality();
  14406. }
  14407. virtual IFinalRoxieInput * queryConcreteInput(unsigned idx)
  14408. {
  14409. if (selectedInputs.isItem(idx))
  14410. return selectedInputs.item(idx);
  14411. return NULL;
  14412. }
  14413. };
  14414. class CRoxieServerNWayInputActivity : public CRoxieServerNWayInputBaseActivity
  14415. {
  14416. IHThorNWayInputArg & helper;
  14417. public:
  14418. CRoxieServerNWayInputActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14419. : CRoxieServerNWayInputBaseActivity(_ctx, _factory, _probeManager, _numInputs), helper((IHThorNWayInputArg &)basehelper)
  14420. {
  14421. }
  14422. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14423. {
  14424. CRoxieServerNWayInputBaseActivity::start(parentExtractSize, parentExtract, paused);
  14425. bool selectionIsAll;
  14426. size32_t selectionLen;
  14427. rtlDataAttr selection;
  14428. helper.getInputSelection(selectionIsAll, selectionLen, selection.refdata());
  14429. selectedInputs.kill();
  14430. assertex(numInputs==numStreams); // Will need refactoring when that ceases to be true
  14431. if (selectionIsAll)
  14432. {
  14433. for (unsigned i=0; i < numInputs; i++)
  14434. {
  14435. selectedInputs.append(inputArray[i]);
  14436. selectedStreams.append(streamArray[i]); // Assumes 1:1 relationship - is that good?
  14437. }
  14438. }
  14439. else
  14440. {
  14441. const size32_t * selections = (const size32_t *)selection.getdata();
  14442. unsigned max = selectionLen/sizeof(size32_t);
  14443. for (unsigned i = 0; i < max; i++)
  14444. {
  14445. unsigned nextIndex = selections[i];
  14446. //Check there are no duplicates..... Assumes there are a fairly small number of inputs, so n^2 search is ok.
  14447. for (unsigned j=i+1; j < max; j++)
  14448. {
  14449. if (nextIndex == selections[j])
  14450. throw MakeStringException(ROXIE_NWAY_INPUT_ERROR, "Selection list for nway input can not contain duplicates");
  14451. }
  14452. if (nextIndex > numInputs || nextIndex > numStreams)
  14453. throw MakeStringException(ROXIE_NWAY_INPUT_ERROR, "Index %d in RANGE selection list is out of range", nextIndex);
  14454. selectedInputs.append(inputArray[nextIndex-1]);
  14455. selectedStreams.append(streamArray[nextIndex-1]); // Assumes 1:1 relationship - is that good?
  14456. }
  14457. }
  14458. ForEachItemIn(i2, selectedInputs)
  14459. selectedInputs.item(i2)->start(parentExtractSize, parentExtract, paused);
  14460. }
  14461. };
  14462. class CRoxieServerNWayInputActivityFactory : public CRoxieServerMultiInputFactory
  14463. {
  14464. public:
  14465. CRoxieServerNWayInputActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  14466. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  14467. {
  14468. }
  14469. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  14470. {
  14471. return new CRoxieServerNWayInputActivity(_ctx, this, _probeManager, numInputs());
  14472. }
  14473. };
  14474. IRoxieServerActivityFactory *createRoxieServerNWayInputActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  14475. {
  14476. return new CRoxieServerNWayInputActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  14477. }
  14478. //=====================================================================================================
  14479. class CRoxieServerNWayGraphLoopResultReadActivity : public CRoxieServerNWayInputBaseActivity
  14480. {
  14481. IHThorNWayGraphLoopResultReadArg & helper;
  14482. CIArrayOf<CRoxieServerActivity> resultReaders;
  14483. Owned<IStrandJunction> *resultJunctions;
  14484. unsigned graphId;
  14485. bool grouped;
  14486. bool selectionIsAll;
  14487. size32_t selectionLen;
  14488. rtlDataAttr selection;
  14489. public:
  14490. CRoxieServerNWayGraphLoopResultReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId)
  14491. : CRoxieServerNWayInputBaseActivity(_ctx, _factory, _probeManager, 0), helper((IHThorNWayGraphLoopResultReadArg &)basehelper)
  14492. {
  14493. grouped = helper.isGrouped();
  14494. graphId = _graphId;
  14495. selectionIsAll = false;
  14496. selectionLen = 0;
  14497. resultJunctions = NULL;
  14498. }
  14499. ~CRoxieServerNWayGraphLoopResultReadActivity()
  14500. {
  14501. delete [] resultJunctions;
  14502. }
  14503. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14504. {
  14505. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14506. if (selectedInputs.ordinality() == 0)
  14507. {
  14508. initInputSelection();
  14509. unsigned max = selectionLen / sizeof(size32_t);
  14510. const size32_t * selections = (const size32_t *)selection.getdata();
  14511. IProbeManager * probeManager = NULL; // MORE!!
  14512. for (unsigned i = 0; i < max; i++)
  14513. {
  14514. CRoxieServerActivity * resultInput = new CRoxieServerInternalGraphLoopResultReadActivity(ctx, factory, probeManager, graphId, selections[i]);
  14515. resultReaders.append(*resultInput);
  14516. selectedInputs.append(resultInput);
  14517. resultInput->onCreate(colocalParent);
  14518. resultInput->start(parentExtractSize, parentExtract, paused);
  14519. selectedStreams.append(connectSingleStream(ctx, resultInput, 0, resultJunctions[i], true));
  14520. }
  14521. }
  14522. else
  14523. {
  14524. ForEachItemIn(i, selectedInputs)
  14525. selectedInputs.item(i)->start(parentExtractSize, parentExtract, paused);
  14526. }
  14527. ForEachItemIn(i, selectedStreams)
  14528. startJunction(resultJunctions[i]);
  14529. }
  14530. virtual void reset()
  14531. {
  14532. resultReaders.kill();
  14533. CRoxieServerNWayInputBaseActivity::reset();
  14534. ForEachItemIn(i, selectedStreams)
  14535. resetJunction(resultJunctions[i]);
  14536. }
  14537. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract)
  14538. {
  14539. ensureCreated();
  14540. basehelper.onStart(parentExtract, NULL);
  14541. initInputSelection();
  14542. unsigned max = selectionLen / sizeof(size32_t);
  14543. const size32_t * selections = (const size32_t *)selection.getdata();
  14544. for (unsigned i = 0; i < max; i++)
  14545. processor.noteUseIteration(selections[i]);
  14546. }
  14547. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract, IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes)
  14548. {
  14549. //selection etc. already initialised from the gatherIterationUsage() call.
  14550. unsigned max = selectionLen / sizeof(size32_t);
  14551. const size32_t * selections = (const size32_t *)selection.getdata();
  14552. resultJunctions = new Owned<IStrandJunction> [max];
  14553. for (unsigned i = 0; i < max; i++)
  14554. {
  14555. IFinalRoxieInput *in = processor.connectIterationOutput(selections[i], probeManager, probes, this, i);
  14556. selectedInputs.append(in);
  14557. selectedStreams.append(connectSingleStream(ctx, in, 0, resultJunctions[i], true));
  14558. }
  14559. }
  14560. protected:
  14561. void initInputSelection()
  14562. {
  14563. helper.getInputSelection(selectionIsAll, selectionLen, selection.refdata());
  14564. if (selectionIsAll)
  14565. throw MakeStringException(ROXIE_NWAY_INPUT_ERROR, "ALL not yet supported for NWay graph inputs");
  14566. }
  14567. };
  14568. class CRoxieServerNWayGraphLoopResultReadActivityFactory : public CRoxieServerActivityFactory
  14569. {
  14570. unsigned graphId;
  14571. public:
  14572. CRoxieServerNWayGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _graphId)
  14573. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), graphId(_graphId)
  14574. {
  14575. }
  14576. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  14577. {
  14578. return new CRoxieServerNWayGraphLoopResultReadActivity(_ctx, this, _probeManager, graphId);
  14579. }
  14580. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  14581. {
  14582. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for NWay GraphLoopResultRead activity");
  14583. }
  14584. };
  14585. IRoxieServerActivityFactory *createRoxieServerNWayGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned graphId)
  14586. {
  14587. return new CRoxieServerNWayGraphLoopResultReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, graphId);
  14588. }
  14589. //=================================================================================
  14590. class RoxieSteppedInput : public CInterface, implements ISteppedInput
  14591. {
  14592. public:
  14593. RoxieSteppedInput(IFinalRoxieInput * _input, IEngineRowStream *_stream) { input = _input; inputStream = _stream; }
  14594. IMPLEMENT_IINTERFACE
  14595. protected:
  14596. virtual const void * nextInputRow()
  14597. {
  14598. #ifdef TRACE_SEEK_REQUESTS
  14599. IRoxieContextLogger * logger = input->queryActivity();
  14600. const void * ret = doNextInputRow();
  14601. {
  14602. CommonXmlWriter xmlwrite(XWFtrim|XWFopt|XWFnoindent);
  14603. if (!ret)
  14604. xmlwrite.outputBool(true,"eof");
  14605. else if (input->queryOutputMeta()->hasXML())
  14606. input->queryOutputMeta()->toXML((byte *) ret, xmlwrite);
  14607. logger->CTXLOG("next() returns (%s)", xmlwrite.str());
  14608. }
  14609. return ret;
  14610. #else
  14611. return inputStream->ungroupedNextRow();
  14612. #endif
  14613. }
  14614. virtual const void * nextInputRowGE(const void * seek, unsigned numFields, bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  14615. {
  14616. #ifdef TRACE_SEEK_REQUESTS
  14617. IRoxieContextLogger * logger = input->queryActivity();
  14618. {
  14619. CommonXmlWriter xmlwrite(XWFtrim|XWFopt|XWFnoindent);
  14620. if (input->queryOutputMeta()->hasXML())
  14621. input->queryOutputMeta()->toXML((byte *) seek, xmlwrite);
  14622. logger->CTXLOG("nextInputRowGE(%d, %s%s%s, %s) seek(%s)",
  14623. numFields,
  14624. stepExtra.readAheadManyResults() ? "readahead " : "",
  14625. stepExtra.returnMismatches() ? "mismatch" : "exact",
  14626. stepExtra.onlyReturnFirstSeekMatch() ? " single-match" : "",
  14627. stepExtra.queryExtraSeeks() ? "multi-seek":"",
  14628. xmlwrite.str());
  14629. }
  14630. const void * ret = doNextInputRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  14631. {
  14632. CommonXmlWriter xmlwrite(XWFtrim|XWFopt|XWFnoindent);
  14633. if (!ret)
  14634. xmlwrite.outputBool(true,"eof");
  14635. else if (input->queryOutputMeta()->hasXML())
  14636. input->queryOutputMeta()->toXML((byte *) ret, xmlwrite);
  14637. logger->CTXLOG("nextInputRowGE(%d, %s%s%s, %s) result(%s)",
  14638. numFields,
  14639. stepExtra.readAheadManyResults() ? "readahead " : "",
  14640. stepExtra.returnMismatches() ? "mismatch" : "exact",
  14641. stepExtra.onlyReturnFirstSeekMatch() ? " single-match" : "",
  14642. stepExtra.queryExtraSeeks() ? "multi-seek":"",
  14643. xmlwrite.str());
  14644. }
  14645. return ret;
  14646. #else
  14647. return doNextInputRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  14648. #endif
  14649. }
  14650. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  14651. {
  14652. return input->gatherConjunctions(collector);
  14653. }
  14654. virtual void resetEOF()
  14655. {
  14656. inputStream->resetEOF();
  14657. }
  14658. virtual IInputSteppingMeta * queryInputSteppingMeta()
  14659. {
  14660. return input->querySteppingMeta();
  14661. }
  14662. inline const void * doNextInputRowGE(const void * seek, unsigned numFields, bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  14663. {
  14664. assertex(wasCompleteMatch);
  14665. return inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  14666. }
  14667. protected:
  14668. IFinalRoxieInput * input;
  14669. IEngineRowStream * inputStream;
  14670. };
  14671. //=================================================================================
  14672. class CRoxieServerNaryActivity : public CRoxieServerMultiInputActivity
  14673. {
  14674. public:
  14675. CRoxieServerNaryActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14676. : CRoxieServerMultiInputActivity(_ctx, _factory, _probeManager, _numInputs), expandedJunctions(nullptr)
  14677. {
  14678. }
  14679. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14680. {
  14681. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  14682. for (unsigned i=0; i < numInputs; i++)
  14683. {
  14684. IFinalRoxieInput * cur = inputArray[i];
  14685. unsigned numRealInputs = cur->numConcreteOutputs();
  14686. for (unsigned j = 0; j < numRealInputs; j++)
  14687. {
  14688. IFinalRoxieInput * curReal = cur->queryConcreteInput(j);
  14689. expandedInputs.append(curReal);
  14690. }
  14691. }
  14692. expandedJunctions = new Owned<IStrandJunction> [expandedInputs.length()];
  14693. ForEachItemIn(idx, expandedInputs)
  14694. {
  14695. expandedStreams.append(connectSingleStream(ctx, expandedInputs.item(idx), 0, expandedJunctions[idx], true)); // MORE - is the index 0 right?
  14696. startJunction(expandedJunctions[idx]);
  14697. }
  14698. }
  14699. virtual void reset()
  14700. {
  14701. ForEachItemIn(idx, expandedInputs)
  14702. resetJunction(expandedJunctions[idx]);
  14703. expandedInputs.kill();
  14704. expandedStreams.kill();
  14705. delete [] expandedJunctions;
  14706. expandedJunctions = nullptr;
  14707. CRoxieServerMultiInputActivity::reset();
  14708. }
  14709. protected:
  14710. PointerArrayOf<IFinalRoxieInput> expandedInputs;
  14711. PointerArrayOf<IEngineRowStream> expandedStreams;
  14712. Owned<IStrandJunction> *expandedJunctions;
  14713. };
  14714. //=================================================================================
  14715. class CRoxieStreamMerger : public CStreamMerger
  14716. {
  14717. public:
  14718. CRoxieStreamMerger() : CStreamMerger(true)
  14719. {
  14720. streamArray = NULL;
  14721. }
  14722. void initInputs(unsigned _numInputs, IEngineRowStream ** _streamArray)
  14723. {
  14724. CStreamMerger::initInputs(_numInputs);
  14725. streamArray = _streamArray;
  14726. }
  14727. virtual bool pullInput(unsigned i, const void * seek, unsigned numFields, const SmartStepExtra * stepExtra)
  14728. {
  14729. const void * next;
  14730. bool matches = true;
  14731. if (seek)
  14732. next = streamArray[i]->nextRowGE(seek, numFields, matches, *stepExtra);
  14733. else
  14734. next = streamArray[i]->ungroupedNextRow();
  14735. pending[i] = next;
  14736. pendingMatches[i] = matches;
  14737. return (next != NULL);
  14738. }
  14739. virtual void releaseRow(const void * row)
  14740. {
  14741. ReleaseRoxieRow(row);
  14742. }
  14743. protected:
  14744. IEngineRowStream **streamArray;
  14745. };
  14746. class CRoxieServerNWayMergeActivity : public CRoxieServerNaryActivity
  14747. {
  14748. public:
  14749. CRoxieServerNWayMergeActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14750. : CRoxieServerNaryActivity(_ctx, _factory, _probeManager, _numInputs),
  14751. helper((IHThorNWayMergeArg &)basehelper)
  14752. {
  14753. initializedMeta = false;
  14754. }
  14755. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14756. {
  14757. CRoxieServerNaryActivity::start(parentExtractSize, parentExtract, paused);
  14758. merger.init(helper.queryCompare(), helper.dedup(), helper.querySteppingMeta()->queryCompare());
  14759. merger.initInputs(expandedStreams.length(), expandedStreams.getArray());
  14760. }
  14761. virtual void stop()
  14762. {
  14763. merger.done();
  14764. CRoxieServerNaryActivity::stop();
  14765. }
  14766. virtual void reset()
  14767. {
  14768. merger.cleanup();
  14769. CRoxieServerNaryActivity::reset();
  14770. initializedMeta = false;
  14771. }
  14772. virtual const void * nextRow()
  14773. {
  14774. ActivityTimer t(totalCycles, timeActivities);
  14775. const void * next = merger.nextRow();
  14776. if (next)
  14777. processed++;
  14778. return next;
  14779. }
  14780. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  14781. {
  14782. ActivityTimer t(totalCycles, timeActivities);
  14783. const void * next = merger.nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  14784. if (next)
  14785. processed++;
  14786. return next;
  14787. }
  14788. virtual IInputSteppingMeta * querySteppingMeta()
  14789. {
  14790. if (expandedStreams.ordinality() == 0)
  14791. return NULL;
  14792. if (!initializedMeta)
  14793. {
  14794. meta.init(helper.querySteppingMeta(), false);
  14795. ForEachItemIn(i, expandedStreams)
  14796. {
  14797. if (meta.getNumFields() == 0)
  14798. break;
  14799. IInputSteppingMeta * inputMeta = expandedInputs.item(i)->querySteppingMeta();
  14800. meta.intersect(inputMeta);
  14801. }
  14802. initializedMeta = true;
  14803. }
  14804. if (meta.getNumFields() == 0)
  14805. return NULL;
  14806. return &meta;
  14807. }
  14808. protected:
  14809. IHThorNWayMergeArg &helper;
  14810. CRoxieStreamMerger merger;
  14811. CSteppingMeta meta;
  14812. bool initializedMeta;
  14813. };
  14814. class CRoxieServerNWayMergeActivityFactory : public CRoxieServerMultiInputFactory
  14815. {
  14816. public:
  14817. CRoxieServerNWayMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  14818. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  14819. {
  14820. }
  14821. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  14822. {
  14823. return new CRoxieServerNWayMergeActivity(_ctx, this, _probeManager, numInputs());
  14824. }
  14825. };
  14826. IRoxieServerActivityFactory *createRoxieServerNWayMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  14827. {
  14828. return new CRoxieServerNWayMergeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  14829. }
  14830. //=================================================================================
  14831. class CRoxieServerNWayMergeJoinActivity : public CRoxieServerNaryActivity
  14832. {
  14833. public:
  14834. CRoxieServerNWayMergeJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs, CMergeJoinProcessor & _processor)
  14835. : CRoxieServerNaryActivity(_ctx, _factory, _probeManager, _numInputs),processor(_processor),
  14836. helper((IHThorNWayMergeJoinArg &)basehelper)
  14837. {
  14838. }
  14839. virtual void onCreate(IHThorArg *_colocalParent)
  14840. {
  14841. CRoxieServerNaryActivity::onCreate(_colocalParent);
  14842. ICodeContext * codectx = ctx->queryCodeContext();
  14843. inputAllocator.setown(codectx->getRowAllocator(helper.queryInputMeta(), activityId));
  14844. outputAllocator.setown(codectx->getRowAllocator(helper.queryOutputMeta(), activityId));
  14845. }
  14846. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14847. {
  14848. CRoxieServerNaryActivity::start(parentExtractSize, parentExtract, paused);
  14849. ForEachItemIn(i1, expandedInputs)
  14850. {
  14851. Owned<RoxieSteppedInput> stepInput = new RoxieSteppedInput(expandedInputs.item(i1), expandedStreams.item(i1));
  14852. processor.addInput(stepInput);
  14853. }
  14854. processor.beforeProcessing(inputAllocator, outputAllocator);
  14855. }
  14856. virtual void stop()
  14857. {
  14858. processor.afterProcessing();
  14859. CRoxieServerNaryActivity::stop();
  14860. }
  14861. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  14862. {
  14863. return processor.gatherConjunctions(collector);
  14864. }
  14865. virtual void resetEOF()
  14866. {
  14867. processor.queryResetEOF();
  14868. }
  14869. virtual const void * nextRow()
  14870. {
  14871. ActivityTimer t(totalCycles, timeActivities);
  14872. const void * next = processor.nextRow();
  14873. if (next)
  14874. processed++;
  14875. return next;
  14876. }
  14877. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  14878. {
  14879. ActivityTimer t(totalCycles, timeActivities);
  14880. const void * next = processor.nextGE(seek, numFields, wasCompleteMatch, stepExtra);
  14881. if (next)
  14882. processed++;
  14883. return next;
  14884. }
  14885. virtual IInputSteppingMeta * querySteppingMeta()
  14886. {
  14887. return processor.queryInputSteppingMeta();
  14888. }
  14889. protected:
  14890. IHThorNWayMergeJoinArg & helper;
  14891. CMergeJoinProcessor & processor;
  14892. Owned<IEngineRowAllocator> inputAllocator;
  14893. Owned<IEngineRowAllocator> outputAllocator;
  14894. };
  14895. class CRoxieServerAndMergeJoinActivity : public CRoxieServerNWayMergeJoinActivity
  14896. {
  14897. public:
  14898. CRoxieServerAndMergeJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14899. : CRoxieServerNWayMergeJoinActivity(_ctx, _factory, _probeManager, _numInputs, andProcessor), andProcessor(helper)
  14900. {
  14901. }
  14902. protected:
  14903. CAndMergeJoinProcessor andProcessor;
  14904. };
  14905. class CRoxieServerAndLeftMergeJoinActivity : public CRoxieServerNWayMergeJoinActivity
  14906. {
  14907. public:
  14908. CRoxieServerAndLeftMergeJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14909. : CRoxieServerNWayMergeJoinActivity(_ctx, _factory, _probeManager, _numInputs, andLeftProcessor), andLeftProcessor(helper)
  14910. {
  14911. }
  14912. protected:
  14913. CAndLeftMergeJoinProcessor andLeftProcessor;
  14914. };
  14915. class CRoxieServerMofNMergeJoinActivity : public CRoxieServerNWayMergeJoinActivity
  14916. {
  14917. public:
  14918. CRoxieServerMofNMergeJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14919. : CRoxieServerNWayMergeJoinActivity(_ctx, _factory, _probeManager, _numInputs, mofnProcessor), mofnProcessor(helper)
  14920. {
  14921. }
  14922. protected:
  14923. CMofNMergeJoinProcessor mofnProcessor;
  14924. };
  14925. class CRoxieServerProximityJoinActivity : public CRoxieServerNWayMergeJoinActivity
  14926. {
  14927. public:
  14928. CRoxieServerProximityJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14929. : CRoxieServerNWayMergeJoinActivity(_ctx, _factory, _probeManager, _numInputs, proximityProcessor), proximityProcessor(helper)
  14930. {
  14931. }
  14932. protected:
  14933. CProximityJoinProcessor proximityProcessor;
  14934. };
  14935. class CRoxieServerNWayMergeJoinActivityFactory : public CRoxieServerMultiInputFactory
  14936. {
  14937. unsigned flags;
  14938. public:
  14939. CRoxieServerNWayMergeJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  14940. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  14941. {
  14942. Owned<IHThorNWayMergeJoinArg> helper = (IHThorNWayMergeJoinArg *) helperFactory();
  14943. flags = helper->getJoinFlags();
  14944. }
  14945. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  14946. {
  14947. if (flags & IHThorNWayMergeJoinArg::MJFhasrange)
  14948. return new CRoxieServerProximityJoinActivity(_ctx, this, _probeManager, numInputs());
  14949. switch (flags & IHThorNWayMergeJoinArg::MJFkindmask)
  14950. {
  14951. case IHThorNWayMergeJoinArg::MJFinner:
  14952. return new CRoxieServerAndMergeJoinActivity(_ctx, this, _probeManager, numInputs());
  14953. case IHThorNWayMergeJoinArg::MJFleftonly:
  14954. case IHThorNWayMergeJoinArg::MJFleftouter:
  14955. return new CRoxieServerAndLeftMergeJoinActivity(_ctx, this, _probeManager, numInputs());
  14956. case IHThorNWayMergeJoinArg::MJFmofn:
  14957. return new CRoxieServerMofNMergeJoinActivity(_ctx, this, _probeManager, numInputs());
  14958. default:
  14959. throwUnexpected();
  14960. }
  14961. }
  14962. };
  14963. IRoxieServerActivityFactory *createRoxieServerNWayMergeJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  14964. {
  14965. return new CRoxieServerNWayMergeJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  14966. }
  14967. //=================================================================================
  14968. class CRoxieServerNWaySelectActivity : public CRoxieServerMultiInputActivity
  14969. {
  14970. IHThorNWaySelectArg &helper;
  14971. public:
  14972. CRoxieServerNWaySelectActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14973. : CRoxieServerMultiInputActivity(_ctx, _factory, _probeManager, _numInputs),
  14974. helper((IHThorNWaySelectArg &)basehelper)
  14975. {
  14976. selectedInput = NULL;
  14977. selectedStream = NULL;
  14978. }
  14979. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14980. {
  14981. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  14982. unsigned whichInput = helper.getInputIndex();
  14983. selectedInput = NULL;
  14984. selectedStream = NULL;
  14985. if (whichInput--)
  14986. {
  14987. for (unsigned i=0; i < numInputs; i++)
  14988. {
  14989. IFinalRoxieInput * cur = inputArray[i];
  14990. unsigned numRealInputs = cur->numConcreteOutputs();
  14991. if (whichInput < numRealInputs)
  14992. {
  14993. selectedInput = cur->queryConcreteInput(whichInput);
  14994. selectedStream = connectSingleStream(ctx, selectedInput, 0, selectedJunction, true); // Should this be passing whichInput??
  14995. break;
  14996. }
  14997. whichInput -= numRealInputs;
  14998. }
  14999. }
  15000. startJunction(selectedJunction);
  15001. }
  15002. virtual void reset()
  15003. {
  15004. selectedInput = NULL;
  15005. selectedStream = NULL;
  15006. resetJunction(selectedJunction);
  15007. selectedJunction.clear();
  15008. CRoxieServerMultiInputActivity::reset();
  15009. }
  15010. const void * nextRow()
  15011. {
  15012. ActivityTimer t(totalCycles, timeActivities);
  15013. if (!selectedStream)
  15014. return NULL;
  15015. return selectedStream->nextRow();
  15016. }
  15017. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  15018. {
  15019. if (!selectedInput)
  15020. return false;
  15021. return selectedInput->gatherConjunctions(collector);
  15022. }
  15023. virtual void resetEOF()
  15024. {
  15025. if (selectedStream)
  15026. selectedStream->resetEOF();
  15027. }
  15028. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  15029. {
  15030. ActivityTimer t(totalCycles, timeActivities);
  15031. if (!selectedStream)
  15032. return NULL;
  15033. return selectedStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  15034. }
  15035. IInputSteppingMeta * querySteppingMeta()
  15036. {
  15037. if (selectedInput)
  15038. return selectedInput->querySteppingMeta();
  15039. return NULL;
  15040. }
  15041. protected:
  15042. IFinalRoxieInput * selectedInput;
  15043. IEngineRowStream * selectedStream;
  15044. Owned<IStrandJunction> selectedJunction;
  15045. };
  15046. class CRoxieServerNWaySelectActivityFactory : public CRoxieServerMultiInputFactory
  15047. {
  15048. public:
  15049. CRoxieServerNWaySelectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15050. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15051. {
  15052. }
  15053. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15054. {
  15055. return new CRoxieServerNWaySelectActivity(_ctx, this, _probeManager, numInputs());
  15056. }
  15057. };
  15058. IRoxieServerActivityFactory *createRoxieServerNWaySelectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15059. {
  15060. return new CRoxieServerNWaySelectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15061. }
  15062. //=================================================================================
  15063. class CRoxieServerRemoteActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler
  15064. {
  15065. protected:
  15066. IHThorRemoteArg &helper;
  15067. CRemoteResultAdaptor remote;
  15068. public:
  15069. CRoxieServerRemoteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteID)
  15070. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  15071. helper((IHThorRemoteArg &)basehelper),
  15072. remote(_ctx, this, _remoteID, meta.queryOriginal(), helper, *this, false, false) // MORE - if they need it stable we'll have to think!
  15073. {
  15074. }
  15075. virtual const IResolvedFile *queryVarFileInfo() const
  15076. {
  15077. return NULL;
  15078. }
  15079. virtual void onCreate(IHThorArg *_colocalParent)
  15080. {
  15081. CRoxieServerActivity::onCreate(_colocalParent);
  15082. remote.onCreate(_colocalParent);
  15083. }
  15084. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15085. {
  15086. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  15087. remote.onStart(parentExtractSize, parentExtract);
  15088. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  15089. unsigned fileNo = 0; // MORE - superfiles require us to do this per file part... maybe (needs thought)
  15090. remote.getMem(0, fileNo, 0); // the cached context is all we need to send
  15091. remote.flush();
  15092. remote.senddone();
  15093. }
  15094. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  15095. {
  15096. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  15097. }
  15098. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  15099. {
  15100. if (idx==(unsigned)-1)
  15101. idx = 0;
  15102. return idx ? NULL: &remote;
  15103. }
  15104. virtual void reset()
  15105. {
  15106. processed = remote.processed;
  15107. remote.processed = 0;
  15108. CRoxieServerActivity::reset();
  15109. }
  15110. virtual void onLimitExceeded(bool isKeyed)
  15111. {
  15112. if (traceLevel > 4)
  15113. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  15114. helper.onLimitExceeded();
  15115. }
  15116. virtual const void *createLimitFailRow(bool isKeyed)
  15117. {
  15118. UNIMPLEMENTED; // MORE - is there an ONFAIL for a limit folded into a remote?
  15119. }
  15120. virtual const void *nextRow()
  15121. {
  15122. throwUnexpected(); // I am nobody's input
  15123. }
  15124. };
  15125. class CRoxieServerRemoteActivityFactory : public CRoxieServerActivityFactory
  15126. {
  15127. public:
  15128. RemoteActivityId remoteId;
  15129. bool isRoot;
  15130. CRoxieServerRemoteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId, bool _isRoot)
  15131. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), remoteId(_remoteId), isRoot(_isRoot)
  15132. {
  15133. }
  15134. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15135. {
  15136. return new CRoxieServerRemoteActivity(_ctx, this, _probeManager, remoteId);
  15137. }
  15138. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  15139. {
  15140. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  15141. }
  15142. virtual bool isSink() const
  15143. {
  15144. //I don't think the action version of this is implemented - but this would be the code
  15145. return isRoot && !meta.queryOriginal();
  15146. }
  15147. virtual const StatisticsMapping &queryStatsMapping() const
  15148. {
  15149. return allStatistics; // Child queries...
  15150. }
  15151. };
  15152. IRoxieServerActivityFactory *createRoxieServerRemoteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId, bool _isRoot)
  15153. {
  15154. return new CRoxieServerRemoteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId, _isRoot);
  15155. }
  15156. //=================================================================================
  15157. class CRoxieServerIterateActivity : public CRoxieServerActivity
  15158. {
  15159. IHThorIterateArg &helper;
  15160. OwnedConstRoxieRow defaultRecord;
  15161. OwnedConstRoxieRow left;
  15162. OwnedConstRoxieRow right;
  15163. unsigned counter;
  15164. public:
  15165. CRoxieServerIterateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  15166. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  15167. helper((IHThorIterateArg &)basehelper)
  15168. {
  15169. counter = 0;
  15170. }
  15171. virtual bool needsAllocator() const { return true; }
  15172. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15173. {
  15174. counter = 0;
  15175. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  15176. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15177. size32_t thisSize = helper.createDefault(rowBuilder);
  15178. defaultRecord.setown(rowBuilder.finalizeRowClear(thisSize));
  15179. }
  15180. virtual void reset()
  15181. {
  15182. defaultRecord.clear();
  15183. right.clear();
  15184. left.clear();
  15185. CRoxieServerActivity::reset();
  15186. }
  15187. virtual const void * nextRow()
  15188. {
  15189. ActivityTimer t(totalCycles, timeActivities);
  15190. loop
  15191. {
  15192. right.setown(inputStream->nextRow());
  15193. if (!right)
  15194. {
  15195. bool skippedGroup = (left == NULL) && (counter > 0); //we have just skipped entire group, but shouldn't output a double null
  15196. left.clear();
  15197. counter = 0;
  15198. if (skippedGroup) continue;
  15199. return NULL;
  15200. }
  15201. try
  15202. {
  15203. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15204. unsigned outSize = helper.transform(rowBuilder, left ? left : defaultRecord, right, ++counter);
  15205. if (outSize)
  15206. {
  15207. left.setown(rowBuilder.finalizeRowClear(outSize));
  15208. processed++;
  15209. return left.getLink();
  15210. }
  15211. }
  15212. catch (IException *E)
  15213. {
  15214. throw makeWrappedException(E);
  15215. }
  15216. }
  15217. }
  15218. };
  15219. class CRoxieServerIterateActivityFactory : public CRoxieServerActivityFactory
  15220. {
  15221. public:
  15222. CRoxieServerIterateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15223. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15224. {
  15225. }
  15226. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15227. {
  15228. return new CRoxieServerIterateActivity(_ctx, this, _probeManager);
  15229. }
  15230. };
  15231. IRoxieServerActivityFactory *createRoxieServerIterateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15232. {
  15233. return new CRoxieServerIterateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15234. }
  15235. //=================================================================================
  15236. class CRoxieServerProcessActivity : public CRoxieServerActivity
  15237. {
  15238. IHThorProcessArg &helper;
  15239. OwnedConstRoxieRow curRight;
  15240. OwnedConstRoxieRow initialRight;
  15241. unsigned counter;
  15242. Owned<IEngineRowAllocator> rightRowAllocator;
  15243. public:
  15244. CRoxieServerProcessActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  15245. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorProcessArg &)basehelper)
  15246. {
  15247. counter = 0;
  15248. }
  15249. virtual bool needsAllocator() const { return true; }
  15250. virtual void onCreate(IHThorArg *_colocalParent)
  15251. {
  15252. CRoxieServerActivity::onCreate(_colocalParent);
  15253. rightRowAllocator.setown(ctx->queryCodeContext()->getRowAllocator(QUERYINTERFACE(helper.queryRightRecordSize(), IOutputMetaData), activityId));
  15254. }
  15255. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15256. {
  15257. counter = 0;
  15258. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  15259. RtlDynamicRowBuilder rowBuilder(rightRowAllocator);
  15260. size32_t thisSize = helper.createInitialRight(rowBuilder);
  15261. initialRight.setown(rowBuilder.finalizeRowClear(thisSize));
  15262. curRight.set(initialRight);
  15263. }
  15264. virtual const void * nextRow()
  15265. {
  15266. ActivityTimer t(totalCycles, timeActivities);
  15267. try
  15268. {
  15269. loop
  15270. {
  15271. const void * in = inputStream->nextRow();
  15272. if (!in)
  15273. {
  15274. bool eog = (curRight != initialRight); // processed any records?
  15275. counter = 0;
  15276. curRight.set(initialRight);
  15277. if (eog)
  15278. return NULL;
  15279. in = inputStream->nextRow();
  15280. if (!in)
  15281. return NULL;
  15282. }
  15283. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15284. RtlDynamicRowBuilder rightRowBuilder(rightRowAllocator);
  15285. size32_t outSize = helper.transform(rowBuilder, rightRowBuilder, in, curRight, ++counter);
  15286. ReleaseRoxieRow(in);
  15287. if (outSize)
  15288. {
  15289. //MORE: This should be returned...
  15290. size32_t rightSize = rightRowAllocator->queryOutputMeta()->getRecordSize(rightRowBuilder.getSelf());
  15291. curRight.setown(rightRowBuilder.finalizeRowClear(rightSize));
  15292. processed++;
  15293. return rowBuilder.finalizeRowClear(outSize);
  15294. }
  15295. }
  15296. }
  15297. catch (IException *E)
  15298. {
  15299. throw makeWrappedException(E);
  15300. }
  15301. }
  15302. };
  15303. class CRoxieServerProcessActivityFactory : public CRoxieServerActivityFactory
  15304. {
  15305. public:
  15306. CRoxieServerProcessActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15307. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15308. {
  15309. }
  15310. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15311. {
  15312. return new CRoxieServerProcessActivity(_ctx, this, _probeManager);
  15313. }
  15314. };
  15315. IRoxieServerActivityFactory *createRoxieServerProcessActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15316. {
  15317. return new CRoxieServerProcessActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15318. }
  15319. //=================================================================================
  15320. class CRoxieServerGroupActivity : public CRoxieServerActivity
  15321. {
  15322. IHThorGroupArg &helper;
  15323. bool endPending;
  15324. bool eof;
  15325. bool first;
  15326. unsigned numGroups;
  15327. unsigned numGroupMax;
  15328. unsigned numProcessedLastGroup;
  15329. const void *next;
  15330. public:
  15331. CRoxieServerGroupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  15332. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorGroupArg &)basehelper)
  15333. {
  15334. next = NULL;
  15335. endPending = false;
  15336. eof = false;
  15337. first = true;
  15338. numGroups = 0;
  15339. numGroupMax = 0;
  15340. numProcessedLastGroup = 0;
  15341. }
  15342. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15343. {
  15344. endPending = false;
  15345. eof = false;
  15346. first = true;
  15347. numGroups = 0;
  15348. numGroupMax = 0;
  15349. numProcessedLastGroup = processed;
  15350. assertex(next == NULL);
  15351. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  15352. }
  15353. virtual void reset()
  15354. {
  15355. noteStatistic(StNumGroups, numGroups);
  15356. noteStatistic(StNumGroupMax, numGroupMax);
  15357. ReleaseClearRoxieRow(next);
  15358. CRoxieServerActivity::reset();
  15359. }
  15360. virtual const void * nextRow()
  15361. {
  15362. ActivityTimer t(totalCycles, timeActivities);
  15363. if (first)
  15364. {
  15365. next = inputStream->nextRow();
  15366. first = false;
  15367. }
  15368. if (eof || endPending)
  15369. {
  15370. endPending = false;
  15371. return NULL;
  15372. }
  15373. const void * prev = next;
  15374. next = inputStream->ungroupedNextRow();
  15375. if (next)
  15376. {
  15377. assertex(prev);
  15378. if (!helper.isSameGroup(prev, next))
  15379. {
  15380. noteEndOfGroup();
  15381. endPending = true;
  15382. }
  15383. }
  15384. else
  15385. {
  15386. noteEndOfGroup();
  15387. eof = true;
  15388. }
  15389. if (prev)
  15390. processed++;
  15391. return prev;
  15392. }
  15393. inline void noteEndOfGroup()
  15394. {
  15395. unsigned numThisGroup = processed - numProcessedLastGroup;
  15396. if (numThisGroup == 0)
  15397. return;
  15398. numProcessedLastGroup = processed;
  15399. if (numThisGroup > numGroupMax)
  15400. numGroupMax = numThisGroup;
  15401. numGroups++;
  15402. }
  15403. };
  15404. class CRoxieServerGroupActivityFactory : public CRoxieServerActivityFactory
  15405. {
  15406. public:
  15407. CRoxieServerGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15408. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15409. {
  15410. }
  15411. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15412. {
  15413. return new CRoxieServerGroupActivity(_ctx, this, _probeManager);
  15414. }
  15415. virtual const StatisticsMapping &queryStatsMapping() const
  15416. {
  15417. return groupStatistics;
  15418. }
  15419. };
  15420. IRoxieServerActivityFactory *createRoxieServerGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15421. {
  15422. return new CRoxieServerGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15423. }
  15424. //=================================================================================
  15425. class CRoxieServerFirstNActivity : public CRoxieServerLateStartActivity
  15426. {
  15427. unsigned __int64 limit;
  15428. unsigned __int64 skip;
  15429. unsigned doneThisGroup;
  15430. IHThorFirstNArg &helper;
  15431. public:
  15432. CRoxieServerFirstNActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  15433. : CRoxieServerLateStartActivity(_ctx, _factory, _probeManager), helper((IHThorFirstNArg &)basehelper)
  15434. {
  15435. doneThisGroup = 0;
  15436. limit = 0;
  15437. skip = 0;
  15438. }
  15439. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15440. {
  15441. doneThisGroup = 0;
  15442. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  15443. limit = helper.getLimit();
  15444. skip = helper.numToSkip();
  15445. lateStart(parentExtractSize, parentExtract, limit > 0);
  15446. if (limit + skip >= limit)
  15447. limit += skip;
  15448. }
  15449. const void * nextRow()
  15450. {
  15451. ActivityTimer t(totalCycles, timeActivities);
  15452. if (eof)
  15453. return NULL;
  15454. const void *ret;
  15455. loop
  15456. {
  15457. ret = inputStream->nextRow();
  15458. if (!ret)
  15459. {
  15460. if (meta.isGrouped())
  15461. {
  15462. if (doneThisGroup > skip)
  15463. {
  15464. doneThisGroup = 0;
  15465. return NULL;
  15466. }
  15467. doneThisGroup = 0;
  15468. }
  15469. ret = inputStream->nextRow();
  15470. if (!ret)
  15471. {
  15472. eof = true;
  15473. return NULL;
  15474. }
  15475. }
  15476. doneThisGroup++;
  15477. if (doneThisGroup > skip)
  15478. break;
  15479. ReleaseRoxieRow(ret);
  15480. }
  15481. if (doneThisGroup <= limit)
  15482. {
  15483. processed++;
  15484. return ret;
  15485. }
  15486. ReleaseRoxieRow(ret);
  15487. if (meta.isGrouped())
  15488. {
  15489. while ((ret = inputStream->nextRow()) != NULL)
  15490. ReleaseRoxieRow(ret);
  15491. doneThisGroup = 0;
  15492. }
  15493. else
  15494. eof = true;
  15495. return NULL;
  15496. }
  15497. };
  15498. class CRoxieServerFirstNActivityFactory : public CRoxieServerActivityFactory
  15499. {
  15500. public:
  15501. CRoxieServerFirstNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15502. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15503. {
  15504. }
  15505. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15506. {
  15507. return new CRoxieServerFirstNActivity(_ctx, this, _probeManager);
  15508. }
  15509. };
  15510. IRoxieServerActivityFactory *createRoxieServerFirstNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15511. {
  15512. return new CRoxieServerFirstNActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15513. }
  15514. //=================================================================================
  15515. class CRoxieServerSelectNActivity : public CRoxieServerActivity
  15516. {
  15517. bool done;
  15518. IHThorSelectNArg &helper;
  15519. public:
  15520. CRoxieServerSelectNActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  15521. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorSelectNArg &)basehelper)
  15522. {
  15523. done = false;
  15524. }
  15525. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15526. {
  15527. done = false;
  15528. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  15529. }
  15530. const void *defaultRow()
  15531. {
  15532. if (!rowAllocator)
  15533. createRowAllocator(); // We delay as often not needed...
  15534. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15535. size32_t thisSize = helper.createDefault(rowBuilder);
  15536. return rowBuilder.finalizeRowClear(thisSize);
  15537. }
  15538. virtual const void * nextRow()
  15539. {
  15540. ActivityTimer t(totalCycles, timeActivities);
  15541. if (done)
  15542. return NULL;
  15543. done = true;
  15544. processed++; // always going to return a row!
  15545. unsigned __int64 index = helper.getRowToSelect();
  15546. while (--index)
  15547. {
  15548. const void * next = inputStream->ungroupedNextRow();
  15549. if (!next)
  15550. return defaultRow();
  15551. ReleaseRoxieRow(next);
  15552. }
  15553. const void * next = inputStream->ungroupedNextRow();
  15554. if (!next)
  15555. next = defaultRow();
  15556. return next;
  15557. }
  15558. };
  15559. class CRoxieServerSelectNActivityFactory : public CRoxieServerActivityFactory
  15560. {
  15561. public:
  15562. CRoxieServerSelectNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15563. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15564. {
  15565. }
  15566. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15567. {
  15568. return new CRoxieServerSelectNActivity(_ctx, this, _probeManager);
  15569. }
  15570. };
  15571. IRoxieServerActivityFactory *createRoxieServerSelectNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15572. {
  15573. return new CRoxieServerSelectNActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15574. }
  15575. //=================================================================================
  15576. class CRoxieServerSelfJoinActivity : public CRoxieServerActivity
  15577. {
  15578. IHThorJoinArg &helper;
  15579. ICompare *collate;
  15580. OwnedRowArray group;
  15581. bool matchedLeft;
  15582. BoolArray matchedRight;
  15583. bool eof;
  15584. bool first;
  15585. unsigned leftIndex;
  15586. unsigned rightIndex;
  15587. unsigned rightOuterIndex;
  15588. unsigned joinLimit;
  15589. unsigned atmostLimit;
  15590. unsigned atmostsTriggered;
  15591. unsigned abortLimit;
  15592. unsigned keepLimit;
  15593. unsigned joinCounter;
  15594. bool leftOuterJoin;
  15595. bool rightOuterJoin;
  15596. bool exclude;
  15597. bool limitFail;
  15598. bool limitOnFail;
  15599. bool cloneLeft;
  15600. bool forceSpill;
  15601. OwnedConstRoxieRow defaultLeft;
  15602. OwnedConstRoxieRow defaultRight;
  15603. OwnedConstRoxieRow lhs;
  15604. Owned<IException> failingLimit;
  15605. bool failingOuterAtmost;
  15606. Owned<IEngineRowAllocator> defaultAllocator;
  15607. Owned<IRHLimitedCompareHelper> limitedhelper;
  15608. Owned<CRHDualCache> dualcache;
  15609. Owned<IGroupedInput> groupedInput;
  15610. IRowStream *dualCacheInput;
  15611. bool fillGroup()
  15612. {
  15613. group.clear();
  15614. matchedLeft = false;
  15615. matchedRight.kill();
  15616. failingOuterAtmost = false;
  15617. const void * next;
  15618. unsigned groupCount = 0;
  15619. while((next = groupedInput->nextRow()) != NULL)
  15620. {
  15621. if(groupCount==abortLimit)
  15622. {
  15623. if(limitFail)
  15624. failLimit(next);
  15625. if (ctx->queryDebugContext())
  15626. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  15627. if(limitOnFail)
  15628. {
  15629. assertex(!failingLimit);
  15630. try
  15631. {
  15632. failLimit(next);
  15633. }
  15634. catch(IException * except)
  15635. {
  15636. failingLimit.setown(except);
  15637. }
  15638. assertex(failingLimit != NULL);
  15639. group.append(next);
  15640. groupCount++;
  15641. break;
  15642. }
  15643. group.clear();
  15644. groupCount = 0;
  15645. while(next)
  15646. {
  15647. ReleaseRoxieRow(next);
  15648. next = groupedInput->nextRow();
  15649. }
  15650. }
  15651. else if(groupCount==atmostLimit)
  15652. {
  15653. atmostsTriggered++;
  15654. if(leftOuterJoin)
  15655. {
  15656. group.append(next);
  15657. groupCount++;
  15658. failingOuterAtmost = true;
  15659. break;
  15660. }
  15661. else
  15662. {
  15663. group.clear();
  15664. groupCount = 0;
  15665. while (next)
  15666. {
  15667. ReleaseRoxieRow(next);
  15668. next = groupedInput->nextRow();
  15669. }
  15670. }
  15671. }
  15672. else
  15673. {
  15674. group.append(next);
  15675. groupCount++;
  15676. }
  15677. }
  15678. if(group.ordinality()==0)
  15679. {
  15680. eof = true;
  15681. return false;
  15682. }
  15683. leftIndex = 0;
  15684. rightIndex = 0;
  15685. rightOuterIndex = 0;
  15686. joinCounter = 0;
  15687. joinLimit = keepLimit;
  15688. ForEachItemIn(idx, group)
  15689. matchedRight.append(false);
  15690. return true;
  15691. }
  15692. void failLimit(const void * next)
  15693. {
  15694. helper.onMatchAbortLimitExceeded();
  15695. CommonXmlWriter xmlwrite(XWFtrim|XWFopt );
  15696. if (!ctx->isBlind() && input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  15697. {
  15698. input->queryOutputMeta()->toXML((byte *) next, xmlwrite);
  15699. }
  15700. throw MakeStringException(ROXIE_TOO_MANY_RESULTS, "More than %d match candidates in self-join %d for row %s", abortLimit, queryId(), xmlwrite.str());
  15701. }
  15702. virtual bool needsAllocator() const { return true; }
  15703. const void *joinRecords(const void * curLeft, const void * curRight, unsigned counter, IException * except)
  15704. {
  15705. try
  15706. {
  15707. if (cloneLeft && !except)
  15708. {
  15709. LinkRoxieRow(curLeft);
  15710. return curLeft;
  15711. }
  15712. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15713. size32_t outsize = except ? helper.onFailTransform(rowBuilder, curLeft, curRight, except) : helper.transform(rowBuilder, curLeft, curRight, counter);
  15714. if (outsize)
  15715. return rowBuilder.finalizeRowClear(outsize);
  15716. else
  15717. return NULL;
  15718. }
  15719. catch (IException *E)
  15720. {
  15721. throw makeWrappedException(E);
  15722. }
  15723. }
  15724. void createDefaultLeft()
  15725. {
  15726. if (!defaultLeft)
  15727. {
  15728. if (!defaultAllocator)
  15729. defaultAllocator.setown(ctx->queryCodeContext()->getRowAllocator(input->queryOutputMeta(), activityId));
  15730. RtlDynamicRowBuilder rowBuilder(defaultAllocator);
  15731. size32_t thisSize = helper.createDefaultLeft(rowBuilder);
  15732. defaultLeft.setown(rowBuilder.finalizeRowClear(thisSize));
  15733. }
  15734. }
  15735. void createDefaultRight()
  15736. {
  15737. if (!defaultRight)
  15738. {
  15739. if (!defaultAllocator)
  15740. defaultAllocator.setown(ctx->queryCodeContext()->getRowAllocator(input->queryOutputMeta(), activityId));
  15741. RtlDynamicRowBuilder rowBuilder(defaultAllocator);
  15742. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  15743. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  15744. }
  15745. }
  15746. public:
  15747. CRoxieServerSelfJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _forceSpill)
  15748. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorJoinArg &)basehelper), forceSpill(_forceSpill)
  15749. {
  15750. collate = helper.queryCompareLeftRight();
  15751. eof = false;
  15752. first = true;
  15753. keepLimit = 0;
  15754. atmostLimit = 0;
  15755. atmostsTriggered = 0;
  15756. unsigned joinFlags = helper.getJoinFlags();
  15757. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  15758. rightOuterJoin = (joinFlags & JFrightouter) != 0;
  15759. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  15760. exclude = (joinFlags & JFexclude) != 0;
  15761. abortLimit = 0;
  15762. joinLimit = 0;
  15763. assertex((joinFlags & (JFfirst | JFfirstleft | JFfirstright)) == 0); // no longer supported
  15764. getLimitType(joinFlags, limitFail, limitOnFail);
  15765. if((joinFlags & JFslidingmatch) != 0)
  15766. throw MakeStringException(ROXIE_UNIMPLEMENTED_ERROR, "Internal Error: Sliding self join not supported");
  15767. failingOuterAtmost = false;
  15768. matchedLeft = false;
  15769. leftIndex = 0;
  15770. rightIndex = 0;
  15771. rightOuterIndex = 0;
  15772. joinCounter = 0;
  15773. dualCacheInput = NULL;
  15774. }
  15775. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15776. {
  15777. eof = false;
  15778. first = true;
  15779. failingLimit.clear();
  15780. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  15781. keepLimit = helper.getKeepLimit();
  15782. if(keepLimit == 0)
  15783. keepLimit = (unsigned)-1;
  15784. atmostsTriggered = 0;
  15785. atmostLimit = helper.getJoinLimit();
  15786. if(atmostLimit == 0)
  15787. atmostLimit = (unsigned)-1;
  15788. else
  15789. assertex(!rightOuterJoin);
  15790. abortLimit = helper.getMatchAbortLimit();
  15791. if (abortLimit == 0)
  15792. abortLimit = (unsigned)-1;
  15793. if (rightOuterJoin)
  15794. createDefaultLeft();
  15795. if (leftOuterJoin || limitOnFail)
  15796. createDefaultRight();
  15797. ICompare *compareLeft = helper.queryCompareLeft();
  15798. if (helper.isLeftAlreadySorted())
  15799. groupedInput.setown(createGroupedInputReader(inputStream, compareLeft));
  15800. else
  15801. {
  15802. bool isStable = (helper.getJoinFlags() & JFunstable) == 0;
  15803. RoxieSortAlgorithm sortAlgorithm;
  15804. if (forceSpill)
  15805. sortAlgorithm = isStable ? stableSpillingQuickSortAlgorithm : spillingQuickSortAlgorithm;
  15806. else
  15807. sortAlgorithm = isStable ? stableQuickSortAlgorithm : quickSortAlgorithm;
  15808. groupedInput.setown(createSortedGroupedInputReader(inputStream, compareLeft, createSortAlgorithm(sortAlgorithm, compareLeft, ctx->queryRowManager(), input->queryOutputMeta(), ctx->queryCodeContext(), tempDirectory, activityId)));
  15809. }
  15810. if ((helper.getJoinFlags() & JFlimitedprefixjoin) && helper.getJoinLimit())
  15811. { //limited match join (s[1..n])
  15812. dualcache.setown(new CRHDualCache());
  15813. dualcache->init(groupedInput);
  15814. dualCacheInput = dualcache->queryOut1();
  15815. failingOuterAtmost = false;
  15816. matchedLeft = false;
  15817. leftIndex = 0;
  15818. rightOuterIndex = 0;
  15819. joinCounter = 0;
  15820. limitedhelper.setown(createRHLimitedCompareHelper());
  15821. limitedhelper->init( helper.getJoinLimit(), dualcache->queryOut2(), collate, helper.queryPrefixCompare() );
  15822. }
  15823. }
  15824. virtual void reset()
  15825. {
  15826. if (atmostsTriggered)
  15827. noteStatistic(StNumAtmostTriggered, atmostsTriggered);
  15828. group.clear();
  15829. groupedInput.clear();
  15830. CRoxieServerActivity::reset();
  15831. defaultLeft.clear();
  15832. defaultRight.clear();
  15833. }
  15834. virtual const void * nextRow()
  15835. {
  15836. ActivityTimer t(totalCycles, timeActivities);
  15837. if (limitedhelper)
  15838. {
  15839. while(!eof) //limited match join
  15840. {
  15841. if (!group.isItem(rightIndex))
  15842. {
  15843. lhs.setown(dualCacheInput->nextRow());
  15844. if (lhs)
  15845. {
  15846. rightIndex = 0;
  15847. joinCounter = 0;
  15848. group.clear();
  15849. limitedhelper->getGroup(group,lhs);
  15850. }
  15851. else
  15852. {
  15853. eof = true;
  15854. }
  15855. }
  15856. if (group.isItem(rightIndex))
  15857. {
  15858. const void * rhs = group.item(rightIndex++);
  15859. if(helper.match(lhs, rhs))
  15860. {
  15861. const void * ret = joinRecords(lhs, rhs, ++joinCounter, NULL);
  15862. if(ret)
  15863. {
  15864. processed++;
  15865. return ret;
  15866. }
  15867. }
  15868. }
  15869. }
  15870. return NULL;
  15871. }
  15872. else
  15873. {
  15874. if (first)
  15875. {
  15876. first = false;
  15877. fillGroup();
  15878. }
  15879. while(!eof)
  15880. {
  15881. if(failingOuterAtmost)
  15882. while(group.isItem(leftIndex))
  15883. {
  15884. const void * ret = joinRecords(group.item(leftIndex++), defaultRight, 0, NULL);
  15885. if(ret)
  15886. {
  15887. processed++;
  15888. return ret;
  15889. }
  15890. }
  15891. if((joinLimit == 0) || !group.isItem(rightIndex))
  15892. {
  15893. if(leftOuterJoin && !matchedLeft && !failingLimit)
  15894. {
  15895. const void * ret = joinRecords(group.item(leftIndex), defaultRight, 0, NULL);
  15896. if(ret)
  15897. {
  15898. matchedLeft = true;
  15899. processed++;
  15900. return ret;
  15901. }
  15902. }
  15903. leftIndex++;
  15904. matchedLeft = false;
  15905. rightIndex = 0;
  15906. joinCounter = 0;
  15907. joinLimit = keepLimit;
  15908. }
  15909. if(!group.isItem(leftIndex))
  15910. {
  15911. if(failingLimit || failingOuterAtmost)
  15912. {
  15913. const void * lhs;
  15914. while((lhs = groupedInput->nextRow()) != NULL) // dualCache never active here
  15915. {
  15916. const void * ret = joinRecords(lhs, defaultRight, 0, failingLimit);
  15917. ReleaseRoxieRow(lhs);
  15918. if(ret)
  15919. {
  15920. processed++;
  15921. return ret;
  15922. }
  15923. }
  15924. failingLimit.clear();
  15925. }
  15926. if(rightOuterJoin && !failingLimit)
  15927. while(group.isItem(rightOuterIndex))
  15928. if(!matchedRight.item(rightOuterIndex++))
  15929. {
  15930. const void * ret = joinRecords(defaultLeft, group.item(rightOuterIndex-1), 0, NULL);
  15931. if(ret)
  15932. {
  15933. processed++;
  15934. return ret;
  15935. }
  15936. }
  15937. if(!fillGroup())
  15938. return NULL;
  15939. continue;
  15940. }
  15941. const void * lhs = group.item(leftIndex);
  15942. if(failingLimit)
  15943. {
  15944. leftIndex++;
  15945. const void * ret = joinRecords(lhs, defaultRight, 0, failingLimit);
  15946. if(ret)
  15947. {
  15948. processed++;
  15949. return ret;
  15950. }
  15951. }
  15952. else
  15953. {
  15954. const void * rhs = group.item(rightIndex++);
  15955. if(helper.match(lhs, rhs))
  15956. {
  15957. matchedLeft = true;
  15958. matchedRight.replace(true, rightIndex-1);
  15959. if(!exclude)
  15960. {
  15961. const void * ret = joinRecords(lhs, rhs, ++joinCounter, NULL);
  15962. if(ret)
  15963. {
  15964. processed++;
  15965. joinLimit--;
  15966. return ret;
  15967. }
  15968. }
  15969. }
  15970. }
  15971. }
  15972. return NULL;
  15973. }
  15974. }
  15975. };
  15976. class CRoxieServerSelfJoinActivityFactory : public CRoxieServerActivityFactory
  15977. {
  15978. bool forceSpill;
  15979. public:
  15980. CRoxieServerSelfJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15981. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15982. {
  15983. forceSpill = queryFactory.queryOptions().allSortsMaySpill || _graphNode.getPropBool("hint[@name='spill']/@value", false);;
  15984. }
  15985. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15986. {
  15987. return new CRoxieServerSelfJoinActivity(_ctx, this, _probeManager, forceSpill);
  15988. }
  15989. virtual const StatisticsMapping &queryStatsMapping() const
  15990. {
  15991. return joinStatistics;
  15992. }
  15993. };
  15994. IRoxieServerActivityFactory *createRoxieServerSelfJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15995. {
  15996. return new CRoxieServerSelfJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15997. }
  15998. //=====================================================================================================
  15999. class CRoxieServerLookupJoinActivity : public CRoxieServerTwoInputActivity
  16000. {
  16001. private:
  16002. class LookupTable : public CInterface
  16003. {
  16004. public:
  16005. LookupTable(IHThorHashJoinArg &helper)
  16006. : leftRightCompare(helper.queryCompareLeftRight()), rightCompare(helper.queryCompareRight()),
  16007. leftHash(helper.queryHashLeft()), rightHash(helper.queryHashRight())
  16008. {
  16009. size = 0;
  16010. }
  16011. virtual const void *find(const void * left) const = 0;
  16012. virtual const void *findNext(const void * left) const = 0;
  16013. protected:
  16014. ICompare * leftRightCompare;
  16015. ICompare * rightCompare;
  16016. IHash * leftHash;
  16017. IHash * rightHash;
  16018. unsigned size;
  16019. };
  16020. class DedupLookupTable : public LookupTable
  16021. {
  16022. public:
  16023. DedupLookupTable(ConstPointerArray &rightRows, IHThorHashJoinArg &helper)
  16024. : LookupTable(helper)
  16025. {
  16026. size = (4*rightRows.length())/3 + 1;
  16027. table = (const void * *)calloc(size, sizeof(void *)); // This should probably be allocated from roxiemem (and size rounded up to actual available size)
  16028. ForEachItemIn(idx, rightRows)
  16029. add(rightRows.item(idx));
  16030. }
  16031. ~DedupLookupTable()
  16032. {
  16033. roxiemem::ReleaseRoxieRowArray(size, table);
  16034. free(table);
  16035. }
  16036. virtual const void *find(const void * left) const
  16037. {
  16038. unsigned index = leftHash->hash(left) % size;
  16039. unsigned start = index;
  16040. while (table[index])
  16041. {
  16042. if(leftRightCompare->docompare(left, table[index]) == 0)
  16043. return table[index];
  16044. index++;
  16045. if (index==size)
  16046. index = 0;
  16047. if (index==start)
  16048. throw MakeStringException(ROXIE_JOIN_ERROR, "Internal error in lookup join activity (hash table full on lookup)");
  16049. }
  16050. return NULL;
  16051. }
  16052. virtual const void *findNext(const void * left) const
  16053. {
  16054. return NULL;
  16055. }
  16056. protected:
  16057. void add(const void * right)
  16058. {
  16059. unsigned index = rightHash->hash(right) % size;
  16060. unsigned start = index;
  16061. while (table[index])
  16062. {
  16063. if (rightCompare->docompare(table[index], right) == 0)
  16064. {
  16065. ReleaseRoxieRow(right);
  16066. return;
  16067. }
  16068. index++;
  16069. if (index==size)
  16070. index = 0;
  16071. if (index==start)
  16072. throw MakeStringException(ROXIE_JOIN_ERROR, "Internal error in lookup join activity (hash table full on add)");
  16073. }
  16074. table[index] = right;
  16075. }
  16076. const void * * table;
  16077. };
  16078. class FewLookupTable : public LookupTable
  16079. {
  16080. public:
  16081. FewLookupTable(ConstPointerArray &rightRows, IHThorHashJoinArg &helper)
  16082. : LookupTable(helper)
  16083. {
  16084. size = (4*rightRows.length())/3 + 1;
  16085. table = (const void * *)calloc(size, sizeof(void *)); // This should probably be allocated from roxiemem
  16086. findex = fstart = BadIndex;
  16087. ForEachItemIn(idx, rightRows)
  16088. add(rightRows.item(idx));
  16089. }
  16090. ~FewLookupTable()
  16091. {
  16092. roxiemem::ReleaseRoxieRowArray(size, table);
  16093. free(table);
  16094. }
  16095. virtual const void *find(const void * left) const
  16096. {
  16097. fstart = leftHash->hash(left) % size;
  16098. findex = fstart;
  16099. return doFind(left);
  16100. }
  16101. virtual const void *findNext(const void * left) const
  16102. {
  16103. if (findex == BadIndex)
  16104. return NULL;
  16105. advance();
  16106. return doFind(left);
  16107. }
  16108. protected:
  16109. void add(const void * right)
  16110. {
  16111. unsigned start = rightHash->hash(right) % size;
  16112. unsigned index = start;
  16113. while (table[index])
  16114. {
  16115. index++;
  16116. if (index==size)
  16117. index = 0;
  16118. if (index==start)
  16119. throwUnexpected(); //table is full, should never happen
  16120. }
  16121. table[index] = right;
  16122. }
  16123. void advance() const
  16124. {
  16125. findex++;
  16126. if(findex==size)
  16127. findex = 0;
  16128. if(findex==fstart)
  16129. throw MakeStringException(ROXIE_JOIN_ERROR, "Internal error in lookup join activity (hash table full on lookup)");
  16130. }
  16131. const void *doFind(const void * left) const
  16132. {
  16133. while(table[findex])
  16134. {
  16135. if (leftRightCompare->docompare(left, table[findex]) == 0)
  16136. return table[findex];
  16137. advance();
  16138. }
  16139. findex = BadIndex;
  16140. return NULL;
  16141. }
  16142. const void * * table;
  16143. unsigned mutable fstart;
  16144. unsigned mutable findex;
  16145. static unsigned const BadIndex;
  16146. };
  16147. class ManyLookupTable : public LookupTable
  16148. {
  16149. public:
  16150. ManyLookupTable(ConstPointerArray &rightRows, IHThorHashJoinArg &helper)
  16151. : LookupTable(helper)
  16152. {
  16153. rightRows.swapWith(rowtable);
  16154. UInt64Array groups;
  16155. unsigned numRows = rowtable.length();
  16156. if (numRows)
  16157. {
  16158. unsigned groupStart = 0;
  16159. const void *groupStartRow = rowtable.item(0);
  16160. for (unsigned i=1; i < numRows; i++)
  16161. {
  16162. const void *thisRow = rowtable.item(i);
  16163. if (rightCompare->docompare(groupStartRow, thisRow))
  16164. {
  16165. groups.append(makeint64(groupStart, i-groupStart));
  16166. groupStart = i;
  16167. groupStartRow = thisRow;
  16168. }
  16169. }
  16170. groups.append(makeint64(groupStart, numRows-groupStart));
  16171. }
  16172. size = (4*groups.length())/3 + 1;
  16173. table = (__uint64 *) calloc(size, sizeof(__uint64)); // This should probably be allocated from roxiemem
  16174. ForEachItemIn(idx, groups)
  16175. {
  16176. unsigned __int64 group = groups.item(idx);
  16177. unsigned groupstart = high(group);
  16178. const void *row = rowtable.item(groupstart);
  16179. add(row, group);
  16180. }
  16181. }
  16182. ~ManyLookupTable()
  16183. {
  16184. roxiemem::ReleaseRoxieRows(rowtable);
  16185. free(table);
  16186. }
  16187. void add(const void *row, unsigned __int64 group)
  16188. {
  16189. unsigned start = rightHash->hash(row) % size;
  16190. unsigned index = start;
  16191. while (table[index])
  16192. {
  16193. index++;
  16194. if (index==size)
  16195. index = 0;
  16196. if (index==start)
  16197. throwUnexpected(); //table is full, should never happen
  16198. }
  16199. table[index] = group;
  16200. }
  16201. virtual const void *find(const void * left) const
  16202. {
  16203. unsigned index = leftHash->hash(left) % size;
  16204. unsigned start = index;
  16205. while (table[index])
  16206. {
  16207. __uint64 group = table[index];
  16208. currentMatch = high(group);
  16209. const void *right = rowtable.item(currentMatch);
  16210. if (leftRightCompare->docompare(left, right) == 0)
  16211. {
  16212. currentMatch++;
  16213. matchCount = low(group) - 1;
  16214. return right;
  16215. }
  16216. index++;
  16217. if (index==size)
  16218. index = 0;
  16219. if (index==start)
  16220. throw MakeStringException(ROXIE_JOIN_ERROR, "Internal error in lookup join activity (hash table full on lookup)");
  16221. }
  16222. matchCount = 0;
  16223. return NULL;
  16224. }
  16225. virtual const void *findNext(const void * left) const
  16226. {
  16227. if (!matchCount)
  16228. return NULL;
  16229. matchCount--;
  16230. return rowtable.item(currentMatch++);
  16231. }
  16232. protected:
  16233. __uint64 *table;
  16234. ConstPointerArray rowtable;
  16235. mutable unsigned currentMatch;
  16236. mutable unsigned matchCount;
  16237. };
  16238. IHThorHashJoinArg &helper;
  16239. bool leftOuterJoin;
  16240. bool exclude;
  16241. bool eog;
  16242. bool many;
  16243. bool dedupRHS;
  16244. bool useFewTable;
  16245. bool matchedGroup;
  16246. const void *left;
  16247. OwnedConstRoxieRow defaultRight;
  16248. Owned<LookupTable> table;
  16249. unsigned keepLimit;
  16250. unsigned atmostLimit;
  16251. unsigned atmostsTriggered;
  16252. unsigned limitLimit;
  16253. unsigned joinCounter;
  16254. bool limitFail;
  16255. bool limitOnFail;
  16256. bool hasGroupLimit;
  16257. bool isSmartJoin;
  16258. unsigned keepCount;
  16259. bool gotMatch;
  16260. bool cloneLeft;
  16261. ConstPointerArray rightGroup;
  16262. aindex_t rightGroupIndex;
  16263. Owned<IException> failingLimit;
  16264. ConstPointerArray filteredRight;
  16265. ThorActivityKind activityKind;
  16266. Owned<IEngineRowAllocator> defaultRightAllocator;
  16267. void createDefaultRight()
  16268. {
  16269. if (!defaultRight)
  16270. {
  16271. if (!defaultRightAllocator)
  16272. defaultRightAllocator.setown(ctx->queryCodeContext()->getRowAllocator(input1->queryOutputMeta(), activityId));
  16273. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  16274. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  16275. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  16276. }
  16277. }
  16278. public:
  16279. CRoxieServerLookupJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _useFewTable)
  16280. : CRoxieServerTwoInputActivity(_ctx, _factory, _probeManager), helper((IHThorHashJoinArg &)basehelper), useFewTable(_useFewTable)
  16281. {
  16282. unsigned joinFlags = helper.getJoinFlags();
  16283. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  16284. assertex((joinFlags & JFrightouter) == 0);
  16285. exclude = (joinFlags & JFexclude) != 0;
  16286. many = (joinFlags & JFmanylookup) != 0;
  16287. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  16288. dedupRHS = (joinFlags & (JFmanylookup | JFmatchrequired | JFtransformMaySkip)) == 0; // optimisation: can implicitly dedup RHS unless is many lookup, or match required, or transform may skip
  16289. left = NULL;
  16290. activityKind = factory->getKind();
  16291. eog = false;
  16292. matchedGroup = false;
  16293. gotMatch = false;
  16294. keepLimit = 0;
  16295. keepCount = 0;
  16296. joinCounter = 0;
  16297. atmostLimit = 0;
  16298. atmostsTriggered = 0;
  16299. limitLimit = 0;
  16300. rightGroupIndex = 0;
  16301. hasGroupLimit = false;
  16302. isSmartJoin = (joinFlags & JFsmart) != 0;
  16303. getLimitType(joinFlags, limitFail, limitOnFail);
  16304. }
  16305. void loadRight()
  16306. {
  16307. ConstPointerArray rightset;
  16308. try
  16309. {
  16310. const void * next;
  16311. while(true)
  16312. {
  16313. next = inputStream1->ungroupedNextRow();
  16314. if(!next)
  16315. break;
  16316. rightset.append(next);
  16317. }
  16318. if (!dedupRHS)
  16319. {
  16320. if (useFewTable)
  16321. {
  16322. table.setown(new FewLookupTable(rightset, helper)); // NOTE - takes ownership of rightset
  16323. }
  16324. else
  16325. {
  16326. if (!helper.isRightAlreadySorted())
  16327. {
  16328. if (helper.getJoinFlags() & JFunstable)
  16329. {
  16330. qsortvec(const_cast<void * *>(rightset.getArray()), rightset.ordinality(), *helper.queryCompareRight());
  16331. }
  16332. else
  16333. {
  16334. unsigned rightord = rightset.ordinality();
  16335. MemoryAttr tempAttr(rightord*sizeof(void **)); // Temp storage for stable sort. This should probably be allocated from roxiemem
  16336. void **temp = (void **) tempAttr.bufferBase();
  16337. void **_rows = const_cast<void * *>(rightset.getArray());
  16338. msortvecstableinplace(_rows, rightord, *helper.queryCompareRight(), temp);
  16339. }
  16340. }
  16341. table.setown(new ManyLookupTable(rightset, helper)); // NOTE - takes ownership of rightset
  16342. }
  16343. }
  16344. else
  16345. {
  16346. table.setown(new DedupLookupTable(rightset, helper)); // NOTE - takes ownership of rightset
  16347. }
  16348. }
  16349. catch (...)
  16350. {
  16351. roxiemem::ReleaseRoxieRows(rightset);
  16352. throw;
  16353. }
  16354. };
  16355. virtual void reset()
  16356. {
  16357. if (atmostsTriggered)
  16358. noteStatistic(StNumAtmostTriggered, atmostsTriggered);
  16359. CRoxieServerTwoInputActivity::reset();
  16360. ReleaseClearRoxieRow(left);
  16361. defaultRight.clear();
  16362. table.clear();
  16363. }
  16364. virtual bool needsAllocator() const { return true; }
  16365. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16366. {
  16367. eog = false;
  16368. matchedGroup = false;
  16369. left = NULL;
  16370. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  16371. keepLimit = helper.getKeepLimit();
  16372. if(keepLimit==0) keepLimit = static_cast<unsigned>(-1);
  16373. atmostsTriggered = 0;
  16374. atmostLimit = helper.getJoinLimit();
  16375. limitLimit = helper.getMatchAbortLimit();
  16376. hasGroupLimit = ((atmostLimit > 0) || (limitLimit > 0));
  16377. if(atmostLimit==0) atmostLimit = static_cast<unsigned>(-1);
  16378. if(limitLimit==0) limitLimit = static_cast<unsigned>(-1);
  16379. getLimitType(helper.getJoinFlags(), limitFail, limitOnFail);
  16380. switch (activityKind)
  16381. {
  16382. case TAKlookupjoin:
  16383. case TAKlookupdenormalizegroup:
  16384. case TAKsmartjoin:
  16385. case TAKsmartdenormalizegroup:
  16386. if (leftOuterJoin)
  16387. createDefaultRight();
  16388. break;
  16389. }
  16390. if (limitOnFail)
  16391. createDefaultRight();
  16392. }
  16393. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  16394. {
  16395. if (!idx && (helper.getJoinFlags() & JFparallel) != 0)
  16396. {
  16397. puller.setown(new CRoxieServerReadAheadInput(ctx, ctx->queryOptions().parallelJoinPreload));
  16398. puller->setInput(0, _sourceIdx, _in);
  16399. _in = puller;
  16400. _sourceIdx = 0;
  16401. }
  16402. CRoxieServerTwoInputActivity::setInput(idx, _sourceIdx, _in);
  16403. }
  16404. virtual const void * nextRow()
  16405. {
  16406. ActivityTimer t(totalCycles, timeActivities);
  16407. if(!table)
  16408. loadRight();
  16409. switch (activityKind)
  16410. {
  16411. case TAKlookupjoin:
  16412. case TAKsmartjoin:
  16413. return nextRowJoin();
  16414. case TAKlookupdenormalize:
  16415. case TAKlookupdenormalizegroup:
  16416. case TAKsmartdenormalize:
  16417. case TAKsmartdenormalizegroup:
  16418. return nextRowDenormalize();
  16419. }
  16420. throwUnexpected();
  16421. }
  16422. private:
  16423. const void * nextRowJoin()
  16424. {
  16425. if(!table)
  16426. loadRight();
  16427. while(true)
  16428. {
  16429. const void * right = NULL;
  16430. if(!left)
  16431. {
  16432. left = inputStream->nextRow();
  16433. keepCount = keepLimit;
  16434. joinCounter = 0;
  16435. if(!left)
  16436. {
  16437. if (isSmartJoin)
  16438. left = inputStream->nextRow();
  16439. if (!left)
  16440. {
  16441. if(matchedGroup || eog)
  16442. {
  16443. matchedGroup = false;
  16444. eog = true;
  16445. return NULL;
  16446. }
  16447. eog = true;
  16448. continue;
  16449. }
  16450. }
  16451. eog = false;
  16452. gotMatch = false;
  16453. right = getRightFirst();
  16454. }
  16455. else
  16456. right = getRightNext();
  16457. const void * ret = NULL;
  16458. if(failingLimit)
  16459. {
  16460. ret = joinException(left, failingLimit);
  16461. }
  16462. else
  16463. {
  16464. while(right)
  16465. {
  16466. if(helper.match(left, right))
  16467. {
  16468. gotMatch = true;
  16469. if(exclude)
  16470. break;
  16471. ret = joinRecords(left, right, ++joinCounter);
  16472. if(ret)
  16473. {
  16474. processed++;
  16475. break;
  16476. }
  16477. }
  16478. right = getRightNext();
  16479. ret = NULL;
  16480. }
  16481. if(leftOuterJoin && !gotMatch)
  16482. {
  16483. ret = joinRecords(left, defaultRight, 0);
  16484. gotMatch = true;
  16485. }
  16486. }
  16487. if(ret)
  16488. {
  16489. matchedGroup = true;
  16490. processed++;
  16491. if(!many || (--keepCount == 0) || failingLimit)
  16492. {
  16493. ReleaseClearRoxieRow(left);
  16494. failingLimit.clear();
  16495. }
  16496. return ret;
  16497. }
  16498. ReleaseClearRoxieRow(left);
  16499. }
  16500. }
  16501. const void * nextRowDenormalize()
  16502. {
  16503. while(true)
  16504. {
  16505. left = inputStream->nextRow();
  16506. if(!left)
  16507. {
  16508. if (!matchedGroup || isSmartJoin)
  16509. left = inputStream->nextRow();
  16510. if (!left)
  16511. {
  16512. matchedGroup = false;
  16513. return NULL;
  16514. }
  16515. }
  16516. gotMatch = false;
  16517. const void * right = getRightFirst();
  16518. const void * ret = NULL;
  16519. if (failingLimit)
  16520. ret = joinException(left, failingLimit);
  16521. else if (activityKind == TAKlookupdenormalize || activityKind == TAKsmartdenormalize)
  16522. {
  16523. OwnedConstRoxieRow newLeft;
  16524. newLeft.set(left);
  16525. unsigned rowSize = 0;
  16526. unsigned leftCount = 0;
  16527. keepCount = keepLimit;
  16528. while (right)
  16529. {
  16530. try
  16531. {
  16532. if (helper.match(left, right))
  16533. {
  16534. gotMatch = true;
  16535. if (exclude)
  16536. break;
  16537. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16538. unsigned thisSize = helper.transform(rowBuilder, newLeft, right, ++leftCount);
  16539. if (thisSize)
  16540. {
  16541. rowSize = thisSize;
  16542. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  16543. }
  16544. if(!many || (--keepCount == 0))
  16545. break;
  16546. }
  16547. right = getRightNext();
  16548. }
  16549. catch (IException *E)
  16550. {
  16551. throw makeWrappedException(E);
  16552. }
  16553. }
  16554. if (rowSize)
  16555. ret = newLeft.getClear();
  16556. else if (leftOuterJoin && !gotMatch)
  16557. {
  16558. ret = left;
  16559. left = NULL;
  16560. }
  16561. }
  16562. else
  16563. {
  16564. filteredRight.kill();
  16565. keepCount = keepLimit;
  16566. while (right)
  16567. {
  16568. if (helper.match(left, right))
  16569. {
  16570. gotMatch = true;
  16571. if(exclude)
  16572. break;
  16573. filteredRight.append(right);
  16574. if(!many || (--keepCount == 0))
  16575. break;
  16576. }
  16577. right = getRightNext();
  16578. }
  16579. if((filteredRight.ordinality() > 0) || (leftOuterJoin && !gotMatch))
  16580. ret = denormalizeRecords(left, filteredRight);
  16581. filteredRight.kill();
  16582. }
  16583. ReleaseRoxieRow(left);
  16584. left = NULL;
  16585. failingLimit.clear();
  16586. if(ret)
  16587. {
  16588. matchedGroup = true;
  16589. processed++;
  16590. return ret;
  16591. }
  16592. }
  16593. }
  16594. const void * joinRecords(const void * left, const void * right, unsigned counter)
  16595. {
  16596. if (cloneLeft)
  16597. {
  16598. LinkRoxieRow(left);
  16599. return left;
  16600. }
  16601. try
  16602. {
  16603. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16604. unsigned outSize = helper.transform(rowBuilder, left, right, counter);
  16605. if (outSize)
  16606. return rowBuilder.finalizeRowClear(outSize);
  16607. else
  16608. return NULL;
  16609. }
  16610. catch (IException *E)
  16611. {
  16612. throw makeWrappedException(E);
  16613. }
  16614. }
  16615. const void * joinException(const void * left, IException * except)
  16616. {
  16617. try
  16618. {
  16619. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16620. unsigned outSize = helper.onFailTransform(rowBuilder, left, defaultRight, except);
  16621. if (outSize)
  16622. return rowBuilder.finalizeRowClear(outSize);
  16623. else
  16624. return NULL;
  16625. }
  16626. catch (IException *E)
  16627. {
  16628. throw makeWrappedException(E);
  16629. }
  16630. }
  16631. const void * denormalizeRecords(const void * left, ConstPointerArray & rows)
  16632. {
  16633. try
  16634. {
  16635. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16636. unsigned numRows = rows.ordinality();
  16637. const void * right = numRows ? rows.item(0) : defaultRight.get();
  16638. unsigned outSize = helper.transform(rowBuilder, left, right, numRows, (const void * *)rows.getArray());
  16639. if (outSize)
  16640. return rowBuilder.finalizeRowClear(outSize);
  16641. else
  16642. return NULL;
  16643. }
  16644. catch (IException *E)
  16645. {
  16646. throw makeWrappedException(E);
  16647. }
  16648. }
  16649. const void * getRightFirst() { if(hasGroupLimit) return fillRightGroup(); else return table->find(left); }
  16650. const void * getRightNext() { if(hasGroupLimit) return readRightGroup(); else return table->findNext(left); }
  16651. const void * readRightGroup() { if(rightGroup.isItem(rightGroupIndex)) return rightGroup.item(rightGroupIndex++); else return NULL; }
  16652. const void *fillRightGroup()
  16653. {
  16654. rightGroup.kill();
  16655. for(const void * right = table->find(left); right; right = table->findNext(left))
  16656. {
  16657. rightGroup.append(right);
  16658. if(rightGroup.ordinality() > limitLimit)
  16659. {
  16660. if(limitFail)
  16661. failLimit();
  16662. gotMatch = true;
  16663. if (ctx->queryDebugContext())
  16664. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  16665. if(limitOnFail)
  16666. {
  16667. assertex(!failingLimit);
  16668. try
  16669. {
  16670. failLimit();
  16671. }
  16672. catch(IException * e)
  16673. {
  16674. failingLimit.setown(e);
  16675. }
  16676. assertex(failingLimit != NULL);
  16677. }
  16678. else
  16679. {
  16680. rightGroup.kill();
  16681. }
  16682. break;
  16683. }
  16684. if(rightGroup.ordinality() > atmostLimit)
  16685. {
  16686. atmostsTriggered++;
  16687. rightGroup.kill();
  16688. break;
  16689. }
  16690. }
  16691. rightGroupIndex = 0;
  16692. return readRightGroup();
  16693. }
  16694. void failLimit()
  16695. {
  16696. helper.onMatchAbortLimitExceeded();
  16697. CommonXmlWriter xmlwrite(XWFtrim|XWFopt );
  16698. if(!ctx->isBlind() && input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  16699. {
  16700. input->queryOutputMeta()->toXML(static_cast<const unsigned char *>(left), xmlwrite);
  16701. }
  16702. throw MakeStringException(ROXIE_TOO_MANY_RESULTS, "More than %u match candidates in join %d for row %s", limitLimit, queryId(), xmlwrite.str());
  16703. }
  16704. };
  16705. unsigned const CRoxieServerLookupJoinActivity::FewLookupTable::BadIndex(static_cast<unsigned>(-1));
  16706. class CRoxieServerLookupJoinActivityFactory : public CRoxieServerJoinActivityFactory
  16707. {
  16708. public:
  16709. CRoxieServerLookupJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  16710. : CRoxieServerJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  16711. {
  16712. Owned<IHThorHashJoinArg> helper = (IHThorHashJoinArg *) helperFactory();
  16713. useFewTable = _graphNode.getPropBool("hint[@name='usefewtable']/@value", false);
  16714. if((helper->getJoinFlags() & (JFfirst | JFfirstleft | JFfirstright | JFslidingmatch)) != 0)
  16715. throw MakeStringException(ROXIE_INVALID_FLAGS, "Invalid flags for lookup join activity"); // code generator should never create such an activity
  16716. }
  16717. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  16718. {
  16719. return new CRoxieServerLookupJoinActivity(_ctx, this, _probeManager, useFewTable);
  16720. }
  16721. virtual const StatisticsMapping &queryStatsMapping() const
  16722. {
  16723. return joinStatistics;
  16724. }
  16725. protected:
  16726. bool useFewTable;
  16727. };
  16728. IRoxieServerActivityFactory *createRoxieServerLookupJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  16729. {
  16730. return new CRoxieServerLookupJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  16731. }
  16732. //=====================================================================================================
  16733. class CRoxieServerAllJoinActivity : public CRoxieServerTwoInputActivity
  16734. {
  16735. private:
  16736. IHThorAllJoinArg &helper;
  16737. bool leftOuterJoin;
  16738. bool rightOuterJoin;
  16739. bool exclude;
  16740. OwnedConstRoxieRow defaultRight;
  16741. OwnedConstRoxieRow defaultLeft;
  16742. Owned<IEngineRowAllocator> defaultRightAllocator;
  16743. Owned<IEngineRowAllocator> defaultLeftAllocator;
  16744. const void *left;
  16745. unsigned countForLeft;
  16746. ConstPointerArray rightset;
  16747. BoolArray matchedRight; // MORE - could use a bitset...
  16748. unsigned keepLimit;
  16749. bool started;
  16750. bool eog;
  16751. bool eos;
  16752. bool matchedLeft;
  16753. bool matchedGroup;
  16754. bool leftIsGrouped;
  16755. bool cloneLeft;
  16756. unsigned rightIndex;
  16757. unsigned joinCounter;
  16758. unsigned rightOrdinality;
  16759. ThorActivityKind activityKind;
  16760. ConstPointerArray filteredRight;
  16761. void createDefaultLeft()
  16762. {
  16763. if (!defaultLeft)
  16764. {
  16765. if (!defaultLeftAllocator)
  16766. defaultLeftAllocator.setown(ctx->queryCodeContext()->getRowAllocator(input->queryOutputMeta(), activityId));
  16767. RtlDynamicRowBuilder rowBuilder(defaultLeftAllocator);
  16768. size32_t thisSize = helper.createDefaultLeft(rowBuilder);
  16769. defaultLeft.setown(rowBuilder.finalizeRowClear(thisSize));
  16770. }
  16771. }
  16772. void createDefaultRight()
  16773. {
  16774. if (!defaultRight)
  16775. {
  16776. if (!defaultRightAllocator)
  16777. defaultRightAllocator.setown(ctx->queryCodeContext()->getRowAllocator(input1->queryOutputMeta(), activityId));
  16778. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  16779. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  16780. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  16781. }
  16782. }
  16783. public:
  16784. CRoxieServerAllJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  16785. : CRoxieServerTwoInputActivity(_ctx, _factory, _probeManager), helper((IHThorAllJoinArg &)basehelper)
  16786. {
  16787. unsigned joinFlags = helper.getJoinFlags();
  16788. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  16789. rightOuterJoin = (joinFlags & JFrightouter) != 0;
  16790. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  16791. keepLimit = (unsigned) -1;
  16792. exclude = (joinFlags & JFexclude) != 0;
  16793. left = NULL;
  16794. started = true;
  16795. eog = false;
  16796. eos = false;
  16797. matchedLeft = false;
  16798. matchedGroup = false;
  16799. activityKind = factory->getKind();
  16800. rightIndex = 0;
  16801. rightOrdinality = 0;
  16802. leftIsGrouped = false;
  16803. countForLeft = 0;
  16804. joinCounter = 0;
  16805. }
  16806. virtual void reset()
  16807. {
  16808. defaultRight.clear();
  16809. defaultLeft.clear();
  16810. ReleaseRoxieRows(rightset);
  16811. matchedRight.kill();
  16812. CRoxieServerTwoInputActivity::reset();
  16813. }
  16814. virtual bool needsAllocator() const { return true; }
  16815. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16816. {
  16817. eog = false;
  16818. eos = false;
  16819. matchedLeft = false;
  16820. matchedGroup = false;
  16821. started = false;
  16822. left = NULL;
  16823. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  16824. keepLimit = helper.getKeepLimit();
  16825. if(keepLimit==0)
  16826. keepLimit = (unsigned) -1;
  16827. countForLeft = keepLimit;
  16828. joinCounter = 0;
  16829. leftIsGrouped = input->queryOutputMeta()->isGrouped();
  16830. if((activityKind==TAKalljoin || activityKind==TAKalldenormalizegroup) && leftOuterJoin)
  16831. createDefaultRight();
  16832. if(rightOuterJoin)
  16833. createDefaultLeft();
  16834. }
  16835. void loadRight()
  16836. {
  16837. const void * next;
  16838. while(true)
  16839. {
  16840. next = inputStream1->ungroupedNextRow();
  16841. if(!next)
  16842. break;
  16843. rightset.append(next);
  16844. matchedRight.append(false);
  16845. }
  16846. rightIndex = 0;
  16847. joinCounter = 0;
  16848. rightOrdinality = rightset.ordinality();
  16849. }
  16850. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  16851. {
  16852. if (!idx && (helper.getJoinFlags() & JFparallel) != 0)
  16853. {
  16854. puller.setown(new CRoxieServerReadAheadInput(ctx, ctx->queryOptions().parallelJoinPreload));
  16855. puller->setInput(0, _sourceIdx, _in);
  16856. _in = puller;
  16857. _sourceIdx = 0;
  16858. }
  16859. CRoxieServerTwoInputActivity::setInput(idx, _sourceIdx, _in);
  16860. }
  16861. const void * joinRecords(const void * left, const void * right, unsigned counter)
  16862. {
  16863. // MORE - could share some code with lookup join
  16864. if (cloneLeft)
  16865. {
  16866. LinkRoxieRow(left);
  16867. return left;
  16868. }
  16869. try
  16870. {
  16871. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16872. unsigned outSize = helper.transform(rowBuilder, left, right, counter);
  16873. if (outSize)
  16874. return rowBuilder.finalizeRowClear(outSize);
  16875. else
  16876. return NULL;
  16877. }
  16878. catch (IException *E)
  16879. {
  16880. throw makeWrappedException(E);
  16881. }
  16882. }
  16883. const void * denormalizeRecords(const void * curLeft, ConstPointerArray & rows)
  16884. {
  16885. try
  16886. {
  16887. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16888. unsigned numRows = rows.ordinality();
  16889. const void * right = numRows ? rows.item(0) : defaultRight.get();
  16890. unsigned outSize = helper.transform(rowBuilder, curLeft, right, numRows, rows.getArray());
  16891. if (outSize)
  16892. return rowBuilder.finalizeRowClear(outSize);
  16893. else
  16894. return NULL;
  16895. }
  16896. catch (IException *E)
  16897. {
  16898. throw makeWrappedException(E);
  16899. }
  16900. }
  16901. virtual const void *nextRow()
  16902. {
  16903. ActivityTimer t(totalCycles, timeActivities);
  16904. if(!started)
  16905. {
  16906. started = true;
  16907. left = inputStream->nextRow();
  16908. matchedLeft = false;
  16909. countForLeft = keepLimit;
  16910. joinCounter = 0;
  16911. if(left == NULL)
  16912. {
  16913. eos = true;
  16914. return NULL;
  16915. }
  16916. loadRight();
  16917. }
  16918. const void * ret;
  16919. const void * right;
  16920. if(eos)
  16921. return NULL;
  16922. while(true)
  16923. {
  16924. ret = NULL;
  16925. if((rightIndex == rightOrdinality) || (countForLeft==0))
  16926. {
  16927. if(leftOuterJoin && left && !matchedLeft)
  16928. {
  16929. switch(activityKind)
  16930. {
  16931. case TAKalljoin:
  16932. ret = joinRecords(left, defaultRight, 0);
  16933. break;
  16934. case TAKalldenormalize:
  16935. ret = left;
  16936. left = NULL;
  16937. break;
  16938. case TAKalldenormalizegroup:
  16939. filteredRight.kill();
  16940. ret = denormalizeRecords(left, filteredRight);
  16941. break;
  16942. default:
  16943. throwUnexpected();
  16944. }
  16945. }
  16946. rightIndex = 0;
  16947. joinCounter = 0;
  16948. ReleaseRoxieRow(left);
  16949. left = NULL;
  16950. if(ret)
  16951. {
  16952. matchedGroup = true;
  16953. processed++;
  16954. return ret;
  16955. }
  16956. }
  16957. if(!left)
  16958. {
  16959. left = inputStream->nextRow();
  16960. matchedLeft = false;
  16961. countForLeft = keepLimit;
  16962. joinCounter = 0;
  16963. }
  16964. if(!left)
  16965. {
  16966. if(eog)
  16967. {
  16968. eos = true;
  16969. matchedGroup = false;
  16970. return NULL;
  16971. }
  16972. eog = true;
  16973. if (matchedGroup && leftIsGrouped)
  16974. {
  16975. matchedGroup = false;
  16976. return NULL;
  16977. }
  16978. matchedGroup = false;
  16979. continue;
  16980. }
  16981. eog = false;
  16982. switch(activityKind)
  16983. {
  16984. case TAKalljoin:
  16985. while(rightIndex < rightOrdinality)
  16986. {
  16987. right = rightset.item(rightIndex);
  16988. if(helper.match(left, right))
  16989. {
  16990. matchedLeft = true;
  16991. matchedRight.replace(true, rightIndex);
  16992. if(!exclude)
  16993. ret = joinRecords(left, right, ++joinCounter);
  16994. }
  16995. rightIndex++;
  16996. if(ret)
  16997. {
  16998. countForLeft--;
  16999. matchedGroup = true;
  17000. processed++;
  17001. return ret;
  17002. }
  17003. }
  17004. break;
  17005. case TAKalldenormalize:
  17006. {
  17007. OwnedConstRoxieRow newLeft;
  17008. newLeft.set(left);
  17009. unsigned rowSize = 0;
  17010. unsigned leftCount = 0;
  17011. while((rightIndex < rightOrdinality) && countForLeft)
  17012. {
  17013. right = rightset.item(rightIndex);
  17014. if(helper.match(left, right))
  17015. {
  17016. matchedLeft = true;
  17017. matchedRight.replace(true, rightIndex);
  17018. if(!exclude)
  17019. {
  17020. try
  17021. {
  17022. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17023. unsigned thisSize = helper.transform(rowBuilder, newLeft, right, ++leftCount);
  17024. if(thisSize)
  17025. {
  17026. rowSize = thisSize;
  17027. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  17028. --countForLeft;
  17029. }
  17030. }
  17031. catch (IException *e)
  17032. {
  17033. throw makeWrappedException(e);
  17034. }
  17035. }
  17036. }
  17037. rightIndex++;
  17038. }
  17039. if(rowSize)
  17040. {
  17041. processed++;
  17042. return newLeft.getClear();
  17043. }
  17044. }
  17045. break;
  17046. case TAKalldenormalizegroup:
  17047. filteredRight.kill();
  17048. while((rightIndex < rightOrdinality) && countForLeft)
  17049. {
  17050. right = rightset.item(rightIndex);
  17051. if(helper.match(left, right))
  17052. {
  17053. matchedLeft = true;
  17054. matchedRight.replace(true, rightIndex);
  17055. filteredRight.append(right);
  17056. --countForLeft;
  17057. }
  17058. ++rightIndex;
  17059. }
  17060. if(!exclude && filteredRight.ordinality())
  17061. {
  17062. ret = denormalizeRecords(left, filteredRight);
  17063. filteredRight.kill();
  17064. if(ret)
  17065. {
  17066. processed++;
  17067. return ret;
  17068. }
  17069. }
  17070. break;
  17071. default:
  17072. throwUnexpected();
  17073. }
  17074. }
  17075. }
  17076. };
  17077. class CRoxieServerAllJoinActivityFactory : public CRoxieServerJoinActivityFactory
  17078. {
  17079. public:
  17080. CRoxieServerAllJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17081. : CRoxieServerJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  17082. {
  17083. Owned<IHThorAllJoinArg> helper = (IHThorAllJoinArg *) helperFactory();
  17084. if((helper->getJoinFlags() & (JFfirst | JFfirstleft | JFfirstright)) != 0)
  17085. throw MakeStringException(ROXIE_INVALID_FLAGS, "Invalid flags for join all activity"); // code generator should never create such an activity
  17086. }
  17087. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  17088. {
  17089. return new CRoxieServerAllJoinActivity(_ctx, this, _probeManager);
  17090. }
  17091. virtual const StatisticsMapping &queryStatsMapping() const
  17092. {
  17093. return joinStatistics;
  17094. }
  17095. };
  17096. IRoxieServerActivityFactory *createRoxieServerAllJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17097. {
  17098. return new CRoxieServerAllJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  17099. }
  17100. //=====================================================================================================
  17101. class CRoxieServerTopNActivity : public CRoxieServerLateStartActivity
  17102. {
  17103. unsigned limit;
  17104. bool hasBest;
  17105. bool eoi;
  17106. const void **sorted;
  17107. unsigned sortedCount;
  17108. unsigned curIndex;
  17109. IHThorTopNArg &helper;
  17110. ICompare &compare;
  17111. public:
  17112. CRoxieServerTopNActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17113. : CRoxieServerLateStartActivity(_ctx, _factory, _probeManager), helper((IHThorTopNArg &)basehelper), compare(*helper.queryCompare())
  17114. {
  17115. sorted = NULL;
  17116. sortedCount = 0;
  17117. curIndex = 0;
  17118. limit = 0;
  17119. eoi = false;
  17120. hasBest = false;
  17121. }
  17122. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17123. {
  17124. assertex(sorted == NULL);
  17125. sortedCount = 0;
  17126. curIndex = 0;
  17127. eoi = false;
  17128. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  17129. limit = (unsigned) helper.getLimit();
  17130. hasBest = helper.hasBest();
  17131. lateStart(parentExtractSize, parentExtract, limit > 0);
  17132. // MORE - should we use an expanding array instead?
  17133. if (limit > 0)
  17134. sorted = (const void **) ctx->queryRowManager().allocate((limit+1) * sizeof(const void *), activityId);
  17135. }
  17136. virtual void reset()
  17137. {
  17138. if (sorted)
  17139. {
  17140. roxiemem::ReleaseRoxieRowRange(sorted, curIndex, sortedCount);
  17141. curIndex = 0;
  17142. sortedCount = 0;
  17143. ReleaseRoxieRow(sorted);
  17144. sorted = NULL;
  17145. }
  17146. CRoxieServerLateStartActivity::reset();
  17147. }
  17148. bool abortEarly()
  17149. {
  17150. if (hasBest && (sortedCount == limit))
  17151. {
  17152. int compare = helper.compareBest(sorted[sortedCount-1]);
  17153. if (compare == 0)
  17154. {
  17155. if (meta.isGrouped())
  17156. {
  17157. //MORE: This would be more efficient if we had a away of skipping to the end of the incoming group.
  17158. const void * next;
  17159. while ((next = inputStream->nextRow()) != NULL)
  17160. ReleaseRoxieRow(next);
  17161. }
  17162. else
  17163. eoi = true;
  17164. return true;
  17165. }
  17166. //This only checks the lowest element - we could check all elements inserted, but it would increase the number of compares
  17167. if (compare < 0)
  17168. throw MakeStringException(ROXIE_TOPN_ROW_ERROR, "TOPN: row found that exceeds the best value");
  17169. }
  17170. return false;
  17171. }
  17172. void getSorted()
  17173. {
  17174. curIndex = 0;
  17175. sortedCount = 0;
  17176. if(eoi)
  17177. return;
  17178. const void * next;
  17179. while ((next = inputStream->nextRow()) != NULL)
  17180. {
  17181. if (sortedCount < limit)
  17182. {
  17183. binary_vec_insert_stable(next, sorted, sortedCount, compare);
  17184. sortedCount++;
  17185. if(abortEarly())
  17186. return;
  17187. }
  17188. else
  17189. {
  17190. if(limit && compare.docompare(sorted[sortedCount-1], next) > 0) // MORE - if stability is an issue, need to consider whether this should be > or >=
  17191. {
  17192. binary_vec_insert_stable(next, sorted, sortedCount, compare); // MORE - not sure this is stable!
  17193. ReleaseRoxieRow(sorted[sortedCount]);
  17194. if(abortEarly())
  17195. return;
  17196. }
  17197. else
  17198. {
  17199. ReleaseRoxieRow(next); // do not bother with insertion sort if we know next will fall off the end
  17200. }
  17201. }
  17202. }
  17203. }
  17204. virtual const void * nextRow()
  17205. {
  17206. ActivityTimer t(totalCycles, timeActivities);
  17207. if (eof)
  17208. return NULL;
  17209. if (curIndex >= sortedCount)
  17210. {
  17211. bool eog = sortedCount != 0;
  17212. getSorted();
  17213. if(sortedCount == 0)
  17214. {
  17215. eof = true;
  17216. return NULL;
  17217. }
  17218. if (eog)
  17219. return NULL;
  17220. }
  17221. processed++;
  17222. return sorted[curIndex++];
  17223. }
  17224. };
  17225. class CRoxieServerTopNActivityFactory : public CRoxieServerActivityFactory
  17226. {
  17227. public:
  17228. CRoxieServerTopNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17229. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  17230. {
  17231. }
  17232. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  17233. {
  17234. return new CRoxieServerTopNActivity(_ctx, this, _probeManager);
  17235. }
  17236. };
  17237. IRoxieServerActivityFactory *createRoxieServerTopNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17238. {
  17239. return new CRoxieServerTopNActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  17240. }
  17241. //=================================================================================
  17242. class CRoxieServerLimitActivity : public CRoxieServerActivity
  17243. {
  17244. protected:
  17245. unsigned __int64 rowLimit;
  17246. IHThorLimitArg &helper;
  17247. public:
  17248. CRoxieServerLimitActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17249. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorLimitArg &)basehelper)
  17250. {
  17251. rowLimit = 0;
  17252. }
  17253. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17254. {
  17255. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  17256. rowLimit = helper.getRowLimit(); // could conceivably depend on context so should not compute any earlier than this
  17257. }
  17258. virtual const void *nextRow()
  17259. {
  17260. ActivityTimer t(totalCycles, timeActivities);
  17261. const void * ret = inputStream->nextRow();
  17262. if (ret)
  17263. {
  17264. processed++;
  17265. if (processed > rowLimit)
  17266. {
  17267. ReleaseRoxieRow(ret);
  17268. if (traceLevel > 4)
  17269. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  17270. helper.onLimitExceeded();
  17271. }
  17272. }
  17273. return ret;
  17274. }
  17275. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  17276. {
  17277. ActivityTimer t(totalCycles, timeActivities);
  17278. const void * ret = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  17279. if (ret)
  17280. {
  17281. if (wasCompleteMatch)
  17282. processed++;
  17283. if (processed > rowLimit)
  17284. {
  17285. ReleaseRoxieRow(ret);
  17286. if (traceLevel > 4)
  17287. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  17288. helper.onLimitExceeded();
  17289. }
  17290. }
  17291. return ret;
  17292. }
  17293. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  17294. {
  17295. return input->gatherConjunctions(collector);
  17296. }
  17297. virtual void resetEOF()
  17298. {
  17299. //Do not reset the rowLimit
  17300. inputStream->resetEOF();
  17301. }
  17302. IInputSteppingMeta * querySteppingMeta()
  17303. {
  17304. return input->querySteppingMeta();
  17305. }
  17306. };
  17307. class CRoxieServerLimitActivityFactory : public CRoxieServerActivityFactory
  17308. {
  17309. public:
  17310. CRoxieServerLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17311. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  17312. {
  17313. }
  17314. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  17315. {
  17316. return new CRoxieServerLimitActivity(_ctx, this, _probeManager);
  17317. }
  17318. };
  17319. IRoxieServerActivityFactory *createRoxieServerLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17320. {
  17321. return new CRoxieServerLimitActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  17322. }
  17323. //=====================================================================================================
  17324. class CRoxieServerSkipLimitActivity : public CRoxieServerLimitActivity
  17325. {
  17326. ConstPointerArray buff;
  17327. bool started;
  17328. unsigned index;
  17329. IHThorLimitTransformExtra * transformExtra;
  17330. public:
  17331. CRoxieServerSkipLimitActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _onFail)
  17332. : CRoxieServerLimitActivity(_ctx, _factory, _probeManager)
  17333. {
  17334. transformExtra = NULL;
  17335. started = false;
  17336. index = 0;
  17337. if (_onFail)
  17338. transformExtra = static_cast<IHThorLimitTransformExtra *>(helper.selectInterface(TAIlimittransformextra_1));
  17339. }
  17340. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17341. {
  17342. started = false;
  17343. index = 0;
  17344. CRoxieServerLimitActivity::start(parentExtractSize, parentExtract, paused);
  17345. }
  17346. virtual void reset()
  17347. {
  17348. roxiemem::ReleaseRoxieRowRange(buff.getArray(), index, buff.ordinality());
  17349. buff.kill();
  17350. index = 0;
  17351. started = false;
  17352. CRoxieServerLimitActivity::reset();
  17353. }
  17354. virtual const void *nextRow()
  17355. {
  17356. ActivityTimer t(totalCycles, timeActivities);
  17357. if (!started)
  17358. pullInput();
  17359. if (buff.isItem(index))
  17360. {
  17361. const void * next = buff.item(index++);
  17362. if(next)
  17363. processed++;
  17364. return next;
  17365. }
  17366. return NULL;
  17367. }
  17368. protected:
  17369. void pullInput()
  17370. {
  17371. unsigned count = 0;
  17372. loop
  17373. {
  17374. const void * next = inputStream->nextRow();
  17375. if (next == NULL)
  17376. {
  17377. next = inputStream->nextRow();
  17378. if(next == NULL)
  17379. break;
  17380. buff.append(NULL);
  17381. }
  17382. count++;
  17383. if (count > rowLimit)
  17384. {
  17385. ReleaseRoxieRow(next);
  17386. ReleaseRoxieRows(buff);
  17387. if (ctx->queryDebugContext())
  17388. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  17389. if (transformExtra)
  17390. {
  17391. createRowAllocator();
  17392. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17393. size32_t outSize = transformExtra->transformOnLimitExceeded(rowBuilder);
  17394. if (outSize)
  17395. buff.append(rowBuilder.finalizeRowClear(outSize));
  17396. }
  17397. break;
  17398. }
  17399. buff.append(next);
  17400. }
  17401. started = true;
  17402. }
  17403. };
  17404. class CRoxieServerSkipLimitActivityFactory : public CRoxieServerActivityFactory
  17405. {
  17406. public:
  17407. CRoxieServerSkipLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17408. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  17409. {
  17410. }
  17411. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  17412. {
  17413. return new CRoxieServerSkipLimitActivity(_ctx, this, _probeManager, kind==TAKcreaterowlimit);
  17414. }
  17415. };
  17416. IRoxieServerActivityFactory *createRoxieServerSkipLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17417. {
  17418. return new CRoxieServerSkipLimitActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  17419. }
  17420. //=================================================================================
  17421. class CRoxieServerCatchActivity : public CRoxieServerActivity
  17422. {
  17423. IHThorCatchArg &helper;
  17424. public:
  17425. CRoxieServerCatchActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17426. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorCatchArg &)basehelper)
  17427. {
  17428. }
  17429. virtual const void *nextRow()
  17430. {
  17431. ActivityTimer t(totalCycles, timeActivities);
  17432. try
  17433. {
  17434. const void *ret = inputStream->nextRow();
  17435. if (ret)
  17436. processed++;
  17437. return ret;
  17438. }
  17439. catch (IException *E)
  17440. {
  17441. E->Release();
  17442. helper.onExceptionCaught();
  17443. }
  17444. catch (...)
  17445. {
  17446. helper.onExceptionCaught();
  17447. }
  17448. throwUnexpected(); // onExceptionCaught should have thrown something
  17449. }
  17450. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  17451. {
  17452. try
  17453. {
  17454. ActivityTimer t(totalCycles, timeActivities);
  17455. const void * ret = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  17456. if (ret && wasCompleteMatch)
  17457. processed++;
  17458. return ret;
  17459. }
  17460. catch (IException *E)
  17461. {
  17462. E->Release();
  17463. helper.onExceptionCaught();
  17464. }
  17465. catch (...)
  17466. {
  17467. helper.onExceptionCaught();
  17468. }
  17469. throwUnexpected(); // onExceptionCaught should have thrown something
  17470. }
  17471. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  17472. {
  17473. return input->gatherConjunctions(collector);
  17474. }
  17475. virtual void resetEOF()
  17476. {
  17477. inputStream->resetEOF(); // MORE - why not in base class?
  17478. }
  17479. IInputSteppingMeta * querySteppingMeta()
  17480. {
  17481. return input->querySteppingMeta();
  17482. }
  17483. };
  17484. class CRoxieServerSkipCatchActivity : public CRoxieServerActivity
  17485. {
  17486. ConstPointerArray buff;
  17487. bool started;
  17488. unsigned index;
  17489. IHThorCatchArg &helper;
  17490. bool createRow;
  17491. public:
  17492. CRoxieServerSkipCatchActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _createRow)
  17493. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorCatchArg &)basehelper), createRow(_createRow)
  17494. {
  17495. started = false;
  17496. index = 0;
  17497. }
  17498. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17499. {
  17500. started = false;
  17501. index = 0;
  17502. try
  17503. {
  17504. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  17505. }
  17506. catch (IException *E)
  17507. {
  17508. onException(E);
  17509. started = true;
  17510. }
  17511. catch (...)
  17512. {
  17513. onException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught"));
  17514. started = true;
  17515. }
  17516. }
  17517. virtual void reset()
  17518. {
  17519. roxiemem::ReleaseRoxieRowRange(buff.getArray(), index, buff.ordinality());
  17520. buff.kill();
  17521. index = 0;
  17522. started = false;
  17523. CRoxieServerActivity::reset();
  17524. }
  17525. virtual const void *nextRow()
  17526. {
  17527. ActivityTimer t(totalCycles, timeActivities);
  17528. if (!started)
  17529. pullInput();
  17530. if (buff.isItem(index))
  17531. {
  17532. const void * next = buff.item(index++);
  17533. if(next)
  17534. processed++;
  17535. return next;
  17536. }
  17537. return NULL;
  17538. }
  17539. protected:
  17540. void onException(IException *E)
  17541. {
  17542. inputStream->stop();
  17543. ReleaseRoxieRows(buff);
  17544. if (createRow)
  17545. {
  17546. createRowAllocator();
  17547. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17548. size32_t outSize = helper.transformOnExceptionCaught(rowBuilder, E);
  17549. if (outSize)
  17550. buff.append(rowBuilder.finalizeRowClear(outSize));
  17551. }
  17552. E->Release();
  17553. }
  17554. void pullInput()
  17555. {
  17556. try
  17557. {
  17558. bool EOGseen = false;
  17559. loop
  17560. {
  17561. const void * next = inputStream->nextRow();
  17562. buff.append(next);
  17563. if (next == NULL)
  17564. {
  17565. if (EOGseen)
  17566. break;
  17567. EOGseen = true;
  17568. }
  17569. else
  17570. EOGseen = false;
  17571. }
  17572. }
  17573. catch (IException *E)
  17574. {
  17575. onException(E);
  17576. }
  17577. catch (...)
  17578. {
  17579. onException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught"));
  17580. }
  17581. started = true;
  17582. }
  17583. };
  17584. class CRoxieServerCatchActivityFactory : public CRoxieServerActivityFactory
  17585. {
  17586. public:
  17587. CRoxieServerCatchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17588. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  17589. {
  17590. }
  17591. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  17592. {
  17593. switch (kind)
  17594. {
  17595. case TAKcatch:
  17596. return new CRoxieServerCatchActivity(_ctx, this, _probeManager);
  17597. case TAKskipcatch:
  17598. return new CRoxieServerSkipCatchActivity(_ctx, this, _probeManager, false);
  17599. case TAKcreaterowcatch:
  17600. return new CRoxieServerSkipCatchActivity(_ctx, this, _probeManager, true);
  17601. default:
  17602. throwUnexpected();
  17603. }
  17604. }
  17605. };
  17606. IRoxieServerActivityFactory *createRoxieServerCatchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17607. {
  17608. return new CRoxieServerCatchActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  17609. }
  17610. //=================================================================================
  17611. class CRoxieServerPullActivity : public CRoxieServerActivity
  17612. {
  17613. ConstPointerArray buff;
  17614. bool started;
  17615. unsigned index;
  17616. public:
  17617. CRoxieServerPullActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17618. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  17619. {
  17620. started = false;
  17621. index = 0;
  17622. }
  17623. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17624. {
  17625. started = false;
  17626. index = 0;
  17627. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  17628. }
  17629. virtual void reset()
  17630. {
  17631. while (buff.isItem(index))
  17632. ReleaseRoxieRow(buff.item(index++));
  17633. buff.kill();
  17634. started = false;
  17635. index = 0;
  17636. CRoxieServerActivity::reset();
  17637. }
  17638. virtual const void *nextRow()
  17639. {
  17640. ActivityTimer t(totalCycles, timeActivities);
  17641. if (!started)
  17642. pullInput();
  17643. if (buff.isItem(index))
  17644. {
  17645. const void * next = buff.item(index++);
  17646. if (next)
  17647. processed++;
  17648. return next;
  17649. }
  17650. return NULL;
  17651. }
  17652. protected:
  17653. void pullInput()
  17654. {
  17655. bool EOGseen = false;
  17656. loop
  17657. {
  17658. const void * next = inputStream->nextRow();
  17659. buff.append(next);
  17660. if (next == NULL)
  17661. {
  17662. if (EOGseen)
  17663. break;
  17664. EOGseen = true;
  17665. }
  17666. else
  17667. EOGseen = false;
  17668. }
  17669. started = true;
  17670. }
  17671. };
  17672. class CRoxieServerPullActivityFactory : public CRoxieServerActivityFactory
  17673. {
  17674. public:
  17675. CRoxieServerPullActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17676. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  17677. {
  17678. }
  17679. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  17680. {
  17681. return new CRoxieServerPullActivity(_ctx, this, _probeManager);
  17682. }
  17683. };
  17684. IRoxieServerActivityFactory *createRoxieServerPullActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17685. {
  17686. return new CRoxieServerPullActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  17687. }
  17688. //=================================================================================
  17689. class CRoxieServerTraceActivity : public CRoxieServerActivity
  17690. {
  17691. public:
  17692. CRoxieServerTraceActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17693. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorTraceArg &) basehelper),
  17694. keepLimit(0), skip(0), sample(0)
  17695. {
  17696. assertex(meta.hasXML());
  17697. traceEnabled = defaultTraceEnabled && !isBlind();
  17698. }
  17699. virtual void onCreate(IHThorArg *_colocalParent)
  17700. {
  17701. CRoxieServerActivity::onCreate(_colocalParent);
  17702. if (ctx)
  17703. traceEnabled = ctx->queryOptions().traceEnabled && !isBlind();
  17704. }
  17705. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17706. {
  17707. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  17708. if (traceEnabled && helper.canMatchAny())
  17709. {
  17710. keepLimit = helper.getKeepLimit();
  17711. if (keepLimit==(unsigned) -1)
  17712. keepLimit = ctx->queryOptions().traceLimit;
  17713. skip = helper.getSkip();
  17714. sample = helper.getSample();
  17715. if (sample)
  17716. sample--;
  17717. name.setown(helper.getName());
  17718. if (!name)
  17719. name.set("Row");
  17720. }
  17721. else
  17722. keepLimit = 0;
  17723. }
  17724. virtual void stop()
  17725. {
  17726. name.clear();
  17727. CRoxieServerActivity::stop();
  17728. }
  17729. virtual bool isPassThrough()
  17730. {
  17731. return true;
  17732. }
  17733. virtual const void *nextRow()
  17734. {
  17735. ActivityTimer t(totalCycles, timeActivities);
  17736. const void *row = inputStream->nextRow();
  17737. if (row)
  17738. {
  17739. onTrace(row);
  17740. processed++;
  17741. }
  17742. return row;
  17743. }
  17744. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  17745. {
  17746. // MORE - will need rethinking once we rethink the nextRowGE interface for global smart-stepping.
  17747. ActivityTimer t(totalCycles, timeActivities);
  17748. const void * row = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  17749. if (row)
  17750. {
  17751. onTrace(row);
  17752. processed++;
  17753. }
  17754. return row;
  17755. }
  17756. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  17757. {
  17758. return input->gatherConjunctions(collector);
  17759. }
  17760. virtual void resetEOF()
  17761. {
  17762. inputStream->resetEOF();
  17763. }
  17764. IInputSteppingMeta * querySteppingMeta()
  17765. {
  17766. return input->querySteppingMeta();
  17767. }
  17768. protected:
  17769. void onTrace(const void *row)
  17770. {
  17771. if (keepLimit && helper.isValid(row))
  17772. {
  17773. if (skip)
  17774. skip--;
  17775. else if (sample)
  17776. sample--;
  17777. else
  17778. {
  17779. CommonXmlWriter xmlwrite(XWFnoindent);
  17780. meta.toXML((const byte *) row, xmlwrite);
  17781. CTXLOG("TRACE: <%s>%s<%s>", name.get(), xmlwrite.str(), name.get());
  17782. keepLimit--;
  17783. sample = helper.getSample();
  17784. if (sample)
  17785. sample--;
  17786. }
  17787. }
  17788. }
  17789. OwnedRoxieString name;
  17790. IHThorTraceArg &helper;
  17791. unsigned keepLimit;
  17792. unsigned skip;
  17793. unsigned sample;
  17794. bool traceEnabled;
  17795. };
  17796. class CRoxieServerTraceActivityFactory : public CRoxieServerActivityFactory
  17797. {
  17798. public:
  17799. CRoxieServerTraceActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17800. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  17801. {
  17802. }
  17803. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  17804. {
  17805. return new CRoxieServerTraceActivity(_ctx, this, _probeManager);
  17806. }
  17807. };
  17808. IRoxieServerActivityFactory *createRoxieServerTraceActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17809. {
  17810. return new CRoxieServerTraceActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  17811. }
  17812. //=================================================================================
  17813. class CRoxieServerCaseActivity : public CRoxieServerMultiInputBaseActivity
  17814. {
  17815. IHThorCaseArg &helper;
  17816. unsigned cond;
  17817. bool unusedStopped;
  17818. IEngineRowStream *active;
  17819. public:
  17820. CRoxieServerCaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  17821. : CRoxieServerMultiInputBaseActivity(_ctx, _factory, _probeManager, _numInputs), helper((IHThorCaseArg &)basehelper)
  17822. {
  17823. unusedStopped = false;
  17824. cond = 0;
  17825. active = NULL;
  17826. }
  17827. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17828. {
  17829. CRoxieServerMultiInputBaseActivity::start(parentExtractSize, parentExtract, paused);
  17830. cond = helper.getBranch();
  17831. //CHOOSE defaults to the last argument if out of range.
  17832. if (cond >= numInputs)
  17833. cond = numInputs - 1;
  17834. inputArray[cond]->start(parentExtractSize, parentExtract, paused);
  17835. startJunction(junctionArray[cond]);
  17836. assertex(numInputs==numStreams);
  17837. for (unsigned idx = 0; idx < numStreams; idx++)
  17838. {
  17839. if (idx!=cond)
  17840. streamArray[idx]->stop(); // Note: stopping unused branches early helps us avoid buffering splits too long.
  17841. }
  17842. active = streamArray[cond];
  17843. unusedStopped = true;
  17844. }
  17845. virtual void stop()
  17846. {
  17847. for (unsigned idx = 0; idx < numStreams; idx++)
  17848. {
  17849. if (idx==cond || !unusedStopped)
  17850. streamArray[idx]->stop();
  17851. }
  17852. CRoxieServerMultiInputBaseActivity::stop();
  17853. }
  17854. virtual void reset()
  17855. {
  17856. unusedStopped = false;
  17857. active = NULL;
  17858. CRoxieServerMultiInputBaseActivity::reset();
  17859. }
  17860. virtual const void *nextRow()
  17861. {
  17862. ActivityTimer t(totalCycles, timeActivities);
  17863. if (active)
  17864. {
  17865. const void *ret = active->nextRow();
  17866. if (ret)
  17867. processed++;
  17868. return ret;
  17869. }
  17870. return NULL;
  17871. }
  17872. };
  17873. class CRoxieServerCaseActivityFactory : public CRoxieServerMultiInputFactory
  17874. {
  17875. bool graphInvariant;
  17876. public:
  17877. CRoxieServerCaseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _graphInvariant)
  17878. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  17879. {
  17880. graphInvariant = _graphInvariant;
  17881. }
  17882. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  17883. {
  17884. return new CRoxieServerCaseActivity(_ctx, this, _probeManager, numInputs());
  17885. }
  17886. virtual bool isGraphInvariant() const
  17887. {
  17888. return graphInvariant;
  17889. }
  17890. };
  17891. IRoxieServerActivityFactory *createRoxieServerCaseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _graphInvariant)
  17892. {
  17893. return new CRoxieServerCaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _graphInvariant);
  17894. }
  17895. //=================================================================================
  17896. class CRoxieServerIfActivity : public CRoxieServerActivity
  17897. {
  17898. IHThorIfArg &helper;
  17899. IFinalRoxieInput *inputTrue;
  17900. IFinalRoxieInput *inputFalse;
  17901. IEngineRowStream *streamTrue;
  17902. IEngineRowStream *streamFalse;
  17903. unsigned sourceIdxFalse = 0;
  17904. unsigned sourceIdxTrue = 0;
  17905. Owned<IStrandJunction> junctionTrue;
  17906. Owned<IStrandJunction> junctionFalse;
  17907. bool cond;
  17908. bool unusedStopped;
  17909. public:
  17910. CRoxieServerIfActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17911. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorIfArg &)basehelper)
  17912. {
  17913. inputFalse = NULL;
  17914. inputTrue = NULL;
  17915. streamTrue = NULL;
  17916. streamFalse = NULL;
  17917. unusedStopped = false;
  17918. cond = false;
  17919. }
  17920. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17921. {
  17922. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  17923. cond = helper.getCondition();
  17924. if (cond)
  17925. {
  17926. inputTrue->start(parentExtractSize, parentExtract, paused);
  17927. startJunction(junctionTrue);
  17928. if (streamFalse)
  17929. streamFalse->stop(); // Note: stopping unused branches early helps us avoid buffering splits too long.
  17930. }
  17931. else
  17932. {
  17933. if (inputFalse)
  17934. {
  17935. inputFalse->start(parentExtractSize, parentExtract, paused);
  17936. startJunction(junctionFalse);
  17937. }
  17938. streamTrue->stop();
  17939. }
  17940. unusedStopped = true;
  17941. }
  17942. virtual void stop()
  17943. {
  17944. if (!unusedStopped || cond)
  17945. streamTrue->stop();
  17946. if (streamFalse && (!unusedStopped || !cond))
  17947. streamFalse->stop();
  17948. CRoxieServerActivity::stop();
  17949. }
  17950. virtual unsigned __int64 queryLocalCycles() const
  17951. {
  17952. __int64 localCycles = totalCycles.totalCycles;
  17953. localCycles -= inputTrue->queryTotalCycles();
  17954. if (inputFalse)
  17955. localCycles -= inputFalse->queryTotalCycles();
  17956. if (localCycles < 0)
  17957. localCycles = 0;
  17958. return localCycles;
  17959. }
  17960. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  17961. {
  17962. switch (idx)
  17963. {
  17964. case 0:
  17965. return inputTrue;
  17966. case 1:
  17967. return inputFalse;
  17968. default:
  17969. return NULL;
  17970. }
  17971. }
  17972. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  17973. {
  17974. IFinalRoxieInput *in = cond ? inputTrue : inputFalse;
  17975. if (in)
  17976. return in->queryIndexReadActivity();
  17977. return NULL;
  17978. }
  17979. virtual void reset()
  17980. {
  17981. CRoxieServerActivity::reset();
  17982. inputTrue->reset();
  17983. if (inputFalse)
  17984. inputFalse->reset();
  17985. resetJunction(junctionTrue);
  17986. resetJunction(junctionFalse);
  17987. unusedStopped = false;
  17988. }
  17989. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  17990. {
  17991. if (idx==1)
  17992. {
  17993. inputFalse = _in;
  17994. sourceIdxFalse = _sourceIdx;
  17995. }
  17996. else
  17997. {
  17998. assertex(!idx);
  17999. inputTrue = _in;
  18000. sourceIdxTrue = _sourceIdx;
  18001. }
  18002. }
  18003. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  18004. {
  18005. //It should be possible to stream IF(), but the number of strands would need to match on the two branches.
  18006. streamTrue = connectSingleStream(ctx, inputTrue, sourceIdxTrue, junctionTrue, consumerOrdered);
  18007. streamFalse = connectSingleStream(ctx, inputFalse, sourceIdxFalse, junctionFalse, consumerOrdered);
  18008. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, nullptr, consumerOrdered, nullptr);
  18009. }
  18010. virtual const void *nextRow()
  18011. {
  18012. ActivityTimer t(totalCycles, timeActivities);
  18013. IEngineRowStream *in = cond ? streamTrue : streamFalse;
  18014. if (in)
  18015. {
  18016. const void * ret;
  18017. if ((ret = in->nextRow()) != NULL)
  18018. processed++;
  18019. return ret;
  18020. }
  18021. return NULL;
  18022. }
  18023. };
  18024. class CRoxieServerIfActivityFactory : public CRoxieServerActivityFactory
  18025. {
  18026. unsigned input2;
  18027. unsigned input2idx;
  18028. bool graphInvariant;
  18029. public:
  18030. CRoxieServerIfActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _graphInvariant)
  18031. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  18032. {
  18033. graphInvariant = _graphInvariant;
  18034. input2 = (unsigned)-1;
  18035. input2idx = (unsigned)-1;
  18036. }
  18037. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18038. {
  18039. return new CRoxieServerIfActivity(_ctx, this, _probeManager);
  18040. }
  18041. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  18042. {
  18043. if (idx==1)
  18044. {
  18045. input2 = source;
  18046. input2idx = sourceidx;
  18047. }
  18048. else
  18049. CRoxieServerActivityFactory::setInput(idx, source, sourceidx);
  18050. }
  18051. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  18052. {
  18053. switch (idx)
  18054. {
  18055. case 1:
  18056. sourceidx = input2idx;
  18057. return input2;
  18058. case 0:
  18059. return CRoxieServerActivityFactory::getInput(idx, sourceidx);
  18060. default:
  18061. return (unsigned) -1;
  18062. }
  18063. }
  18064. virtual unsigned numInputs() const { return (input2 == (unsigned)-1) ? 1 : 2; }
  18065. virtual bool isGraphInvariant() const
  18066. {
  18067. return graphInvariant;
  18068. }
  18069. };
  18070. IRoxieServerActivityFactory *createRoxieServerIfActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _graphInvariant)
  18071. {
  18072. return new CRoxieServerIfActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _graphInvariant);
  18073. }
  18074. //=================================================================================
  18075. class CRoxieServerActionBaseActivity : public CRoxieServerActivity
  18076. {
  18077. CriticalSection ecrit;
  18078. Owned<IException> exception;
  18079. bool executed;
  18080. public:
  18081. CRoxieServerActionBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18082. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  18083. {
  18084. executed = false;
  18085. }
  18086. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract) = 0;
  18087. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  18088. {
  18089. CriticalBlock b(ecrit);
  18090. if (exception)
  18091. throw(exception.getLink());
  18092. if (!executed)
  18093. {
  18094. try
  18095. {
  18096. executed = true;
  18097. start(parentExtractSize, parentExtract, false);
  18098. doExecuteAction(parentExtractSize, parentExtract);
  18099. stop();
  18100. }
  18101. catch (IException * E)
  18102. {
  18103. ctx->notifyAbort(E);
  18104. abort();
  18105. exception.set(E);
  18106. throw;
  18107. }
  18108. }
  18109. }
  18110. virtual void reset()
  18111. {
  18112. executed = false;
  18113. exception.clear();
  18114. CRoxieServerActivity::reset();
  18115. }
  18116. virtual const void *nextRow()
  18117. {
  18118. throwUnexpected(); // I am nobody's input
  18119. }
  18120. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  18121. {
  18122. return NULL;
  18123. }
  18124. };
  18125. class CRoxieServerIfActionActivity : public CRoxieServerActionBaseActivity
  18126. {
  18127. IHThorIfArg &helper;
  18128. public:
  18129. CRoxieServerIfActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18130. : CRoxieServerActionBaseActivity(_ctx, _factory, _probeManager), helper((IHThorIfArg &)basehelper)
  18131. {
  18132. }
  18133. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  18134. {
  18135. bool cond;
  18136. {
  18137. ActivityTimer t(totalCycles, timeActivities);
  18138. cond = helper.getCondition();
  18139. }
  18140. stopDependencies(parentExtractSize, parentExtract, cond ? 2 : 1);
  18141. executeDependencies(parentExtractSize, parentExtract, cond ? 1 : 2);
  18142. }
  18143. };
  18144. class CRoxieServerIfActionActivityFactory : public CRoxieServerActivityFactory
  18145. {
  18146. bool isRoot;
  18147. public:
  18148. CRoxieServerIfActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18149. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  18150. {
  18151. }
  18152. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18153. {
  18154. return new CRoxieServerIfActionActivity(_ctx, this, _probeManager);
  18155. }
  18156. virtual bool isSink() const
  18157. {
  18158. return isRoot;
  18159. }
  18160. };
  18161. IRoxieServerActivityFactory *createRoxieServerIfActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18162. {
  18163. return new CRoxieServerIfActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  18164. }
  18165. //=================================================================================
  18166. class CRoxieServerParallelActionActivity : public CRoxieServerActionBaseActivity
  18167. {
  18168. public:
  18169. CRoxieServerParallelActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18170. : CRoxieServerActionBaseActivity(_ctx, _factory, _probeManager)
  18171. {
  18172. }
  18173. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  18174. {
  18175. #ifdef PARALLEL_EXECUTE
  18176. CParallelActivityExecutor afor(dependencies, parentExtractSize, parentExtract);
  18177. afor.For(dependencies.ordinality(), dependencies.ordinality(), true);
  18178. #else
  18179. ForEachItemIn(idx, dependencies)
  18180. {
  18181. dependencies.item(idx).execute(parentExtractSize, parentExtract);
  18182. }
  18183. #endif
  18184. }
  18185. };
  18186. class CRoxieServerParallelActionActivityFactory : public CRoxieServerActivityFactory
  18187. {
  18188. bool isRoot;
  18189. public:
  18190. CRoxieServerParallelActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18191. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  18192. {
  18193. assertex(!isRoot); // non-internal should be expanded out..
  18194. }
  18195. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18196. {
  18197. return new CRoxieServerParallelActionActivity(_ctx, this, _probeManager);
  18198. }
  18199. virtual bool isSink() const
  18200. {
  18201. return isRoot;
  18202. }
  18203. };
  18204. IRoxieServerActivityFactory *createRoxieServerParallelActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18205. {
  18206. return new CRoxieServerParallelActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  18207. }
  18208. //=================================================================================
  18209. class CRoxieServerSequentialActionActivity : public CRoxieServerActionBaseActivity
  18210. {
  18211. IHThorSequentialArg &helper;
  18212. public:
  18213. CRoxieServerSequentialActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18214. : CRoxieServerActionBaseActivity(_ctx, _factory, _probeManager), helper((IHThorSequentialArg &)basehelper)
  18215. {
  18216. }
  18217. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  18218. {
  18219. unsigned numBranches = helper.numBranches();
  18220. for (unsigned branch=1; branch <= numBranches; branch++)
  18221. executeDependencies(parentExtractSize, parentExtract, branch);
  18222. }
  18223. };
  18224. class CRoxieServerSequentialActionActivityFactory : public CRoxieServerActivityFactory
  18225. {
  18226. bool isRoot;
  18227. public:
  18228. CRoxieServerSequentialActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18229. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  18230. {
  18231. }
  18232. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18233. {
  18234. return new CRoxieServerSequentialActionActivity(_ctx, this, _probeManager);
  18235. }
  18236. virtual bool isSink() const
  18237. {
  18238. return isRoot;
  18239. }
  18240. };
  18241. IRoxieServerActivityFactory *createRoxieServerSequentialActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18242. {
  18243. return new CRoxieServerSequentialActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  18244. }
  18245. //=================================================================================
  18246. class CRoxieServerWhenActivity : public CRoxieServerActivity
  18247. {
  18248. public:
  18249. CRoxieServerWhenActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18250. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  18251. {
  18252. savedExtractSize = 0;
  18253. savedExtract = NULL;
  18254. eofseen = false;
  18255. eogseen = false;
  18256. }
  18257. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18258. {
  18259. savedExtractSize = parentExtractSize;
  18260. savedExtract = parentExtract;
  18261. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  18262. executeDependencies(parentExtractSize, parentExtract, WhenBeforeId);
  18263. executeDependencies(parentExtractSize, parentExtract, WhenParallelId); // MORE: This should probably be done in parallel!
  18264. eofseen = false;
  18265. eogseen = false;
  18266. }
  18267. virtual void stop()
  18268. {
  18269. if (state == STATEreset || (!aborted && !eofseen)) // If someone else aborted, then WHEN clauses don't trigger, whatever
  18270. {
  18271. stopDependencies(savedExtractSize, savedExtract, WhenSuccessId);
  18272. stopDependencies(savedExtractSize, savedExtract, WhenFailureId);
  18273. }
  18274. else if (state != STATEstopped)
  18275. {
  18276. stopDependencies(savedExtractSize, savedExtract, aborted ? WhenSuccessId : WhenFailureId); // These ones don't get executed
  18277. executeDependencies(savedExtractSize, savedExtract, aborted ? WhenFailureId : WhenSuccessId); // These ones do
  18278. }
  18279. CRoxieServerActivity::stop();
  18280. }
  18281. virtual const void *nextRow()
  18282. {
  18283. try
  18284. {
  18285. ActivityTimer t(totalCycles, timeActivities); // bit of a waste of time....
  18286. const void *ret = inputStream->nextRow();
  18287. if (!ret)
  18288. {
  18289. if (eogseen)
  18290. eofseen = true;
  18291. else
  18292. eogseen = true;
  18293. }
  18294. else
  18295. eogseen = false;
  18296. return ret;
  18297. }
  18298. catch (...)
  18299. {
  18300. aborted = true;
  18301. throw;
  18302. }
  18303. }
  18304. protected:
  18305. const byte *savedExtract;
  18306. unsigned savedExtractSize;
  18307. bool eofseen;
  18308. bool eogseen;
  18309. };
  18310. class CRoxieServerWhenActivityFactory : public CRoxieServerActivityFactory
  18311. {
  18312. public:
  18313. CRoxieServerWhenActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  18314. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  18315. {
  18316. }
  18317. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18318. {
  18319. return new CRoxieServerWhenActivity(_ctx, this, _probeManager);
  18320. }
  18321. };
  18322. extern IRoxieServerActivityFactory *createRoxieServerWhenActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  18323. {
  18324. return new CRoxieServerWhenActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  18325. }
  18326. //=================================================================================
  18327. class CRoxieServerWhenActionActivity : public CRoxieServerActionBaseActivity
  18328. {
  18329. public:
  18330. CRoxieServerWhenActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18331. : CRoxieServerActionBaseActivity(_ctx, _factory, _probeManager)
  18332. {
  18333. savedExtractSize = 0;
  18334. savedExtract = NULL;
  18335. }
  18336. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18337. {
  18338. savedExtractSize = parentExtractSize;
  18339. savedExtract = parentExtract;
  18340. CRoxieServerActionBaseActivity::start(parentExtractSize, parentExtract, paused);
  18341. executeDependencies(parentExtractSize, parentExtract, WhenBeforeId);
  18342. executeDependencies(parentExtractSize, parentExtract, WhenParallelId); // MORE: This should probably be done in parallel!
  18343. }
  18344. virtual void stop()
  18345. {
  18346. if (state != STATEstopped)
  18347. {
  18348. stopDependencies(savedExtractSize, savedExtract, aborted ? WhenSuccessId : WhenFailureId); // these are NOT going to execute
  18349. executeDependencies(savedExtractSize, savedExtract, aborted ? WhenFailureId : WhenSuccessId);
  18350. }
  18351. CRoxieServerActionBaseActivity::stop();
  18352. }
  18353. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  18354. {
  18355. executeDependencies(parentExtractSize, parentExtract, 1);
  18356. }
  18357. protected:
  18358. unsigned savedExtractSize;
  18359. const byte *savedExtract;
  18360. };
  18361. class CRoxieServerWhenActionActivityFactory : public CRoxieServerActivityFactory
  18362. {
  18363. public:
  18364. CRoxieServerWhenActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18365. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  18366. {
  18367. }
  18368. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18369. {
  18370. return new CRoxieServerWhenActionActivity(_ctx, this, _probeManager);
  18371. }
  18372. virtual bool isSink() const
  18373. {
  18374. return isRoot;
  18375. }
  18376. private:
  18377. bool isRoot;
  18378. };
  18379. extern IRoxieServerActivityFactory *createRoxieServerWhenActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18380. {
  18381. return new CRoxieServerWhenActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  18382. }
  18383. //=================================================================================
  18384. class CRoxieServerStrandedParseActivity : public CRoxieServerStrandedActivity
  18385. {
  18386. INlpParseAlgorithm * algorithm;
  18387. class ParseProcessor : public StrandProcessor, implements IMatchedAction
  18388. {
  18389. protected:
  18390. IHThorParseArg &helper;
  18391. INlpParser * parser;
  18392. INlpResultIterator * rowIter;
  18393. const void * in;
  18394. char * curSearchText;
  18395. size32_t curSearchTextLen;
  18396. bool processRecord(const void * inRec)
  18397. {
  18398. if (helper.searchTextNeedsFree())
  18399. rtlFree(curSearchText);
  18400. curSearchTextLen = 0;
  18401. curSearchText = NULL;
  18402. helper.getSearchText(curSearchTextLen, curSearchText, inRec);
  18403. return parser->performMatch(*this, in, curSearchTextLen, curSearchText);
  18404. }
  18405. public:
  18406. ParseProcessor(CRoxieServerActivity &_parent, IEngineRowStream *_inputStream, IHThorParseArg &_helper, INlpParseAlgorithm * _algorithm)
  18407. : StrandProcessor(_parent, _inputStream, false), helper(_helper)
  18408. {
  18409. parser = _algorithm->createParser(parent.queryCodeContext(), parent.queryId(), helper.queryHelper(), &helper);
  18410. rowIter = parser->queryResultIter();
  18411. in = NULL;
  18412. curSearchText = NULL;
  18413. curSearchTextLen = 0;
  18414. }
  18415. ~ParseProcessor()
  18416. {
  18417. ::Release(parser);
  18418. }
  18419. virtual void start()
  18420. {
  18421. StrandProcessor::start();
  18422. numProcessedLastGroup = 0;
  18423. curSearchTextLen = 0;
  18424. curSearchText = NULL;
  18425. in = NULL;
  18426. parser->reset();
  18427. }
  18428. virtual void reset()
  18429. {
  18430. if (helper.searchTextNeedsFree())
  18431. rtlFree(curSearchText);
  18432. curSearchText = NULL;
  18433. ReleaseClearRoxieRow(in);
  18434. StrandProcessor::reset();
  18435. }
  18436. virtual const void * nextRow()
  18437. {
  18438. ActivityTimer t(totalCycles, timeActivities);
  18439. loop
  18440. {
  18441. if (rowIter->isValid())
  18442. {
  18443. OwnedConstRoxieRow out = rowIter->getRow();
  18444. rowIter->next();
  18445. processed++;
  18446. return out.getClear();
  18447. }
  18448. ReleaseClearRoxieRow(in);
  18449. in = inputStream->nextRow();
  18450. if (!in)
  18451. {
  18452. if (processed == numProcessedLastGroup)
  18453. in = inputStream->nextRow();
  18454. if (!in)
  18455. {
  18456. processed = numProcessedLastGroup;
  18457. return NULL;
  18458. }
  18459. in = inputStream->nextRow();
  18460. if (!in)
  18461. return NULL;
  18462. }
  18463. processRecord(in);
  18464. rowIter->first();
  18465. }
  18466. }
  18467. virtual unsigned onMatch(ARowBuilder & self, const void * curRecord, IMatchedResults * results, IMatchWalker * walker)
  18468. {
  18469. try
  18470. {
  18471. return helper.transform(self, curRecord, results, walker);
  18472. }
  18473. catch (IException *E)
  18474. {
  18475. throw parent.makeWrappedException(E);
  18476. }
  18477. }
  18478. };
  18479. public:
  18480. CRoxieServerStrandedParseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, INlpParseAlgorithm * _algorithm, const StrandOptions &_strandOptions)
  18481. : CRoxieServerStrandedActivity(_ctx, _factory, _probeManager, _strandOptions), algorithm(_algorithm)
  18482. {
  18483. }
  18484. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18485. {
  18486. CRoxieServerStrandedActivity::start(parentExtractSize, parentExtract, paused);
  18487. onStartStrands();
  18488. }
  18489. virtual StrandProcessor *createStrandProcessor(IEngineRowStream *instream)
  18490. {
  18491. return new ParseProcessor(*this, instream, (IHThorParseArg &) basehelper, algorithm);
  18492. }
  18493. virtual StrandProcessor *createStrandSourceProcessor(bool inputOrdered) { throwUnexpected(); }
  18494. };
  18495. class CRoxieServerParseActivityFactory : public CRoxieServerActivityFactory
  18496. {
  18497. Owned<INlpParseAlgorithm> algorithm;
  18498. Owned<IHThorParseArg> helper;
  18499. StrandOptions strandOptions;
  18500. public:
  18501. CRoxieServerParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, IResourceContext *rc)
  18502. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), strandOptions(_graphNode)
  18503. {
  18504. helper.setown((IHThorParseArg *) helperFactory());
  18505. algorithm.setown(createThorParser(rc, *helper));
  18506. optStableInput = false;
  18507. }
  18508. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18509. {
  18510. return new CRoxieServerStrandedParseActivity(_ctx, this, _probeManager, algorithm, strandOptions);
  18511. }
  18512. };
  18513. IRoxieServerActivityFactory *createRoxieServerParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, IResourceContext *rc)
  18514. {
  18515. return new CRoxieServerParseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, rc);
  18516. }
  18517. //=====================================================================================================
  18518. class CRoxieServerWorkUnitWriteActivity : public CRoxieServerInternalSinkActivity
  18519. {
  18520. IHThorWorkUnitWriteArg &helper;
  18521. bool isReread;
  18522. bool grouped;
  18523. IRoxieServerContext *serverContext;
  18524. public:
  18525. CRoxieServerWorkUnitWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _isReread, unsigned _numOutputs)
  18526. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _numOutputs), helper((IHThorWorkUnitWriteArg &)basehelper), isReread(_isReread)
  18527. {
  18528. grouped = (helper.getFlags() & POFgrouped) != 0;
  18529. serverContext = NULL;
  18530. }
  18531. virtual void onCreate(IHThorArg *_colocalParent)
  18532. {
  18533. CRoxieServerInternalSinkActivity::onCreate(_colocalParent);
  18534. serverContext = ctx->queryServerContext();
  18535. if (!serverContext)
  18536. {
  18537. throw MakeStringException(ROXIE_PIPE_ERROR, "Pipe output activity cannot be executed in slave context");
  18538. }
  18539. }
  18540. virtual bool needsAllocator() const { return true; }
  18541. virtual void onExecute()
  18542. {
  18543. int sequence = helper.getSequence();
  18544. const char *storedName = helper.queryName();
  18545. if (!storedName)
  18546. storedName = "Dataset";
  18547. MemoryBuffer result;
  18548. bool saveInContext = (int) sequence < 0 || isReread;
  18549. if (!meta.queryOriginal()) // this is a bit of a hack - don't know why no meta on an output....
  18550. meta.set(input->queryOutputMeta());
  18551. Owned<IOutputRowSerializer> rowSerializer;
  18552. Owned<IXmlWriter> xmlwriter;
  18553. bool appendRaw = false;
  18554. IHpccProtocolResultsWriter *results = NULL;
  18555. IHpccNativeProtocolResultsWriter *nativeResults = NULL;
  18556. IHpccProtocolResponse *protocol = serverContext->queryProtocol();
  18557. unsigned protocolFlags = (protocol) ? protocol->getFlags() : 0;
  18558. if ((int) sequence >= 0)
  18559. {
  18560. results = (protocol) ? protocol->queryHpccResultsSection() : NULL;
  18561. if (results)
  18562. {
  18563. nativeResults = dynamic_cast<IHpccNativeProtocolResultsWriter*>(results);
  18564. xmlwriter.setown(results->addDataset(helper.queryName(), sequence, "Dataset", appendRaw, serverContext->getXmlFlags(), (helper.getFlags() & POFextend) != 0, serverContext->queryXmlns(sequence))); //xmlwriter only returned if needed
  18565. }
  18566. }
  18567. size32_t outputLimitBytes = 0;
  18568. IConstWorkUnit *workunit = serverContext->queryWorkUnit();
  18569. if (workunit)
  18570. {
  18571. size32_t outputLimit;
  18572. if (helper.getFlags() & POFmaxsize)
  18573. outputLimit = helper.getMaxSize();
  18574. else
  18575. {
  18576. // In absense of OPT_OUTPUTLIMIT check pre 5.2 legacy name OPT_OUTPUTLIMIT_LEGACY
  18577. outputLimit = workunit->getDebugValueInt(OPT_OUTPUTLIMIT, workunit->getDebugValueInt(OPT_OUTPUTLIMIT_LEGACY, defaultDaliResultLimit));
  18578. }
  18579. if (outputLimit>defaultDaliResultOutputMax)
  18580. 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);
  18581. assertex(outputLimit<=0x1000); // 32bit limit because MemoryBuffer/CMessageBuffers involved etc.
  18582. outputLimitBytes = outputLimit * 0x100000;
  18583. }
  18584. if (workunit != NULL || (results && protocol->getFlags() & HPCC_PROTOCOL_NATIVE_RAW))
  18585. {
  18586. createRowAllocator();
  18587. rowSerializer.setown(rowAllocator->createDiskSerializer(ctx->queryCodeContext()));
  18588. }
  18589. __int64 initialProcessed = processed;
  18590. RtlLinkedDatasetBuilder builder(rowAllocator);
  18591. loop
  18592. {
  18593. const void *row = inputStream->nextRow();
  18594. if (saveInContext)
  18595. {
  18596. if (row || grouped)
  18597. builder.append(row);
  18598. }
  18599. if (grouped && (processed != initialProcessed))
  18600. {
  18601. if (workunit)
  18602. result.append(row == NULL);
  18603. if (results)
  18604. {
  18605. if (protocolFlags & HPCC_PROTOCOL_NATIVE_RAW && nativeResults)
  18606. {
  18607. char val = (char)(row == NULL);
  18608. nativeResults->appendRaw(sequence, 1, &val);
  18609. }
  18610. else if (xmlwriter)
  18611. {
  18612. xmlwriter->outputBeginNested("Row", false);
  18613. xmlwriter->outputCString("1", "@__GroupBreak__");
  18614. xmlwriter->outputEndNested("Row");
  18615. }
  18616. }
  18617. }
  18618. if (!row)
  18619. {
  18620. row = inputStream->nextRow();
  18621. if (!row)
  18622. break;
  18623. if (saveInContext)
  18624. builder.append(row);
  18625. }
  18626. processed++;
  18627. if (workunit)
  18628. {
  18629. CThorDemoRowSerializer serializerTarget(result);
  18630. rowSerializer->serialize(serializerTarget, (const byte *) row);
  18631. }
  18632. if ((int) sequence >= 0)
  18633. {
  18634. if (appendRaw && nativeResults)
  18635. {
  18636. // MORE - should be able to serialize straight to the response...
  18637. MemoryBuffer rowbuff;
  18638. CThorDemoRowSerializer serializerTarget(rowbuff);
  18639. rowSerializer->serialize(serializerTarget, (const byte *) row);
  18640. nativeResults->appendRawRow(sequence, rowbuff.length(), rowbuff.toByteArray());
  18641. }
  18642. else if (xmlwriter)
  18643. {
  18644. xmlwriter->outputBeginNested(DEFAULTXMLROWTAG, false);
  18645. helper.serializeXml((byte *) row, *xmlwriter);
  18646. xmlwriter->outputEndNested(DEFAULTXMLROWTAG);
  18647. results->finalizeXmlRow(sequence);
  18648. }
  18649. else if (nativeResults)
  18650. {
  18651. SimpleOutputWriter x;
  18652. helper.serializeXml((byte *) row, x);
  18653. x.newline();
  18654. nativeResults->appendSimpleRow(sequence, x.str());
  18655. }
  18656. }
  18657. ReleaseRoxieRow(row);
  18658. if (outputLimitBytes && result.length() > outputLimitBytes)
  18659. {
  18660. StringBuffer errMsg("Dataset too large to output to workunit (limit ");
  18661. errMsg.append(outputLimitBytes/0x100000).append(" megabytes), in result (");
  18662. const char *name = helper.queryName();
  18663. if (name)
  18664. errMsg.append("name=").append(name);
  18665. else
  18666. errMsg.append("sequence=").append(helper.getSequence());
  18667. errMsg.append(")");
  18668. throw MakeStringExceptionDirect(0, errMsg.str());
  18669. }
  18670. }
  18671. if (xmlwriter)
  18672. xmlwriter->outputEndArray(DEFAULTXMLROWTAG);
  18673. if (saveInContext)
  18674. serverContext->appendResultDeserialized(storedName, sequence, builder.getcount(), builder.linkrows(), (helper.getFlags() & POFextend) != 0, LINK(meta.queryOriginal()));
  18675. if (workunit)
  18676. serverContext->appendResultRawContext(storedName, sequence, result.length(), result.toByteArray(), processed, (helper.getFlags() & POFextend) != 0, false); // MORE - shame to do extra copy...
  18677. }
  18678. };
  18679. class CRoxieServerWorkUnitWriteActivityFactory : public CRoxieServerInternalSinkFactory
  18680. {
  18681. bool isReread;
  18682. public:
  18683. CRoxieServerWorkUnitWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  18684. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot)
  18685. {
  18686. isReread = usageCount > 0;
  18687. Owned<IHThorWorkUnitWriteArg> helper = (IHThorWorkUnitWriteArg *) helperFactory();
  18688. isInternal = (helper->getSequence()==ResultSequenceInternal);
  18689. }
  18690. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18691. {
  18692. return new CRoxieServerWorkUnitWriteActivity(_ctx, this, _probeManager, isReread, usageCount);
  18693. }
  18694. };
  18695. IRoxieServerActivityFactory *createRoxieServerWorkUnitWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  18696. {
  18697. return new CRoxieServerWorkUnitWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot);
  18698. }
  18699. //=====================================================================================================
  18700. class CRoxieServerWorkUnitWriteDictActivity : public CRoxieServerInternalSinkActivity
  18701. {
  18702. IHThorDictionaryWorkUnitWriteArg &helper;
  18703. IRoxieServerContext *serverContext;
  18704. public:
  18705. CRoxieServerWorkUnitWriteDictActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _usageCount)
  18706. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _usageCount), helper((IHThorDictionaryWorkUnitWriteArg &)basehelper)
  18707. {
  18708. serverContext = NULL;
  18709. }
  18710. virtual void onCreate(IHThorArg *_colocalParent)
  18711. {
  18712. CRoxieServerInternalSinkActivity::onCreate(_colocalParent);
  18713. serverContext = ctx->queryServerContext();
  18714. if (!serverContext)
  18715. {
  18716. throw MakeStringException(ROXIE_PIPE_ERROR, "Write Dictionary activity cannot be executed in slave context");
  18717. }
  18718. }
  18719. virtual bool needsAllocator() const { return true; }
  18720. virtual void onExecute()
  18721. {
  18722. int sequence = helper.getSequence();
  18723. const char *storedName = helper.queryName();
  18724. assertex(storedName && *storedName);
  18725. assertex(sequence < 0);
  18726. RtlLinkedDictionaryBuilder builder(rowAllocator, helper.queryHashLookupInfo());
  18727. loop
  18728. {
  18729. const void *row = inputStream->ungroupedNextRow();
  18730. if (!row)
  18731. break;
  18732. builder.appendOwn(row);
  18733. processed++;
  18734. }
  18735. serverContext->appendResultDeserialized(storedName, sequence, builder.getcount(), builder.linkrows(), (helper.getFlags() & POFextend) != 0, LINK(meta.queryOriginal()));
  18736. }
  18737. };
  18738. class CRoxieServerWorkUnitWriteDictActivityFactory : public CRoxieServerInternalSinkFactory
  18739. {
  18740. public:
  18741. CRoxieServerWorkUnitWriteDictActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  18742. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot)
  18743. {
  18744. Owned<IHThorDictionaryWorkUnitWriteArg> helper = (IHThorDictionaryWorkUnitWriteArg *) helperFactory();
  18745. isInternal = (helper->getSequence()==ResultSequenceInternal);
  18746. }
  18747. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18748. {
  18749. return new CRoxieServerWorkUnitWriteDictActivity(_ctx, this, _probeManager, usageCount);
  18750. }
  18751. };
  18752. IRoxieServerActivityFactory *createRoxieServerWorkUnitWriteDictActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  18753. {
  18754. return new CRoxieServerWorkUnitWriteDictActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot);
  18755. }
  18756. //=================================================================================
  18757. class CRoxieServerRemoteResultActivity : public CRoxieServerInternalSinkActivity
  18758. {
  18759. IHThorRemoteResultArg &helper;
  18760. public:
  18761. CRoxieServerRemoteResultActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  18762. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _numOutputs), helper((IHThorRemoteResultArg &)basehelper)
  18763. {
  18764. }
  18765. virtual void onExecute()
  18766. {
  18767. OwnedConstRoxieRow row = inputStream->nextRow();
  18768. helper.sendResult(row); // should be only one row or something has gone wrong!
  18769. }
  18770. };
  18771. class CRoxieServerRemoteResultActivityFactory : public CRoxieServerInternalSinkFactory
  18772. {
  18773. public:
  18774. CRoxieServerRemoteResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  18775. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot)
  18776. {
  18777. Owned<IHThorRemoteResultArg> helper = (IHThorRemoteResultArg *) helperFactory();
  18778. isInternal = (helper->getSequence()==ResultSequenceInternal);
  18779. }
  18780. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18781. {
  18782. return new CRoxieServerRemoteResultActivity(_ctx, this, _probeManager, usageCount);
  18783. }
  18784. };
  18785. IRoxieServerActivityFactory *createRoxieServerRemoteResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  18786. {
  18787. return new CRoxieServerRemoteResultActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot);
  18788. }
  18789. //=================================================================================
  18790. class CRoxieServerXmlParseActivity : public CRoxieServerActivity, implements IXMLSelect
  18791. {
  18792. IHThorXmlParseArg &helper;
  18793. Owned<IXMLParse> xmlParser;
  18794. const void * in;
  18795. char * srchStr;
  18796. unsigned numProcessedLastGroup;
  18797. bool srchStrNeedsFree;
  18798. Owned<IColumnProvider> lastMatch;
  18799. public:
  18800. IMPLEMENT_IINTERFACE;
  18801. CRoxieServerXmlParseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18802. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  18803. helper((IHThorXmlParseArg &)basehelper)
  18804. {
  18805. srchStrNeedsFree = helper.searchTextNeedsFree();
  18806. numProcessedLastGroup = 0;
  18807. srchStr = NULL;
  18808. in = NULL;
  18809. }
  18810. ~CRoxieServerXmlParseActivity()
  18811. {
  18812. }
  18813. virtual bool needsAllocator() const { return true; }
  18814. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18815. {
  18816. numProcessedLastGroup = 0;
  18817. srchStr = NULL;
  18818. in = NULL;
  18819. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  18820. }
  18821. virtual void reset()
  18822. {
  18823. if (helper.searchTextNeedsFree())
  18824. rtlFree(srchStr);
  18825. srchStr = NULL;
  18826. ReleaseClearRoxieRow(in);
  18827. xmlParser.clear();
  18828. CRoxieServerActivity::reset();
  18829. }
  18830. virtual void match(IColumnProvider &entry, offset_t startOffset, offset_t endOffset)
  18831. {
  18832. lastMatch.set(&entry);
  18833. }
  18834. virtual const void *nextRow()
  18835. {
  18836. ActivityTimer t(totalCycles, timeActivities);
  18837. loop
  18838. {
  18839. if(xmlParser)
  18840. {
  18841. loop
  18842. {
  18843. if(!xmlParser->next())
  18844. {
  18845. if (srchStrNeedsFree)
  18846. {
  18847. rtlFree(srchStr);
  18848. srchStr = NULL;
  18849. }
  18850. xmlParser.clear();
  18851. break;
  18852. }
  18853. if(lastMatch)
  18854. {
  18855. try
  18856. {
  18857. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  18858. size32_t outSize = helper.transform(rowBuilder, in, lastMatch);
  18859. lastMatch.clear();
  18860. if (outSize)
  18861. {
  18862. processed++;
  18863. return rowBuilder.finalizeRowClear(outSize);
  18864. }
  18865. }
  18866. catch (IException *E)
  18867. {
  18868. throw makeWrappedException(E);
  18869. }
  18870. }
  18871. }
  18872. }
  18873. ReleaseClearRoxieRow(in);
  18874. in = inputStream->nextRow();
  18875. if(!in)
  18876. {
  18877. if(numProcessedLastGroup == processed)
  18878. in = inputStream->nextRow();
  18879. if(!in)
  18880. {
  18881. numProcessedLastGroup = processed;
  18882. return NULL;
  18883. }
  18884. }
  18885. size32_t srchLen;
  18886. helper.getSearchText(srchLen, srchStr, in);
  18887. OwnedRoxieString xmlIteratorPath(helper.getXmlIteratorPath());
  18888. xmlParser.setown(createXMLParse(srchStr, srchLen, xmlIteratorPath, *this));
  18889. }
  18890. }
  18891. };
  18892. class CRoxieServerXmlParseActivityFactory : public CRoxieServerActivityFactory
  18893. {
  18894. public:
  18895. CRoxieServerXmlParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  18896. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  18897. {
  18898. }
  18899. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18900. {
  18901. return new CRoxieServerXmlParseActivity(_ctx, this, _probeManager);
  18902. }
  18903. };
  18904. IRoxieServerActivityFactory *createRoxieServerXmlParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  18905. {
  18906. return new CRoxieServerXmlParseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  18907. }
  18908. //=====================================================================================================
  18909. class CRoxieServerDiskReadBaseActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler, implements IIndexReadContext
  18910. {
  18911. protected:
  18912. IHThorDiskReadBaseArg &helper;
  18913. IHThorCompoundExtra * compoundHelper;
  18914. RemoteActivityId remoteId; // Note we copy it rather than reference
  18915. Owned<CSkippableRemoteResultAdaptor> remote;
  18916. unsigned numParts;
  18917. unsigned __int64 rowLimit;
  18918. unsigned __int64 stopAfter;
  18919. Linked<IInMemoryIndexManager> manager;
  18920. Owned<IInMemoryIndexCursor> cursor;
  18921. Owned<IDirectReader> reader;
  18922. CThorContiguousRowBuffer deserializeSource;
  18923. Owned<ISourceRowPrefetcher> prefetcher;
  18924. bool eof;
  18925. bool isKeyed;
  18926. bool variableFileName;
  18927. bool isOpt;
  18928. bool sorted;
  18929. bool maySkip;
  18930. bool isLocal;
  18931. bool forceRemote;
  18932. CachedOutputMetaData diskSize;
  18933. Owned<const IResolvedFile> varFileInfo;
  18934. Owned<IFileIOArray> varFiles;
  18935. inline bool useRemote()
  18936. {
  18937. return remote != NULL && (forceRemote || numParts > 1);
  18938. }
  18939. public:
  18940. IMPLEMENT_IINTERFACE;
  18941. CRoxieServerDiskReadBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager)
  18942. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  18943. helper((IHThorDiskReadBaseArg &)basehelper),
  18944. numParts(_numParts),
  18945. remoteId(_remoteId),
  18946. manager(_manager),
  18947. isLocal(_isLocal),
  18948. sorted(_sorted),
  18949. maySkip(_maySkip),
  18950. deserializeSource(NULL)
  18951. {
  18952. forceRemote = factory->queryQueryFactory().queryOptions().disableLocalOptimizations;
  18953. if ((forceRemote || numParts != 1) && !isLocal) // NOTE : when numParts == 0 (variable case) we create, even though we may not use
  18954. remote.setown(new CSkippableRemoteResultAdaptor(_ctx, this, remoteId, meta.queryOriginal(), helper, *this, sorted, false, _maySkip));
  18955. compoundHelper = NULL;
  18956. eof = false;
  18957. rowLimit = (unsigned __int64) -1;
  18958. isKeyed = false;
  18959. stopAfter = I64C(0x7FFFFFFFFFFFFFFF);
  18960. diskSize.set(helper.queryDiskRecordSize());
  18961. variableFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getFlags() & (TDXvarfilename|TDXdynamicfilename)) != 0);
  18962. isOpt = (helper.getFlags() & TDRoptional) != 0;
  18963. }
  18964. virtual const IResolvedFile *queryVarFileInfo() const
  18965. {
  18966. return varFileInfo;
  18967. }
  18968. virtual void onCreate(IHThorArg *_colocalParent)
  18969. {
  18970. CRoxieServerActivity::onCreate(_colocalParent);
  18971. if (remote)
  18972. remote->onCreate(_colocalParent);
  18973. }
  18974. virtual bool needsAllocator() const { return true; }
  18975. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18976. {
  18977. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  18978. if (compoundHelper)
  18979. {
  18980. rowLimit = compoundHelper->getRowLimit();
  18981. stopAfter = compoundHelper->getChooseNLimit();
  18982. }
  18983. if (!helper.canMatchAny())
  18984. eof = true;
  18985. else
  18986. {
  18987. if (variableFileName)
  18988. {
  18989. OwnedRoxieString fileName(helper.getFileName());
  18990. varFileInfo.setown(resolveLFN(fileName, isOpt));
  18991. numParts = 0;
  18992. if (varFileInfo)
  18993. numParts = varFileInfo->getNumParts();
  18994. }
  18995. if (!numParts)
  18996. {
  18997. eof = true;
  18998. }
  18999. else if (useRemote())
  19000. {
  19001. remote->onStart(parentExtractSize, parentExtract);
  19002. remote->setLimits(rowLimit, (unsigned __int64) -1, stopAfter);
  19003. unsigned fileNo = 0;
  19004. // Translation into a message per channel done elsewhere....
  19005. remote->getMem(0, fileNo, 0);
  19006. remote->flush();
  19007. remote->senddone();
  19008. }
  19009. else
  19010. {
  19011. if (variableFileName)
  19012. {
  19013. unsigned channel = isLocal ? factory->queryQueryFactory().queryChannel() : 0;
  19014. varFiles.setown(varFileInfo->getIFileIOArray(isOpt, channel));
  19015. manager.setown(varFileInfo->getIndexManager(isOpt, channel, varFiles, diskSize, false, 0));
  19016. }
  19017. assertex(manager != NULL);
  19018. helper.createSegmentMonitors(this);
  19019. if (cursor)
  19020. {
  19021. isKeyed = cursor->selectKey();
  19022. cursor->reset();
  19023. }
  19024. if (!isKeyed)
  19025. {
  19026. reader.setown(manager->createReader(0, 0, 1));
  19027. deserializeSource.setStream(reader);
  19028. prefetcher.setown(diskSize.queryOriginal()->createDiskPrefetcher(ctx->queryCodeContext(), activityId));
  19029. }
  19030. helper.setCallback(reader ? reader->queryThorDiskCallback() : cursor);
  19031. }
  19032. }
  19033. }
  19034. virtual void append(IKeySegmentMonitor *segment)
  19035. {
  19036. if (!segment->isWild())
  19037. {
  19038. if (!cursor)
  19039. cursor.setown(manager->createCursor());
  19040. cursor->append(segment);
  19041. }
  19042. }
  19043. virtual unsigned ordinality() const
  19044. {
  19045. return cursor ? cursor->ordinality() : 0;
  19046. }
  19047. virtual IKeySegmentMonitor *item(unsigned idx) const
  19048. {
  19049. return cursor ? cursor->item(idx) : 0;
  19050. }
  19051. virtual void setMergeBarrier(unsigned barrierOffset)
  19052. {
  19053. // no merging so no issue...
  19054. }
  19055. virtual void stop()
  19056. {
  19057. if (useRemote())
  19058. remote->onStop();
  19059. CRoxieServerActivity::stop();
  19060. }
  19061. virtual void reset()
  19062. {
  19063. if (useRemote())
  19064. {
  19065. processed = remote->processed;
  19066. remote->processed = 0;
  19067. remote->onReset();
  19068. }
  19069. varFileInfo.clear();
  19070. eof = false;
  19071. if (cursor)
  19072. cursor->reset();
  19073. deserializeSource.clearStream();
  19074. CRoxieServerActivity::reset();
  19075. }
  19076. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  19077. {
  19078. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  19079. }
  19080. virtual void onLimitExceeded(bool isKeyed)
  19081. {
  19082. if (traceLevel > 4)
  19083. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  19084. assertex(compoundHelper);
  19085. if (isKeyed) // MORE does this exist for diskread? should it?
  19086. {
  19087. if (helper.getFlags() & (TDRkeyedlimitskips|TDRkeyedlimitcreates))
  19088. {
  19089. if (ctx->queryDebugContext())
  19090. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  19091. throw makeLimitSkipException(true);
  19092. }
  19093. else
  19094. {
  19095. UNIMPLEMENTED;
  19096. //compoundHelper->onKeyedLimitExceeded(); Doesn't exist - though the flags do... interesting...
  19097. }
  19098. }
  19099. else
  19100. {
  19101. if (helper.getFlags() & (TDRlimitskips|TDRlimitcreates))
  19102. {
  19103. if (ctx->queryDebugContext())
  19104. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  19105. throw makeLimitSkipException(false);
  19106. }
  19107. else
  19108. compoundHelper->onLimitExceeded();
  19109. }
  19110. }
  19111. virtual const void * createLimitFailRow(bool isKeyed)
  19112. {
  19113. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  19114. IHThorSourceLimitTransformExtra *limitTransformExtra = static_cast<IHThorSourceLimitTransformExtra *>(helper.selectInterface(TAIsourcelimittransformextra_1));
  19115. assertex(limitTransformExtra);
  19116. size32_t outSize = isKeyed ? limitTransformExtra->transformOnKeyedLimitExceeded(rowBuilder) : limitTransformExtra->transformOnLimitExceeded(rowBuilder);
  19117. if (outSize)
  19118. return rowBuilder.finalizeRowClear(outSize);
  19119. return NULL;
  19120. }
  19121. };
  19122. class CRoxieServerDiskReadActivity : public CRoxieServerDiskReadBaseActivity
  19123. {
  19124. IHThorCompoundReadExtra * readHelper;
  19125. ConstPointerArray readrows;
  19126. bool readAheadDone;
  19127. unsigned readIndex;
  19128. public:
  19129. CRoxieServerDiskReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager)
  19130. : CRoxieServerDiskReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, _maySkip, _manager)
  19131. {
  19132. compoundHelper = (IHThorDiskReadArg *)&helper;
  19133. readHelper = (IHThorDiskReadArg *)&helper;
  19134. readAheadDone = false;
  19135. readIndex = 0;
  19136. }
  19137. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19138. {
  19139. rowLimit = compoundHelper->getRowLimit();
  19140. stopAfter = compoundHelper->getChooseNLimit();
  19141. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  19142. readAheadDone = false;
  19143. readIndex = 0;
  19144. }
  19145. virtual void reset()
  19146. {
  19147. roxiemem::ReleaseRoxieRowRange(readrows.getArray(), readIndex, readrows.ordinality());
  19148. readrows.kill();
  19149. readAheadDone = false;
  19150. readIndex = 0;
  19151. CRoxieServerDiskReadBaseActivity::reset();
  19152. }
  19153. virtual const void *nextRow()
  19154. {
  19155. if (eof)
  19156. return NULL;
  19157. else if (useRemote())
  19158. return remote->nextRow();
  19159. else if (maySkip)
  19160. {
  19161. if (!readAheadDone)
  19162. {
  19163. unsigned preprocessed = 0;
  19164. while (!eof)
  19165. {
  19166. const void *row = _nextRow();
  19167. if (row)
  19168. preprocessed++;
  19169. if (preprocessed > rowLimit)
  19170. {
  19171. ReleaseRoxieRow(row);
  19172. roxiemem::ReleaseRoxieRowRange(readrows.getArray(), readIndex, readrows.ordinality());
  19173. readrows.kill();
  19174. readIndex = 0;
  19175. eof = true;
  19176. if (ctx->queryDebugContext())
  19177. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  19178. if (helper.getFlags() & TDRlimitskips)
  19179. return NULL;
  19180. else if (helper.getFlags() & TDRlimitcreates)
  19181. return createLimitFailRow(false);
  19182. else
  19183. throwUnexpected();
  19184. }
  19185. if (preprocessed > stopAfter) // MORE - bit of a strange place to check
  19186. {
  19187. eof = true;
  19188. ReleaseRoxieRow(row);
  19189. break;
  19190. }
  19191. readrows.append(row);
  19192. }
  19193. readAheadDone = true;
  19194. }
  19195. if (readrows.isItem(readIndex))
  19196. {
  19197. const void *ret = readrows.item(readIndex++);
  19198. if (ret)
  19199. processed++;
  19200. return ret;
  19201. }
  19202. else
  19203. {
  19204. eof = true;
  19205. return NULL;
  19206. }
  19207. }
  19208. else
  19209. {
  19210. const void *ret = _nextRow();
  19211. if (ret)
  19212. {
  19213. processed++;
  19214. if (processed > rowLimit)
  19215. {
  19216. if (traceLevel > 4)
  19217. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  19218. ReleaseRoxieRow(ret);
  19219. compoundHelper->onLimitExceeded();
  19220. throwUnexpected(); // onLimitExceeded is not supposed to return
  19221. }
  19222. if (processed > stopAfter) // MORE - bit of a strange place to check
  19223. {
  19224. eof = true;
  19225. ReleaseRoxieRow(ret);
  19226. return NULL;
  19227. }
  19228. }
  19229. return ret;
  19230. }
  19231. }
  19232. const void *_nextRow()
  19233. {
  19234. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  19235. unsigned transformedSize = 0;
  19236. if (isKeyed)
  19237. {
  19238. loop
  19239. {
  19240. const void *nextCandidate = cursor->nextMatch();
  19241. if (!nextCandidate)
  19242. {
  19243. eof = true;
  19244. return NULL;
  19245. }
  19246. transformedSize = readHelper->transform(rowBuilder, nextCandidate);
  19247. if (transformedSize)
  19248. break;
  19249. }
  19250. }
  19251. else // use reader...
  19252. {
  19253. assertex(reader != NULL);
  19254. loop
  19255. {
  19256. if (deserializeSource.eos())
  19257. {
  19258. eof = true;
  19259. return NULL;
  19260. }
  19261. prefetcher->readAhead(deserializeSource);
  19262. const byte *nextRec = deserializeSource.queryRow();
  19263. if (cursor && cursor->isFiltered(nextRec))
  19264. transformedSize = 0;
  19265. else
  19266. transformedSize = readHelper->transform(rowBuilder, nextRec);
  19267. deserializeSource.finishedRow();
  19268. if (transformedSize)
  19269. break;
  19270. }
  19271. }
  19272. return rowBuilder.finalizeRowClear(transformedSize);
  19273. }
  19274. };
  19275. class CRoxieServerXmlReadActivity : public CRoxieServerDiskReadBaseActivity, implements IXMLSelect, implements IThorDiskCallback
  19276. {
  19277. IHThorXmlReadArg * readHelper;
  19278. Owned<IXmlToRowTransformer> rowTransformer;
  19279. Owned<IXMLParse> xmlParser;
  19280. Owned<IColumnProvider> lastMatch;
  19281. unsigned __int64 fileoffset;
  19282. public:
  19283. IMPLEMENT_IINTERFACE;
  19284. CRoxieServerXmlReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager)
  19285. : CRoxieServerDiskReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, _maySkip, _manager)
  19286. {
  19287. compoundHelper = NULL;
  19288. readHelper = (IHThorXmlReadArg *)&helper;
  19289. fileoffset = 0;
  19290. }
  19291. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19292. {
  19293. rowLimit = readHelper->getRowLimit();
  19294. stopAfter = readHelper->getChooseNLimit();
  19295. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  19296. if (!useRemote())
  19297. {
  19298. rowTransformer.set(readHelper->queryTransformer());
  19299. assertex(reader != NULL);
  19300. OwnedRoxieString xmlIterator(readHelper->getXmlIteratorPath());
  19301. if (factory->getKind()==TAKjsonread)
  19302. xmlParser.setown(createJSONParse(*reader->querySimpleStream(), xmlIterator, *this, (0 != (TDRxmlnoroot & readHelper->getFlags()))?ptr_noRoot:ptr_none, (readHelper->getFlags() & TDRusexmlcontents) != 0));
  19303. else
  19304. xmlParser.setown(createXMLParse(*reader->querySimpleStream(), xmlIterator, *this, (0 != (TDRxmlnoroot & readHelper->getFlags()))?ptr_noRoot:ptr_none, (readHelper->getFlags() & TDRusexmlcontents) != 0));
  19305. }
  19306. }
  19307. virtual void reset()
  19308. {
  19309. CRoxieServerDiskReadBaseActivity::reset();
  19310. rowTransformer.clear();
  19311. xmlParser.clear();
  19312. }
  19313. virtual void match(IColumnProvider &entry, offset_t startOffset, offset_t endOffset)
  19314. {
  19315. fileoffset = startOffset;
  19316. lastMatch.set(&entry);
  19317. }
  19318. //interface IThorDiskCallback
  19319. virtual unsigned __int64 getFilePosition(const void * row)
  19320. {
  19321. return fileoffset;
  19322. }
  19323. virtual unsigned __int64 getLocalFilePosition(const void * row)
  19324. {
  19325. return reader->makeFilePositionLocal(fileoffset);
  19326. }
  19327. virtual const char * queryLogicalFilename(const void * row)
  19328. {
  19329. return reader->queryThorDiskCallback()->queryLogicalFilename(row);
  19330. }
  19331. virtual const void *nextRow()
  19332. {
  19333. if (eof)
  19334. return NULL;
  19335. else if (useRemote())
  19336. return remote->nextRow();
  19337. assertex(xmlParser != NULL);
  19338. try
  19339. {
  19340. while (!eof)
  19341. {
  19342. //call to next() will callback on the IXmlSelect interface
  19343. bool gotNext = false;
  19344. gotNext = xmlParser->next();
  19345. if(!gotNext)
  19346. eof = true;
  19347. else if (lastMatch)
  19348. {
  19349. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  19350. unsigned sizeGot = rowTransformer->transform(rowBuilder, lastMatch, this);
  19351. lastMatch.clear();
  19352. fileoffset = 0;
  19353. if (sizeGot)
  19354. {
  19355. OwnedConstRoxieRow ret = rowBuilder.finalizeRowClear(sizeGot);
  19356. if (processed > rowLimit)
  19357. {
  19358. if (traceLevel > 4)
  19359. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  19360. readHelper->onLimitExceeded();
  19361. throwUnexpected(); // onLimitExceeded is not supposed to return
  19362. }
  19363. processed++;
  19364. if (processed > stopAfter) // MORE - bit of a strange place to check
  19365. {
  19366. eof = true;
  19367. return NULL;
  19368. }
  19369. return ret.getClear();
  19370. }
  19371. }
  19372. }
  19373. return NULL;
  19374. }
  19375. catch(IException *E)
  19376. {
  19377. throw makeWrappedException(E);
  19378. }
  19379. }
  19380. };
  19381. class CRoxieServerCsvReadActivity : public CRoxieServerDiskReadBaseActivity
  19382. {
  19383. IHThorCsvReadArg *readHelper;
  19384. ICsvParameters * csvInfo;
  19385. unsigned headerLines;
  19386. unsigned maxDiskSize;
  19387. CSVSplitter csvSplitter;
  19388. unsigned __int64 localOffset;
  19389. const char *quotes;
  19390. const char *separators;
  19391. const char *terminators;
  19392. const char *escapes;
  19393. size32_t maxRowSize;
  19394. public:
  19395. CRoxieServerCsvReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  19396. unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager,
  19397. const char *_quotes, const char *_separators, const char *_terminators, const char *_escapes, size32_t _maxRowSize)
  19398. : CRoxieServerDiskReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, _maySkip, _manager),
  19399. quotes(_quotes), separators(_separators), terminators(_terminators), escapes(_escapes), maxRowSize(_maxRowSize)
  19400. {
  19401. compoundHelper = NULL;
  19402. readHelper = (IHThorCsvReadArg *)&helper;
  19403. rowLimit = readHelper->getRowLimit();
  19404. stopAfter = readHelper->getChooseNLimit();
  19405. csvInfo = readHelper->queryCsvParameters();
  19406. maxDiskSize = csvInfo->queryMaxSize();
  19407. localOffset = 0;
  19408. headerLines = 0;
  19409. }
  19410. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19411. {
  19412. rowLimit = readHelper->getRowLimit();
  19413. stopAfter = readHelper->getChooseNLimit();
  19414. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  19415. if (!useRemote())
  19416. {
  19417. headerLines = csvInfo->queryHeaderLen();
  19418. if (headerLines && isLocal && reader->queryFilePart() != 1)
  19419. 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...
  19420. if (!eof)
  19421. {
  19422. if (varFileInfo)
  19423. {
  19424. const IPropertyTree *options = varFileInfo->queryProperties();
  19425. if (options)
  19426. {
  19427. quotes = options->queryProp("@csvQuote");
  19428. separators = options->queryProp("@csvSeparate");
  19429. terminators = options->queryProp("@csvTerminate");
  19430. escapes = options->queryProp("@csvEscape");
  19431. }
  19432. }
  19433. csvSplitter.init(readHelper->getMaxColumns(), csvInfo, quotes, separators, terminators, escapes);
  19434. }
  19435. }
  19436. }
  19437. virtual const void *nextRow()
  19438. {
  19439. if (eof)
  19440. return NULL;
  19441. else if (useRemote())
  19442. return remote->nextRow();
  19443. try
  19444. {
  19445. while (!eof)
  19446. {
  19447. if (reader->eos())
  19448. {
  19449. eof = true;
  19450. break;
  19451. }
  19452. // MORE - there are rumours of a csvSplitter that operates on a stream... if/when it exists, this should use it
  19453. size32_t rowSize = 4096; // MORE - make configurable
  19454. size32_t thisLineLength;
  19455. loop
  19456. {
  19457. size32_t avail;
  19458. const void *peek = reader->peek(rowSize, avail);
  19459. thisLineLength = csvSplitter.splitLine(avail, (const byte *)peek);
  19460. if (thisLineLength < rowSize || avail < rowSize)
  19461. break;
  19462. if (rowSize == maxRowSize)
  19463. throw MakeStringException(0, "File contained a line of length greater than %d bytes.", maxRowSize);
  19464. if (rowSize >= maxRowSize/2)
  19465. rowSize = maxRowSize;
  19466. else
  19467. rowSize += rowSize;
  19468. }
  19469. if (headerLines)
  19470. {
  19471. headerLines--;
  19472. reader->skip(thisLineLength);
  19473. }
  19474. else
  19475. {
  19476. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  19477. unsigned transformedSize = readHelper->transform(rowBuilder, csvSplitter.queryLengths(), (const char * *)csvSplitter.queryData());
  19478. reader->skip(thisLineLength);
  19479. if (transformedSize)
  19480. {
  19481. OwnedConstRoxieRow ret = rowBuilder.finalizeRowClear(transformedSize);
  19482. if (processed > rowLimit)
  19483. {
  19484. readHelper->onLimitExceeded();
  19485. throwUnexpected(); // onLimitExceeded is not supposed to return
  19486. }
  19487. processed++;
  19488. if (processed > stopAfter) // MORE - bit of a strange place to check
  19489. {
  19490. eof = true;
  19491. return NULL;
  19492. }
  19493. return ret.getClear();
  19494. }
  19495. }
  19496. }
  19497. return NULL;
  19498. }
  19499. catch(IException *E)
  19500. {
  19501. throw makeWrappedException(E);
  19502. }
  19503. }
  19504. virtual void reset()
  19505. {
  19506. CRoxieServerDiskReadBaseActivity::reset();
  19507. csvSplitter.reset();
  19508. localOffset = 0;
  19509. }
  19510. virtual unsigned __int64 getFilePosition(const void * row)
  19511. {
  19512. UNIMPLEMENTED; // we know offset in the reader but not sure it helps us much
  19513. }
  19514. virtual unsigned __int64 getLocalFilePosition(const void * row)
  19515. {
  19516. UNIMPLEMENTED;
  19517. }
  19518. };
  19519. class CRoxieServerDiskNormalizeActivity : public CRoxieServerDiskReadBaseActivity
  19520. {
  19521. IHThorDiskNormalizeArg *normalizeHelper;
  19522. bool firstPending;
  19523. public:
  19524. CRoxieServerDiskNormalizeActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, IInMemoryIndexManager *_manager)
  19525. : CRoxieServerDiskReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, false, _manager)
  19526. {
  19527. compoundHelper = (IHThorDiskNormalizeArg *)&helper;
  19528. normalizeHelper = (IHThorDiskNormalizeArg *)&helper;
  19529. firstPending = true;
  19530. }
  19531. virtual void reset()
  19532. {
  19533. firstPending = true;
  19534. CRoxieServerDiskReadBaseActivity::reset();
  19535. }
  19536. virtual const void *nextRow()
  19537. {
  19538. if (eof)
  19539. return NULL;
  19540. else if (useRemote())
  19541. return remote->nextRow();
  19542. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  19543. unsigned transformedSize = 0;
  19544. if (isKeyed)
  19545. {
  19546. loop
  19547. {
  19548. while (firstPending)
  19549. {
  19550. const void *nextCandidate = cursor->nextMatch();
  19551. if (!nextCandidate)
  19552. {
  19553. eof = true;
  19554. return NULL;
  19555. }
  19556. if (normalizeHelper->first(nextCandidate))
  19557. {
  19558. firstPending = false;
  19559. break;
  19560. }
  19561. }
  19562. transformedSize = normalizeHelper->transform(rowBuilder);
  19563. firstPending = !normalizeHelper->next();
  19564. if (transformedSize)
  19565. break;
  19566. }
  19567. }
  19568. else
  19569. {
  19570. assertex(reader != NULL);
  19571. loop
  19572. {
  19573. while (firstPending)
  19574. {
  19575. if (deserializeSource.eos())
  19576. {
  19577. eof = true;
  19578. return NULL;
  19579. }
  19580. prefetcher->readAhead(deserializeSource);
  19581. const byte *nextRec = deserializeSource.queryRow();
  19582. if (!cursor || !cursor->isFiltered(nextRec))
  19583. {
  19584. if (normalizeHelper->first(nextRec))
  19585. firstPending = false;
  19586. }
  19587. deserializeSource.finishedRow();
  19588. }
  19589. transformedSize = normalizeHelper->transform(rowBuilder);
  19590. firstPending = !normalizeHelper->next();
  19591. if (transformedSize)
  19592. break;
  19593. }
  19594. }
  19595. OwnedConstRoxieRow recBuffer = rowBuilder.finalizeRowClear(transformedSize);
  19596. processed++;
  19597. if (processed > rowLimit)
  19598. {
  19599. compoundHelper->onLimitExceeded();
  19600. throwUnexpected(); // onLimitExceeded is not supposed to return
  19601. }
  19602. if (processed > stopAfter) // MORE - bit of a strange place to check
  19603. {
  19604. eof = true;
  19605. return NULL;
  19606. }
  19607. return recBuffer.getClear();
  19608. }
  19609. };
  19610. class CRoxieServerDiskAggregateBaseActivity : public CRoxieServerDiskReadBaseActivity
  19611. {
  19612. protected:
  19613. bool done;
  19614. public:
  19615. CRoxieServerDiskAggregateBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager)
  19616. : CRoxieServerDiskReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, false, false, _manager),
  19617. done(false)
  19618. {
  19619. }
  19620. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19621. {
  19622. done = false;
  19623. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  19624. }
  19625. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  19626. {
  19627. if (idx==(unsigned)-1)
  19628. idx = 0;
  19629. return idx ? NULL: this;
  19630. }
  19631. };
  19632. class CRoxieServerDiskCountActivity : public CRoxieServerDiskAggregateBaseActivity
  19633. {
  19634. IHThorDiskCountArg & countHelper;
  19635. unsigned __int64 choosenLimit;
  19636. IHThorSourceCountLimit *limitHelper;
  19637. unsigned __int64 getSkippedCount()
  19638. {
  19639. unsigned flags = countHelper.getFlags();
  19640. if (flags & TDRlimitskips)
  19641. return 0;
  19642. else if (flags & TDRlimitcreates)
  19643. return 1;
  19644. else
  19645. {
  19646. assertex(limitHelper);
  19647. if (traceLevel > 4)
  19648. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  19649. limitHelper->onLimitExceeded();
  19650. throwUnexpected(); // onLimitExceeded should always throw exception
  19651. }
  19652. }
  19653. public:
  19654. CRoxieServerDiskCountActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager)
  19655. : CRoxieServerDiskAggregateBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _manager),
  19656. countHelper((IHThorDiskCountArg &)basehelper)
  19657. {
  19658. limitHelper = static_cast<IHThorSourceCountLimit *>(basehelper.selectInterface(TAIsourcecountlimit_1));
  19659. choosenLimit = 0;
  19660. }
  19661. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19662. {
  19663. choosenLimit = countHelper.getChooseNLimit();
  19664. if (limitHelper)
  19665. {
  19666. rowLimit = limitHelper->getRowLimit();
  19667. // keyedLimit = limitHelper->getKeyedLimit(); // more - should there be one?
  19668. }
  19669. CRoxieServerDiskAggregateBaseActivity::start(parentExtractSize, parentExtract, paused);
  19670. }
  19671. virtual const void *nextRow()
  19672. {
  19673. ActivityTimer t(totalCycles, timeActivities);
  19674. if (done) return NULL;
  19675. done = true;
  19676. unsigned __int64 totalCount = 0;
  19677. if (helper.canMatchAny() && !eof)
  19678. {
  19679. if (useRemote())
  19680. {
  19681. loop
  19682. {
  19683. const void * next = remote->nextRow();
  19684. if (!next)
  19685. break;
  19686. if (meta.getFixedSize() == 1)
  19687. totalCount += *(byte *)next;
  19688. else
  19689. totalCount += *(unsigned __int64 *)next;
  19690. ReleaseRoxieRow(next);
  19691. if (totalCount > rowLimit)
  19692. {
  19693. totalCount = getSkippedCount();
  19694. break;
  19695. }
  19696. else if (totalCount >= choosenLimit)
  19697. {
  19698. totalCount = choosenLimit;
  19699. break;
  19700. }
  19701. }
  19702. }
  19703. else
  19704. {
  19705. if (isKeyed)
  19706. {
  19707. loop
  19708. {
  19709. const void *nextCandidate = cursor->nextMatch();
  19710. if (!nextCandidate)
  19711. break;
  19712. totalCount += countHelper.numValid(nextCandidate);
  19713. if (totalCount > rowLimit)
  19714. {
  19715. totalCount = getSkippedCount();
  19716. break;
  19717. }
  19718. else if (totalCount >= choosenLimit)
  19719. {
  19720. totalCount = choosenLimit;
  19721. break;
  19722. }
  19723. }
  19724. }
  19725. else
  19726. {
  19727. assertex(reader != NULL);
  19728. while (!deserializeSource.eos())
  19729. {
  19730. prefetcher->readAhead(deserializeSource);
  19731. const byte *nextRec = deserializeSource.queryRow();
  19732. if (!cursor || !cursor->isFiltered(nextRec))
  19733. {
  19734. totalCount += countHelper.numValid(nextRec);
  19735. }
  19736. deserializeSource.finishedRow();
  19737. if (totalCount > rowLimit)
  19738. {
  19739. totalCount = getSkippedCount();
  19740. break;
  19741. }
  19742. else if (totalCount >= choosenLimit)
  19743. {
  19744. totalCount = choosenLimit;
  19745. break;
  19746. }
  19747. }
  19748. }
  19749. }
  19750. }
  19751. size32_t rowSize = meta.getFixedSize();
  19752. void * result = rowAllocator->createRow();
  19753. if (rowSize == 1)
  19754. *(byte *)result = (byte)totalCount;
  19755. else
  19756. {
  19757. assertex(rowSize == sizeof(unsigned __int64));
  19758. *(unsigned __int64 *)result = totalCount;
  19759. }
  19760. return rowAllocator->finalizeRow(rowSize, result, rowSize);
  19761. }
  19762. };
  19763. class CRoxieServerDiskAggregateActivity : public CRoxieServerDiskAggregateBaseActivity
  19764. {
  19765. IHThorCompoundAggregateExtra & aggregateHelper;
  19766. public:
  19767. CRoxieServerDiskAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  19768. unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager)
  19769. : CRoxieServerDiskAggregateBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _manager),
  19770. aggregateHelper((IHThorDiskAggregateArg &)basehelper)
  19771. {
  19772. }
  19773. const void * gatherMerged()
  19774. {
  19775. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  19776. size32_t finalSize = 0;
  19777. if (useRemote())
  19778. {
  19779. const void * firstRow = remote->nextRow();
  19780. if (!firstRow)
  19781. {
  19782. rowBuilder.ensureRow();
  19783. finalSize = aggregateHelper.clearAggregate(rowBuilder);
  19784. }
  19785. else
  19786. {
  19787. // NOTE need to clone this because going to modify below, could special case 1 row only
  19788. finalSize = cloneRow(rowBuilder, firstRow, meta);
  19789. ReleaseRoxieRow(firstRow);
  19790. }
  19791. loop
  19792. {
  19793. const void * next = remote->nextRow();
  19794. if (!next)
  19795. break;
  19796. finalSize = aggregateHelper.mergeAggregate(rowBuilder, next);
  19797. ReleaseRoxieRow(next);
  19798. }
  19799. }
  19800. else
  19801. {
  19802. aggregateHelper.clearAggregate(rowBuilder);
  19803. if (helper.canMatchAny() && !eof)
  19804. {
  19805. if (isKeyed)
  19806. {
  19807. loop
  19808. {
  19809. const void *next = cursor->nextMatch();
  19810. if (!next)
  19811. break;
  19812. aggregateHelper.processRow(rowBuilder, next);
  19813. }
  19814. }
  19815. else
  19816. {
  19817. assertex(reader != NULL);
  19818. while (!deserializeSource.eos())
  19819. {
  19820. prefetcher->readAhead(deserializeSource);
  19821. const byte *nextRec = deserializeSource.queryRow();
  19822. if (!cursor || !cursor->isFiltered(nextRec))
  19823. {
  19824. aggregateHelper.processRow(rowBuilder, nextRec);
  19825. }
  19826. deserializeSource.finishedRow();
  19827. }
  19828. }
  19829. }
  19830. finalSize = meta.getRecordSize(rowBuilder.getSelf());
  19831. }
  19832. return rowBuilder.finalizeRowClear(finalSize);
  19833. }
  19834. virtual const void *nextRow()
  19835. {
  19836. ActivityTimer t(totalCycles, timeActivities);
  19837. if (done) return NULL;
  19838. const void * ret = gatherMerged();
  19839. done = true;
  19840. return ret;
  19841. }
  19842. };
  19843. class CRoxieServerDiskGroupAggregateActivity : public CRoxieServerDiskAggregateBaseActivity
  19844. {
  19845. IHThorDiskGroupAggregateArg & aggregateHelper;
  19846. RowAggregator resultAggregator;
  19847. bool gathered;
  19848. public:
  19849. IMPLEMENT_IINTERFACE;
  19850. CRoxieServerDiskGroupAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager)
  19851. : CRoxieServerDiskAggregateBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _manager),
  19852. aggregateHelper((IHThorDiskGroupAggregateArg &)basehelper),
  19853. resultAggregator(aggregateHelper, aggregateHelper),
  19854. gathered(false)
  19855. {
  19856. }
  19857. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19858. {
  19859. gathered= false;
  19860. CRoxieServerDiskAggregateBaseActivity::start(parentExtractSize, parentExtract, paused);
  19861. resultAggregator.start(rowAllocator);
  19862. }
  19863. virtual void reset()
  19864. {
  19865. resultAggregator.reset();
  19866. CRoxieServerDiskAggregateBaseActivity::reset();
  19867. }
  19868. void gatherMerged()
  19869. {
  19870. if (useRemote())
  19871. {
  19872. loop
  19873. {
  19874. const void * next = remote->nextRow();
  19875. if (!next)
  19876. break;
  19877. resultAggregator.mergeElement(next);
  19878. ReleaseRoxieRow(next);
  19879. }
  19880. }
  19881. else
  19882. {
  19883. if (helper.canMatchAny() && !eof)
  19884. {
  19885. Owned<IInMemoryFileProcessor> processor = isKeyed ?
  19886. createKeyedGroupAggregateRecordProcessor(cursor, resultAggregator, aggregateHelper) :
  19887. createUnkeyedGroupAggregateRecordProcessor(cursor, resultAggregator, aggregateHelper, manager->createReader(0, 0, 1),
  19888. ctx->queryCodeContext(), activityId);
  19889. processor->doQuery(NULL, 0, 0, 0);
  19890. }
  19891. }
  19892. gathered = true;
  19893. }
  19894. virtual const void *nextRow()
  19895. {
  19896. ActivityTimer t(totalCycles, timeActivities);
  19897. if (done)
  19898. return NULL;
  19899. if (!gathered)
  19900. gatherMerged();
  19901. Owned<AggregateRowBuilder> next = resultAggregator.nextResult();
  19902. if (next)
  19903. {
  19904. processed++;
  19905. return next->finalizeRowClear();
  19906. }
  19907. done = true;
  19908. return NULL;
  19909. }
  19910. };
  19911. class CRoxieServerDiskReadActivityFactory : public CRoxieServerActivityFactory
  19912. {
  19913. public:
  19914. RemoteActivityId remoteId;
  19915. bool isLocal;
  19916. bool sorted;
  19917. bool maySkip;
  19918. bool variableFileName;
  19919. Owned<IFileIOArray> files;
  19920. Owned<IInMemoryIndexManager> manager;
  19921. Owned<const IResolvedFile> datafile;
  19922. const char *quotes;
  19923. const char *separators;
  19924. const char *terminators;
  19925. const char *escapes;
  19926. size32_t maxCsvRowSize;
  19927. CRoxieServerDiskReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  19928. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), remoteId(_remoteId)
  19929. {
  19930. isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  19931. Owned<IHThorDiskReadBaseArg> helper = (IHThorDiskReadBaseArg *) helperFactory();
  19932. sorted = (helper->getFlags() & TDRunsorted) == 0;
  19933. variableFileName = allFilesDynamic || _queryFactory.isDynamic() || ((helper->getFlags() & (TDXvarfilename|TDXdynamicfilename)) != 0);
  19934. maySkip = (helper->getFlags() & (TDRkeyedlimitskips|TDRkeyedlimitcreates|TDRlimitskips|TDRlimitcreates)) != 0;
  19935. quotes = separators = terminators = escapes = NULL;
  19936. if (!variableFileName)
  19937. {
  19938. bool isOpt = (helper->getFlags() & TDRoptional) != 0;
  19939. OwnedRoxieString fileName(helper->getFileName());
  19940. datafile.setown(_queryFactory.queryPackage().lookupFileName(fileName, isOpt, true, true, _queryFactory.queryWorkUnit(), true));
  19941. bool isSimple = (datafile && datafile->getNumParts()==1 && !_queryFactory.queryOptions().disableLocalOptimizations);
  19942. if (isLocal || isSimple)
  19943. {
  19944. if (datafile)
  19945. {
  19946. unsigned channel = isLocal ? queryFactory.queryChannel() : 0;
  19947. files.setown(datafile->getIFileIOArray(isOpt, channel));
  19948. manager.setown(datafile->getIndexManager(isOpt, channel, files, helper->queryDiskRecordSize(), _graphNode.getPropBool("att[@name=\"preload\"]/@value", false), _graphNode.getPropInt("att[@name=\"_preloadSize\"]/@value", 0)));
  19949. const IPropertyTree *options = datafile->queryProperties();
  19950. if (options)
  19951. {
  19952. quotes = options->queryProp("@csvQuote");
  19953. separators = options->queryProp("@csvSeparate");
  19954. terminators = options->queryProp("@csvTerminate");
  19955. escapes = options->queryProp("@csvEscape");
  19956. }
  19957. }
  19958. else
  19959. manager.setown(getEmptyIndexManager());
  19960. }
  19961. }
  19962. switch (kind)
  19963. {
  19964. case TAKcsvread:
  19965. {
  19966. maxCsvRowSize = defaultMaxCsvRowSize * 1024 * 1024;
  19967. IConstWorkUnit *workunit = _queryFactory.queryWorkUnit();
  19968. if (workunit)
  19969. maxCsvRowSize = workunit->getDebugValueInt(OPT_MAXCSVROWSIZE, defaultMaxCsvRowSize) * 1024 * 1024;
  19970. break;
  19971. }
  19972. default:
  19973. maxCsvRowSize = 0; // unused
  19974. }
  19975. }
  19976. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  19977. {
  19978. unsigned numParts = datafile ? datafile->getNumParts() : 0;
  19979. switch (kind)
  19980. {
  19981. case TAKcsvread:
  19982. return new CRoxieServerCsvReadActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, sorted, maySkip, manager,
  19983. quotes, separators, terminators, escapes, maxCsvRowSize);
  19984. case TAKxmlread:
  19985. case TAKjsonread:
  19986. return new CRoxieServerXmlReadActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, sorted, maySkip, manager);
  19987. case TAKdiskread:
  19988. return new CRoxieServerDiskReadActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, sorted, maySkip, manager);
  19989. case TAKdisknormalize:
  19990. return new CRoxieServerDiskNormalizeActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, sorted, manager);
  19991. case TAKdiskcount:
  19992. return new CRoxieServerDiskCountActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, manager);
  19993. case TAKdiskaggregate:
  19994. return new CRoxieServerDiskAggregateActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, manager);
  19995. case TAKdiskgroupaggregate:
  19996. return new CRoxieServerDiskGroupAggregateActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, manager);
  19997. }
  19998. throwUnexpected();
  19999. }
  20000. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  20001. {
  20002. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  20003. }
  20004. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  20005. {
  20006. if (datafile)
  20007. addXrefFileInfo(reply, datafile);
  20008. else
  20009. {
  20010. // Temporarily resolve the file
  20011. Owned<IHThorDiskReadBaseArg> helper = (IHThorDiskReadBaseArg *) helperFactory();
  20012. if ((helper->getFlags() & (TDXvarfilename|TDXdynamicfilename)) == 0)
  20013. {
  20014. OwnedRoxieString fileName(helper->getFileName());
  20015. Owned<const IResolvedFile> temp = queryFactory.queryPackage().lookupFileName(fileName, true, true, false, queryFactory.queryWorkUnit(), true);
  20016. if (temp)
  20017. addXrefFileInfo(reply, temp);
  20018. }
  20019. }
  20020. }
  20021. virtual const StatisticsMapping &queryStatsMapping() const
  20022. {
  20023. return diskStatistics;
  20024. }
  20025. };
  20026. IRoxieServerActivityFactory *createRoxieServerDiskReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  20027. {
  20028. return new CRoxieServerDiskReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  20029. }
  20030. //=================================================================================
  20031. class CRoxieServerIndexActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler
  20032. {
  20033. protected:
  20034. IHThorIndexReadBaseArg &indexHelper;
  20035. IHThorSteppedSourceExtra * steppedExtra;
  20036. Linked<IKeyArray> keySet;
  20037. Linked<TranslatorArray> translators;
  20038. CSkippableRemoteResultAdaptor remote;
  20039. CIndexTransformCallback callback;
  20040. bool sorted;
  20041. bool variableFileName;
  20042. bool variableInfoPending;
  20043. bool isOpt;
  20044. bool isLocal;
  20045. unsigned __int64 rowLimit;
  20046. unsigned __int64 keyedLimit;
  20047. unsigned __int64 choosenLimit;
  20048. unsigned accepted;
  20049. unsigned rejected;
  20050. unsigned seekGEOffset;
  20051. Owned<IKeyManager> tlk;
  20052. Owned<const IResolvedFile> varFileInfo;
  20053. const RemoteActivityId &remoteId;
  20054. void setVariableFileInfo()
  20055. {
  20056. OwnedRoxieString indexName(indexHelper.getFileName());
  20057. varFileInfo.setown(resolveLFN(indexName, isOpt));
  20058. if (varFileInfo)
  20059. {
  20060. translators.setown(new TranslatorArray) ;
  20061. keySet.setown(varFileInfo->getKeyArray(factory->queryActivityMeta(), translators, isOpt, isLocal ? factory->queryQueryFactory().queryChannel() : 0, factory->queryQueryFactory().queryOptions().enableFieldTranslation));
  20062. }
  20063. variableInfoPending = false;
  20064. }
  20065. public:
  20066. CRoxieServerIndexActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  20067. IKeyArray * _keySet, TranslatorArray *_translators, bool _sorted, bool _isLocal, bool _maySkip)
  20068. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  20069. keySet(_keySet),
  20070. translators(_translators),
  20071. indexHelper((IHThorIndexReadBaseArg &)basehelper),
  20072. remote(_ctx, this, _remoteId, meta.queryOriginal(), indexHelper, *this, _sorted, false, _maySkip),
  20073. remoteId(_remoteId),
  20074. sorted(_sorted),
  20075. isLocal(_isLocal)
  20076. {
  20077. indexHelper.setCallback(&callback);
  20078. steppedExtra = static_cast<IHThorSteppedSourceExtra *>(indexHelper.selectInterface(TAIsteppedsourceextra_1));
  20079. variableFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((indexHelper.getFlags() & (TIRvarfilename|TIRdynamicfilename)) != 0);
  20080. variableInfoPending = false;
  20081. isOpt = (indexHelper.getFlags() & TIRoptional) != 0;
  20082. seekGEOffset = 0;
  20083. // started = false;
  20084. rejected = accepted = 0;
  20085. rowLimit = choosenLimit = keyedLimit = 0;
  20086. }
  20087. virtual const IResolvedFile *queryVarFileInfo() const
  20088. {
  20089. return varFileInfo;
  20090. }
  20091. virtual void onCreate(IHThorArg *_colocalParent)
  20092. {
  20093. CRoxieServerActivity::onCreate(_colocalParent);
  20094. remote.onCreate(_colocalParent);
  20095. }
  20096. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20097. {
  20098. accepted = 0;
  20099. rejected = 0;
  20100. rowLimit = (unsigned __int64) -1;
  20101. keyedLimit = (unsigned __int64 ) -1;
  20102. choosenLimit = I64C(0x7fffffffffffffff);
  20103. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  20104. remote.onStart(parentExtractSize, parentExtract);
  20105. variableInfoPending = variableFileName;
  20106. }
  20107. void processAllKeys()
  20108. {
  20109. try
  20110. {
  20111. if (indexHelper.canMatchAny())
  20112. {
  20113. if (variableInfoPending)
  20114. setVariableFileInfo();
  20115. remote.setLimits(rowLimit, keyedLimit, choosenLimit);
  20116. if (keySet)
  20117. {
  20118. // MORE - this recreates the segmonitors per part but not per fileno (which is a little backwards).
  20119. // 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
  20120. // However order is probably better to iterate fileno's inside partnos
  20121. // MORE - also not properly supporting STEPPED I fear.
  20122. // A superkey that mixes single and multipart or tlk and roroot keys might be hard
  20123. for (unsigned partNo = 0; partNo < keySet->length(); partNo++)
  20124. {
  20125. IKeyIndexBase *thisBase = keySet->queryKeyPart(partNo);
  20126. if (thisBase)
  20127. {
  20128. unsigned fileNo = 0;
  20129. IKeyIndex *thisKey = thisBase->queryPart(fileNo);
  20130. if (!thisKey->isTopLevelKey())
  20131. {
  20132. if (keyedLimit != (unsigned __int64) -1)
  20133. {
  20134. if ((indexHelper.getFlags() & TIRcountkeyedlimit) != 0)
  20135. {
  20136. Owned<IKeyManager> countKey;
  20137. countKey.setown(createKeyManager(thisKey, 0, this));
  20138. countKey->setLayoutTranslator(translators->item(fileNo));
  20139. createSegmentMonitors(countKey);
  20140. unsigned __int64 count = countKey->checkCount(keyedLimit);
  20141. if (count > keyedLimit)
  20142. {
  20143. if (traceLevel > 4)
  20144. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  20145. onLimitExceeded(true);
  20146. }
  20147. }
  20148. }
  20149. }
  20150. if (seekGEOffset && !thisKey->isTopLevelKey())
  20151. {
  20152. tlk.setown(createSingleKeyMerger(thisKey, 0, seekGEOffset, this));
  20153. }
  20154. else
  20155. {
  20156. tlk.setown(createKeyManager(thisKey, 0, this));
  20157. tlk->setLayoutTranslator(translators->item(fileNo));
  20158. }
  20159. createSegmentMonitors(tlk);
  20160. if (queryTraceLevel() > 3 || ctx->queryProbeManager())
  20161. {
  20162. StringBuffer out;
  20163. printKeyedValues(out, tlk, indexHelper.queryDiskRecordSize());
  20164. CTXLOG("Using filter %s", out.str());
  20165. if (ctx->queryProbeManager())
  20166. ctx->queryProbeManager()->setNodeProperty(this, "filter", out.str());
  20167. }
  20168. tlk->reset();
  20169. loop // for each file part
  20170. {
  20171. //block for TransformCallbackAssociation
  20172. {
  20173. TransformCallbackAssociation associate(callback, tlk);
  20174. if (thisKey->isTopLevelKey())
  20175. {
  20176. if (thisKey->isFullySorted())
  20177. {
  20178. while (tlk->lookup(false))
  20179. {
  20180. unsigned slavePart = (unsigned) tlk->queryFpos();
  20181. if (slavePart)
  20182. {
  20183. accepted++;
  20184. remote.getMem(slavePart, fileNo, 0); // the cached context is all we need to send
  20185. if (sorted && numChannels>1)
  20186. remote.flush(); // don't combine parts if we need result sorted, except on a 1-way
  20187. }
  20188. }
  20189. }
  20190. else
  20191. {
  20192. // MORE - we could check whether there are any matching parts if we wanted.
  20193. // If people are in the habit of sending null values that would be worthwhile
  20194. remote.getMem(0, fileNo, 0);
  20195. }
  20196. }
  20197. else
  20198. {
  20199. if (processSingleKey(thisKey, translators->item(fileNo)))
  20200. break;
  20201. }
  20202. }
  20203. if (++fileNo < thisBase->numParts())
  20204. {
  20205. thisKey = thisBase->queryPart(fileNo);
  20206. tlk->setKey(thisKey);
  20207. tlk->setLayoutTranslator(translators->item(fileNo));
  20208. tlk->reset();
  20209. }
  20210. else
  20211. break;
  20212. }
  20213. tlk->releaseSegmentMonitors();
  20214. tlk->setKey(NULL);
  20215. }
  20216. }
  20217. }
  20218. }
  20219. remote.flush();
  20220. remote.senddone();
  20221. }
  20222. catch (IException *E)
  20223. {
  20224. remote.setException(E);
  20225. }
  20226. }
  20227. virtual void createSegmentMonitors(IKeyManager *key)
  20228. {
  20229. indexHelper.createSegmentMonitors(key);
  20230. key->finishSegmentMonitors();
  20231. }
  20232. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans) = 0;
  20233. virtual void reset()
  20234. {
  20235. if (accepted)
  20236. noteStatistic(StNumIndexAccepted, accepted);
  20237. if (rejected)
  20238. noteStatistic(StNumIndexRejected, rejected);
  20239. remote.onReset();
  20240. CRoxieServerActivity::reset();
  20241. if (varFileInfo)
  20242. {
  20243. keySet.clear();
  20244. varFileInfo.clear();
  20245. }
  20246. variableInfoPending = false;
  20247. }
  20248. virtual void stop()
  20249. {
  20250. remote.onStop();
  20251. CRoxieServerActivity::stop();
  20252. }
  20253. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  20254. {
  20255. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  20256. }
  20257. };
  20258. class CRoxieServerIndexReadBaseActivity : public CRoxieServerIndexActivity
  20259. {
  20260. IHThorSourceLimitTransformExtra * limitTransformExtra;
  20261. public:
  20262. CRoxieServerIndexReadBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  20263. IKeyArray * _keySet, TranslatorArray *_translators, bool _sorted, bool _isLocal, bool _maySkip)
  20264. : CRoxieServerIndexActivity(_ctx, _factory, _probeManager, _remoteId, _keySet, _translators, _sorted, _isLocal, _maySkip)
  20265. {
  20266. limitTransformExtra = static_cast<IHThorSourceLimitTransformExtra *>(indexHelper.selectInterface(TAIsourcelimittransformextra_1));
  20267. }
  20268. virtual void reset()
  20269. {
  20270. remote.onReset();
  20271. CRoxieServerIndexActivity::reset();
  20272. }
  20273. virtual const void *nextRow()
  20274. {
  20275. ActivityTimer t(totalCycles, timeActivities);
  20276. try
  20277. {
  20278. const void *ret = remote.nextRow();
  20279. if (ret)
  20280. processed++;
  20281. return ret;
  20282. }
  20283. catch (IException *E)
  20284. {
  20285. throw makeWrappedException(E);
  20286. }
  20287. }
  20288. protected:
  20289. virtual const void * createLimitFailRow(bool isKeyed)
  20290. {
  20291. createRowAllocator();
  20292. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  20293. size32_t outSize = isKeyed ? limitTransformExtra->transformOnKeyedLimitExceeded(rowBuilder) : limitTransformExtra->transformOnLimitExceeded(rowBuilder);
  20294. if (outSize)
  20295. return rowBuilder.finalizeRowClear(outSize);
  20296. return NULL;
  20297. }
  20298. };
  20299. class CRoxieServerIndexReadActivity : public CRoxieServerIndexReadBaseActivity, implements IIndexReadActivityInfo
  20300. {
  20301. protected:
  20302. IHThorCompoundReadExtra & readHelper;
  20303. ISteppingMeta *rawMeta;
  20304. CSteppingMeta steppingMeta;
  20305. unsigned * seekSizes;
  20306. bool optimizeSteppedPostFilter;
  20307. ISteppingMeta * projectedMeta;
  20308. unsigned maxSeekLookahead;
  20309. public:
  20310. CRoxieServerIndexReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  20311. IKeyArray * _keySet, TranslatorArray *_translators, bool _sorted, bool _isLocal, bool _maySkip, unsigned _maxSeekLookahead)
  20312. : CRoxieServerIndexReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _keySet, _translators, _sorted, _isLocal, _maySkip),
  20313. readHelper((IHThorIndexReadArg &)basehelper)
  20314. {
  20315. rawMeta = readHelper.queryRawSteppingMeta();
  20316. unsigned flags = indexHelper.getFlags();
  20317. optimizeSteppedPostFilter = (flags & TIRunfilteredtransform) != 0;
  20318. seekSizes = NULL;
  20319. maxSeekLookahead = _maxSeekLookahead;
  20320. if (rawMeta)
  20321. {
  20322. const CFieldOffsetSize * fields = rawMeta->queryFields();
  20323. unsigned maxFields = rawMeta->getNumFields();
  20324. seekGEOffset = fields[0].offset;
  20325. seekSizes = new unsigned[maxFields];
  20326. seekSizes[0] = fields[0].size;
  20327. for (unsigned i=1; i < maxFields; i++)
  20328. seekSizes[i] = seekSizes[i-1] + fields[i].size;
  20329. projectedMeta = readHelper.queryProjectedSteppingMeta();
  20330. ISteppingMeta *useMeta = projectedMeta ? projectedMeta : rawMeta;
  20331. remote.setMergeInfo(useMeta); // also need to consider superfile case where there is a mix of multiway and singleparts.. ?
  20332. bool hasPostFilter = readHelper.transformMayFilter() && optimizeSteppedPostFilter;
  20333. steppingMeta.init(useMeta, hasPostFilter);
  20334. }
  20335. }
  20336. ~CRoxieServerIndexReadActivity()
  20337. {
  20338. delete [] seekSizes;
  20339. }
  20340. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20341. {
  20342. CRoxieServerIndexReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  20343. steppingMeta.setDistributed();
  20344. if (steppedExtra)
  20345. steppingMeta.setExtra(steppedExtra);
  20346. rowLimit = readHelper.getRowLimit();
  20347. keyedLimit = readHelper.getKeyedLimit();
  20348. choosenLimit = readHelper.getChooseNLimit();
  20349. if (!paused)
  20350. processAllKeys();
  20351. }
  20352. class LazyLocalKeyReader : public CInterface, implements IMessageResult, implements IMessageUnpackCursor
  20353. {
  20354. public:
  20355. IMPLEMENT_IINTERFACE;
  20356. virtual IMessageUnpackCursor *getCursor(roxiemem::IRowManager *rowMgr) const
  20357. {
  20358. Link();
  20359. return const_cast<LazyLocalKeyReader*> (this);
  20360. }
  20361. virtual const void *getMessageHeader(unsigned &length) const
  20362. {
  20363. length = 0;
  20364. return NULL;
  20365. }
  20366. virtual const void *getMessageMetadata(unsigned &length) const
  20367. {
  20368. length = 0;
  20369. return NULL;
  20370. }
  20371. virtual void discard() const
  20372. {
  20373. // nothing to do.
  20374. }
  20375. unsigned keyedCount;
  20376. unsigned matched;
  20377. bool EOFseen;
  20378. Owned<IKeyIndexSet> keySet;
  20379. Owned<IKeyManager> tlk;
  20380. CRoxieServerIndexReadActivity &owner;
  20381. LazyLocalKeyReader(CRoxieServerIndexReadActivity &_owner, IKeyIndex *key, IRecordLayoutTranslator * trans)
  20382. : owner(_owner)
  20383. {
  20384. keyedCount = 0;
  20385. matched = 0;
  20386. EOFseen = false;
  20387. keySet.setown(createKeyIndexSet());
  20388. keySet->addIndex(LINK(key));
  20389. if (owner.seekGEOffset)
  20390. tlk.setown(createKeyMerger(keySet, 0, owner.seekGEOffset, &owner));
  20391. else
  20392. tlk.setown(createKeyManager(keySet->queryPart(0), 0, &owner));
  20393. tlk->setLayoutTranslator(trans);
  20394. owner.indexHelper.createSegmentMonitors(tlk);
  20395. tlk->finishSegmentMonitors();
  20396. tlk->reset();
  20397. }
  20398. virtual const void *getNext(int length)
  20399. {
  20400. TransformCallbackAssociation associate(owner.callback, tlk);
  20401. while (tlk->lookup(true))
  20402. {
  20403. keyedCount++;
  20404. if (keyedCount > owner.keyedLimit)
  20405. {
  20406. owner.onLimitExceeded(true); // Should throw exception
  20407. throwUnexpected();
  20408. }
  20409. size32_t transformedSize;
  20410. RtlDynamicRowBuilder rowBuilder(owner.rowAllocator);
  20411. byte const * keyRow = tlk->queryKeyBuffer(owner.callback.getFPosRef());
  20412. try
  20413. {
  20414. transformedSize = owner.readHelper.transform(rowBuilder, keyRow);
  20415. owner.callback.finishedRow();
  20416. }
  20417. catch (IException *E)
  20418. {
  20419. throw owner.makeWrappedException(E);
  20420. }
  20421. if (transformedSize)
  20422. {
  20423. OwnedConstRoxieRow result = rowBuilder.finalizeRowClear(transformedSize);
  20424. matched++;
  20425. if (matched > owner.rowLimit)
  20426. {
  20427. owner.onLimitExceeded(false); // Should throw exception
  20428. throwUnexpected();
  20429. }
  20430. if (matched > owner.choosenLimit) // MORE - bit of a strange place to check
  20431. {
  20432. break;
  20433. }
  20434. owner.accepted++;
  20435. return result.getClear();
  20436. }
  20437. else
  20438. owner.rejected++;
  20439. }
  20440. EOFseen = true;
  20441. return NULL;
  20442. }
  20443. virtual bool atEOF() const
  20444. {
  20445. return EOFseen;
  20446. }
  20447. virtual bool isSerialized() const
  20448. {
  20449. return false;
  20450. }
  20451. };
  20452. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
  20453. {
  20454. createRowAllocator();
  20455. remote.injectResult(new LazyLocalKeyReader(*this, key, trans));
  20456. return false;
  20457. }
  20458. virtual void onLimitExceeded(bool isKeyed)
  20459. {
  20460. if (traceLevel > 4)
  20461. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  20462. if (isKeyed)
  20463. {
  20464. if (indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates))
  20465. {
  20466. if (ctx->queryDebugContext())
  20467. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  20468. throw makeLimitSkipException(true);
  20469. }
  20470. else
  20471. readHelper.onKeyedLimitExceeded();
  20472. }
  20473. else
  20474. {
  20475. if (indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates))
  20476. {
  20477. if (ctx->queryDebugContext())
  20478. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  20479. throw makeLimitSkipException(false);
  20480. }
  20481. else
  20482. readHelper.onLimitExceeded();
  20483. }
  20484. }
  20485. virtual void serializeSkipInfo(MemoryBuffer &out, unsigned seekLen, const void *rawSeek, unsigned numFields, const void * seek, const SmartStepExtra &stepExtra) const
  20486. {
  20487. out.append((unsigned short) numFields);
  20488. out.append((unsigned short) seekLen);
  20489. out.append((unsigned short) stepExtra.queryFlags());
  20490. IMultipleStepSeekInfo *seeks = stepExtra.queryExtraSeeks();
  20491. if (seeks)
  20492. {
  20493. unsigned lookahead = 40000/seekLen;
  20494. if (maxSeekLookahead && (lookahead > maxSeekLookahead))
  20495. lookahead = maxSeekLookahead;
  20496. seeks->ensureFilled(seek, numFields, lookahead);
  20497. out.append(lookahead != seeks->ordinality()); // seeksAreEof flag
  20498. unsigned serialized = 1; // rawseek is always serialized...
  20499. unsigned patchLength = out.length();
  20500. out.append(serialized); // NOTE - we come back and patch with the actual value...
  20501. out.append(seekLen, rawSeek);
  20502. if (seeks->ordinality())
  20503. {
  20504. const void *lastSeek = rawSeek;
  20505. byte *nextSeek = NULL;
  20506. if (projectedMeta)
  20507. nextSeek = (byte *) alloca(seekLen);
  20508. for (unsigned i = 0; i < seeks->ordinality(); i++)
  20509. {
  20510. if (projectedMeta)
  20511. {
  20512. RtlStaticRowBuilder rowBuilder(nextSeek-seekGEOffset, seekGEOffset+seekLen);
  20513. readHelper.mapOutputToInput(rowBuilder, seeks->querySeek(i), numFields); // NOTE - weird interface to mapOutputToInput means that it STARTS writing at seekGEOffset...
  20514. }
  20515. else
  20516. nextSeek = (byte *) seeks->querySeek(i)+seekGEOffset;
  20517. int diff = memcmp(nextSeek, lastSeek, seekLen);
  20518. if (diff > 0)
  20519. {
  20520. serialized++;
  20521. out.append(seekLen, nextSeek);
  20522. lastSeek = (const byte *) out.reserve(0) - seekLen;
  20523. }
  20524. }
  20525. unsigned length = out.length();
  20526. out.setWritePos(patchLength);
  20527. out.append(serialized);
  20528. out.setWritePos(length);
  20529. }
  20530. }
  20531. else
  20532. {
  20533. out.append(false);
  20534. out.append(1);
  20535. out.append(seekLen, rawSeek);
  20536. }
  20537. }
  20538. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  20539. {
  20540. ActivityTimer t(totalCycles, timeActivities);
  20541. try
  20542. {
  20543. unsigned seeklen = 0;
  20544. const void *rawSeek = NULL;
  20545. if (seek && numFields)
  20546. {
  20547. seeklen = seekSizes[numFields-1];
  20548. rawSeek = (const byte *)seek + seekGEOffset;
  20549. if (projectedMeta)
  20550. {
  20551. byte * temp = (byte *) alloca(seeklen);
  20552. RtlStaticRowBuilder rawBuilder(temp-seekGEOffset, seekGEOffset+seeklen);
  20553. readHelper.mapOutputToInput(rawBuilder, seek, numFields); // NOTE - weird interface to mapOutputToInput means that it STARTS writing at seekGEOffset...
  20554. rawSeek = (byte *)temp;
  20555. }
  20556. }
  20557. const void *ret = remote.nextRowGE(seek, rawSeek, numFields, seeklen, wasCompleteMatch, stepExtra);
  20558. if (ret && wasCompleteMatch) // GH pleas confirm the wasCompleteMatch I just added here is right
  20559. processed++;
  20560. return ret;
  20561. }
  20562. catch (IException *E)
  20563. {
  20564. throw makeWrappedException(E);
  20565. }
  20566. }
  20567. virtual IInputSteppingMeta * querySteppingMeta()
  20568. {
  20569. if (rawMeta && steppingEnabled && ((indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates|TIRkeyedlimitskips|TIRkeyedlimitcreates)) == 0))
  20570. return &steppingMeta;
  20571. return NULL;
  20572. }
  20573. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  20574. {
  20575. if (variableInfoPending)
  20576. setVariableFileInfo();
  20577. return this;
  20578. }
  20579. virtual IKeyArray *getKeySet() const
  20580. {
  20581. return keySet.getLink();
  20582. }
  20583. virtual const IResolvedFile *getVarFileInfo() const
  20584. {
  20585. return varFileInfo.getLink();
  20586. }
  20587. virtual TranslatorArray *getTranslators() const
  20588. {
  20589. return translators.getLink();
  20590. }
  20591. virtual void mergeSegmentMonitors(IIndexReadContext *irc) const
  20592. {
  20593. indexHelper.createSegmentMonitors(irc); // NOTE: they will merge
  20594. }
  20595. virtual IRoxieServerActivity *queryActivity() { return this; }
  20596. virtual const RemoteActivityId& queryRemoteId() const
  20597. {
  20598. return remoteId;
  20599. }
  20600. };
  20601. class CRoxieServerSimpleIndexReadActivity : public CRoxieServerActivity, implements IIndexReadActivityInfo
  20602. {
  20603. IHThorCompoundReadExtra & readHelper;
  20604. IHThorIndexReadBaseArg & indexHelper;
  20605. IHThorSourceLimitTransformExtra * limitTransformExtra;
  20606. IHThorSteppedSourceExtra * steppedExtra;
  20607. bool eof;
  20608. Linked<IKeyArray>keySet;
  20609. Owned<IKeyIndexSet>keyIndexSet;
  20610. Owned<IKeyManager> tlk;
  20611. Linked<TranslatorArray> translators;
  20612. CIndexTransformCallback callback;
  20613. unsigned __int64 keyedLimit;
  20614. unsigned rowLimit;
  20615. unsigned chooseNLimit;
  20616. unsigned accepted;
  20617. unsigned rejected;
  20618. unsigned keyedCount;
  20619. ISteppingMeta * rawMeta;
  20620. ISteppingMeta * projectedMeta;
  20621. size32_t seekGEOffset;
  20622. unsigned * seekSizes;
  20623. CSteppingMeta steppingMeta;
  20624. Owned<const IResolvedFile> varFileInfo;
  20625. const RemoteActivityId &remoteId;
  20626. bool firstRead;
  20627. bool variableFileName;
  20628. bool variableInfoPending;
  20629. bool isOpt;
  20630. bool isLocal;
  20631. bool optimizeSteppedPostFilter;
  20632. // MORE there may be enough in common between this and CRoxieServerIndexActivity to warrant some refactoring
  20633. void initKeySet()
  20634. {
  20635. if ((keySet->length() > 1 || rawMeta != NULL) && translators->needsTranslation())
  20636. {
  20637. throw MakeStringException(ROXIE_UNIMPLEMENTED_ERROR, "Layout translation is not available when merging key parts or smart-stepping, as it may change record order");
  20638. }
  20639. keyIndexSet.setown(createKeyIndexSet());
  20640. for (unsigned part = 0; part < keySet->length(); part++)
  20641. {
  20642. IKeyIndexBase *kib = keySet->queryKeyPart(part);
  20643. if (kib)
  20644. {
  20645. for (unsigned subpart = 0; subpart < kib->numParts(); subpart++)
  20646. {
  20647. IKeyIndex *k = kib->queryPart(subpart);
  20648. if (k)
  20649. {
  20650. assertex(!k->isTopLevelKey());
  20651. keyIndexSet->addIndex(LINK(k));
  20652. }
  20653. }
  20654. }
  20655. }
  20656. }
  20657. void setVariableFileInfo()
  20658. {
  20659. OwnedRoxieString indexName(indexHelper.getFileName());
  20660. varFileInfo.setown(resolveLFN(indexName, isOpt));
  20661. translators.setown(new TranslatorArray) ;
  20662. keySet.setown(varFileInfo->getKeyArray(factory->queryActivityMeta(), translators, isOpt, isLocal ? factory->queryQueryFactory().queryChannel() : 0, factory->queryQueryFactory().queryOptions().enableFieldTranslation));
  20663. initKeySet();
  20664. variableInfoPending = false;
  20665. }
  20666. void onEOF()
  20667. {
  20668. callback.setManager(NULL);
  20669. eof = true;
  20670. tlk.clear();
  20671. }
  20672. public:
  20673. CRoxieServerSimpleIndexReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  20674. IKeyArray *_keyArray, TranslatorArray *_translatorArray, bool _isLocal)
  20675. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  20676. readHelper((IHThorIndexReadArg &)basehelper),
  20677. indexHelper((IHThorIndexReadArg &)basehelper),
  20678. translators(_translatorArray),
  20679. keySet(_keyArray),
  20680. isLocal(_isLocal),
  20681. remoteId(_remoteId)
  20682. {
  20683. rowLimit = 0;
  20684. keyedLimit = 0;
  20685. chooseNLimit = 0;
  20686. indexHelper.setCallback(&callback);
  20687. steppedExtra = static_cast<IHThorSteppedSourceExtra *>(indexHelper.selectInterface(TAIsteppedsourceextra_1));
  20688. limitTransformExtra = static_cast<IHThorSourceLimitTransformExtra *>(indexHelper.selectInterface(TAIsourcelimittransformextra_1));
  20689. unsigned flags = indexHelper.getFlags();
  20690. variableFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((flags & (TIRvarfilename|TIRdynamicfilename)) != 0);
  20691. variableInfoPending = false;
  20692. isOpt = (flags & TIRoptional) != 0;
  20693. optimizeSteppedPostFilter = (flags & TIRunfilteredtransform) != 0;
  20694. firstRead = true;
  20695. accepted = 0;
  20696. rejected = 0;
  20697. keyedCount = 0;
  20698. eof = false;
  20699. rawMeta = readHelper.queryRawSteppingMeta();
  20700. projectedMeta = readHelper.queryProjectedSteppingMeta();
  20701. seekGEOffset = 0;
  20702. seekSizes = NULL;
  20703. if (rawMeta)
  20704. {
  20705. // MORE - should check all keys in maxFields list can actually be keyed.
  20706. const CFieldOffsetSize * fields = rawMeta->queryFields();
  20707. unsigned maxFields = rawMeta->getNumFields();
  20708. seekGEOffset = fields[0].offset;
  20709. seekSizes = new unsigned[maxFields];
  20710. seekSizes[0] = fields[0].size;
  20711. for (unsigned i=1; i < maxFields; i++)
  20712. seekSizes[i] = seekSizes[i-1] + fields[i].size;
  20713. bool hasPostFilter = readHelper.transformMayFilter() && optimizeSteppedPostFilter;
  20714. if (projectedMeta)
  20715. steppingMeta.init(projectedMeta, hasPostFilter);
  20716. else
  20717. steppingMeta.init(rawMeta, hasPostFilter);
  20718. }
  20719. }
  20720. virtual const IResolvedFile *queryVarFileInfo() const
  20721. {
  20722. return varFileInfo;
  20723. }
  20724. ~CRoxieServerSimpleIndexReadActivity()
  20725. {
  20726. delete [] seekSizes;
  20727. }
  20728. virtual bool needsAllocator() const { return true; }
  20729. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20730. {
  20731. firstRead = true;
  20732. accepted = 0;
  20733. rejected = 0;
  20734. keyedCount = 0;
  20735. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  20736. if (steppedExtra)
  20737. steppingMeta.setExtra(steppedExtra);
  20738. eof = !indexHelper.canMatchAny();
  20739. if (variableFileName)
  20740. variableInfoPending = true;
  20741. else
  20742. {
  20743. variableInfoPending = false;
  20744. if (!keyIndexSet)
  20745. initKeySet();
  20746. }
  20747. }
  20748. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  20749. {
  20750. if (variableInfoPending)
  20751. setVariableFileInfo();
  20752. return this;
  20753. }
  20754. virtual IKeyArray *getKeySet() const
  20755. {
  20756. return keySet.getLink();
  20757. }
  20758. virtual const IResolvedFile *getVarFileInfo() const
  20759. {
  20760. return varFileInfo.getLink();
  20761. }
  20762. virtual TranslatorArray *getTranslators() const
  20763. {
  20764. return translators.getLink();
  20765. }
  20766. virtual void mergeSegmentMonitors(IIndexReadContext *irc) const
  20767. {
  20768. indexHelper.createSegmentMonitors(irc); // NOTE: they will merge
  20769. }
  20770. virtual IRoxieServerActivity *queryActivity() { return this; }
  20771. virtual const RemoteActivityId& queryRemoteId() const
  20772. {
  20773. return remoteId;
  20774. }
  20775. const void *nextRow()
  20776. {
  20777. bool matched = true;
  20778. return nextRowGE(NULL, 0, matched, dummySmartStepExtra);
  20779. }
  20780. unsigned __int64 checkCount(unsigned __int64 limit)
  20781. {
  20782. unsigned numParts = keyIndexSet->numParts();
  20783. unsigned __int64 result = 0;
  20784. for (unsigned i = 0; i < numParts; i++)
  20785. {
  20786. Owned<IKeyManager> countTlk = createKeyManager(keyIndexSet->queryPart(i), 0, this);
  20787. countTlk->setLayoutTranslator(translators->item(i));
  20788. indexHelper.createSegmentMonitors(countTlk);
  20789. countTlk->finishSegmentMonitors();
  20790. result += countTlk->checkCount(limit-result);
  20791. if (result > limit)
  20792. break;
  20793. }
  20794. return result;
  20795. }
  20796. virtual const void *nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  20797. {
  20798. ActivityTimer t(totalCycles, timeActivities);
  20799. if (eof)
  20800. return NULL;
  20801. if (firstRead)
  20802. {
  20803. if (variableInfoPending)
  20804. setVariableFileInfo();
  20805. rowLimit = (unsigned) readHelper.getRowLimit();
  20806. chooseNLimit = (unsigned) readHelper.getChooseNLimit();
  20807. unsigned numParts = keyIndexSet->numParts();
  20808. if (!numParts)
  20809. {
  20810. onEOF();
  20811. return NULL;
  20812. }
  20813. if (numParts > 1 || seekGEOffset)
  20814. {
  20815. tlk.setown(createKeyMerger(keyIndexSet, 0, seekGEOffset, this));
  20816. // note that we don't set up translator because we don't support it. If that ever changes...
  20817. }
  20818. else
  20819. {
  20820. tlk.setown(createKeyManager(keyIndexSet->queryPart(0), 0, this));
  20821. tlk->setLayoutTranslator(translators->item(0));
  20822. }
  20823. indexHelper.createSegmentMonitors(tlk);
  20824. tlk->finishSegmentMonitors();
  20825. if (queryTraceLevel() > 3 || ctx->queryProbeManager())
  20826. {
  20827. StringBuffer out;
  20828. printKeyedValues(out, tlk, indexHelper.queryDiskRecordSize());
  20829. CTXLOG("Using filter %s", out.str());
  20830. if (ctx->queryProbeManager())
  20831. ctx->queryProbeManager()->setNodeProperty(this, "filter", out.str());
  20832. }
  20833. tlk->reset();
  20834. callback.setManager(tlk);
  20835. keyedLimit = readHelper.getKeyedLimit();
  20836. if (keyedLimit != (unsigned __int64) -1)
  20837. {
  20838. if ((indexHelper.getFlags() & TIRcountkeyedlimit) != 0)
  20839. {
  20840. unsigned __int64 count = checkCount(keyedLimit);
  20841. if (count > keyedLimit)
  20842. {
  20843. if ((indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates)) == 0)
  20844. readHelper.onKeyedLimitExceeded();
  20845. const void * ret = NULL;
  20846. if (indexHelper.getFlags() & TIRkeyedlimitcreates)
  20847. ret = createKeyedLimitOnFailRow();
  20848. onEOF();
  20849. return ret;
  20850. }
  20851. keyedLimit = (unsigned __int64) -1;
  20852. }
  20853. }
  20854. firstRead = false;
  20855. }
  20856. if (accepted == chooseNLimit)
  20857. {
  20858. onEOF();
  20859. return NULL;
  20860. }
  20861. const byte * rawSeek = NULL;
  20862. unsigned seekSize = 0;
  20863. if (seek)
  20864. {
  20865. seekSize = seekSizes[numFields-1];
  20866. rawSeek = (const byte *)seek + seekGEOffset;
  20867. if (projectedMeta)
  20868. {
  20869. byte *temp = (byte *) alloca(seekSize);
  20870. RtlStaticRowBuilder rawBuilder(temp-seekGEOffset, seekGEOffset+seekSize);
  20871. readHelper.mapOutputToInput(rawBuilder, seek, numFields);// NOTE - weird interface to mapOutputToInput means that it STARTS writing at seekGEOffset...
  20872. rawSeek = (byte *)temp;
  20873. }
  20874. #ifdef _DEBUG
  20875. // StringBuffer seekStr;
  20876. // for (unsigned i = 0; i < seekSize; i++)
  20877. // {
  20878. // seekStr.appendf("%02x ", ((unsigned char *) rawSeek)[i]);
  20879. // }
  20880. // DBGLOG("nextRowGE can skip offset %d size %d value %s", seekGEOffset, seekSize, seekStr.str());
  20881. #endif
  20882. }
  20883. const byte * originalRawSeek = rawSeek;
  20884. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  20885. while (rawSeek ? tlk->lookupSkip(rawSeek, seekGEOffset, seekSize) : tlk->lookup(true))
  20886. {
  20887. checkAbort();
  20888. keyedCount++;
  20889. if (keyedCount > keyedLimit)
  20890. {
  20891. readHelper.onKeyedLimitExceeded();
  20892. break;
  20893. }
  20894. byte const * keyRow = tlk->queryKeyBuffer(callback.getFPosRef());
  20895. #ifdef _DEBUG
  20896. // StringBuffer recstr;
  20897. // unsigned size = (tlk->queryRecordSize()<80) ? tlk->queryRecordSize() : 80;
  20898. // for (unsigned i = 0; i < size; i++)
  20899. // {
  20900. // recstr.appendf("%02x ", ((unsigned char *) keyRow)[i]);
  20901. // }
  20902. // DBGLOG("nextRowGE Got %s", recstr.str());
  20903. if (originalRawSeek && memcmp(keyRow + seekGEOffset, originalRawSeek, seekSize) < 0)
  20904. assertex(!"smart seek failure");
  20905. #endif
  20906. size32_t transformedSize;
  20907. rowBuilder.ensureRow();
  20908. try
  20909. {
  20910. transformedSize = readHelper.transform(rowBuilder, keyRow);
  20911. //if the post filter causes a mismatch, and the stepping condition no longer matches
  20912. //then return a mismatch record - so the join code can start seeking on the other input.
  20913. if (transformedSize == 0 && optimizeSteppedPostFilter && stepExtra.returnMismatches())
  20914. {
  20915. if (memcmp(keyRow + seekGEOffset, originalRawSeek, seekSize) != 0)
  20916. {
  20917. transformedSize = readHelper.unfilteredTransform(rowBuilder, keyRow);
  20918. if (transformedSize != 0)
  20919. wasCompleteMatch = false;
  20920. }
  20921. }
  20922. callback.finishedRow();
  20923. }
  20924. catch (IException *E)
  20925. {
  20926. throw makeWrappedException(E);
  20927. }
  20928. if (transformedSize)
  20929. {
  20930. accepted++;
  20931. if (accepted > rowLimit)
  20932. {
  20933. if ((indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates)) != 0)
  20934. {
  20935. throwUnexpected(); // should not have used simple variant if maySkip set...
  20936. }
  20937. if (traceLevel > 4)
  20938. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  20939. readHelper.onLimitExceeded();
  20940. break;
  20941. }
  20942. processed++;
  20943. #ifdef _DEBUG
  20944. // const byte *ret = (const byte *) out.get();
  20945. // CommonXmlWriter xmlwrite(XWFnoindent|XWFtrim|XWFopt);
  20946. // queryOutputMeta()->toXML(ret, xmlwrite);
  20947. // DBGLOG("ROW: {%p} %s", ret, xmlwrite.str());
  20948. #endif
  20949. return rowBuilder.finalizeRowClear(transformedSize);
  20950. }
  20951. else
  20952. rejected++;
  20953. rawSeek = NULL;
  20954. }
  20955. onEOF();
  20956. return NULL;
  20957. }
  20958. virtual void reset()
  20959. {
  20960. onEOF();
  20961. if (accepted)
  20962. noteStatistic(StNumIndexAccepted, accepted);
  20963. if (rejected)
  20964. noteStatistic(StNumIndexRejected, rejected);
  20965. if (variableFileName)
  20966. {
  20967. varFileInfo.clear();
  20968. translators.clear();
  20969. }
  20970. variableInfoPending = false;
  20971. CRoxieServerActivity::reset();
  20972. }
  20973. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  20974. {
  20975. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  20976. }
  20977. virtual IInputSteppingMeta * querySteppingMeta()
  20978. {
  20979. if (rawMeta && steppingEnabled && ((indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates|TIRkeyedlimitskips|TIRkeyedlimitcreates)) == 0))
  20980. return &steppingMeta;
  20981. return NULL;
  20982. }
  20983. protected:
  20984. const void * createKeyedLimitOnFailRow()
  20985. {
  20986. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  20987. size32_t outSize = limitTransformExtra->transformOnKeyedLimitExceeded(rowBuilder);
  20988. if (outSize)
  20989. return rowBuilder.finalizeRowClear(outSize);
  20990. return NULL;
  20991. }
  20992. };
  20993. class CRoxieServerBaseIndexActivityFactory : public CRoxieServerActivityFactory
  20994. {
  20995. public:
  20996. Owned<IKeyArray> keySet;
  20997. Owned<TranslatorArray> translatorArray;
  20998. Owned<IDefRecordMeta> activityMeta;
  20999. RemoteActivityId remoteId;
  21000. bool isSimple;
  21001. bool isLocal;
  21002. bool maySkip;
  21003. bool sorted;
  21004. bool variableFileName;
  21005. bool enableFieldTranslation;
  21006. unsigned maxSeekLookahead;
  21007. Owned<const IResolvedFile> indexfile;
  21008. CRoxieServerSideCache *cache;
  21009. CRoxieServerBaseIndexActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21010. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), remoteId(_remoteId)
  21011. {
  21012. Owned<IHThorIndexReadBaseArg> indexHelper = (IHThorIndexReadBaseArg *) helperFactory();
  21013. unsigned flags = indexHelper->getFlags();
  21014. sorted = (flags & TIRunordered) == 0;
  21015. isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  21016. rtlDataAttr indexLayoutMeta;
  21017. size32_t indexLayoutSize;
  21018. if(!indexHelper->getIndexLayout(indexLayoutSize, indexLayoutMeta.refdata()))
  21019. assertex(indexLayoutSize==0);
  21020. MemoryBuffer m;
  21021. m.setBuffer(indexLayoutSize, indexLayoutMeta.getdata());
  21022. activityMeta.setown(deserializeRecordMeta(m, true));
  21023. enableFieldTranslation = queryFactory.queryOptions().enableFieldTranslation;
  21024. translatorArray.setown(new TranslatorArray);
  21025. variableFileName = allFilesDynamic || _queryFactory.isDynamic() || ((flags & (TIRvarfilename|TIRdynamicfilename)) != 0);
  21026. if (!variableFileName)
  21027. {
  21028. bool isOpt = (flags & TIRoptional) != 0;
  21029. OwnedRoxieString indexName(indexHelper->getFileName());
  21030. indexfile.setown(queryFactory.queryPackage().lookupFileName(indexName, isOpt, true, true, queryFactory.queryWorkUnit(), true));
  21031. if (indexfile)
  21032. keySet.setown(indexfile->getKeyArray(activityMeta, translatorArray, isOpt, isLocal ? queryFactory.queryChannel() : 0, enableFieldTranslation));
  21033. }
  21034. isSimple = isLocal;
  21035. maySkip = (flags & (TIRkeyedlimitskips|TIRlimitskips|TIRlimitcreates|TIRkeyedlimitcreates)) != 0;
  21036. if (keySet && keySet->length()==1 && !isLocal && (flags & (TIRlimitskips|TIRlimitcreates|TIRkeyedlimitskips|TIRkeyedlimitcreates))==0)
  21037. {
  21038. IKeyIndexBase *thisBase = keySet->queryKeyPart(0);
  21039. if (thisBase->numParts()==1 && !thisBase->queryPart(0)->isTopLevelKey() && !_queryFactory.queryOptions().disableLocalOptimizations)
  21040. isSimple = true;
  21041. }
  21042. int cacheSize = _graphNode.getPropInt("hint[@name='cachehits']/@value", serverSideCacheSize);
  21043. cache = cacheSize ? new CRoxieServerSideCache(cacheSize) : NULL;
  21044. maxSeekLookahead = _graphNode.getPropInt("hint[@name='maxseeklookahead']/@value", 0);
  21045. }
  21046. ~CRoxieServerBaseIndexActivityFactory()
  21047. {
  21048. delete cache;
  21049. }
  21050. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  21051. {
  21052. if (indexfile)
  21053. addXrefFileInfo(reply, indexfile);
  21054. else
  21055. {
  21056. Owned<IHThorIndexReadBaseArg> indexHelper = (IHThorIndexReadBaseArg *) helperFactory();
  21057. if ((indexHelper->getFlags() & (TIRvarfilename|TIRdynamicfilename)) == 0)
  21058. {
  21059. OwnedRoxieString indexName(indexHelper->getFileName());
  21060. Owned<const IResolvedFile> temp = queryFactory.queryPackage().lookupFileName(indexName, true, true, false, queryFactory.queryWorkUnit(), true);
  21061. if (temp)
  21062. addXrefFileInfo(reply, temp);
  21063. }
  21064. }
  21065. }
  21066. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  21067. {
  21068. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for indexread activity");
  21069. }
  21070. virtual IRoxieServerSideCache *queryServerSideCache() const
  21071. {
  21072. return cache;
  21073. }
  21074. virtual bool getEnableFieldTranslation() const
  21075. {
  21076. return enableFieldTranslation;
  21077. }
  21078. virtual IDefRecordMeta *queryActivityMeta() const
  21079. {
  21080. return activityMeta;
  21081. }
  21082. virtual const StatisticsMapping &queryStatsMapping() const
  21083. {
  21084. return indexStatistics;
  21085. }
  21086. };
  21087. class CRoxieServerIndexReadActivityFactory : public CRoxieServerBaseIndexActivityFactory
  21088. {
  21089. public:
  21090. CRoxieServerIndexReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21091. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId)
  21092. {
  21093. }
  21094. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  21095. {
  21096. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  21097. return new CRoxieServerNullActivity(_ctx, this, _probeManager);
  21098. else if (isSimple && !maySkip)
  21099. return new CRoxieServerSimpleIndexReadActivity(_ctx, this, _probeManager, remoteId, keySet, translatorArray, isLocal);
  21100. else
  21101. return new CRoxieServerIndexReadActivity(_ctx, this, _probeManager, remoteId, keySet, translatorArray, sorted, isLocal, maySkip, maxSeekLookahead);
  21102. }
  21103. };
  21104. IRoxieServerActivityFactory *createRoxieServerIndexReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21105. {
  21106. return new CRoxieServerIndexReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  21107. }
  21108. //--------------------------------------------------------------------------------------------------------------------------
  21109. class CRoxieServerNullCountActivity : public CRoxieServerActivity
  21110. {
  21111. bool done;
  21112. public:
  21113. CRoxieServerNullCountActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  21114. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  21115. {
  21116. done = false;
  21117. }
  21118. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21119. {
  21120. done = false;
  21121. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  21122. }
  21123. virtual bool needsAllocator() const { return true; }
  21124. virtual const void *nextRow()
  21125. {
  21126. ActivityTimer t(totalCycles, timeActivities);
  21127. if (done) return NULL;
  21128. done = true;
  21129. size32_t rowSize = meta.getFixedSize();
  21130. void * nullRow = rowAllocator->createRow();
  21131. if (rowSize == 1)
  21132. *(byte *)nullRow = 0;
  21133. else
  21134. {
  21135. assertex(rowSize == sizeof(unsigned __int64));
  21136. *(unsigned __int64 *)nullRow = 0;
  21137. }
  21138. return rowAllocator->finalizeRow(rowSize, nullRow, rowSize);
  21139. }
  21140. };
  21141. class CRoxieServerIndexCountActivity : public CRoxieServerIndexActivity
  21142. {
  21143. IHThorCompoundCountExtra & countHelper;
  21144. IHThorSourceCountLimit * limitHelper;
  21145. bool done;
  21146. public:
  21147. CRoxieServerIndexCountActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IKeyArray * _keySet, TranslatorArray *_translators, bool _isLocal)
  21148. : CRoxieServerIndexActivity(_ctx, _factory, _probeManager, _remoteId, _keySet, _translators, false, _isLocal, false),
  21149. countHelper((IHThorIndexCountArg &)basehelper),
  21150. done(false)
  21151. {
  21152. limitHelper = static_cast<IHThorSourceCountLimit *>(basehelper.selectInterface(TAIsourcecountlimit_1));
  21153. }
  21154. virtual bool needsAllocator() const { return true; }
  21155. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21156. {
  21157. done = false;
  21158. CRoxieServerIndexActivity::start(parentExtractSize, parentExtract, paused);
  21159. choosenLimit = countHelper.getChooseNLimit();
  21160. if (limitHelper)
  21161. {
  21162. rowLimit = limitHelper->getRowLimit();
  21163. keyedLimit = limitHelper->getKeyedLimit();
  21164. }
  21165. if (!paused)
  21166. processAllKeys();
  21167. }
  21168. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
  21169. {
  21170. unsigned __int64 count = 0;
  21171. if (countHelper.hasFilter())
  21172. {
  21173. while (tlk->lookup(true))
  21174. {
  21175. try
  21176. {
  21177. count += countHelper.numValid(tlk->queryKeyBuffer(callback.getFPosRef()));
  21178. callback.finishedRow();
  21179. }
  21180. catch (IException *E)
  21181. {
  21182. throw makeWrappedException(E);
  21183. }
  21184. accepted++;
  21185. if (count >= choosenLimit) // MORE - what about limit?
  21186. break;
  21187. }
  21188. }
  21189. else
  21190. count = tlk->getCount(); //MORE: GH->RKC There should be value in providing a max limit to getCount()
  21191. if (count)
  21192. {
  21193. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), false);
  21194. if (count > choosenLimit)
  21195. count = choosenLimit;
  21196. void * recBuffer = rowAllocator->createRow();
  21197. if (meta.getFixedSize() == 1)
  21198. *(byte *)recBuffer = (byte)count;
  21199. else
  21200. {
  21201. assertex(meta.getFixedSize() == sizeof(unsigned __int64));
  21202. *(unsigned __int64 *)recBuffer = count;
  21203. }
  21204. recBuffer = rowAllocator->finalizeRow(meta.getFixedSize(), recBuffer, meta.getFixedSize());
  21205. result->append(recBuffer);
  21206. remote.injectResult(result.getClear());
  21207. //GH->RKC for count(,choosen)/exists passing in the previous count would short-circuit this much earlier
  21208. if (count >= choosenLimit)
  21209. return true;
  21210. }
  21211. return false;
  21212. }
  21213. virtual void onLimitExceeded(bool isKeyed)
  21214. {
  21215. if (traceLevel > 4)
  21216. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  21217. if (isKeyed)
  21218. {
  21219. if (indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates))
  21220. {
  21221. if (ctx->queryDebugContext())
  21222. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  21223. throw makeLimitSkipException(true);
  21224. }
  21225. else
  21226. {
  21227. assertex(limitHelper); // Should not be able to generate exception if there was not one...
  21228. limitHelper->onKeyedLimitExceeded();
  21229. }
  21230. }
  21231. else
  21232. {
  21233. if (indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates))
  21234. {
  21235. if (ctx->queryDebugContext())
  21236. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  21237. throw makeLimitSkipException(false);
  21238. }
  21239. else
  21240. {
  21241. assertex(limitHelper);
  21242. limitHelper->onLimitExceeded();
  21243. }
  21244. }
  21245. }
  21246. virtual const void *createLimitFailRow(bool isKeyed)
  21247. {
  21248. throwUnexpected();
  21249. }
  21250. virtual const void *nextRow()
  21251. {
  21252. ActivityTimer t(totalCycles, timeActivities);
  21253. if (done) return NULL;
  21254. done = true;
  21255. unsigned __int64 totalCount = 0;
  21256. bool hasLimit = rowLimit != (unsigned __int64) -1;
  21257. try
  21258. {
  21259. loop
  21260. {
  21261. const void * next = remote.nextRow();
  21262. if (!next)
  21263. break;
  21264. if (meta.getFixedSize() == 1)
  21265. totalCount += *(byte *)next;
  21266. else
  21267. totalCount += *(unsigned __int64 *) next;
  21268. ReleaseRoxieRow(next);
  21269. if (totalCount > rowLimit || (totalCount > choosenLimit && !hasLimit)) // can't break out early if there is a possibility of later slave throwing limit exception
  21270. break;
  21271. }
  21272. if (totalCount > rowLimit)
  21273. {
  21274. unsigned flags = indexHelper.getFlags();
  21275. if (flags & TIRlimitskips)
  21276. totalCount = 0;
  21277. else if (flags & TIRlimitcreates)
  21278. totalCount = 1;
  21279. else
  21280. {
  21281. assertex(limitHelper);
  21282. limitHelper->onLimitExceeded();
  21283. }
  21284. }
  21285. else if (totalCount > choosenLimit)
  21286. totalCount = choosenLimit;
  21287. }
  21288. catch (IException *E)
  21289. {
  21290. if (QUERYINTERFACE(E, LimitSkipException))
  21291. {
  21292. totalCount = 0;
  21293. unsigned flags = indexHelper.getFlags();
  21294. if (E->errorCode() == KeyedLimitSkipErrorCode)
  21295. {
  21296. if (flags & TIRkeyedlimitcreates)
  21297. totalCount++;
  21298. }
  21299. else
  21300. {
  21301. if (flags & TIRlimitcreates)
  21302. totalCount++;
  21303. }
  21304. if (totalCount > choosenLimit)
  21305. totalCount = choosenLimit; // would have to be weird code (and escape the optimizer...)
  21306. E->Release();
  21307. }
  21308. else
  21309. throw ;
  21310. }
  21311. void * result = rowAllocator->createRow();
  21312. if (meta.getFixedSize() == 1)
  21313. *(byte *)result = (byte)totalCount;
  21314. else
  21315. {
  21316. assertex(meta.getFixedSize() == sizeof(unsigned __int64));
  21317. *(unsigned __int64 *)result = totalCount;
  21318. }
  21319. return rowAllocator->finalizeRow(meta.getFixedSize(), result, meta.getFixedSize());
  21320. }
  21321. };
  21322. class CRoxieServerIndexCountActivityFactory : public CRoxieServerBaseIndexActivityFactory
  21323. {
  21324. public:
  21325. CRoxieServerIndexCountActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21326. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId)
  21327. {
  21328. }
  21329. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  21330. {
  21331. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  21332. return new CRoxieServerNullCountActivity(_ctx, this, _probeManager);
  21333. // else if (isSimple)
  21334. // return new CRoxieServerSimpleIndexCountActivity(this, keySet->queryKeyPart(0)->queryPart(0));
  21335. else
  21336. return new CRoxieServerIndexCountActivity(_ctx, this, _probeManager, remoteId, keySet, translatorArray, isLocal);
  21337. }
  21338. };
  21339. IRoxieServerActivityFactory *createRoxieServerIndexCountActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21340. {
  21341. return new CRoxieServerIndexCountActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  21342. }
  21343. //--------------------------------------------------------------------------------------------------------------------------
  21344. class CRoxieServerNullIndexAggregateActivity : public CRoxieServerActivity
  21345. {
  21346. IHThorIndexAggregateArg &aggregateHelper;
  21347. bool done;
  21348. public:
  21349. CRoxieServerNullIndexAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  21350. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  21351. aggregateHelper((IHThorIndexAggregateArg &)basehelper)
  21352. {
  21353. done = false;
  21354. }
  21355. virtual bool needsAllocator() const { return true; }
  21356. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21357. {
  21358. done = false;
  21359. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  21360. }
  21361. virtual const void *nextRow()
  21362. {
  21363. ActivityTimer t(totalCycles, timeActivities);
  21364. if (done) return NULL;
  21365. done = true;
  21366. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  21367. size32_t thisSize = aggregateHelper.clearAggregate(rowBuilder);
  21368. return rowBuilder.finalizeRowClear(thisSize);
  21369. }
  21370. };
  21371. class CRoxieServerIndexAggregateActivity : public CRoxieServerIndexActivity
  21372. {
  21373. IHThorCompoundAggregateExtra & aggregateHelper;
  21374. bool done;
  21375. public:
  21376. CRoxieServerIndexAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  21377. IKeyArray * _keySet, TranslatorArray *_translators, bool _isLocal)
  21378. : CRoxieServerIndexActivity(_ctx, _factory, _probeManager, _remoteId, _keySet, _translators, false, _isLocal, false),
  21379. aggregateHelper((IHThorIndexAggregateArg &)basehelper),
  21380. done(false)
  21381. {
  21382. }
  21383. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21384. {
  21385. done = false;
  21386. CRoxieServerIndexActivity::start(parentExtractSize, parentExtract, paused);
  21387. if (!paused)
  21388. processAllKeys();
  21389. }
  21390. virtual bool needsAllocator() const { return true; }
  21391. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
  21392. {
  21393. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  21394. while (tlk->lookup(true))
  21395. {
  21396. if (!rowBuilder.exists())
  21397. {
  21398. rowBuilder.ensureRow();
  21399. aggregateHelper.clearAggregate(rowBuilder);
  21400. }
  21401. try
  21402. {
  21403. aggregateHelper.processRow(rowBuilder, tlk->queryKeyBuffer(callback.getFPosRef()));
  21404. callback.finishedRow();
  21405. }
  21406. catch (IException *E)
  21407. {
  21408. throw makeWrappedException(E);
  21409. }
  21410. accepted++;
  21411. }
  21412. if (aggregateHelper.processedAnyRows())
  21413. {
  21414. size32_t size = meta.getRecordSize(rowBuilder.getSelf());
  21415. const void * recBuffer = rowBuilder.finalizeRowClear(size);
  21416. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), meta.isVariableSize());
  21417. result->append(recBuffer);
  21418. remote.injectResult(result.getClear());
  21419. }
  21420. return false;
  21421. }
  21422. virtual void onLimitExceeded(bool isKeyed)
  21423. {
  21424. if (traceLevel > 4)
  21425. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  21426. throwUnexpected();
  21427. }
  21428. virtual const void *createLimitFailRow(bool isKeyed)
  21429. {
  21430. throwUnexpected();
  21431. }
  21432. const void * gatherMerged()
  21433. {
  21434. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  21435. const void * firstRow = remote.nextRow();
  21436. size32_t finalSize = 0;
  21437. if (!firstRow)
  21438. {
  21439. rowBuilder.ensureRow();
  21440. finalSize = aggregateHelper.clearAggregate(rowBuilder);
  21441. }
  21442. else
  21443. {
  21444. // NOTE need to clone this because going to modify below, could special case 1 row only
  21445. finalSize = cloneRow(rowBuilder, firstRow, meta);
  21446. ReleaseRoxieRow(firstRow);
  21447. }
  21448. loop
  21449. {
  21450. const void * next = remote.nextRow();
  21451. if (!next)
  21452. break;
  21453. finalSize = aggregateHelper.mergeAggregate(rowBuilder, next);
  21454. ReleaseRoxieRow(next);
  21455. }
  21456. return rowBuilder.finalizeRowClear(finalSize);
  21457. }
  21458. virtual const void *nextRow()
  21459. {
  21460. ActivityTimer t(totalCycles, timeActivities);
  21461. if (done) return NULL;
  21462. const void * ret = gatherMerged();
  21463. done = true;
  21464. return ret;
  21465. }
  21466. };
  21467. class CRoxieServerIndexAggregateActivityFactory : public CRoxieServerBaseIndexActivityFactory
  21468. {
  21469. public:
  21470. CRoxieServerIndexAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21471. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId)
  21472. {
  21473. }
  21474. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  21475. {
  21476. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  21477. return new CRoxieServerNullIndexAggregateActivity(_ctx, this, _probeManager);
  21478. // else if (isSimple)
  21479. // return new CRoxieServerSimpleIndexAggregateActivity(this, keySet->queryKeyPart(0)->queryPart(0));
  21480. else
  21481. return new CRoxieServerIndexAggregateActivity(_ctx, this, _probeManager, remoteId, keySet, translatorArray, isLocal);
  21482. }
  21483. };
  21484. IRoxieServerActivityFactory *createRoxieServerIndexAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21485. {
  21486. return new CRoxieServerIndexAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  21487. }
  21488. //--------------------------------------------------------------------------------------------------------------------------
  21489. class CRoxieServerIndexGroupAggregateActivity : public CRoxieServerIndexActivity, implements IHThorGroupAggregateCallback
  21490. {
  21491. IHThorCompoundGroupAggregateExtra & aggregateHelper;
  21492. RowAggregator singleAggregator;
  21493. RowAggregator resultAggregator;
  21494. unsigned groupSegCount;
  21495. bool gathered;
  21496. bool eof;
  21497. public:
  21498. CRoxieServerIndexGroupAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  21499. IKeyArray * _keySet, TranslatorArray *_translators, bool _isLocal)
  21500. : CRoxieServerIndexActivity(_ctx, _factory, _probeManager, _remoteId, _keySet, _translators, false, _isLocal, false),
  21501. aggregateHelper((IHThorIndexGroupAggregateArg &)basehelper),
  21502. singleAggregator(aggregateHelper, aggregateHelper),
  21503. resultAggregator(aggregateHelper, aggregateHelper),
  21504. gathered(false), eof(true)
  21505. {
  21506. groupSegCount = 0;
  21507. }
  21508. IMPLEMENT_IINTERFACE
  21509. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21510. {
  21511. eof = false;
  21512. gathered= false;
  21513. CRoxieServerIndexActivity::start(parentExtractSize, parentExtract, paused);
  21514. groupSegCount = 0;
  21515. if (!paused)
  21516. processAllKeys();
  21517. resultAggregator.start(rowAllocator);
  21518. }
  21519. virtual bool needsAllocator() const { return true; }
  21520. virtual void reset()
  21521. {
  21522. resultAggregator.reset();
  21523. CRoxieServerIndexActivity::reset();
  21524. }
  21525. virtual void processRow(const void * next)
  21526. {
  21527. singleAggregator.addRow(next);
  21528. }
  21529. virtual void createSegmentMonitors(IKeyManager *key)
  21530. {
  21531. unsigned groupSegSize;
  21532. ThorActivityKind kind = factory->getKind();
  21533. if ((kind==TAKindexgroupcount || kind==TAKindexgroupexists))
  21534. groupSegSize = aggregateHelper.getGroupSegmentMonitorsSize();
  21535. else
  21536. groupSegSize = 0;
  21537. if (groupSegSize)
  21538. {
  21539. key->setMergeBarrier(groupSegSize);
  21540. CRoxieServerIndexActivity::createSegmentMonitors(key);
  21541. unsigned numSegs = tlk->ordinality();
  21542. for (unsigned segNo = 0; segNo < numSegs; segNo++)
  21543. {
  21544. IKeySegmentMonitor *seg = tlk->item(segNo);
  21545. if (seg->getOffset()+seg->getSize()==groupSegSize)
  21546. {
  21547. groupSegCount = segNo+1;
  21548. break;
  21549. }
  21550. }
  21551. assertex(groupSegCount);
  21552. }
  21553. else
  21554. CRoxieServerIndexActivity::createSegmentMonitors(key);
  21555. }
  21556. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
  21557. {
  21558. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), meta.isVariableSize());
  21559. singleAggregator.start(rowAllocator);
  21560. ThorActivityKind kind = factory->getKind();
  21561. while (tlk->lookup(true))
  21562. {
  21563. try
  21564. {
  21565. if (groupSegCount && !trans)
  21566. {
  21567. AggregateRowBuilder &rowBuilder = singleAggregator.addRow(tlk->queryKeyBuffer(callback.getFPosRef()));
  21568. callback.finishedRow();
  21569. if (kind==TAKindexgroupcount)
  21570. {
  21571. unsigned __int64 count = tlk->getCurrentRangeCount(groupSegCount);
  21572. aggregateHelper.processCountGrouping(rowBuilder, count-1);
  21573. }
  21574. if (!tlk->nextRange(groupSegCount))
  21575. break;
  21576. }
  21577. else
  21578. {
  21579. aggregateHelper.processRow(tlk->queryKeyBuffer(callback.getFPosRef()), this);
  21580. callback.finishedRow();
  21581. }
  21582. }
  21583. catch (IException *E)
  21584. {
  21585. throw makeWrappedException(E);
  21586. }
  21587. accepted++;
  21588. }
  21589. loop
  21590. {
  21591. Owned<AggregateRowBuilder> next = singleAggregator.nextResult();
  21592. if (!next)
  21593. break;
  21594. size32_t size = next->querySize();
  21595. result->append(next->finalizeRowClear());
  21596. }
  21597. remote.injectResult(result.getClear());
  21598. singleAggregator.reset();
  21599. return false;
  21600. }
  21601. virtual void onLimitExceeded(bool isKeyed)
  21602. {
  21603. if (traceLevel > 4)
  21604. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);DBGLOG("%d activityid = %d", __LINE__, activityId);
  21605. throwUnexpected();
  21606. }
  21607. virtual const void *createLimitFailRow(bool isKeyed)
  21608. {
  21609. throwUnexpected();
  21610. }
  21611. void gatherMerged()
  21612. {
  21613. gathered = true;
  21614. loop
  21615. {
  21616. const void * next = remote.nextRow();
  21617. if (!next)
  21618. break;
  21619. resultAggregator.mergeElement(next);
  21620. ReleaseRoxieRow(next);
  21621. }
  21622. }
  21623. virtual const void *nextRow()
  21624. {
  21625. ActivityTimer t(totalCycles, timeActivities);
  21626. if (eof)
  21627. return NULL;
  21628. if (!gathered)
  21629. gatherMerged();
  21630. Owned<AggregateRowBuilder> next = resultAggregator.nextResult();
  21631. if (next)
  21632. {
  21633. processed++;
  21634. return next->finalizeRowClear();
  21635. }
  21636. eof = true;
  21637. return NULL;
  21638. }
  21639. };
  21640. class CRoxieServerIndexGroupAggregateActivityFactory : public CRoxieServerBaseIndexActivityFactory
  21641. {
  21642. public:
  21643. CRoxieServerIndexGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21644. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId)
  21645. {
  21646. }
  21647. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  21648. {
  21649. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  21650. return new CRoxieServerNullActivity(_ctx, this, _probeManager);
  21651. // else if (isSimple)
  21652. // return new CRoxieServerSimpleIndexGroupAggregateActivity(this, keySet->queryKeyPart(0)->queryPart(0));
  21653. else
  21654. return new CRoxieServerIndexGroupAggregateActivity(_ctx, this, _probeManager, remoteId, keySet, translatorArray, isLocal);
  21655. }
  21656. };
  21657. IRoxieServerActivityFactory *createRoxieServerIndexGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21658. {
  21659. return new CRoxieServerIndexGroupAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  21660. }
  21661. //--------------------------------------------------------------------------------------------------------------------------
  21662. class CRoxieServerIndexNormalizeActivity : public CRoxieServerIndexReadBaseActivity
  21663. {
  21664. IHThorCompoundNormalizeExtra & readHelper;
  21665. public:
  21666. CRoxieServerIndexNormalizeActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  21667. IKeyArray * _keySet, TranslatorArray *_translators, bool _sorted, bool _isLocal)
  21668. : CRoxieServerIndexReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _keySet, _translators, _sorted, _isLocal, false),
  21669. readHelper((IHThorIndexNormalizeArg &)basehelper)
  21670. {
  21671. }
  21672. virtual bool needsAllocator() const { return true; }
  21673. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21674. {
  21675. CRoxieServerIndexReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  21676. rowLimit = readHelper.getRowLimit();
  21677. keyedLimit = readHelper.getKeyedLimit();
  21678. choosenLimit = readHelper.getChooseNLimit();
  21679. if (!paused)
  21680. processAllKeys();
  21681. }
  21682. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
  21683. {
  21684. unsigned keyedCount = 0;
  21685. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  21686. while (tlk->lookup(true))
  21687. {
  21688. keyedCount++;
  21689. if (keyedCount > keyedLimit)
  21690. {
  21691. if (traceLevel > 4)
  21692. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  21693. onLimitExceeded(true);
  21694. break;
  21695. }
  21696. size32_t transformedSize;
  21697. if (readHelper.first(tlk->queryKeyBuffer(callback.getFPosRef())))
  21698. {
  21699. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), meta.isVariableSize());
  21700. do
  21701. {
  21702. if (accepted>=choosenLimit)
  21703. break;
  21704. rowBuilder.ensureRow();
  21705. try
  21706. {
  21707. transformedSize = readHelper.transform(rowBuilder);
  21708. }
  21709. catch (IException *E)
  21710. {
  21711. throw makeWrappedException(E);
  21712. }
  21713. if (transformedSize)
  21714. {
  21715. // MORE - would be a good idea to stop these asap if rowlimit exceeded
  21716. result->append(rowBuilder.finalizeRowClear(transformedSize));
  21717. accepted++;
  21718. }
  21719. else
  21720. rejected++;
  21721. } while (readHelper.next());
  21722. remote.injectResult(result.getClear());
  21723. callback.finishedRow();
  21724. if (accepted>=choosenLimit)
  21725. return true;
  21726. }
  21727. }
  21728. return false;
  21729. }
  21730. virtual void onLimitExceeded(bool isKeyed)
  21731. {
  21732. if (traceLevel > 4)
  21733. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  21734. if (isKeyed)
  21735. {
  21736. if (indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates))
  21737. {
  21738. if (ctx->queryDebugContext())
  21739. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  21740. throw makeLimitSkipException(true);
  21741. }
  21742. else
  21743. readHelper.onKeyedLimitExceeded();
  21744. }
  21745. else
  21746. {
  21747. if (indexHelper.getFlags() & (TIRlimitskips||TIRlimitcreates))
  21748. {
  21749. if (ctx->queryDebugContext())
  21750. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  21751. throw makeLimitSkipException(false);
  21752. }
  21753. else
  21754. readHelper.onLimitExceeded();
  21755. }
  21756. }
  21757. virtual const void *createLimitFailRow(bool isKeyed)
  21758. {
  21759. UNIMPLEMENTED;
  21760. }
  21761. };
  21762. class CRoxieServerIndexNormalizeActivityFactory : public CRoxieServerBaseIndexActivityFactory
  21763. {
  21764. public:
  21765. CRoxieServerIndexNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21766. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId)
  21767. {
  21768. }
  21769. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  21770. {
  21771. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  21772. return new CRoxieServerNullActivity(_ctx, this, _probeManager);
  21773. else
  21774. return new CRoxieServerIndexNormalizeActivity(_ctx, this, _probeManager, remoteId, keySet, translatorArray, sorted, isLocal);
  21775. }
  21776. };
  21777. IRoxieServerActivityFactory *createRoxieServerIndexNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21778. {
  21779. return new CRoxieServerIndexNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  21780. }
  21781. //=================================================================================
  21782. class CRoxieServerFetchActivity : public CRoxieServerActivity, implements IRecordPullerCallback, implements IRoxieServerErrorHandler
  21783. {
  21784. IHThorFetchBaseArg &helper;
  21785. IHThorFetchContext * fetchContext;
  21786. Linked<IFilePartMap> map;
  21787. CRemoteResultAdaptor remote;
  21788. RecordPullerThread puller;
  21789. bool needsRHS;
  21790. bool variableFileName;
  21791. bool isOpt;
  21792. Owned<const IResolvedFile> varFileInfo;
  21793. public:
  21794. CRoxieServerFetchActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IFilePartMap *_map)
  21795. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorFetchBaseArg &)basehelper), map(_map), remote(_ctx, this, _remoteId, meta.queryOriginal(), helper, *this, true, true), puller(false)
  21796. {
  21797. fetchContext = static_cast<IHThorFetchContext *>(helper.selectInterface(TAIfetchcontext_1));
  21798. needsRHS = helper.transformNeedsRhs();
  21799. variableFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((fetchContext->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  21800. isOpt = (fetchContext->getFetchFlags() & FFdatafileoptional) != 0;
  21801. }
  21802. virtual const IResolvedFile *queryVarFileInfo() const
  21803. {
  21804. return varFileInfo;
  21805. }
  21806. virtual void onCreate(IHThorArg *_colocalParent)
  21807. {
  21808. CRoxieServerActivity::onCreate(_colocalParent);
  21809. remote.onCreate(_colocalParent);
  21810. }
  21811. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  21812. {
  21813. if (idx)
  21814. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  21815. puller.setInput(this, _sourceIdx, _in);
  21816. }
  21817. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  21818. {
  21819. puller.connectInputStreams(ctx, consumerOrdered);
  21820. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
  21821. }
  21822. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  21823. {
  21824. if (idx==0)
  21825. return puller.queryInput();
  21826. else
  21827. return NULL;
  21828. }
  21829. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21830. {
  21831. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  21832. remote.onStart(parentExtractSize, parentExtract);
  21833. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  21834. if (variableFileName)
  21835. {
  21836. OwnedRoxieString fname(fetchContext->getFileName());
  21837. varFileInfo.setown(resolveLFN(fname, isOpt));
  21838. if (varFileInfo)
  21839. map.setown(varFileInfo->getFileMap());
  21840. }
  21841. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().fetchPreload, false, ctx);
  21842. }
  21843. virtual void stop()
  21844. {
  21845. // Called from remote, so no need to call back to it....
  21846. puller.stop();
  21847. CRoxieServerActivity::stop();
  21848. }
  21849. virtual void reset()
  21850. {
  21851. processed = remote.processed;
  21852. remote.processed = 0;
  21853. puller.reset();
  21854. if (variableFileName)
  21855. {
  21856. varFileInfo.clear();
  21857. map.clear();
  21858. }
  21859. CRoxieServerActivity::reset();
  21860. }
  21861. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  21862. {
  21863. if (idx==(unsigned)-1)
  21864. idx = 0;
  21865. return idx ? NULL : &remote;
  21866. }
  21867. virtual void processRow(const void *row)
  21868. {
  21869. // called from puller thread
  21870. offset_t rp = fetchContext->extractPosition(row);
  21871. unsigned partNo;
  21872. if (isLocalFpos(rp))
  21873. partNo = getLocalFposPart(rp) + 1;
  21874. else
  21875. partNo = map->mapOffset(rp);
  21876. if (needsRHS)
  21877. {
  21878. Owned<IEngineRowAllocator> extractAllocator = ctx->queryCodeContext()->getRowAllocator(helper.queryExtractedSize(), activityId);
  21879. RtlDynamicRowBuilder rb(extractAllocator, true);
  21880. unsigned rhsSize = helper.extractJoinFields(rb, row);
  21881. char * block = (char *) remote.getMem(partNo, 0, sizeof(rp) + sizeof(rhsSize) + rhsSize); // MORE - superfiles
  21882. *(offset_t *) block = rp;
  21883. block += sizeof(rp);
  21884. *(unsigned *) block = rhsSize;
  21885. block += sizeof(rhsSize);
  21886. memcpy(block, rb.row(), rhsSize);
  21887. }
  21888. else
  21889. *(offset_t *) remote.getMem(partNo, 0, sizeof(rp)) = rp; // MORE - superfiles
  21890. ReleaseRoxieRow(row);
  21891. }
  21892. void processEOG()
  21893. {
  21894. #ifdef FETCH_PRESERVES_GROUPING
  21895. UNIMPLEMENTED;
  21896. #endif
  21897. // else discard is correct
  21898. }
  21899. void processGroup(const ConstPointerArray &)
  21900. {
  21901. throwUnexpected();
  21902. }
  21903. void processDone()
  21904. {
  21905. // called from puller thread
  21906. remote.flush();
  21907. remote.senddone();
  21908. }
  21909. virtual bool fireException(IException *e)
  21910. {
  21911. return remote.fireException(e);
  21912. }
  21913. virtual void onLimitExceeded(bool isKeyed)
  21914. {
  21915. if (traceLevel > 4)
  21916. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  21917. if (isKeyed)
  21918. throwUnexpected();
  21919. helper.onLimitExceeded();
  21920. }
  21921. virtual const void *createLimitFailRow(bool isKeyed)
  21922. {
  21923. UNIMPLEMENTED;
  21924. }
  21925. virtual const void *nextRow()
  21926. {
  21927. throwUnexpected(); // I am nobody's input
  21928. }
  21929. };
  21930. class CRoxieServerFetchActivityFactory : public CRoxieServerActivityFactory
  21931. {
  21932. RemoteActivityId remoteId;
  21933. Owned<IFilePartMap> map;
  21934. bool variableFileName;
  21935. Owned<const IResolvedFile> datafile;
  21936. public:
  21937. CRoxieServerFetchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21938. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), remoteId(_remoteId)
  21939. {
  21940. Owned<IHThorFetchBaseArg> helper = (IHThorFetchBaseArg *) helperFactory();
  21941. IHThorFetchContext *fetchContext = static_cast<IHThorFetchContext *>(helper->selectInterface(TAIfetchcontext_1));
  21942. variableFileName = allFilesDynamic || _queryFactory.isDynamic() || ((fetchContext->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  21943. if (!variableFileName)
  21944. {
  21945. OwnedRoxieString fname(fetchContext->getFileName());
  21946. datafile.setown(_queryFactory.queryPackage().lookupFileName(fname,
  21947. (fetchContext->getFetchFlags() & FFdatafileoptional) != 0,
  21948. true, true,
  21949. _queryFactory.queryWorkUnit(), true));
  21950. if (datafile)
  21951. map.setown(datafile->getFileMap());
  21952. }
  21953. }
  21954. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  21955. {
  21956. return new CRoxieServerFetchActivity(_ctx, this, _probeManager, remoteId, map);
  21957. }
  21958. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  21959. {
  21960. if (datafile)
  21961. addXrefFileInfo(reply, datafile);
  21962. else
  21963. {
  21964. // Temporarily resolve the file
  21965. Owned<IHThorFetchBaseArg> helper = (IHThorFetchBaseArg *) helperFactory();
  21966. IHThorFetchContext *fetchContext = static_cast<IHThorFetchContext *>(helper->selectInterface(TAIfetchcontext_1));
  21967. if ((fetchContext->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) == 0)
  21968. {
  21969. OwnedRoxieString fileName(fetchContext->getFileName());
  21970. Owned<const IResolvedFile> temp = queryFactory.queryPackage().lookupFileName(fileName, true, true, false, queryFactory.queryWorkUnit(), true);
  21971. if (temp)
  21972. addXrefFileInfo(reply, temp);
  21973. }
  21974. }
  21975. }
  21976. virtual const StatisticsMapping &queryStatsMapping() const
  21977. {
  21978. return diskStatistics;
  21979. }
  21980. };
  21981. IRoxieServerActivityFactory *createRoxieServerFetchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21982. {
  21983. return new CRoxieServerFetchActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  21984. }
  21985. // MORE - is there any point keeping this now?
  21986. class CRoxieServerDummyActivityFactory : public CRoxieServerActivityFactory // not a real activity - just used to properly link files
  21987. {
  21988. public:
  21989. Owned<const IResolvedFile> indexfile;
  21990. Owned<const IResolvedFile> datafile;
  21991. StringAttr fileName;
  21992. StringAttr indexName;
  21993. Owned<IKeyArray> keySet;
  21994. Owned<IFileIOArray> files;
  21995. TranslatorArray layoutTranslators;
  21996. CRoxieServerDummyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool isLoadDataOnly)
  21997. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  21998. {
  21999. try // does not want any missing file errors to be fatal, or throw traps - just log it
  22000. {
  22001. if (_graphNode.getPropBool("att[@name='_isSpill']/@value", false) || _graphNode.getPropBool("att[@name='_isSpillGlobal']/@value", false))
  22002. return; // ignore 'spills'
  22003. bool isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  22004. ThorActivityKind kind = getActivityKind(_graphNode);
  22005. if (kind != TAKdiskwrite && kind != TAKindexwrite && kind != TAKpiperead && kind != TAKpipewrite)
  22006. {
  22007. fileName.set(queryNodeFileName(_graphNode, kind));
  22008. indexName.set(queryNodeIndexName(_graphNode, kind));
  22009. if (indexName && !allFilesDynamic && !queryFactory.isDynamic())
  22010. {
  22011. bool isOpt = pretendAllOpt || _graphNode.getPropBool("att[@name='_isIndexOpt']/@value");
  22012. indexfile.setown(queryFactory.queryPackage().lookupFileName(indexName, isOpt, true, true, queryFactory.queryWorkUnit(), true));
  22013. if (indexfile)
  22014. keySet.setown(indexfile->getKeyArray(NULL, &layoutTranslators, isOpt, isLocal ? queryFactory.queryChannel() : 0, false));
  22015. }
  22016. if (fileName && !allFilesDynamic && !queryFactory.isDynamic())
  22017. {
  22018. bool isOpt = pretendAllOpt || _graphNode.getPropBool("att[@name='_isOpt']/@value");
  22019. datafile.setown(_queryFactory.queryPackage().lookupFileName(fileName, isOpt, true, true, queryFactory.queryWorkUnit(), true));
  22020. if (datafile)
  22021. {
  22022. if (isLocal)
  22023. files.setown(datafile->getIFileIOArray(isOpt, queryFactory.queryChannel()));
  22024. }
  22025. }
  22026. }
  22027. }
  22028. catch(IException *E)
  22029. {
  22030. StringBuffer errors;
  22031. E->errorMessage(errors);
  22032. DBGLOG("%s File error = %s", (isLoadDataOnly) ? "LOADDATAONLY" : "SUSPENDED QUERY", errors.str());
  22033. E->Release();
  22034. }
  22035. }
  22036. 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(), __FILE__, __LINE__); }
  22037. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  22038. {
  22039. if (!allFilesDynamic)
  22040. {
  22041. if (datafile)
  22042. addXrefFileInfo(reply, datafile);
  22043. if (indexfile)
  22044. addXrefFileInfo(reply, indexfile);
  22045. }
  22046. else
  22047. {
  22048. Owned<const IResolvedFile> temp;
  22049. if (fileName.length())
  22050. {
  22051. temp.setown(queryFactory.queryPackage().lookupFileName(fileName, true, true, false, queryFactory.queryWorkUnit(), true));
  22052. if (temp)
  22053. addXrefFileInfo(reply, temp);
  22054. }
  22055. if (indexName.length())
  22056. {
  22057. temp.setown(queryFactory.queryPackage().lookupFileName(indexName, true, true, false, queryFactory.queryWorkUnit(), true));
  22058. if (temp)
  22059. addXrefFileInfo(reply, temp);
  22060. }
  22061. }
  22062. }
  22063. };
  22064. IRoxieServerActivityFactory *createRoxieServerDummyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool isLoadDataOnly)
  22065. {
  22066. return new CRoxieServerDummyActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, isLoadDataOnly);
  22067. }
  22068. //=====================================================================================================
  22069. // Keyed joins...
  22070. //
  22071. // Input records are pulled by a puller thread, which checks each LHS record to determine which (if any) channels it
  22072. // may have RHS matches on, and sends the relevant fields to the relevant slaves.
  22073. // 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
  22074. // the transform and returns rows that are created.
  22075. // 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)
  22076. //
  22077. //=====================================================================================================
  22078. class CJoinGroup;
  22079. interface IJoinProcessor
  22080. {
  22081. virtual void processEOG() = 0;
  22082. virtual CJoinGroup *createJoinGroup(const void *row) = 0;
  22083. virtual void noteEndReceived(CJoinGroup *jg, unsigned candidateCount) = 0;
  22084. virtual bool fireException(IException *E) = 0;
  22085. virtual void processCompletedGroups() = 0;
  22086. };
  22087. //------------------------------------------------------------------------------------------------------
  22088. // Class CJoinGroup has a record per LHS row, plus (if preserving grouping) a 'head of group' record
  22089. // It gathers all the corresponding RHS rows, keeping track of how may slave transactions are pending in endMarkersPending
  22090. // If preserving groups, the 'head of group' record keeps track of how many LHS records in the group are still incomplete.
  22091. // CJoinGroup records are allocated out of the Roxie row memory manager by overloading operator new, so that they are included in the
  22092. // per-query limits etc (Note that the pointer array block is not though).
  22093. // Because of that, the exact size is significant - especially whether fit just under or just over a chunking threshold...
  22094. //
  22095. // There are two phases to the life of a JoinGroup - it is created by the puller thread that is also firing off slave requests
  22096. // notePending will be called once for every slave request. Puller thread calls noteEndReceived(0) once when done - this corresponds to the
  22097. // initial count when created.
  22098. // Slave replies and are noted by the consumer thread calling addRightMatch() and noteEndReceived(n).
  22099. // Once endMarkersPending reaches 0, JoinGroup is complete. Last thread to call noteEndReceived will process the rows and destroy the group.
  22100. // There is no need for a critsec because although multiple threads will access at different times, only the consumer thread will
  22101. // access any modifiable member variables while endMarkersPending != 0 (i.e. complete() is false). Once complete returns true there is a single
  22102. // remaining reference and the JoinGroup will be processed and destroyed.
  22103. //
  22104. //------------------------------------------------------------------------------------------------------
  22105. class CJoinGroup : public CInterface, implements IInterface
  22106. {
  22107. protected:
  22108. const void *left; // LHS row
  22109. PointerArrayOf<KeyedJoinHeader> rows; // matching RHS rows
  22110. atomic_t endMarkersPending; // How many slave responses still waiting for
  22111. CJoinGroup *groupStart; // Head of group, or NULL if not grouping
  22112. unsigned lastPartNo;
  22113. unsigned pos;
  22114. unsigned candidates; // Number of RHS keyed candidates - note this may not be the same as rows.ordinality()
  22115. public:
  22116. #undef new
  22117. void *operator new(size_t size, IRowManager *a, unsigned activityId)
  22118. {
  22119. return a->allocate(size, activityId);
  22120. }
  22121. #if defined(_DEBUG) && defined(_WIN32) && !defined(USING_MPATROL)
  22122. #define new new(_NORMAL_BLOCK, __FILE__, __LINE__)
  22123. #endif
  22124. void operator delete(void *ptr, IRowManager *a, unsigned activityId)
  22125. {
  22126. ReleaseRoxieRow(ptr);
  22127. }
  22128. void operator delete(void *ptr)
  22129. {
  22130. ReleaseRoxieRow(ptr);
  22131. }
  22132. public:
  22133. IMPLEMENT_IINTERFACE;
  22134. CJoinGroup(const void *_left, CJoinGroup *_groupStart)
  22135. {
  22136. #ifdef TRACE_JOINGROUPS
  22137. DBGLOG("Creating joinGroup %p, groupstart %p", this, _groupStart);
  22138. #endif
  22139. candidates = 0;
  22140. lastPartNo = 0;
  22141. pos = 0;
  22142. left = _left;
  22143. groupStart = _groupStart;
  22144. if (_groupStart)
  22145. {
  22146. atomic_inc(&_groupStart->endMarkersPending);
  22147. }
  22148. atomic_set(&endMarkersPending, 1);
  22149. }
  22150. ~CJoinGroup()
  22151. {
  22152. #ifdef TRACE_JOINGROUPS
  22153. DBGLOG("Destroying joinGroup %p", this);
  22154. #endif
  22155. if (left)
  22156. {
  22157. ReleaseRoxieRow(left);
  22158. roxiemem::ReleaseRoxieRowArray(rows.ordinality(), (const void * *)rows.getArray());
  22159. rows.kill();
  22160. }
  22161. }
  22162. inline bool isHeadRecord() const
  22163. {
  22164. return left==NULL;
  22165. }
  22166. inline bool complete() const
  22167. {
  22168. return atomic_read(&endMarkersPending) == 0;
  22169. }
  22170. #ifdef TRACE_JOINGROUPS
  22171. inline void notePending(unsigned lineNo)
  22172. #else
  22173. inline void notePending()
  22174. #endif
  22175. {
  22176. assert(!complete());
  22177. atomic_inc(&endMarkersPending);
  22178. #ifdef TRACE_JOINGROUPS
  22179. DBGLOG("CJoinGroup::notePending %p from %d, count became %d group count %d", this, lineNo, atomic_read(&endMarkersPending), groupStart ? atomic_read(&groupStart->endMarkersPending) : 0);
  22180. #endif
  22181. }
  22182. inline bool inGroup(CJoinGroup *leader) const
  22183. {
  22184. return groupStart==leader;
  22185. }
  22186. inline const KeyedJoinHeader *queryRow(unsigned idx) const
  22187. {
  22188. // Single threaded by now
  22189. assert(complete());
  22190. return rows.item(idx);
  22191. }
  22192. #ifdef TRACE_JOINGROUPS
  22193. bool noteEndReceived(unsigned candidateCount, unsigned lineNo)
  22194. #else
  22195. bool noteEndReceived(unsigned candidateCount)
  22196. #endif
  22197. {
  22198. assert(!complete());
  22199. if (candidateCount)
  22200. {
  22201. candidates += candidateCount;
  22202. }
  22203. #ifdef TRACE_JOINGROUPS
  22204. 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);
  22205. #endif
  22206. // NOTE - as soon as endMarkersPending and groupStart->endMarkersPending are decremented to zero this object may get released asynchronously by other threads
  22207. // There must therefore be nothing in this method after them that acceses member variables. Think of it as a delete this...
  22208. // In particular, we can't safely reference groupStart after the dec_and_test of endMarkersPending, hence copy local first
  22209. CJoinGroup *localGroupStart = groupStart;
  22210. if (atomic_dec_and_test(&endMarkersPending))
  22211. {
  22212. if (localGroupStart)
  22213. return atomic_dec_and_test(&localGroupStart->endMarkersPending);
  22214. else
  22215. return true;
  22216. }
  22217. else
  22218. return false;
  22219. }
  22220. inline const void *queryLeft() const
  22221. {
  22222. return left;
  22223. }
  22224. void addRightMatch(KeyedJoinHeader *right)
  22225. {
  22226. assert(!complete());
  22227. unsigned short partNo = right->partNo;
  22228. if (partNo != lastPartNo)
  22229. {
  22230. // MORE - should we binchop? If we did we would need to be careful to find LAST match
  22231. if (partNo > lastPartNo)
  22232. pos = rows.length();
  22233. while (pos>0)
  22234. {
  22235. if (rows.item(pos-1)->partNo <= partNo)
  22236. break;
  22237. pos--;
  22238. }
  22239. lastPartNo = partNo;
  22240. }
  22241. rows.add(right, pos);
  22242. pos++;
  22243. }
  22244. inline unsigned rowsSeen() const
  22245. {
  22246. assert(complete());
  22247. return rows.length();
  22248. }
  22249. inline unsigned candidateCount() const
  22250. {
  22251. assert(complete());
  22252. return candidates;
  22253. }
  22254. };
  22255. #ifdef TRACE_JOINGROUPS
  22256. #define notePending() notePending(__LINE__)
  22257. #define noteEndReceived(a) noteEndReceived(a, __LINE__)
  22258. #endif
  22259. class KeyedJoinRemoteAdaptor : public CRemoteResultAdaptor // MORE - not sure it should be derived from this - makes processed all wrong, for example
  22260. {
  22261. private:
  22262. SafeQueueOf<const void, true> ready;
  22263. public:
  22264. IHThorKeyedJoinArg &helper;
  22265. unsigned joinProcessed;
  22266. bool isFullKey;
  22267. bool eof;
  22268. bool isSimple;
  22269. bool allPulled;
  22270. ActivityTimeAccumulator totalCycles;
  22271. unsigned activityId;
  22272. RecordPullerThread &puller;
  22273. SafeQueueOf<const void, true> injected; // Used in isSimple mode
  22274. Owned<IEngineRowAllocator> ccdRecordAllocator;
  22275. IJoinProcessor &processor;
  22276. KeyedJoinRemoteAdaptor(IRoxieSlaveContext *_ctx, IRoxieServerErrorHandler *_errorHandler, const RemoteActivityId &_remoteId, IHThorKeyedJoinArg &_helper,
  22277. IRoxieServerActivity &_activity, bool _isFullKey, bool _isSimple,
  22278. RecordPullerThread &_puller, IJoinProcessor &_processor)
  22279. : helper(_helper),
  22280. CRemoteResultAdaptor(_ctx, _errorHandler, _remoteId, 0, _helper, _activity, true, true),
  22281. isFullKey(_isFullKey),
  22282. isSimple(_isSimple),
  22283. puller(_puller),
  22284. processor(_processor),
  22285. activityId(_activity.queryId())
  22286. {
  22287. joinProcessed = 0;
  22288. allPulled = false;
  22289. eof = false;
  22290. }
  22291. virtual void onCreate(IHThorArg *_colocalArg)
  22292. {
  22293. CRemoteResultAdaptor::onCreate(_colocalArg);
  22294. ccdRecordAllocator.setown(ctx->queryCodeContext()->getRowAllocator(QUERYINTERFACE(helper.queryJoinFieldsRecordSize(), IOutputMetaData), activityId));
  22295. }
  22296. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  22297. {
  22298. eof = false;
  22299. joinProcessed = 0;
  22300. totalCycles.totalCycles = 0;
  22301. allPulled = false;
  22302. assertex(ready.ordinality()==0);
  22303. CRemoteResultAdaptor::start(parentExtractSize, parentExtract, paused);
  22304. }
  22305. virtual void reset()
  22306. {
  22307. CRemoteResultAdaptor::reset();
  22308. while (ready.ordinality())
  22309. {
  22310. const void *goer = ready.dequeue();
  22311. if (goer)
  22312. ReleaseRoxieRow(goer);
  22313. }
  22314. while (injected.ordinality())
  22315. {
  22316. const void *goer = injected.dequeue();
  22317. if (goer)
  22318. ReleaseRoxieRow(goer);
  22319. }
  22320. }
  22321. inline void addResult(const void *row)
  22322. {
  22323. ready.enqueue(row);
  22324. }
  22325. virtual unsigned __int64 queryTotalCycles() const
  22326. {
  22327. return totalCycles.totalCycles;
  22328. }
  22329. virtual const void *nextRow()
  22330. {
  22331. ActivityTimer t(totalCycles, timeActivities);
  22332. loop
  22333. {
  22334. if (eof)
  22335. return NULL;
  22336. processSlaveResults();
  22337. if (ready.ordinality())
  22338. {
  22339. const void *result = ready.dequeue();
  22340. if (result)
  22341. joinProcessed++;
  22342. return result;
  22343. }
  22344. else
  22345. eof = true;
  22346. }
  22347. }
  22348. private:
  22349. void processSlaveResults()
  22350. {
  22351. while (!ready.ordinality())
  22352. {
  22353. KeyedJoinHeader *fetchedData;
  22354. if (isSimple)
  22355. {
  22356. while (!allPulled && !injected.ordinality())
  22357. {
  22358. if (!puller.pullRecords(1))
  22359. {
  22360. puller.done();
  22361. allPulled = true;
  22362. }
  22363. }
  22364. fetchedData = (KeyedJoinHeader *) injected.dequeue();
  22365. }
  22366. else
  22367. fetchedData = (KeyedJoinHeader *) CRemoteResultAdaptor::nextRow();
  22368. if (fetchedData)
  22369. {
  22370. CJoinGroup *thisGroup = fetchedData->thisGroup;
  22371. if (fetchedData->partNo == (unsigned short) -1)
  22372. {
  22373. #ifdef TRACE_JOINGROUPS
  22374. CTXLOG("Got end for group %p", thisGroup);
  22375. #endif
  22376. unsigned candidateCount = (unsigned) fetchedData->fpos;
  22377. ReleaseRoxieRow(fetchedData);
  22378. processor.noteEndReceived(thisGroup, candidateCount); // note - this can throw exception. So release fetchdata before calling
  22379. }
  22380. else
  22381. {
  22382. #ifdef TRACE_JOINGROUPS
  22383. CTXLOG("Reading another %d bytes for group %p data", ccdRecordSize, thisGroup);
  22384. #endif
  22385. thisGroup->addRightMatch(fetchedData);
  22386. if (isFullKey)
  22387. {
  22388. #ifdef TRACE_JOINGROUPS
  22389. CTXLOG("Calling noteEndReceived for record returned from FETCH of full keyed join");
  22390. #endif
  22391. processor.noteEndReceived(thisGroup, 0); // note - this can throw exception. So release fetchdata before calling
  22392. }
  22393. }
  22394. }
  22395. else
  22396. break;
  22397. }
  22398. }
  22399. };
  22400. class CRoxieServerFullKeyedJoinHead: public CRoxieServerActivity, implements IRecordPullerCallback, implements IRoxieServerErrorHandler
  22401. {
  22402. IHThorKeyedJoinArg &helper;
  22403. Owned<IKeyManager> tlk;
  22404. Linked<IKeyArray> keySet;
  22405. Linked<TranslatorArray> translators;
  22406. CRemoteResultAdaptor remote;
  22407. RecordPullerThread puller;
  22408. IOutputMetaData *indexReadMeta;
  22409. IJoinProcessor *joinHandler;
  22410. bool variableIndexFileName;
  22411. bool indexReadInputRecordVariable;
  22412. bool isLocal;
  22413. Owned<IEngineRowAllocator> indexReadAllocator;
  22414. Owned<const IResolvedFile> varFileInfo;
  22415. IFinalRoxieInput *indexReadInput;
  22416. unsigned indexReadIdx = 0;
  22417. IIndexReadActivityInfo *rootIndex;
  22418. public:
  22419. CRoxieServerFullKeyedJoinHead(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IKeyArray * _keySet, TranslatorArray *_translators, IOutputMetaData *_indexReadMeta, IJoinProcessor *_joinHandler, bool _isLocal)
  22420. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  22421. helper((IHThorKeyedJoinArg &)basehelper),
  22422. tlk(createKeyManager(NULL, 0, this)),
  22423. translators(_translators),
  22424. keySet(_keySet),
  22425. remote(_ctx, this, _remoteId, 0, helper, *this, true, true),
  22426. indexReadMeta(_indexReadMeta),
  22427. joinHandler(_joinHandler),
  22428. puller(false),
  22429. isLocal(_isLocal)
  22430. {
  22431. variableIndexFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getJoinFlags() & (JFvarindexfilename|JFdynamicindexfilename|JFindexfromactivity)) != 0);
  22432. indexReadInputRecordVariable = indexReadMeta->isVariableSize();
  22433. indexReadInput = NULL;
  22434. rootIndex = NULL;
  22435. }
  22436. virtual const IResolvedFile *queryVarFileInfo() const
  22437. {
  22438. return varFileInfo;
  22439. }
  22440. virtual void onCreate(IHThorArg *_colocalParent)
  22441. {
  22442. CRoxieServerActivity::onCreate(_colocalParent);
  22443. remote.onCreate(_colocalParent);
  22444. indexReadAllocator.setown(ctx->queryCodeContext()->getRowAllocator(indexReadMeta, activityId));
  22445. }
  22446. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  22447. {
  22448. if (!idx)
  22449. puller.setInput(this, _sourceIdx, _in);
  22450. else if (idx==1)
  22451. {
  22452. indexReadInput = _in;
  22453. indexReadIdx = _sourceIdx;
  22454. }
  22455. else
  22456. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  22457. }
  22458. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  22459. {
  22460. puller.connectInputStreams(ctx, consumerOrdered);
  22461. //No rows are read from indexReadInput, so no need to extract the streams
  22462. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
  22463. }
  22464. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  22465. {
  22466. switch (idx)
  22467. {
  22468. case 0:
  22469. return puller.queryInput();
  22470. case 1:
  22471. return indexReadInput;
  22472. default:
  22473. return NULL;
  22474. }
  22475. }
  22476. virtual void serializeExtra(MemoryBuffer &out)
  22477. {
  22478. if (helper.getJoinFlags() & JFindexfromactivity)
  22479. {
  22480. assertex(rootIndex);
  22481. const RemoteActivityId& indexId = rootIndex->queryRemoteId();
  22482. indexId.serialize(out);
  22483. // could mess about reserving space for length then patching it again, to avoid copy, but probably not worth it
  22484. MemoryBuffer tmp;
  22485. rootIndex->queryActivity()->serializeCreateStartContext(tmp);
  22486. if (rootIndex->queryActivity()->queryVarFileInfo())
  22487. {
  22488. rootIndex->queryActivity()->queryVarFileInfo()->queryTimeStamp().serialize(tmp);
  22489. tmp.append(rootIndex->queryActivity()->queryVarFileInfo()->queryCheckSum());
  22490. }
  22491. unsigned ctxlen = tmp.length();
  22492. out.append(ctxlen).append(tmp);
  22493. }
  22494. }
  22495. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  22496. {
  22497. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  22498. if (indexReadInput)
  22499. {
  22500. indexReadInput->start(parentExtractSize, parentExtract, true); // paused=true because we don't want to actually run the index read
  22501. rootIndex = indexReadInput->queryIndexReadActivity();
  22502. if (!rootIndex)
  22503. throw MakeStringException(ROXIE_INTERNAL_ERROR,"Index in keyed join %d could not be resolved", queryId());
  22504. }
  22505. remote.onStart(parentExtractSize, parentExtract);
  22506. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  22507. if (rootIndex)
  22508. {
  22509. varFileInfo.setown(rootIndex->getVarFileInfo());
  22510. translators.setown(rootIndex->getTranslators());
  22511. keySet.setown(rootIndex->getKeySet());
  22512. }
  22513. else if (variableIndexFileName)
  22514. {
  22515. OwnedRoxieString indexFileName(helper.getIndexFileName());
  22516. varFileInfo.setown(resolveLFN(indexFileName, (helper.getJoinFlags() & JFindexoptional) != 0));
  22517. if (varFileInfo)
  22518. {
  22519. translators.setown(new TranslatorArray);
  22520. keySet.setown(varFileInfo->getKeyArray(factory->queryActivityMeta(), translators, false, isLocal ? factory->queryQueryFactory().queryChannel() : 0, factory->queryQueryFactory().queryOptions().enableFieldTranslation)); // MORE - isLocal?
  22521. }
  22522. }
  22523. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().fullKeyedJoinPreload, false, ctx);
  22524. }
  22525. virtual void stop()
  22526. {
  22527. puller.stop();
  22528. CRoxieServerActivity::stop();
  22529. }
  22530. virtual void reset()
  22531. {
  22532. CRoxieServerActivity::reset();
  22533. puller.reset();
  22534. if (varFileInfo)
  22535. {
  22536. keySet.clear();
  22537. varFileInfo.clear();
  22538. }
  22539. }
  22540. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  22541. {
  22542. if (idx==(unsigned)-1)
  22543. idx = 0;
  22544. return idx ? NULL : &remote;
  22545. }
  22546. virtual void processRow(const void *row)
  22547. {
  22548. // MORE - this code seems to be pretty much duplicated below in half-keyed....
  22549. // called from front puller thread
  22550. // buffer up an IndexRead request
  22551. if (helper.leftCanMatch(row))
  22552. {
  22553. RtlDynamicRowBuilder extractedBuilder(indexReadAllocator);
  22554. unsigned indexReadSize = helper.extractIndexReadFields(extractedBuilder, row);
  22555. OwnedConstRoxieRow extracted;
  22556. if (indexReadSize)
  22557. extracted.setown(extractedBuilder.finalizeRowClear(indexReadSize));
  22558. CJoinGroup *jg = joinHandler->createJoinGroup(row);
  22559. for (unsigned partNo = 0; partNo < keySet->length(); partNo++)
  22560. {
  22561. IKeyIndexBase *thisBase = keySet->queryKeyPart(partNo);
  22562. if (thisBase)
  22563. {
  22564. unsigned fileNo = 0;
  22565. IKeyIndex *thisKey = thisBase->queryPart(fileNo);
  22566. try
  22567. {
  22568. tlk->setKey(thisKey);
  22569. tlk->setLayoutTranslator(translators->item(fileNo));
  22570. helper.createSegmentMonitors(tlk, extracted);
  22571. if (rootIndex)
  22572. rootIndex->mergeSegmentMonitors(tlk);
  22573. tlk->finishSegmentMonitors();
  22574. tlk->reset();
  22575. loop
  22576. {
  22577. typedef const void * cvp;
  22578. if (thisKey->isTopLevelKey())
  22579. {
  22580. bool locallySorted = !thisKey->isFullySorted();
  22581. while (locallySorted || tlk->lookup(false))
  22582. {
  22583. unsigned slavePart = locallySorted ? 0 : (unsigned) tlk->queryFpos();
  22584. if (locallySorted || slavePart)
  22585. {
  22586. cvp *outputBuffer = (cvp *) remote.getMem(slavePart, fileNo, indexReadSize + sizeof(cvp) + (indexReadInputRecordVariable ? sizeof(unsigned) : 0));
  22587. *outputBuffer++ = jg;
  22588. if (indexReadInputRecordVariable)
  22589. {
  22590. *(unsigned *) outputBuffer = indexReadSize;
  22591. outputBuffer = (cvp*) (((unsigned *) outputBuffer) + 1);
  22592. }
  22593. jg->notePending();
  22594. memcpy(outputBuffer, extracted, indexReadSize);
  22595. if (locallySorted)
  22596. {
  22597. for (unsigned i = 1; i < numChannels; i++)
  22598. jg->notePending();
  22599. break;
  22600. }
  22601. }
  22602. }
  22603. }
  22604. else
  22605. {
  22606. // MORE - this code seems to be duplicated in half keyed
  22607. unsigned accepted = 0;
  22608. unsigned rejected = 0;
  22609. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), true);
  22610. jg->notePending();
  22611. unsigned candidateCount = 0;
  22612. while (tlk->lookup(true))
  22613. {
  22614. candidateCount++;
  22615. atomic_inc(&indexRecordsRead);
  22616. KLBlobProviderAdapter adapter(tlk);
  22617. offset_t recptr;
  22618. const byte *indexRow = tlk->queryKeyBuffer(recptr);
  22619. if (helper.indexReadMatch(extracted, indexRow, recptr, &adapter))
  22620. {
  22621. KeyedJoinHeader *rhs = (KeyedJoinHeader *) ctx->queryRowManager().allocate(KEYEDJOIN_RECORD_SIZE(0), activityId);
  22622. rhs->fpos = recptr;
  22623. rhs->thisGroup = jg;
  22624. rhs->partNo = partNo;
  22625. result->append(rhs);
  22626. }
  22627. else
  22628. {
  22629. rejected++;
  22630. atomic_inc(&postFiltered);
  22631. }
  22632. }
  22633. // output an end marker for the matches to this group
  22634. KeyedJoinHeader *endMarker = (KeyedJoinHeader *) ctx->queryRowManager().allocate(KEYEDJOIN_RECORD_SIZE(0), activityId);
  22635. endMarker->fpos = (offset_t) candidateCount;
  22636. endMarker->thisGroup = jg;
  22637. endMarker->partNo = (unsigned short) -1;
  22638. result->append(endMarker);
  22639. remote.injectResult(result.getClear());
  22640. if (accepted)
  22641. noteStatistic(StNumIndexAccepted, accepted);
  22642. if (rejected)
  22643. noteStatistic(StNumIndexRejected, rejected);
  22644. }
  22645. if (++fileNo < thisBase->numParts())
  22646. {
  22647. thisKey = thisBase->queryPart(fileNo);
  22648. tlk->setKey(thisKey);
  22649. tlk->setLayoutTranslator(translators->item(fileNo));
  22650. tlk->reset();
  22651. }
  22652. else
  22653. break;
  22654. }
  22655. tlk->releaseSegmentMonitors();
  22656. tlk->setKey(NULL);
  22657. }
  22658. catch (...)
  22659. {
  22660. tlk->releaseSegmentMonitors();
  22661. tlk->setKey(NULL);
  22662. throw;
  22663. }
  22664. }
  22665. }
  22666. joinHandler->noteEndReceived(jg, 0);
  22667. }
  22668. else
  22669. {
  22670. joinHandler->noteEndReceived(joinHandler->createJoinGroup(row), 0);
  22671. }
  22672. }
  22673. void processGroup(const ConstPointerArray &)
  22674. {
  22675. throwUnexpected();
  22676. }
  22677. virtual void processEOG()
  22678. {
  22679. joinHandler->processEOG();
  22680. }
  22681. virtual void processDone()
  22682. {
  22683. // called from puller thread
  22684. remote.flush();
  22685. remote.senddone();
  22686. }
  22687. virtual void onLimitExceeded(bool isKeyed)
  22688. {
  22689. if (traceLevel > 4)
  22690. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  22691. if (isKeyed)
  22692. throwUnexpected();
  22693. helper.onLimitExceeded();
  22694. }
  22695. virtual const void *createLimitFailRow(bool isKeyed)
  22696. {
  22697. throwUnexpected();
  22698. }
  22699. virtual bool fireException(IException *e)
  22700. {
  22701. // called from puller thread on failure
  22702. remote.fireException(LINK(e));
  22703. return joinHandler->fireException(e);
  22704. }
  22705. virtual const void *nextRow()
  22706. {
  22707. throwUnexpected(); // I am nobody's input
  22708. }
  22709. };
  22710. class CRoxieServerKeyedJoinBase : public CRoxieServerActivity, implements IRecordPullerCallback, implements IRoxieServerErrorHandler, implements IJoinProcessor
  22711. {
  22712. protected:
  22713. IHThorKeyedJoinArg &helper;
  22714. KeyedJoinRemoteAdaptor remote;
  22715. RecordPullerThread puller;
  22716. OwnedConstRoxieRow defaultRight;
  22717. Owned<IEngineRowAllocator> defaultRightAllocator;
  22718. unsigned joinFlags;
  22719. unsigned atMost;
  22720. unsigned atmostsTriggered;
  22721. unsigned abortLimit;
  22722. unsigned keepLimit;
  22723. bool limitFail;
  22724. bool limitOnFail;
  22725. bool preserveGroups;
  22726. bool cloneLeft;
  22727. bool isSimple;
  22728. bool isLocal;
  22729. ThorActivityKind activityKind;
  22730. CJoinGroup *groupStart;
  22731. CriticalSection groupsCrit;
  22732. QueueOf<CJoinGroup, false> groups;
  22733. IFinalRoxieInput *indexReadInput;
  22734. unsigned indexReadIdx = 0;
  22735. Owned<IStrandJunction> indexReadJunction;
  22736. IEngineRowStream *indexReadStream = NULL; // Never actually pulled
  22737. IIndexReadActivityInfo *rootIndex;
  22738. void createDefaultRight()
  22739. {
  22740. if (!defaultRight)
  22741. {
  22742. if (!defaultRightAllocator)
  22743. defaultRightAllocator.setown(ctx->queryCodeContext()->getRowAllocator(helper.queryJoinFieldsRecordSize(), activityId));
  22744. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  22745. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  22746. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  22747. }
  22748. }
  22749. public:
  22750. CRoxieServerKeyedJoinBase(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _joinFlags
  22751. , bool isFull, bool _isSimple, bool _isLocal)
  22752. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  22753. helper((IHThorKeyedJoinArg &)basehelper),
  22754. remote(_ctx, this, _remoteId, helper, *this, isFull, _isSimple, puller, *this),
  22755. joinFlags(_joinFlags),
  22756. preserveGroups(meta.isGrouped()),
  22757. puller(false),
  22758. isSimple(_isSimple),
  22759. isLocal(_isLocal),
  22760. abortLimit(0),
  22761. keepLimit(0),
  22762. atMost(0),
  22763. limitFail(false),
  22764. limitOnFail(false),
  22765. cloneLeft(false)
  22766. {
  22767. groupStart = NULL;
  22768. activityKind = _factory->getKind();
  22769. indexReadInput = NULL;
  22770. rootIndex = NULL;
  22771. atmostsTriggered = 0;
  22772. // MORE - code would be easier to read if I got more values from helper rather than passing from factory
  22773. }
  22774. virtual void onCreate(IHThorArg *_colocalParent)
  22775. {
  22776. CRoxieServerActivity::onCreate(_colocalParent);
  22777. remote.onCreate(_colocalParent);
  22778. }
  22779. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  22780. {
  22781. if (!idx)
  22782. puller.setInput(this, _sourceIdx, _in);
  22783. else if (idx==1)
  22784. {
  22785. indexReadInput = _in;
  22786. indexReadIdx = _sourceIdx;
  22787. }
  22788. else
  22789. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  22790. }
  22791. virtual void connectInputStreams(bool consumerOrdered)
  22792. {
  22793. CRoxieServerActivity::connectInputStreams(consumerOrdered);
  22794. puller.connectInputStreams(ctx, consumerOrdered);
  22795. if (indexReadInput)
  22796. indexReadStream = connectSingleStream(ctx, indexReadInput, indexReadIdx, indexReadJunction, consumerOrdered); // We never actually pull the stream
  22797. }
  22798. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  22799. {
  22800. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  22801. if (indexReadInput)
  22802. {
  22803. indexReadInput->start(parentExtractSize, parentExtract, true); // paused=true because we don't want to actually run the index read
  22804. rootIndex = indexReadInput->queryIndexReadActivity();
  22805. if (!rootIndex)
  22806. throw MakeStringException(ROXIE_INTERNAL_ERROR,"Index in keyed join %d could not be resolved", queryId());
  22807. }
  22808. remote.onStart(parentExtractSize, parentExtract);
  22809. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  22810. atmostsTriggered = 0;
  22811. atMost = helper.getJoinLimit();
  22812. if (atMost == 0) atMost = (unsigned)-1;
  22813. abortLimit = helper.getMatchAbortLimit();
  22814. if (abortLimit == 0 || atMost != (unsigned) -1) abortLimit = (unsigned)-1;
  22815. keepLimit = helper.getKeepLimit();
  22816. if (keepLimit == 0) keepLimit = (unsigned)-1;
  22817. getLimitType(joinFlags, limitFail, limitOnFail);
  22818. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  22819. if (joinFlags & JFleftouter || limitOnFail)
  22820. createDefaultRight();
  22821. }
  22822. virtual void stop()
  22823. {
  22824. puller.stop();
  22825. if (indexReadStream)
  22826. indexReadStream->stop(); // Could probably do this as soon as re have fetched rootIndex?
  22827. CRoxieServerActivity::stop();
  22828. }
  22829. virtual unsigned __int64 queryLocalCycles() const
  22830. {
  22831. __int64 localCycles = remote.totalCycles.totalCycles;
  22832. localCycles -= puller.queryTotalCycles(); // MORE - debatable... but probably fair.
  22833. if (localCycles < 0)
  22834. localCycles = 0;
  22835. return localCycles;
  22836. }
  22837. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  22838. {
  22839. if (idx==0)
  22840. return puller.queryInput();
  22841. else if (idx==1)
  22842. return indexReadInput;
  22843. else
  22844. return NULL;
  22845. }
  22846. virtual void reset()
  22847. {
  22848. totalCycles.totalCycles = remote.totalCycles.totalCycles;
  22849. remote.totalCycles.totalCycles = 0;
  22850. processed = remote.joinProcessed;
  22851. remote.joinProcessed = 0;
  22852. defaultRight.clear();
  22853. if (indexReadInput)
  22854. indexReadInput->reset();
  22855. if (atmostsTriggered)
  22856. noteStatistic(StNumAtmostTriggered, atmostsTriggered);
  22857. CRoxieServerActivity::reset();
  22858. puller.reset();
  22859. while (groups.ordinality())
  22860. {
  22861. ::Release(groups.dequeue());
  22862. }
  22863. }
  22864. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  22865. {
  22866. if (idx==(unsigned)-1)
  22867. idx = 0;
  22868. return idx ? NULL : &remote;
  22869. }
  22870. #undef new
  22871. virtual CJoinGroup *createJoinGroup(const void *row)
  22872. {
  22873. // NOTE - we need to protect access to queue, since it's also modified by consumer thread. Groupstart is only modified by puller thread.
  22874. CriticalBlock c(groupsCrit);
  22875. if (preserveGroups && !groupStart)
  22876. {
  22877. groupStart = new (&ctx->queryRowManager(), activityId) CJoinGroup(NULL, NULL);
  22878. groups.enqueue(groupStart);
  22879. }
  22880. CJoinGroup *jg = new (&ctx->queryRowManager(), activityId) CJoinGroup(row, groupStart);
  22881. groups.enqueue(jg);
  22882. return jg;
  22883. }
  22884. #if defined(_DEBUG) && defined(_WIN32) && !defined(USING_MPATROL)
  22885. #define new new(_NORMAL_BLOCK, __FILE__, __LINE__)
  22886. #endif
  22887. void endGroup()
  22888. {
  22889. CriticalBlock c(groupsCrit);
  22890. if (groupStart)
  22891. noteEndReceived(groupStart, 0);
  22892. groupStart = NULL;
  22893. }
  22894. virtual void noteEndReceived(CJoinGroup *jg, unsigned candidateCount)
  22895. {
  22896. if (jg->noteEndReceived(candidateCount))
  22897. processCompletedGroups();
  22898. }
  22899. void processCompletedGroups()
  22900. {
  22901. CriticalBlock c(groupsCrit);
  22902. while (groups.ordinality())
  22903. {
  22904. if (!groups.head()->complete())
  22905. break;
  22906. Owned<CJoinGroup> head = groups.dequeue();
  22907. if (preserveGroups)
  22908. {
  22909. assert(head->isHeadRecord());
  22910. assert(groups.head()->inGroup(head));
  22911. unsigned joinGroupSize = 0;
  22912. while (groups.ordinality() && groups.head()->inGroup(head))
  22913. {
  22914. Owned<CJoinGroup> finger = groups.dequeue();
  22915. joinGroupSize += doJoinGroup(finger);
  22916. }
  22917. if (joinGroupSize)
  22918. remote.addResult(NULL);
  22919. }
  22920. else
  22921. doJoinGroup(head);
  22922. }
  22923. }
  22924. void failLimit(const void * left)
  22925. {
  22926. helper.onMatchAbortLimitExceeded();
  22927. CommonXmlWriter xmlwrite(0);
  22928. if (input && input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  22929. {
  22930. input->queryOutputMeta()->toXML((byte *) left, xmlwrite);
  22931. }
  22932. throw MakeStringException(ROXIE_JOIN_ERROR, "More than %d match candidates in keyed join %d for row %s", abortLimit, queryId(), xmlwrite.str());
  22933. }
  22934. virtual bool needsAllocator() const { return true; }
  22935. unsigned doTransform(const void *left, const void *right, offset_t fpos_or_count, IException *except, const void **group, unsigned counter)
  22936. {
  22937. if (cloneLeft && !except)
  22938. {
  22939. LinkRoxieRow(left);
  22940. remote.addResult((void *) left);
  22941. return 1;
  22942. }
  22943. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  22944. unsigned outSize;
  22945. try
  22946. {
  22947. outSize = except ? helper.onFailTransform(rowBuilder, left, right, fpos_or_count, except) :
  22948. (activityKind == TAKkeyeddenormalizegroup) ? helper.transform(rowBuilder, left, right, (unsigned) fpos_or_count, group) :
  22949. helper.transform(rowBuilder, left, right, fpos_or_count, counter);
  22950. }
  22951. catch (IException *E)
  22952. {
  22953. throw makeWrappedException(E);
  22954. }
  22955. if (outSize)
  22956. {
  22957. const void *shrunk = rowBuilder.finalizeRowClear(outSize);
  22958. remote.addResult(shrunk);
  22959. return 1;
  22960. }
  22961. else
  22962. return 0;
  22963. }
  22964. unsigned doJoinGroup(CJoinGroup *jg)
  22965. {
  22966. unsigned matched = jg->rowsSeen();
  22967. unsigned added = 0;
  22968. const void *left = jg->queryLeft();
  22969. if (jg->candidateCount() > abortLimit)
  22970. {
  22971. if (limitFail)
  22972. failLimit(left);
  22973. if (ctx->queryDebugContext())
  22974. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  22975. if (limitOnFail)
  22976. {
  22977. Owned<IException> except;
  22978. try
  22979. {
  22980. failLimit(left);
  22981. }
  22982. catch(IException * e)
  22983. {
  22984. except.setown(e);
  22985. }
  22986. added = doTransform(left, defaultRight, 0, except, NULL, 0);
  22987. }
  22988. }
  22989. else if (!matched || jg->candidateCount() > atMost)
  22990. {
  22991. if (jg->candidateCount() > atMost)
  22992. atmostsTriggered++;
  22993. switch (joinFlags & JFtypemask)
  22994. {
  22995. case JFleftouter:
  22996. case JFleftonly:
  22997. switch (activityKind)
  22998. {
  22999. case TAKkeyedjoin:
  23000. case TAKkeyeddenormalizegroup:
  23001. added = doTransform(left, defaultRight, 0, NULL, NULL, 0);
  23002. break;
  23003. case TAKkeyeddenormalize:
  23004. LinkRoxieRow(left);
  23005. remote.addResult((void *) left);
  23006. added++;
  23007. break;
  23008. }
  23009. break;
  23010. }
  23011. }
  23012. else if (!(joinFlags & JFexclude))
  23013. {
  23014. unsigned idx = 0;
  23015. switch (activityKind)
  23016. {
  23017. case TAKkeyedjoin:
  23018. while (idx < matched)
  23019. {
  23020. const KeyedJoinHeader *rhs = jg->queryRow(idx);
  23021. added += doTransform(left, &rhs->rhsdata, rhs->fpos, NULL, NULL, idx+1);
  23022. if (added==keepLimit)
  23023. break;
  23024. idx++;
  23025. }
  23026. break;
  23027. case TAKkeyeddenormalize:
  23028. {
  23029. OwnedConstRoxieRow newLeft;
  23030. newLeft.set(left);
  23031. unsigned rowSize = 0;
  23032. unsigned rightAdded = 0;
  23033. while (idx < matched)
  23034. {
  23035. const KeyedJoinHeader *rhs = jg->queryRow(idx);
  23036. try
  23037. {
  23038. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  23039. size32_t transformedSize = helper.transform(rowBuilder, newLeft, &rhs->rhsdata, rhs->fpos, idx+1);
  23040. if (transformedSize)
  23041. {
  23042. rowSize = transformedSize;
  23043. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  23044. rightAdded++;
  23045. if (rightAdded==keepLimit)
  23046. break;
  23047. }
  23048. idx++;
  23049. }
  23050. catch (IException *E)
  23051. {
  23052. throw makeWrappedException(E);
  23053. }
  23054. }
  23055. if (rowSize)
  23056. {
  23057. remote.addResult(newLeft.getClear());
  23058. added++;
  23059. }
  23060. }
  23061. break;
  23062. case TAKkeyeddenormalizegroup:
  23063. {
  23064. ConstPointerArray extractedRows;
  23065. while (idx < matched && idx < keepLimit)
  23066. {
  23067. const KeyedJoinHeader *rhs = jg->queryRow(idx);
  23068. extractedRows.append((void *) &rhs->rhsdata);
  23069. idx++;
  23070. }
  23071. added += doTransform(left, extractedRows.item(0), extractedRows.ordinality(), NULL, (const void * *)extractedRows.getArray(), 0);
  23072. }
  23073. break;
  23074. }
  23075. }
  23076. return added;
  23077. }
  23078. virtual void processDone()
  23079. {
  23080. // called from puller thread
  23081. remote.flush();
  23082. remote.senddone();
  23083. }
  23084. virtual void onLimitExceeded(bool isKeyed)
  23085. {
  23086. if (traceLevel > 4)
  23087. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  23088. if (isKeyed)
  23089. throwUnexpected();
  23090. helper.onLimitExceeded();
  23091. }
  23092. virtual const void *createLimitFailRow(bool isKeyed)
  23093. {
  23094. throwUnexpected();
  23095. }
  23096. virtual bool fireException(IException *e)
  23097. {
  23098. // called from puller thread on failure
  23099. return remote.fireException(e);
  23100. }
  23101. virtual const void *nextRow()
  23102. {
  23103. throwUnexpected(); // I am nobody's input
  23104. }
  23105. };
  23106. #ifdef _MSC_VER
  23107. #pragma warning ( push )
  23108. #pragma warning ( disable: 4355 )
  23109. #endif
  23110. class CRoxieServerKeyedJoinActivity : public CRoxieServerKeyedJoinBase
  23111. {
  23112. CRoxieServerFullKeyedJoinHead head;
  23113. Owned<IEngineRowAllocator> fetchInputAllocator;
  23114. Linked<IFilePartMap> map;
  23115. bool variableFetchFileName;
  23116. Owned<const IResolvedFile> varFetchFileInfo;
  23117. CachedOutputMetaData fetchInputFields;
  23118. public:
  23119. CRoxieServerKeyedJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_headId, IKeyArray * _key, TranslatorArray *_translators, IOutputMetaData *_indexReadMeta,
  23120. const RemoteActivityId &_tailId, IFilePartMap *_map, unsigned _joinFlags, bool _isLocal)
  23121. : CRoxieServerKeyedJoinBase(_ctx, _factory, _probeManager, _tailId, _joinFlags, true, false, _isLocal),
  23122. head(_ctx, _factory, _probeManager, _headId, _key, _translators, _indexReadMeta, this, _isLocal),
  23123. map(_map)
  23124. {
  23125. CRoxieServerKeyedJoinBase::setInput(0, 0, head.queryOutput(0));
  23126. variableFetchFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  23127. }
  23128. virtual const IResolvedFile *queryVarFileInfo() const
  23129. {
  23130. return varFetchFileInfo;
  23131. }
  23132. virtual void onCreate(IHThorArg *_colocalParent)
  23133. {
  23134. CRoxieServerKeyedJoinBase::onCreate(_colocalParent);
  23135. head.onCreate(_colocalParent);
  23136. fetchInputFields.set(helper.queryFetchInputRecordSize());
  23137. fetchInputAllocator.setown(ctx->queryCodeContext()->getRowAllocator(helper.queryFetchInputRecordSize(), activityId));
  23138. }
  23139. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  23140. {
  23141. CRoxieServerKeyedJoinBase::start(parentExtractSize, parentExtract, paused);
  23142. if (variableFetchFileName)
  23143. {
  23144. bool isFetchOpt = (helper.getFetchFlags() & FFdatafileoptional) != 0;
  23145. OwnedRoxieString fname(helper.getFileName());
  23146. varFetchFileInfo.setown(resolveLFN(fname, isFetchOpt));
  23147. if (varFetchFileInfo)
  23148. map.setown(varFetchFileInfo->getFileMap());
  23149. }
  23150. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().keyedJoinPreload, false, ctx);
  23151. }
  23152. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  23153. {
  23154. head.setInput(idx, _sourceIdx, _in);
  23155. }
  23156. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  23157. {
  23158. connectInputStreams(consumerOrdered);
  23159. return head.getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
  23160. }
  23161. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  23162. {
  23163. return head.queryInput(idx);
  23164. }
  23165. virtual void processRow(const void *_rhs)
  23166. {
  23167. // called from puller thread
  23168. KeyedJoinHeader *rhs = (KeyedJoinHeader *) _rhs;
  23169. CJoinGroup *jg = rhs->thisGroup;
  23170. if (rhs->partNo != (unsigned short) -1)
  23171. {
  23172. unsigned partNo = map->mapOffset(rhs->fpos);
  23173. RtlDynamicRowBuilder fetchBuilder(fetchInputAllocator, true);
  23174. size32_t fisize = helper.extractFetchFields(fetchBuilder, jg->queryLeft());
  23175. if (fetchInputFields.isVariableSize())
  23176. {
  23177. KeyedJoinHeader *outRow = (KeyedJoinHeader *) remote.getMem(partNo, 0, KEYEDJOIN_RECORD_SIZE(fisize + sizeof(fisize)));
  23178. memcpy(outRow, rhs, KEYEDJOIN_RECORD_SIZE(0)); // MORE - copy constructor might be more appropriate....
  23179. ReleaseRoxieRow(rhs);
  23180. jg->notePending();
  23181. memcpy(&outRow->rhsdata, &fisize, sizeof(fisize));
  23182. memcpy((&outRow->rhsdata)+sizeof(fisize), fetchBuilder.row(), fisize);
  23183. }
  23184. else
  23185. {
  23186. KeyedJoinHeader *outRow = (KeyedJoinHeader *) remote.getMem(partNo, 0, KEYEDJOIN_RECORD_SIZE(fisize));
  23187. memcpy(outRow, rhs, KEYEDJOIN_RECORD_SIZE(0)); // MORE - copy constructor might be more appropriate....
  23188. ReleaseRoxieRow(rhs);
  23189. jg->notePending();
  23190. memcpy(&outRow->rhsdata, fetchBuilder.row(), fisize);
  23191. }
  23192. }
  23193. else
  23194. {
  23195. unsigned candidateCount = (unsigned) rhs->fpos;
  23196. // CTXLOG("Full keyed join - all results back from index");
  23197. ReleaseRoxieRow(rhs);
  23198. noteEndReceived(jg, candidateCount); // may throw exception - so release row before calling
  23199. }
  23200. }
  23201. virtual void processEOG()
  23202. {
  23203. // called from front puller thread
  23204. if (preserveGroups)
  23205. endGroup();
  23206. }
  23207. void processGroup(const ConstPointerArray &)
  23208. {
  23209. throwUnexpected();
  23210. }
  23211. };
  23212. #ifdef _MSC_VER
  23213. #pragma warning ( pop )
  23214. #endif
  23215. class CRoxieServerHalfKeyedJoinActivity : public CRoxieServerKeyedJoinBase
  23216. {
  23217. IOutputMetaData *indexReadMeta;
  23218. Owned<IEngineRowAllocator> indexReadAllocator;
  23219. Owned<IKeyManager> tlk;
  23220. bool variableIndexFileName;
  23221. bool indexReadInputRecordVariable;
  23222. Owned<const IResolvedFile> varFileInfo;
  23223. Linked<TranslatorArray> translators;
  23224. Linked<IKeyArray> keySet;
  23225. Owned<IOutputMetaData> joinPrefixedMeta;
  23226. Owned<IEngineRowAllocator> joinFieldsAllocator;
  23227. public:
  23228. CRoxieServerHalfKeyedJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IKeyArray * _keySet, TranslatorArray *_translators,
  23229. IOutputMetaData *_indexReadMeta, unsigned _joinFlags, bool _isSimple, bool _isLocal)
  23230. : CRoxieServerKeyedJoinBase(_ctx, _factory, _probeManager, _remoteId, _joinFlags, false, _isSimple, _isLocal),
  23231. indexReadMeta(_indexReadMeta),
  23232. tlk(createKeyManager(NULL, 0, this)),
  23233. keySet(_keySet),
  23234. translators(_translators)
  23235. {
  23236. variableIndexFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getJoinFlags() & (JFvarindexfilename|JFdynamicindexfilename|JFindexfromactivity)) != 0);
  23237. indexReadInputRecordVariable = indexReadMeta->isVariableSize();
  23238. }
  23239. virtual void serializeExtra(MemoryBuffer &out)
  23240. {
  23241. if (helper.getJoinFlags() & JFindexfromactivity)
  23242. {
  23243. assertex(rootIndex);
  23244. const RemoteActivityId& indexId = rootIndex->queryRemoteId();
  23245. indexId.serialize(out);
  23246. // could mess about reserving space for length then patching it again, to avoid copy, but probably not worth it
  23247. MemoryBuffer tmp;
  23248. rootIndex->queryActivity()->serializeCreateStartContext(tmp);
  23249. if (rootIndex->queryActivity()->queryVarFileInfo())
  23250. {
  23251. rootIndex->queryActivity()->queryVarFileInfo()->queryTimeStamp().serialize(tmp);
  23252. tmp.append(rootIndex->queryActivity()->queryVarFileInfo()->queryCheckSum());
  23253. }
  23254. unsigned ctxlen = tmp.length();
  23255. out.append(ctxlen).append(tmp);
  23256. }
  23257. }
  23258. virtual void onCreate(IHThorArg *_colocalParent)
  23259. {
  23260. CRoxieServerKeyedJoinBase::onCreate(_colocalParent);
  23261. indexReadAllocator.setown(ctx->queryCodeContext()->getRowAllocator(indexReadMeta, activityId));
  23262. IOutputMetaData *joinFieldsMeta = helper.queryJoinFieldsRecordSize();
  23263. joinPrefixedMeta.setown(new CPrefixedOutputMeta(KEYEDJOIN_RECORD_SIZE(0), joinFieldsMeta)); // MORE - not sure if we really need this
  23264. joinFieldsAllocator.setown(ctx->queryCodeContext()->getRowAllocator(joinPrefixedMeta, activityId));
  23265. }
  23266. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  23267. {
  23268. CRoxieServerKeyedJoinBase::start(parentExtractSize, parentExtract, paused);
  23269. if (rootIndex)
  23270. {
  23271. varFileInfo.setown(rootIndex->getVarFileInfo());
  23272. translators.setown(rootIndex->getTranslators());
  23273. keySet.setown(rootIndex->getKeySet());
  23274. }
  23275. else if (variableIndexFileName)
  23276. {
  23277. OwnedRoxieString indexFileName(helper.getIndexFileName());
  23278. varFileInfo.setown(resolveLFN(indexFileName, (helper.getJoinFlags() & JFindexoptional) != 0));
  23279. if (varFileInfo)
  23280. {
  23281. translators.setown(new TranslatorArray);
  23282. keySet.setown(varFileInfo->getKeyArray(factory->queryActivityMeta(), translators, false, isLocal ? factory->queryQueryFactory().queryChannel() : 0, factory->queryQueryFactory().queryOptions().enableFieldTranslation));
  23283. }
  23284. }
  23285. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().keyedJoinPreload, isSimple, ctx);
  23286. }
  23287. virtual const IResolvedFile *queryVarFileInfo() const
  23288. {
  23289. return varFileInfo;
  23290. }
  23291. virtual void reset()
  23292. {
  23293. CRoxieServerKeyedJoinBase::reset();
  23294. if (varFileInfo)
  23295. {
  23296. keySet.clear();
  23297. varFileInfo.clear();
  23298. }
  23299. }
  23300. virtual void processRow(const void *row)
  23301. {
  23302. // called from front puller thread
  23303. // buffer up an IndexRead request
  23304. if (helper.leftCanMatch(row) && keySet)
  23305. {
  23306. RtlDynamicRowBuilder extractBuilder(indexReadAllocator);
  23307. unsigned indexReadRecordSize = helper.extractIndexReadFields(extractBuilder, row);
  23308. OwnedConstRoxieRow extracted;
  23309. if (indexReadRecordSize)
  23310. extracted.setown(extractBuilder.finalizeRowClear(indexReadRecordSize));
  23311. CJoinGroup *jg = createJoinGroup(row);
  23312. for (unsigned partNo = 0; partNo < keySet->length(); partNo++)
  23313. {
  23314. IKeyIndexBase *thisBase = keySet->queryKeyPart(partNo);
  23315. if (thisBase)
  23316. {
  23317. unsigned fileNo = 0;
  23318. IKeyIndex *thisKey = thisBase->queryPart(fileNo);
  23319. tlk->setKey(thisKey);
  23320. tlk->setLayoutTranslator(translators->item(fileNo));
  23321. helper.createSegmentMonitors(tlk, extracted);
  23322. if (rootIndex)
  23323. rootIndex->mergeSegmentMonitors(tlk);
  23324. tlk->finishSegmentMonitors();
  23325. try
  23326. {
  23327. tlk->reset();
  23328. loop
  23329. {
  23330. typedef const void * cvp;
  23331. if (thisKey && thisKey->isTopLevelKey())
  23332. {
  23333. bool locallySorted = (!thisKey->isFullySorted());
  23334. while (locallySorted || tlk->lookup(false))
  23335. {
  23336. unsigned slavePart = locallySorted ? 0 : (unsigned) tlk->queryFpos();
  23337. if (locallySorted || slavePart)
  23338. {
  23339. cvp *outputBuffer = (cvp *) remote.getMem(slavePart, fileNo, indexReadRecordSize + sizeof(cvp) + (indexReadInputRecordVariable ? sizeof(unsigned) : 0));
  23340. *outputBuffer++ = jg;
  23341. if (indexReadInputRecordVariable)
  23342. {
  23343. *(unsigned *) outputBuffer = indexReadRecordSize;
  23344. outputBuffer = (cvp *) (((unsigned *) outputBuffer) + 1);
  23345. }
  23346. jg->notePending();
  23347. memcpy(outputBuffer, extracted, indexReadRecordSize);
  23348. if (locallySorted)
  23349. {
  23350. for (unsigned i = 1; i < numChannels; i++)
  23351. jg->notePending();
  23352. break;
  23353. }
  23354. }
  23355. }
  23356. }
  23357. else
  23358. {
  23359. unsigned accepted = 0;
  23360. unsigned rejected = 0;
  23361. Owned<CRowArrayMessageResult> result;
  23362. if (!isSimple)
  23363. result.setown(new CRowArrayMessageResult(ctx->queryRowManager(), true));
  23364. // MORE - This code seems to be duplicated in keyedJoinHead
  23365. jg->notePending();
  23366. unsigned candidateCount = 0;
  23367. while (tlk->lookup(true))
  23368. {
  23369. candidateCount++;
  23370. atomic_inc(&indexRecordsRead);
  23371. KLBlobProviderAdapter adapter(tlk);
  23372. offset_t recptr;
  23373. const byte *indexRow = tlk->queryKeyBuffer(recptr);
  23374. if (helper.indexReadMatch(extracted, indexRow, recptr, &adapter))
  23375. {
  23376. RtlDynamicRowBuilder rb(joinFieldsAllocator, true);
  23377. CPrefixedRowBuilder pb(KEYEDJOIN_RECORD_SIZE(0), rb);
  23378. accepted++;
  23379. KLBlobProviderAdapter adapter(tlk);
  23380. size32_t joinFieldsSize = helper.extractJoinFields(pb, indexRow, recptr, &adapter);
  23381. KeyedJoinHeader *rec = (KeyedJoinHeader *) rb.getUnfinalizedClear(); // lack of finalize ok as unserialized data here.
  23382. rec->fpos = recptr;
  23383. rec->thisGroup = jg;
  23384. rec->partNo = partNo;
  23385. if (isSimple)
  23386. remote.injected.enqueue(rec);
  23387. else
  23388. result->append(rec);
  23389. }
  23390. else
  23391. {
  23392. rejected++;
  23393. atomic_inc(&postFiltered);
  23394. }
  23395. }
  23396. // output an end marker for the matches to this group
  23397. KeyedJoinHeader *rec = (KeyedJoinHeader *) ctx->queryRowManager().allocate(KEYEDJOIN_RECORD_SIZE(0), activityId);
  23398. rec->fpos = (offset_t) candidateCount;
  23399. rec->thisGroup = jg;
  23400. rec->partNo = (unsigned short) -1;
  23401. if (isSimple)
  23402. remote.injected.enqueue(rec);
  23403. else
  23404. {
  23405. result->append(rec);
  23406. remote.injectResult(result.getClear());
  23407. }
  23408. if (accepted)
  23409. noteStatistic(StNumIndexAccepted, accepted);
  23410. if (rejected)
  23411. noteStatistic(StNumIndexRejected, rejected);
  23412. }
  23413. if (++fileNo < thisBase->numParts())
  23414. {
  23415. thisKey = thisBase->queryPart(fileNo);
  23416. tlk->setKey(thisKey);
  23417. tlk->setLayoutTranslator(translators->item(fileNo));
  23418. tlk->reset();
  23419. }
  23420. else
  23421. break;
  23422. }
  23423. tlk->releaseSegmentMonitors();
  23424. tlk->setKey(NULL);
  23425. }
  23426. catch (...)
  23427. {
  23428. tlk->releaseSegmentMonitors();
  23429. tlk->setKey(NULL);
  23430. throw;
  23431. }
  23432. }
  23433. }
  23434. noteEndReceived(jg, 0);
  23435. }
  23436. else
  23437. {
  23438. noteEndReceived(createJoinGroup(row), 0);
  23439. }
  23440. }
  23441. virtual void processEOG()
  23442. {
  23443. // called from front puller thread
  23444. if (preserveGroups)
  23445. endGroup();
  23446. }
  23447. void processGroup(const ConstPointerArray &)
  23448. {
  23449. throwUnexpected();
  23450. }
  23451. };
  23452. class CRoxieServerKeyedJoinActivityFactory : public CRoxieServerMultiInputFactory
  23453. {
  23454. Owned<const IResolvedFile> indexfile;
  23455. Owned<const IResolvedFile> datafile;
  23456. Owned<IKeyArray> keySet;
  23457. Owned<TranslatorArray> translatorArray;
  23458. Owned<IDefRecordMeta> activityMeta;
  23459. RemoteActivityId headId;
  23460. RemoteActivityId tailId;
  23461. IOutputMetaData *indexReadMeta;
  23462. Owned<IFilePartMap> map;
  23463. Owned<IFileIOArray> files;
  23464. unsigned joinFlags;
  23465. bool isHalfKeyed;
  23466. bool isLocal;
  23467. bool enableFieldTranslation;
  23468. bool variableFetchFileName;
  23469. bool variableIndexFileName;
  23470. bool isSimple;
  23471. public:
  23472. CRoxieServerKeyedJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_headId, const RemoteActivityId &_tailId)
  23473. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), headId(_headId), tailId(_tailId)
  23474. {
  23475. Owned<IHThorKeyedJoinArg> helper = (IHThorKeyedJoinArg *) helperFactory();
  23476. isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  23477. isSimple = isLocal;
  23478. rtlDataAttr indexLayoutMeta;
  23479. size32_t indexLayoutSize;
  23480. if(!helper->getIndexLayout(indexLayoutSize, indexLayoutMeta.refdata()))
  23481. assertex(indexLayoutSize== 0);
  23482. MemoryBuffer m;
  23483. m.setBuffer(indexLayoutSize, indexLayoutMeta.getdata());
  23484. activityMeta.setown(deserializeRecordMeta(m, true));
  23485. enableFieldTranslation = queryFactory.queryOptions().enableFieldTranslation;
  23486. translatorArray.setown(new TranslatorArray);
  23487. joinFlags = helper->getJoinFlags();
  23488. variableIndexFileName = allFilesDynamic || _queryFactory.isDynamic() || ((joinFlags & (JFvarindexfilename|JFdynamicindexfilename|JFindexfromactivity)) != 0);
  23489. variableFetchFileName = allFilesDynamic || _queryFactory.isDynamic() || ((helper->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  23490. if (!variableIndexFileName)
  23491. {
  23492. bool isOpt = (joinFlags & JFindexoptional) != 0;
  23493. OwnedRoxieString indexFileName(helper->getIndexFileName());
  23494. indexfile.setown(queryFactory.queryPackage().lookupFileName(indexFileName, isOpt, true, true, queryFactory.queryWorkUnit(), true));
  23495. if (indexfile)
  23496. keySet.setown(indexfile->getKeyArray(activityMeta, translatorArray, isOpt, isLocal ? queryFactory.queryChannel() : 0, enableFieldTranslation));
  23497. }
  23498. if (keySet && keySet->length()==1 && !isSimple)
  23499. {
  23500. IKeyIndexBase *thisBase = keySet->queryKeyPart(0);
  23501. if (thisBase->numParts()==1 && !thisBase->queryPart(0)->isTopLevelKey() && !_queryFactory.queryOptions().disableLocalOptimizations)
  23502. isSimple = true;
  23503. // MORE - if it's a variable filename then it MAY be simple, we don't know. Tough.
  23504. }
  23505. if (!simpleLocalKeyedJoins)
  23506. isSimple = false;
  23507. isHalfKeyed = !helper->diskAccessRequired();
  23508. indexReadMeta = QUERYINTERFACE(helper->queryIndexReadInputRecordSize(), IOutputMetaData);
  23509. if (!isHalfKeyed && !variableFetchFileName)
  23510. {
  23511. bool isFetchOpt = (helper->getFetchFlags() & FFdatafileoptional) != 0;
  23512. datafile.setown(_queryFactory.queryPackage().lookupFileName(queryNodeFileName(_graphNode, _kind), isFetchOpt, true, true, _queryFactory.queryWorkUnit(), true));
  23513. if (datafile)
  23514. {
  23515. if (isLocal)
  23516. files.setown(datafile->getIFileIOArray(isFetchOpt, queryFactory.queryChannel()));
  23517. else
  23518. map.setown(datafile->getFileMap());
  23519. }
  23520. }
  23521. }
  23522. virtual bool getEnableFieldTranslation() const
  23523. {
  23524. return enableFieldTranslation;
  23525. }
  23526. virtual IDefRecordMeta *queryActivityMeta() const
  23527. {
  23528. return activityMeta;
  23529. }
  23530. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  23531. {
  23532. if (isHalfKeyed)
  23533. return new CRoxieServerHalfKeyedJoinActivity(_ctx, this, _probeManager,
  23534. headId, keySet, translatorArray, indexReadMeta, joinFlags, isSimple, isLocal);
  23535. else
  23536. return new CRoxieServerKeyedJoinActivity(_ctx, this, _probeManager,
  23537. headId, keySet, translatorArray, indexReadMeta,
  23538. tailId, map, joinFlags, isLocal);
  23539. }
  23540. virtual const StatisticsMapping &queryStatsMapping() const
  23541. {
  23542. return keyedJoinStatistics;
  23543. }
  23544. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  23545. {
  23546. if (datafile)
  23547. addXrefFileInfo(reply, datafile);
  23548. if (indexfile)
  23549. addXrefFileInfo(reply, indexfile);
  23550. }
  23551. };
  23552. IRoxieServerActivityFactory *createRoxieServerKeyedJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId, const RemoteActivityId &_remoteId2)
  23553. {
  23554. return new CRoxieServerKeyedJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId, _remoteId2);
  23555. }
  23556. //=================================================================================
  23557. class CRoxieServerSoapActivityBase : public CRoxieServerActivity, implements ISoapCallRowProvider, implements IRoxieAbortMonitor
  23558. {
  23559. protected:
  23560. Owned<ISoapCallHelper> soaphelper;
  23561. IHThorSoapActionArg & helper;
  23562. StringBuffer authToken;
  23563. bool eof;
  23564. CriticalSection crit;
  23565. ClientCertificate *pClientCert;
  23566. public:
  23567. IMPLEMENT_IINTERFACE;
  23568. CRoxieServerSoapActivityBase(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  23569. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorSoapActionArg &)basehelper)
  23570. {
  23571. eof = false;
  23572. if (clientCert.certificate.length() > 0 && clientCert.privateKey.length() > 0 && clientCert.passphrase.length() > 0)
  23573. pClientCert = &clientCert;
  23574. else
  23575. pClientCert = NULL;
  23576. }
  23577. // ISoapCallRowProvider
  23578. virtual IHThorSoapActionArg * queryActionHelper() { return &helper; };
  23579. virtual IHThorSoapCallArg * queryCallHelper() { return NULL; };
  23580. virtual const void * getNextRow() { return NULL; };
  23581. virtual void releaseRow(const void * r) { ReleaseRoxieRow(r); };
  23582. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  23583. {
  23584. eof = false;
  23585. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  23586. authToken.append(ctx->queryAuthToken());
  23587. }
  23588. virtual void reset()
  23589. {
  23590. // MORE - Shouldn't we make sure thread is stopped etc???
  23591. soaphelper.clear();
  23592. CRoxieServerActivity::reset();
  23593. }
  23594. // IRoxieAbortMonitor
  23595. virtual void checkForAbort() { checkAbort(); }
  23596. };
  23597. //---------------------------------------------------------------------------
  23598. class CRoxieServerSoapRowCallActivity : public CRoxieServerSoapActivityBase
  23599. {
  23600. IHThorSoapCallArg & callHelper;
  23601. public:
  23602. CRoxieServerSoapRowCallActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  23603. : CRoxieServerSoapActivityBase(_ctx, _factory, _probeManager), callHelper((IHThorSoapCallArg &)basehelper)
  23604. {
  23605. }
  23606. virtual IHThorSoapCallArg * queryCallHelper()
  23607. {
  23608. return &callHelper;
  23609. }
  23610. virtual bool needsAllocator() const { return true; }
  23611. virtual const void *nextRow()
  23612. {
  23613. ActivityTimer t(totalCycles, timeActivities);
  23614. if(eof) return NULL;
  23615. if (soaphelper == NULL)
  23616. {
  23617. if (factory->getKind()==TAKhttp_rowdataset)
  23618. soaphelper.setown(createHttpCallHelper(this, rowAllocator, authToken.str(), SCrow, pClientCert, *this, this));
  23619. else
  23620. soaphelper.setown(createSoapCallHelper(this, rowAllocator, authToken.str(), SCrow, pClientCert, *this, this));
  23621. soaphelper->start();
  23622. }
  23623. OwnedConstRoxieRow ret = soaphelper->getRow();
  23624. if (!ret)
  23625. {
  23626. eof = true;
  23627. return NULL;
  23628. }
  23629. ++processed;
  23630. return ret.getClear();
  23631. }
  23632. };
  23633. class CRoxieServerSoapRowCallActivityFactory : public CRoxieServerActivityFactory
  23634. {
  23635. public:
  23636. CRoxieServerSoapRowCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  23637. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  23638. {
  23639. }
  23640. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  23641. {
  23642. return new CRoxieServerSoapRowCallActivity(_ctx, this, _probeManager);
  23643. }
  23644. virtual const StatisticsMapping &queryStatsMapping() const
  23645. {
  23646. return soapStatistics;
  23647. }
  23648. };
  23649. IRoxieServerActivityFactory *createRoxieServerSoapRowCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  23650. {
  23651. return new CRoxieServerSoapRowCallActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  23652. }
  23653. //---------------------------------------------------------------------------
  23654. class CRoxieServerSoapRowActionActivity : public CRoxieServerSoapActivityBase
  23655. {
  23656. public:
  23657. CRoxieServerSoapRowActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  23658. : CRoxieServerSoapActivityBase(_ctx, _factory, _probeManager)
  23659. {}
  23660. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  23661. {
  23662. //MORE: parentExtract not passed to start - although shouldn't be a problem.
  23663. soaphelper.setown(createSoapCallHelper(this, NULL, ctx->queryAuthToken(), SCrow, pClientCert, *this, this));
  23664. soaphelper->start();
  23665. soaphelper->waitUntilDone();
  23666. IException *e = soaphelper->getError();
  23667. soaphelper.clear();
  23668. if (e)
  23669. throw e;
  23670. }
  23671. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  23672. {
  23673. return NULL;
  23674. }
  23675. virtual const void *nextRow()
  23676. {
  23677. throwUnexpected(); // I am nobody's input
  23678. }
  23679. };
  23680. class CRoxieServerSoapRowActionActivityFactory : public CRoxieServerActivityFactory
  23681. {
  23682. bool isRoot;
  23683. public:
  23684. CRoxieServerSoapRowActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  23685. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  23686. {
  23687. }
  23688. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  23689. {
  23690. return new CRoxieServerSoapRowActionActivity(_ctx, this, _probeManager);
  23691. }
  23692. virtual bool isSink() const
  23693. {
  23694. return isRoot;
  23695. }
  23696. virtual const StatisticsMapping &queryStatsMapping() const
  23697. {
  23698. return soapStatistics;
  23699. }
  23700. };
  23701. IRoxieServerActivityFactory *createRoxieServerSoapRowActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  23702. {
  23703. return new CRoxieServerSoapRowActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  23704. }
  23705. //---------------------------------------------------------------------------
  23706. class CRoxieServerSoapDatasetCallActivity : public CRoxieServerSoapActivityBase
  23707. {
  23708. IHThorSoapCallArg & callHelper;
  23709. public:
  23710. CRoxieServerSoapDatasetCallActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  23711. : CRoxieServerSoapActivityBase(_ctx, _factory, _probeManager), callHelper((IHThorSoapCallArg &)basehelper)
  23712. {
  23713. }
  23714. virtual IHThorSoapCallArg * queryCallHelper()
  23715. {
  23716. return &callHelper;
  23717. }
  23718. virtual const void *getNextRow()
  23719. {
  23720. CriticalBlock b(crit); // MORE - why ?
  23721. return inputStream->ungroupedNextRow();
  23722. }
  23723. virtual bool needsAllocator() const { return true; }
  23724. virtual const void *nextRow()
  23725. {
  23726. ActivityTimer t(totalCycles, timeActivities);
  23727. if(eof) return NULL;
  23728. if (soaphelper == NULL)
  23729. {
  23730. soaphelper.setown(createSoapCallHelper(this, rowAllocator, authToken.str(), SCdataset, pClientCert, *this, this));
  23731. soaphelper->start();
  23732. }
  23733. OwnedConstRoxieRow ret = soaphelper->getRow();
  23734. if (!ret)
  23735. {
  23736. eof = true;
  23737. return NULL;
  23738. }
  23739. ++processed;
  23740. return ret.getClear();
  23741. }
  23742. };
  23743. class CRoxieServerSoapDatasetCallActivityFactory : public CRoxieServerActivityFactory
  23744. {
  23745. public:
  23746. CRoxieServerSoapDatasetCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  23747. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  23748. {
  23749. }
  23750. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  23751. {
  23752. return new CRoxieServerSoapDatasetCallActivity(_ctx, this, _probeManager);
  23753. }
  23754. virtual const StatisticsMapping &queryStatsMapping() const
  23755. {
  23756. return soapStatistics;
  23757. }
  23758. };
  23759. IRoxieServerActivityFactory *createRoxieServerSoapDatasetCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  23760. {
  23761. return new CRoxieServerSoapDatasetCallActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  23762. }
  23763. //---------------------------------------------------------------------------
  23764. class CRoxieServerSoapDatasetActionActivity : public CRoxieServerSoapActivityBase
  23765. {
  23766. public:
  23767. CRoxieServerSoapDatasetActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  23768. : CRoxieServerSoapActivityBase(_ctx, _factory, _probeManager)
  23769. {}
  23770. virtual const void *getNextRow()
  23771. {
  23772. CriticalBlock b(crit); // MORE - Why?
  23773. const void *nextrec = inputStream->ungroupedNextRow();
  23774. if (nextrec)
  23775. processed++;
  23776. return nextrec;
  23777. }
  23778. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  23779. {
  23780. try
  23781. {
  23782. start(parentExtractSize, parentExtract, false);
  23783. soaphelper.setown(createSoapCallHelper(this, NULL, ctx->queryAuthToken(), SCdataset, pClientCert, *this, this));
  23784. soaphelper->start();
  23785. soaphelper->waitUntilDone();
  23786. IException *e = soaphelper->getError();
  23787. soaphelper.clear();
  23788. if (e)
  23789. throw e;
  23790. stop();
  23791. }
  23792. catch (IException *E)
  23793. {
  23794. ctx->notifyAbort(E);
  23795. abort();
  23796. throw;
  23797. }
  23798. catch(...)
  23799. {
  23800. Owned<IException> E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught at %s:%d", __FILE__, __LINE__);
  23801. ctx->notifyAbort(E);
  23802. abort();
  23803. throw;
  23804. }
  23805. }
  23806. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  23807. {
  23808. return NULL;
  23809. }
  23810. virtual const void *nextRow()
  23811. {
  23812. throwUnexpected(); // I am nobody's input
  23813. }
  23814. };
  23815. class CRoxieServerSoapDatasetActionActivityFactory : public CRoxieServerActivityFactory
  23816. {
  23817. bool isRoot;
  23818. public:
  23819. CRoxieServerSoapDatasetActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  23820. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  23821. {
  23822. }
  23823. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  23824. {
  23825. return new CRoxieServerSoapDatasetActionActivity(_ctx, this, _probeManager);
  23826. }
  23827. virtual bool isSink() const
  23828. {
  23829. return isRoot;
  23830. }
  23831. virtual const StatisticsMapping &queryStatsMapping() const
  23832. {
  23833. return soapStatistics;
  23834. }
  23835. };
  23836. IRoxieServerActivityFactory *createRoxieServerSoapDatasetActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  23837. {
  23838. return new CRoxieServerSoapDatasetActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  23839. }
  23840. //=====================================================================================================
  23841. class CGraphResults : public CInterface, implements IRoxieGraphResults
  23842. {
  23843. IArrayOf<IGraphResult> results;
  23844. CriticalSection cs;
  23845. IGraphResult & select(unsigned idx)
  23846. {
  23847. CriticalBlock procedure(cs);
  23848. if (idx >= results.ordinality())
  23849. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Error reading graph result %d before it is calculated", idx);
  23850. return results.item(idx);
  23851. }
  23852. public:
  23853. IMPLEMENT_IINTERFACE
  23854. void clear()
  23855. {
  23856. CriticalBlock procedure(cs);
  23857. results.kill();
  23858. }
  23859. virtual IEngineRowStream * createIterator(unsigned id)
  23860. {
  23861. return select(id).createIterator();
  23862. }
  23863. virtual void getLinkedResult(unsigned & count, byte * * & ret, unsigned id)
  23864. {
  23865. select(id).getLinkedResult(count, ret);
  23866. }
  23867. virtual void getDictionaryResult(unsigned & count, byte * * & ret, unsigned id)
  23868. {
  23869. select(id).getLinkedResult(count, ret);
  23870. }
  23871. virtual const void * getLinkedRowResult(unsigned id)
  23872. {
  23873. return select(id).getLinkedRowResult();
  23874. }
  23875. void setResult(unsigned id, IGraphResult * result)
  23876. {
  23877. CriticalBlock procedure(cs);
  23878. if (results.ordinality() <= id)
  23879. {
  23880. while (results.ordinality() < id)
  23881. results.append(*new CGraphResult);
  23882. results.append(*LINK(result));
  23883. }
  23884. else
  23885. results.replace(*LINK(result), id);
  23886. }
  23887. void appendResult(IGraphResult * result)
  23888. {
  23889. CriticalBlock procedure(cs);
  23890. results.append(*LINK(result));
  23891. }
  23892. };
  23893. //===================================================================================================================
  23894. class CPseudoArg : public CInterface, implements IHThorArg
  23895. {
  23896. public:
  23897. IMPLEMENT_IINTERFACE
  23898. virtual IOutputMetaData * queryOutputMeta() { return NULL; }
  23899. };
  23900. class CPseudoActivity : public CRoxieServerActivity
  23901. {
  23902. public:
  23903. CPseudoActivity(IRoxieSlaveContext *_ctx, IHThorArg & _helper) : CRoxieServerActivity(_ctx, _helper) {}
  23904. virtual const void *nextRow()
  23905. {
  23906. throwUnexpected(); // I am nobody's input
  23907. }
  23908. };
  23909. class CActivityGraph : public CInterface, implements IActivityGraph, implements IThorChildGraph, implements ILocalGraphEx, implements IRoxieServerChildGraph
  23910. {
  23911. protected:
  23912. class ActivityGraphSlaveContext : public IndirectSlaveContext
  23913. {
  23914. SpinLock abortLock;
  23915. bool aborted;
  23916. Owned<IException> exception;
  23917. public:
  23918. ActivityGraphSlaveContext(IRoxieSlaveContext *_ctx, const IRoxieContextLogger &_logctx) : IndirectSlaveContext(_ctx), logctx(_logctx), loopCounter(0), codeContext(NULL)
  23919. {
  23920. aborted = false;
  23921. }
  23922. // Note - we must track exceptions at the child level in case there is a CATCH in parent
  23923. virtual void notifyAbort(IException *E)
  23924. {
  23925. SpinBlock b(abortLock);
  23926. if (!aborted && QUERYINTERFACE(E, InterruptedSemaphoreException) == NULL)
  23927. {
  23928. aborted = true;
  23929. exception.set(E);
  23930. }
  23931. }
  23932. virtual void checkAbort()
  23933. {
  23934. if (aborted) // NOTE - don't bother getting lock before reading this (for speed) - a false read is very unlikely and not a problem
  23935. {
  23936. SpinBlock b(abortLock);
  23937. if (!exception)
  23938. exception.setown(MakeStringException(ROXIE_INTERNAL_ERROR, "Query was aborted"));
  23939. throw exception.getLink();
  23940. }
  23941. IndirectSlaveContext::checkAbort();
  23942. }
  23943. virtual ICodeContext *queryCodeContext()
  23944. {
  23945. return codeContext;
  23946. }
  23947. void setCodeContext(ICodeContext * _codeContext)
  23948. {
  23949. codeContext = _codeContext;
  23950. }
  23951. void setLoopCounter(unsigned _loopCounter)
  23952. {
  23953. loopCounter = _loopCounter;
  23954. }
  23955. virtual void noteChildGraph(unsigned id, IActivityGraph *childGraph)
  23956. {
  23957. childGraphs.setValue(id, childGraph);
  23958. }
  23959. virtual IActivityGraph * queryChildGraph(unsigned id)
  23960. {
  23961. if (queryTraceLevel() > 10)
  23962. CTXLOG("resolveChildGraph %d", id);
  23963. IActivityGraph *childGraph = childGraphs.getValue(id);
  23964. assertex(childGraph);
  23965. return childGraph;
  23966. }
  23967. // 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
  23968. virtual StringBuffer &getLogPrefix(StringBuffer &ret) const
  23969. {
  23970. logctx.getLogPrefix(ret);
  23971. if (loopCounter)
  23972. ret.appendf("{%u}", loopCounter);
  23973. return ret;
  23974. }
  23975. protected:
  23976. const IRoxieContextLogger &logctx;
  23977. unsigned loopCounter;
  23978. ICodeContext * codeContext;
  23979. MapXToMyClass<unsigned, unsigned, IActivityGraph> childGraphs;
  23980. } graphSlaveContext;
  23981. class ActivityGraphCodeContext : public IndirectCodeContext
  23982. {
  23983. public:
  23984. virtual IEclGraphResults * resolveLocalQuery(__int64 activityId)
  23985. {
  23986. if ((unsigned) activityId == container->queryId())
  23987. return container;
  23988. IActivityGraph * match = slaveContext->queryChildGraph((unsigned) activityId);
  23989. if (match)
  23990. return match->queryLocalGraph();
  23991. return IndirectCodeContext::resolveLocalQuery(activityId);
  23992. }
  23993. virtual IThorChildGraph * resolveChildQuery(__int64 activityId, IHThorArg * colocal)
  23994. {
  23995. IActivityGraph * match = slaveContext->queryChildGraph((unsigned) activityId);
  23996. return LINK(match->queryChildGraph());
  23997. }
  23998. virtual unsigned getGraphLoopCounter() const
  23999. {
  24000. return container->queryLoopCounter(); // only called if value is valid
  24001. }
  24002. void setContainer(IRoxieSlaveContext * _slaveContext, CActivityGraph * _container)
  24003. {
  24004. slaveContext = _slaveContext;
  24005. container = _container;
  24006. }
  24007. protected:
  24008. IRoxieSlaveContext * slaveContext;
  24009. CActivityGraph * container;
  24010. } graphCodeContext;
  24011. // NOTE - destructor order is significant - need to destroy graphCodeContext and graphSlaveContext last
  24012. IArrayOf<IRoxieServerActivity> activities;
  24013. IArrayOf<IRoxieProbe> probes;
  24014. IRoxieServerActivityCopyArray sinks;
  24015. StringAttr graphName;
  24016. Owned<CGraphResults> results;
  24017. CGraphResults graphLoopResults;
  24018. ActivityArray & graphDefinition;
  24019. CriticalSection evaluateCrit;
  24020. IProbeManager *probeManager;
  24021. unsigned id;
  24022. unsigned loopCounter;
  24023. public:
  24024. IMPLEMENT_IINTERFACE;
  24025. CActivityGraph(IRoxieSlaveContext *_ctx, const char *_graphName, unsigned _id, ActivityArray &x, IProbeManager *_probeManager, const IRoxieContextLogger &_logctx)
  24026. : probeManager(_probeManager), graphDefinition(x), graphName(_graphName), graphSlaveContext(_ctx, _logctx)
  24027. {
  24028. id = x.getLibraryGraphId();
  24029. if (!id)
  24030. id = _id;
  24031. loopCounter = 0;
  24032. graphSlaveContext.setCodeContext(&graphCodeContext);
  24033. graphCodeContext.setContainer(&graphSlaveContext, this);
  24034. }
  24035. ~CActivityGraph()
  24036. {
  24037. if (probeManager)
  24038. probeManager->deleteGraph((IArrayOf<IActivityBase>*)&activities, (IArrayOf<IInputBase>*)&probes);
  24039. }
  24040. virtual const char *queryName() const
  24041. {
  24042. return graphName.get();
  24043. }
  24044. virtual IRoxieServerActivity *queryActivity(unsigned _activityId)
  24045. {
  24046. unsigned idx = graphDefinition.recursiveFindActivityIndex(_activityId);
  24047. if (idx==NotFound)
  24048. return nullptr;
  24049. assertex(activities.isItem(idx));
  24050. IRoxieServerActivity *activity = &activities.item(idx);
  24051. if (activity->queryId() == _activityId)
  24052. return activity;
  24053. return activity->queryChildActivity(_activityId);
  24054. }
  24055. void createGraph(IRoxieSlaveContext *_ctx)
  24056. {
  24057. if (graphDefinition.isMultiInstance())
  24058. {
  24059. graphCodeContext.set(_ctx->queryCodeContext());
  24060. _ctx = &graphSlaveContext;
  24061. }
  24062. ForEachItemIn(idx, graphDefinition)
  24063. {
  24064. IRoxieServerActivityFactory &donor = graphDefinition.serverItem(idx);
  24065. IRoxieServerActivity &activity = *donor.createActivity(_ctx, probeManager);
  24066. activities.append(activity);
  24067. if (donor.isSink())
  24068. {
  24069. sinks.append(activity);
  24070. if (probeManager)
  24071. probeManager->noteSink(&activity);
  24072. }
  24073. }
  24074. ForEachItemIn(idx1, graphDefinition)
  24075. {
  24076. IRoxieServerActivityFactory &donor = graphDefinition.serverItem(idx1);
  24077. IRoxieServerActivity &activity = activities.item(idx1);
  24078. unsigned inputidx = 0;
  24079. loop
  24080. {
  24081. unsigned outputidx;
  24082. unsigned source = donor.getInput(inputidx, outputidx);
  24083. if (source==(unsigned) -1)
  24084. break;
  24085. connectInput(idx1, inputidx, source, outputidx, 0);
  24086. inputidx++;
  24087. }
  24088. IntArray &dependencies = donor.queryDependencies();
  24089. IntArray &dependencyIndexes = donor.queryDependencyIndexes();
  24090. IntArray &dependencyControlIds = donor.queryDependencyControlIds();
  24091. StringArray &dependencyEdgeIds = donor.queryDependencyEdgeIds();
  24092. ForEachItemIn(idx2, dependencies)
  24093. {
  24094. IRoxieServerActivity &dependencySourceActivity = activities.item(dependencies.item(idx2));
  24095. unsigned dependencySourceIndex = dependencyIndexes.item(idx2);
  24096. unsigned dependencyControlId = dependencyControlIds.item(idx2);
  24097. activity.addDependency(dependencySourceActivity, dependencySourceIndex, dependencyControlId);
  24098. if (probeManager)
  24099. probeManager->noteDependency( &dependencySourceActivity, dependencySourceIndex, dependencyControlId, dependencyEdgeIds.item(idx2), &activity);
  24100. }
  24101. }
  24102. ForEachItemIn(idx2, sinks)
  24103. {
  24104. IRoxieServerActivity &sink = sinks.item(idx2);
  24105. sink.connectInputStreams(true);
  24106. }
  24107. }
  24108. void connectInput(unsigned target, unsigned targetIdx, unsigned source, unsigned sourceIdx, unsigned iteration)
  24109. {
  24110. IRoxieServerActivity &targetActivity = activities.item(target);
  24111. IRoxieServerActivity &sourceActivity = activities.item(source);
  24112. IFinalRoxieInput * output = sourceActivity.queryOutput(sourceIdx);
  24113. if (probeManager)
  24114. {
  24115. IRoxieProbe * inputProbe = probeManager->createProbe(static_cast<IInputBase*>(output), &sourceActivity, &targetActivity, sourceIdx, targetIdx, iteration);
  24116. probes.append(*LINK(inputProbe));
  24117. output = &dynamic_cast<IFinalRoxieInput &>(inputProbe->queryInput());
  24118. }
  24119. targetActivity.setInput(targetIdx, sourceIdx, output);
  24120. }
  24121. virtual void onCreate(IHThorArg *_colocalParent)
  24122. {
  24123. ForEachItemIn(idx, activities)
  24124. {
  24125. IRoxieServerActivity *activity = &activities.item(idx);
  24126. if (activity)
  24127. activity->onCreate(_colocalParent);
  24128. }
  24129. }
  24130. virtual void abort()
  24131. {
  24132. ForEachItemIn(idx, sinks)
  24133. {
  24134. IRoxieServerActivity &sink = sinks.item(idx);
  24135. sink.abort();
  24136. }
  24137. }
  24138. virtual void reset()
  24139. {
  24140. ForEachItemIn(idx, sinks)
  24141. {
  24142. IRoxieServerActivity &sink = sinks.item(idx);
  24143. sink.reset();
  24144. }
  24145. }
  24146. Linked<IException> exception;
  24147. CriticalSection eCrit;
  24148. virtual void noteException(IException *E)
  24149. {
  24150. CriticalBlock b(eCrit);
  24151. if (!exception)
  24152. {
  24153. if (graphSlaveContext.queryDebugContext())
  24154. {
  24155. graphSlaveContext.queryDebugContext()->checkBreakpoint(DebugStateException, NULL, exception);
  24156. }
  24157. exception.set(E);
  24158. }
  24159. }
  24160. virtual void checkAbort()
  24161. {
  24162. CriticalBlock b(eCrit);
  24163. if (exception)
  24164. throw exception.getLink();
  24165. }
  24166. virtual void execute()
  24167. {
  24168. results.setown(new CGraphResults);
  24169. doExecute(0, NULL);
  24170. }
  24171. //New child query code...
  24172. virtual IThorChildGraph * queryChildGraph()
  24173. {
  24174. return this;
  24175. }
  24176. virtual IEclGraphResults * queryLocalGraph()
  24177. {
  24178. return this;
  24179. }
  24180. virtual IRoxieServerChildGraph * queryLoopGraph()
  24181. {
  24182. return this;
  24183. }
  24184. inline unsigned queryId() const
  24185. {
  24186. return id;
  24187. }
  24188. inline unsigned queryLoopCounter() const
  24189. {
  24190. return loopCounter;
  24191. }
  24192. void doExecute(unsigned parentExtractSize, const byte * parentExtract)
  24193. {
  24194. if (sinks.ordinality()==1)
  24195. sinks.item(0).execute(parentExtractSize, parentExtract);
  24196. #ifdef PARALLEL_EXECUTE
  24197. else if (!probeManager && !graphDefinition.isSequential())
  24198. {
  24199. class casyncfor: public CAsyncFor
  24200. {
  24201. public:
  24202. IActivityGraph &parent;
  24203. unsigned parentExtractSize;
  24204. const byte * parentExtract;
  24205. casyncfor(IRoxieServerActivityCopyArray &_sinks, IActivityGraph &_parent, unsigned _parentExtractSize, const byte * _parentExtract) :
  24206. sinks(_sinks), parent(_parent), parentExtractSize(_parentExtractSize), parentExtract(_parentExtract) { }
  24207. void Do(unsigned i)
  24208. {
  24209. try
  24210. {
  24211. sinks.item(i).execute(parentExtractSize, parentExtract);
  24212. }
  24213. catch (IException *E)
  24214. {
  24215. parent.noteException(E);
  24216. throw;
  24217. }
  24218. }
  24219. private:
  24220. IRoxieServerActivityCopyArray &sinks;
  24221. } afor(sinks, *this, parentExtractSize, parentExtract);
  24222. afor.For(sinks.ordinality(), sinks.ordinality());
  24223. }
  24224. #endif
  24225. else
  24226. {
  24227. ForEachItemIn(idx, sinks)
  24228. {
  24229. IRoxieServerActivity &sink = sinks.item(idx);
  24230. sink.execute(parentExtractSize, parentExtract);
  24231. }
  24232. }
  24233. }
  24234. virtual IEclGraphResults *evaluate(unsigned parentExtractSize, const byte * parentExtract)
  24235. {
  24236. CriticalBlock block(evaluateCrit);
  24237. results.setown(new CGraphResults);
  24238. try
  24239. {
  24240. doExecute(parentExtractSize, parentExtract);
  24241. }
  24242. catch (...)
  24243. {
  24244. DBGLOG("Exception thrown in child query - cleaning up");
  24245. reset();
  24246. throw;
  24247. }
  24248. reset();
  24249. return results.getClear();
  24250. }
  24251. //interface IRoxieServerChildGraph
  24252. virtual void beforeExecute()
  24253. {
  24254. results.setown(new CGraphResults);
  24255. }
  24256. virtual IFinalRoxieInput * startOutput(unsigned id, unsigned parentExtractSize, const byte *parentExtract, bool paused)
  24257. {
  24258. IFinalRoxieInput * ret = selectOutput(id);
  24259. ret->start(parentExtractSize, parentExtract, paused);
  24260. return ret;
  24261. }
  24262. virtual IFinalRoxieInput * selectOutput(unsigned id)
  24263. {
  24264. ForEachItemIn(i, sinks)
  24265. {
  24266. IFinalRoxieInput * ret = sinks.item(i).querySelectOutput(id);
  24267. if (ret)
  24268. return ret;
  24269. }
  24270. throwUnexpected();
  24271. return NULL;
  24272. }
  24273. virtual void setInputResult(unsigned id, IGraphResult * result)
  24274. {
  24275. results->setResult(id, result);
  24276. }
  24277. virtual bool querySetInputResult(unsigned id, unsigned _sourceIdx, IFinalRoxieInput * input)
  24278. {
  24279. ForEachItemIn(i, activities)
  24280. {
  24281. if (activities.item(i).querySetStreamInput(id, _sourceIdx, input))
  24282. return true;
  24283. }
  24284. return false;
  24285. }
  24286. virtual void stopUnusedOutputs()
  24287. {
  24288. //Hmm not sure how to do this...
  24289. }
  24290. virtual void afterExecute()
  24291. {
  24292. ForEachItemIn(i, sinks)
  24293. {
  24294. sinks.item(i).stop();
  24295. }
  24296. if (graphSlaveContext.queryDebugContext())
  24297. {
  24298. graphSlaveContext.queryDebugContext()->checkBreakpoint(DebugStateGraphFinished, NULL, NULL);
  24299. }
  24300. reset();
  24301. }
  24302. virtual IRoxieGraphResults * execute(size32_t parentExtractSize, const byte *parentExtract)
  24303. {
  24304. doExecute(parentExtractSize, parentExtract);
  24305. return LINK(results);
  24306. }
  24307. virtual void getLinkedResult(unsigned & count, byte * * & ret, unsigned id)
  24308. {
  24309. results->getLinkedResult(count, ret, id);
  24310. }
  24311. virtual void getDictionaryResult(unsigned & count, byte * * & ret, unsigned id)
  24312. {
  24313. results->getLinkedResult(count, ret, id);
  24314. }
  24315. virtual const void * getLinkedRowResult(unsigned id)
  24316. {
  24317. return results->getLinkedRowResult(id);
  24318. }
  24319. virtual void setResult(unsigned id, IGraphResult * result)
  24320. {
  24321. results->setResult(id, result);
  24322. }
  24323. virtual IEngineRowStream * createResultIterator(unsigned id)
  24324. {
  24325. return results->createIterator(id);
  24326. }
  24327. virtual void setGraphLoopResult(IGraphResult * result)
  24328. {
  24329. graphLoopResults.appendResult(result);
  24330. }
  24331. virtual IEngineRowStream * createGraphLoopResultIterator(unsigned id)
  24332. {
  24333. try
  24334. {
  24335. return graphLoopResults.createIterator(id);
  24336. }
  24337. catch (IException * e)
  24338. {
  24339. e->Release();
  24340. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Error reading graph result %d before it is calculated", id);
  24341. }
  24342. }
  24343. virtual void clearGraphLoopResults()
  24344. {
  24345. graphLoopResults.clear();
  24346. }
  24347. virtual void executeGraphLoop(size32_t parentExtractSize, const byte *parentExtract)
  24348. {
  24349. doExecute(parentExtractSize, parentExtract);
  24350. }
  24351. virtual void setGraphLoopResult(unsigned id, IGraphResult * result)
  24352. {
  24353. graphLoopResults.setResult(id, result);
  24354. }
  24355. virtual IEngineRowStream * getGraphLoopResult(unsigned id)
  24356. {
  24357. return graphLoopResults.createIterator(id);
  24358. }
  24359. virtual void getProbeResponse(IPropertyTree *query)
  24360. {
  24361. if (probeManager)
  24362. probeManager->getProbeResponse(query);
  24363. }
  24364. virtual IRoxieServerChildGraph * createGraphLoopInstance(IRoxieSlaveContext *ctx, unsigned loopCounter, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &logctx)
  24365. {
  24366. throwUnexpected();
  24367. }
  24368. virtual CGraphIterationInfo *selectGraphLoopOutput()
  24369. {
  24370. return NULL;
  24371. }
  24372. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor)
  24373. {
  24374. throwUnexpected();
  24375. }
  24376. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor)
  24377. {
  24378. throwUnexpected();
  24379. }
  24380. };
  24381. class CProxyActivityGraph : public CInterface, implements IActivityGraph, implements IThorChildGraph
  24382. {
  24383. public:
  24384. IMPLEMENT_IINTERFACE;
  24385. CProxyActivityGraph(IRoxieSlaveContext *_ctx, const char *_graphName, unsigned _id, ActivityArray &_graphDefinition, const IRoxieContextLogger &_logctx, unsigned _numParallel)
  24386. : ctx(_ctx), graphName(_graphName), id(_id), graphDefinition(_graphDefinition), logctx(_logctx), numParallel(_numParallel)
  24387. {
  24388. }
  24389. virtual void abort() { throwUnexpected(); }
  24390. virtual void reset() { throwUnexpected(); }
  24391. virtual void execute() { throwUnexpected(); }
  24392. virtual void getProbeResponse(IPropertyTree *query) { throwUnexpected(); }
  24393. virtual void onCreate(IHThorArg *_colocalArg)
  24394. {
  24395. colocalArg = _colocalArg;
  24396. }
  24397. virtual void noteException(IException *E) { throwUnexpected(); }
  24398. virtual void checkAbort() { throwUnexpected(); }
  24399. virtual IThorChildGraph * queryChildGraph() { return this; }
  24400. virtual IEclGraphResults * queryLocalGraph() { throwUnexpected(); }
  24401. virtual IRoxieServerChildGraph * queryLoopGraph() { throwUnexpected(); }
  24402. virtual IRoxieServerChildGraph * createGraphLoopInstance(IRoxieSlaveContext *ctx, unsigned loopCounter, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &logctx) { throwUnexpected(); }
  24403. virtual const char *queryName() const { throwUnexpected(); }
  24404. virtual IRoxieServerActivity *queryActivity(unsigned _activityId) { return nullptr; } // MORE - may need something here!?
  24405. virtual IEclGraphResults * evaluate(unsigned parentExtractSize, const byte * parentExtract)
  24406. {
  24407. Owned<CActivityGraph> realGraph;
  24408. {
  24409. CriticalBlock b(graphCrit);
  24410. if (stack.length())
  24411. realGraph.setown(&stack.popGet());
  24412. }
  24413. if (!realGraph)
  24414. {
  24415. realGraph.setown(new CActivityGraph(ctx, graphName, id, graphDefinition, NULL, logctx));
  24416. realGraph->createGraph(ctx);
  24417. realGraph->onCreate(colocalArg);
  24418. }
  24419. Owned<IEclGraphResults> results = realGraph->evaluate(parentExtractSize, parentExtract);
  24420. {
  24421. CriticalBlock b(graphCrit);
  24422. stack.append(*realGraph.getClear());
  24423. }
  24424. return results.getClear();
  24425. }
  24426. protected:
  24427. IRoxieSlaveContext *ctx;
  24428. StringAttr graphName;
  24429. unsigned id;
  24430. ActivityArray &graphDefinition;
  24431. const IRoxieContextLogger &logctx;
  24432. unsigned numParallel;
  24433. IHThorArg *colocalArg = nullptr;
  24434. CriticalSection graphCrit;
  24435. CIArrayOf<CActivityGraph> stack;
  24436. };
  24437. class CIterationActivityGraph : public CActivityGraph
  24438. {
  24439. IHThorArg * colocalParent;
  24440. unsigned fixedParentExtractSize;
  24441. const byte * fixedParentExtract;
  24442. unsigned graphOutputActivityIndex;
  24443. public:
  24444. CIterationActivityGraph(const char *_graphName, unsigned _id, ActivityArray &x, IProbeManager *_probeManager,
  24445. unsigned _loopCounter, IRoxieSlaveContext *_ctx, IHThorArg * _colocalParent, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &_logctx)
  24446. : CActivityGraph(_ctx, _graphName, _id, x, _probeManager, _logctx)
  24447. {
  24448. graphOutputActivityIndex = 0;
  24449. loopCounter = _loopCounter;
  24450. colocalParent = _colocalParent;
  24451. graphSlaveContext.setLoopCounter(loopCounter);
  24452. graphCodeContext.set(_ctx->queryCodeContext());
  24453. fixedParentExtractSize = parentExtractSize;
  24454. fixedParentExtract = parentExtract;
  24455. }
  24456. void createIterationGraph(IRoxieSlaveContext *_ctx)
  24457. {
  24458. Owned<IRoxieServerActivity> pseudoActivity = new CPseudoActivity(_ctx, *new CPseudoArg);
  24459. ForEachItemIn(idx1, graphDefinition)
  24460. activities.append(*LINK(pseudoActivity));
  24461. graphOutputActivityIndex = queryGraphOutputIndex();
  24462. recursiveCreateGraph(_ctx, graphOutputActivityIndex);
  24463. }
  24464. unsigned queryGraphOutputIndex() const
  24465. {
  24466. ForEachItemIn(i, graphDefinition)
  24467. if (graphDefinition.serverItem(i).getKind() == TAKgraphloopresultwrite)
  24468. return i;
  24469. throwUnexpected();
  24470. }
  24471. void recursiveCreateGraph(IRoxieSlaveContext *_ctx, unsigned whichActivity)
  24472. {
  24473. //Check to see if already created
  24474. IRoxieServerActivity & prevActivity = activities.item(whichActivity);
  24475. if (prevActivity.queryId() != 0)
  24476. {
  24477. prevActivity.noteOutputUsed(); //We need to patch up the number of outputs for splitters.
  24478. return;
  24479. }
  24480. IRoxieServerActivityFactory &donor = graphDefinition.serverItem(whichActivity);
  24481. IRoxieServerActivity * activity = NULL;
  24482. if (donor.isGraphInvariant())
  24483. {
  24484. ThorActivityKind kind = donor.getKind();
  24485. switch (kind)
  24486. {
  24487. case TAKif:
  24488. case TAKchildif:
  24489. case TAKcase:
  24490. case TAKchildcase: // MORE RKC->GH - what about FILTER with a graph-invariant condition and other latestart activities?
  24491. {
  24492. Owned<IHThorArg> helper = &donor.getHelper();
  24493. helper->onCreate(&graphCodeContext, colocalParent, NULL);
  24494. helper->onStart(fixedParentExtract, NULL);
  24495. unsigned branch;
  24496. switch (kind)
  24497. {
  24498. case TAKif: case TAKchildif:
  24499. branch = static_cast<IHThorIfArg *>(helper.get())->getCondition() ? 0 : 1;
  24500. break;
  24501. case TAKcase: case TAKchildcase:
  24502. branch = static_cast<IHThorCaseArg *>(helper.get())->getBranch();
  24503. if (branch >= donor.numInputs())
  24504. branch = donor.numInputs() - 1;
  24505. break;
  24506. default:
  24507. throwUnexpected();
  24508. }
  24509. helper.clear();
  24510. unsigned outputidx;
  24511. unsigned source = donor.getInput(branch, outputidx);
  24512. if (source ==(unsigned) -1)
  24513. activity = createRoxieServerNullActivity(&graphSlaveContext, &donor, probeManager);
  24514. else
  24515. activity = createRoxieServerPassThroughActivity(&graphSlaveContext, &donor, probeManager);
  24516. activities.replace(*activity, whichActivity);
  24517. activity->onCreate(colocalParent);
  24518. if (source ==(unsigned) -1)
  24519. return;
  24520. recursiveCreateGraph(_ctx, source);
  24521. connectInput(whichActivity, 0, source, outputidx, loopCounter);
  24522. break;
  24523. }
  24524. }
  24525. }
  24526. if (!activity)
  24527. {
  24528. activity = donor.createActivity(&graphSlaveContext, probeManager);
  24529. activities.replace(*activity, whichActivity);
  24530. activity->onCreate(colocalParent);
  24531. activity->resetOutputsUsed();
  24532. unsigned inputidx = 0;
  24533. loop
  24534. {
  24535. unsigned outputidx;
  24536. unsigned source = donor.getInput(inputidx, outputidx);
  24537. if (source==(unsigned) -1)
  24538. break;
  24539. recursiveCreateGraph(_ctx, source);
  24540. connectInput(whichActivity, inputidx, source, outputidx, loopCounter);
  24541. inputidx++;
  24542. }
  24543. }
  24544. IntArray &dependencies = donor.queryDependencies();
  24545. IntArray &dependencyIndexes = donor.queryDependencyIndexes();
  24546. IntArray &dependencyControlIds = donor.queryDependencyControlIds();
  24547. ForEachItemIn(idx2, dependencies)
  24548. {
  24549. unsigned input = dependencies.item(idx2);
  24550. recursiveCreateGraph(_ctx, input);
  24551. activity->addDependency(activities.item(input),dependencyIndexes.item(idx2),dependencyControlIds.item(idx2));
  24552. }
  24553. }
  24554. virtual CGraphIterationInfo *selectGraphLoopOutput()
  24555. {
  24556. IRoxieServerActivity &sourceActivity = activities.item(graphOutputActivityIndex);
  24557. IFinalRoxieInput *sourceInput = sourceActivity.queryOutput(0);
  24558. return new CGraphIterationInfo(&sourceActivity, sourceInput, 0, loopCounter);
  24559. }
  24560. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor)
  24561. {
  24562. ForEachItemIn(i, activities)
  24563. activities.item(i).gatherIterationUsage(processor, fixedParentExtractSize, fixedParentExtract);
  24564. }
  24565. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor)
  24566. {
  24567. ForEachItemIn(i, activities)
  24568. activities.item(i).associateIterationOutputs(processor, fixedParentExtractSize, fixedParentExtract, probeManager, probes);
  24569. }
  24570. };
  24571. class CDelayedActivityGraph : public CInterface, implements IActivityGraph
  24572. {
  24573. StringAttr graphName;
  24574. ActivityArray & graphDefinition;
  24575. IProbeManager *probeManager;
  24576. unsigned id;
  24577. IRoxieSlaveContext * ctx;
  24578. IHThorArg * colocalParent;
  24579. public:
  24580. IMPLEMENT_IINTERFACE;
  24581. CDelayedActivityGraph(const char *_graphName, unsigned _id, ActivityArray &x, IProbeManager *_probeManager)
  24582. : probeManager(_probeManager), graphDefinition(x)
  24583. {
  24584. graphName.set(_graphName);
  24585. id = _id;
  24586. ctx = NULL;
  24587. colocalParent = NULL;
  24588. }
  24589. virtual const char *queryName() const { return graphName.get(); }
  24590. virtual void abort() { throwUnexpected(); }
  24591. virtual void reset() { }
  24592. virtual void execute() { throwUnexpected(); }
  24593. virtual void getProbeResponse(IPropertyTree *query) { throwUnexpected(); }
  24594. virtual void noteException(IException *E) { throwUnexpected(); }
  24595. virtual void checkAbort() { throwUnexpected(); }
  24596. virtual IThorChildGraph * queryChildGraph() { throwUnexpected(); }
  24597. virtual IEclGraphResults * queryLocalGraph() { throwUnexpected(); }
  24598. virtual IRoxieServerChildGraph * queryLoopGraph() { throwUnexpected(); }
  24599. virtual IRoxieServerActivity *queryActivity(unsigned _activityId) { return nullptr; } // MORE - may need something here!?
  24600. virtual void onCreate(IHThorArg *_colocalParent)
  24601. {
  24602. colocalParent = _colocalParent;
  24603. }
  24604. virtual IRoxieServerChildGraph * createGraphLoopInstance(IRoxieSlaveContext *ctx, unsigned loopCounter, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &logctx)
  24605. {
  24606. Owned<CIterationActivityGraph> ret = new CIterationActivityGraph(graphName, id, graphDefinition, probeManager, loopCounter, ctx, colocalParent, parentExtractSize, parentExtract, logctx);
  24607. ret->createIterationGraph(ctx);
  24608. return ret.getClear();
  24609. }
  24610. };
  24611. IActivityGraph *createActivityGraph(IRoxieSlaveContext *ctx, const char *_graphName, unsigned id, ActivityArray &childFactories, IRoxieServerActivity *parentActivity, IProbeManager *_probeManager, const IRoxieContextLogger &_logctx, unsigned numParallel)
  24612. {
  24613. if (childFactories.isDelayed())
  24614. {
  24615. assertex(numParallel==1);
  24616. return new CDelayedActivityGraph(_graphName, id, childFactories, _probeManager);
  24617. }
  24618. else
  24619. {
  24620. if (numParallel==1 || _probeManager != nullptr)
  24621. {
  24622. Owned<IProbeManager> childProbe;
  24623. if (_probeManager)
  24624. childProbe.setown(_probeManager->startChildGraph(id, parentActivity));
  24625. Owned<CActivityGraph> ret = new CActivityGraph(ctx, _graphName, id, childFactories, childProbe, _logctx);
  24626. ret->createGraph(ctx);
  24627. if (_probeManager)
  24628. _probeManager->endChildGraph(childProbe, parentActivity);
  24629. return ret.getClear();
  24630. }
  24631. else
  24632. return new CProxyActivityGraph(ctx, _graphName, id, childFactories, _logctx, numParallel);
  24633. }
  24634. }
  24635. //================================================================================================================
  24636. #ifdef _USE_CPPUNIT
  24637. #include "unittests.hpp"
  24638. // 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...
  24639. #if _MSC_VER==1200
  24640. #undef protected
  24641. #endif
  24642. static const char *sortAlgorithm;
  24643. class TestMetaData : public CInterface, implements IOutputMetaData
  24644. {
  24645. public:
  24646. IMPLEMENT_IINTERFACE;
  24647. virtual size32_t getRecordSize(const void *) { return 10; }
  24648. virtual size32_t getMinRecordSize() const { return 10; }
  24649. virtual size32_t getFixedSize() const { return 10; }
  24650. virtual void toXML(const byte * self, IXmlWriter & out) {}
  24651. virtual unsigned getVersion() const { return OUTPUTMETADATA_VERSION; }
  24652. virtual unsigned getMetaFlags() { return 0; }
  24653. virtual void destruct(byte * self) {}
  24654. virtual IOutputRowSerializer * createDiskSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  24655. virtual IOutputRowDeserializer * createDiskDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  24656. virtual ISourceRowPrefetcher * createDiskPrefetcher(ICodeContext * ctx, unsigned activityId) { return NULL; }
  24657. virtual IOutputMetaData * querySerializedDiskMeta() { return NULL; }
  24658. virtual IOutputRowSerializer * createInternalSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  24659. virtual IOutputRowDeserializer * createInternalDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  24660. virtual void walkIndirectMembers(const byte * self, IIndirectMemberVisitor & visitor) {}
  24661. virtual IOutputMetaData * queryChildMeta(unsigned i) { return NULL; }
  24662. } testMeta;
  24663. class TestInput : public CInterface, implements IFinalRoxieInput, implements IEngineRowStream
  24664. {
  24665. char const * const *input;
  24666. IRoxieSlaveContext *ctx;
  24667. unsigned endSeen;
  24668. bool eof;
  24669. unsigned count;
  24670. ActivityTimeAccumulator totalCycles;
  24671. size32_t recordSize;
  24672. unsigned activityId;
  24673. public:
  24674. enum { STATEreset, STATEstarted, STATEstopped } state;
  24675. bool allRead;
  24676. unsigned repeat;
  24677. IMPLEMENT_IINTERFACE;
  24678. TestInput(IRoxieSlaveContext *_ctx, char const * const *_input)
  24679. {
  24680. ctx = _ctx;
  24681. input = _input;
  24682. count = 0;
  24683. eof = false;
  24684. allRead = false;
  24685. endSeen = 0;
  24686. recordSize = testMeta.getFixedSize();
  24687. state = STATEreset;
  24688. activityId = 1;
  24689. repeat = 0;
  24690. }
  24691. virtual IOutputMetaData * queryOutputMeta() const { return &testMeta; }
  24692. virtual void prestart(unsigned parentExtractSize, const byte *parentExtract)
  24693. {
  24694. ASSERT(state == STATEreset);
  24695. }
  24696. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  24697. {
  24698. ASSERT(state == STATEreset);
  24699. state = STATEstarted;
  24700. }
  24701. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  24702. {
  24703. streams.append(this);
  24704. return NULL;
  24705. }
  24706. virtual IRoxieServerActivity *queryActivity()
  24707. {
  24708. throwUnexpected();
  24709. }
  24710. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  24711. {
  24712. throwUnexpected();
  24713. }
  24714. virtual void stop()
  24715. {
  24716. state = STATEstopped;
  24717. }
  24718. virtual void reset()
  24719. {
  24720. ASSERT(state == STATEstopped);
  24721. eof = false; count = 0; endSeen = 0; allRead = false; state = STATEreset;
  24722. }
  24723. virtual void resetEOF()
  24724. {
  24725. throwUnexpected();
  24726. }
  24727. virtual void checkAbort() {}
  24728. virtual unsigned queryId() const { return activityId; };
  24729. virtual const void *nextRow()
  24730. {
  24731. ActivityTimer t(totalCycles, ctx->queryOptions().timeActivities);
  24732. ASSERT(state == STATEstarted);
  24733. ASSERT(allRead || !eof);
  24734. if (eof)
  24735. return NULL;
  24736. again:
  24737. const char *nextSource = input[count++];
  24738. if (nextSource)
  24739. {
  24740. endSeen = 0;
  24741. void *ret = ctx->queryRowManager().ALLOCATE(recordSize);
  24742. memset(ret, 0, recordSize);
  24743. strncpy((char *) ret, nextSource, recordSize);
  24744. return ret;
  24745. }
  24746. else if (repeat)
  24747. {
  24748. repeat--;
  24749. count = 0;
  24750. goto again;
  24751. }
  24752. else
  24753. {
  24754. endSeen++;
  24755. if (endSeen==2)
  24756. eof = true;
  24757. return NULL;
  24758. }
  24759. }
  24760. virtual bool nextGroup(ConstPointerArray & group)
  24761. {
  24762. const void * next;
  24763. while ((next = nextRow()) != NULL)
  24764. group.append(next);
  24765. if (group.ordinality())
  24766. return true;
  24767. return false;
  24768. }
  24769. virtual unsigned __int64 queryTotalCycles() const { return totalCycles.totalCycles; }
  24770. virtual unsigned __int64 queryLocalCycles() const { return totalCycles.totalCycles; }
  24771. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  24772. {
  24773. return NULL;
  24774. }
  24775. };
  24776. struct SortActivityTest : public ccdserver_hqlhelper::CThorSortArg {
  24777. public:
  24778. struct CompareClass : public ICompare {
  24779. virtual int docompare(const void * _left, const void * _right) const {
  24780. return memcmp(_left, _right, 5);
  24781. }
  24782. } compare;
  24783. virtual ICompare * queryCompare() { return &compare; }
  24784. virtual IOutputMetaData * queryOutputMeta()
  24785. {
  24786. return &testMeta;
  24787. }
  24788. virtual unsigned getAlgorithmFlags() { return TAFunstable; }
  24789. virtual const char * getAlgorithm() { return sortAlgorithm; }
  24790. };
  24791. extern "C" IHThorArg * sortActivityTestFactory() { return new SortActivityTest; }
  24792. struct MergeActivityTest : public ccdserver_hqlhelper::CThorMergeArg {
  24793. static bool isDedup;
  24794. public:
  24795. struct CompareClass : public ICompare {
  24796. virtual int docompare(const void * _left, const void * _right) const {
  24797. return memcmp(_left, _right, 5);
  24798. }
  24799. } compare;
  24800. virtual ICompare * queryCompare() { return &compare; }
  24801. virtual IOutputMetaData * queryOutputMeta()
  24802. {
  24803. return &testMeta;
  24804. }
  24805. virtual bool dedup() { return isDedup; }
  24806. };
  24807. bool MergeActivityTest::isDedup = false;
  24808. extern "C" IHThorArg * mergeActivityTestFactory() { return new MergeActivityTest; }
  24809. struct SplitActivityTest : public ccdserver_hqlhelper::CThorSplitArg {
  24810. public:
  24811. virtual unsigned numBranches() { return 2; }
  24812. virtual IOutputMetaData * queryOutputMeta()
  24813. {
  24814. return &testMeta;
  24815. }
  24816. };
  24817. extern "C" IHThorArg * splitActivityTestFactory() { return new SplitActivityTest; }
  24818. class CcdServerTest : public CppUnit::TestFixture
  24819. {
  24820. CPPUNIT_TEST_SUITE(CcdServerTest);
  24821. CPPUNIT_TEST(testSetup);
  24822. CPPUNIT_TEST(testHeapSort);
  24823. CPPUNIT_TEST(testQuickSort);
  24824. CPPUNIT_TEST(testMerge);
  24825. CPPUNIT_TEST(testMergeDedup);
  24826. CPPUNIT_TEST(testMiscellaneous);
  24827. CPPUNIT_TEST(testSplitter);
  24828. CPPUNIT_TEST(testCleanup);
  24829. CPPUNIT_TEST_SUITE_END();
  24830. protected:
  24831. SlaveContextLogger logctx;
  24832. Owned<const IQueryDll> queryDll;
  24833. Owned<IRoxiePackage> package;
  24834. Owned<IPropertyTree> stateInfo;
  24835. Owned<IQueryFactory> queryFactory;
  24836. Owned<IRoxieSlaveContext> ctx;
  24837. void testSetup()
  24838. {
  24839. selfTestMode = true;
  24840. roxiemem::setTotalMemoryLimit(false, true, false, 100 * 1024 * 1024, 0, NULL, NULL);
  24841. }
  24842. void testCleanup()
  24843. {
  24844. roxiemem::releaseRoxieHeap();
  24845. }
  24846. void init()
  24847. {
  24848. package.setown(createRoxiePackage(NULL, NULL));
  24849. queryDll.setown(createExeQueryDll("roxie"));
  24850. stateInfo.setown(createPTreeFromXMLString("<test memoryLimit='50000000'/>"));
  24851. queryFactory.setown(createServerQueryFactory("test", queryDll.getLink(), *package, stateInfo, false, false));
  24852. ctx.setown(createSlaveContext(queryFactory, logctx, NULL, false));
  24853. queryActiveTimer()->reset();
  24854. }
  24855. void testActivity(IRoxieServerActivity *activity, char const * const *input, char const * const *output)
  24856. {
  24857. testActivity(activity, input, NULL, output);
  24858. }
  24859. void testActivity(IRoxieServerActivity *activity, char const * const *input, char const * const *input2, char const * const *output, unsigned outputIdx = 0)
  24860. {
  24861. TestInput in(ctx, input);
  24862. TestInput in2(ctx, input2);
  24863. activity->setInput(0, 0, &in);
  24864. if (input2)
  24865. activity->setInput(1, 0, &in2);
  24866. IFinalRoxieInput *out = activity->queryOutput(outputIdx);
  24867. IEngineRowStream *outStream = connectSingleStream(ctx, out, outputIdx, true);
  24868. IOutputMetaData *meta = out->queryOutputMeta();
  24869. void *buf = alloca(meta->getFixedSize());
  24870. for (unsigned iteration = 0; iteration < 8; iteration++)
  24871. {
  24872. // 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)
  24873. // This should be true whether we read all, some, or none of the data.
  24874. // Should not matter if an activity is not started
  24875. if (iteration % 4 == 0)
  24876. activity->onCreate(NULL);
  24877. unsigned count = 0;
  24878. if (iteration % 4 != 3)
  24879. {
  24880. activity->start(0, NULL, false);
  24881. ASSERT(in.state == TestInput::STATEstarted);
  24882. ASSERT(!input2 || in2.state == TestInput::STATEstarted);
  24883. loop
  24884. {
  24885. const void *next = outStream->nextRow();
  24886. if (!next)
  24887. {
  24888. ASSERT(output[count++] == NULL);
  24889. next = outStream->nextRow();
  24890. if (!next)
  24891. {
  24892. ASSERT(output[count++] == NULL);
  24893. break;
  24894. }
  24895. }
  24896. ASSERT(output[count] != NULL);
  24897. unsigned outsize = meta->getRecordSize(next);
  24898. memset(buf, 0, outsize);
  24899. strncpy((char *) buf, output[count++], outsize);
  24900. ASSERT(memcmp(next, buf, outsize) == 0);
  24901. ReleaseRoxieRow(next);
  24902. if (iteration % 4 == 2)
  24903. break;
  24904. }
  24905. if (iteration % 4 != 2)
  24906. {
  24907. // Check that reading after end is harmless
  24908. in.allRead = true;
  24909. const void *next = outStream->nextRow();
  24910. ASSERT(next == NULL);
  24911. }
  24912. }
  24913. activity->stop();
  24914. ASSERT(in.state == TestInput::STATEstopped);
  24915. ASSERT(!input2 || in2.state == TestInput::STATEstopped);
  24916. activity->reset();
  24917. ASSERT(in.state == TestInput::STATEreset);
  24918. ASSERT(!input2 || in2.state == TestInput::STATEreset);
  24919. ctx->queryRowManager().reportLeaks();
  24920. ASSERT(ctx->queryRowManager().numPagesAfterCleanup(true) == 0);
  24921. }
  24922. }
  24923. void testSplitActivity(IRoxieServerActivityFactory *factory, char const * const *input, char const * const *output, unsigned numOutputs, unsigned repeat)
  24924. {
  24925. Owned <IRoxieServerActivity> activity = factory->createActivity(ctx, NULL);
  24926. TestInput in(ctx, input);
  24927. in.repeat = repeat;
  24928. activity->setInput(0, 0, &in);
  24929. ArrayOf<IFinalRoxieInput *> out;
  24930. for (unsigned i = 0; i < numOutputs; i++)
  24931. {
  24932. out.append(activity->queryOutput(i));
  24933. }
  24934. activity->onCreate(NULL);
  24935. class casyncfor: public CAsyncFor
  24936. {
  24937. public:
  24938. casyncfor(CcdServerTest *_parent, IRoxieServerActivity *_activity, ArrayOf<IFinalRoxieInput *> &_outputs, char const * const *_input, char const * const *_output, unsigned _repeat)
  24939. : parent(_parent), activity(_activity), outputs(_outputs), input(_input), output(_output), repeat(_repeat)
  24940. {}
  24941. void Do(unsigned i)
  24942. {
  24943. IFinalRoxieInput *out = outputs.item(i);
  24944. IEngineRowStream *outStream = connectSingleStream(NULL, out, 0, true);
  24945. out->start(0, NULL, false);
  24946. IOutputMetaData *meta = out->queryOutputMeta();
  24947. void *buf = alloca(meta->getFixedSize());
  24948. unsigned count = 0;
  24949. unsigned repeats = repeat;
  24950. loop
  24951. {
  24952. const void *next = outStream->nextRow();
  24953. if (!next)
  24954. {
  24955. ASSERT(repeats==0);
  24956. ASSERT(output[count++] == NULL);
  24957. next = outStream->nextRow();
  24958. if (!next)
  24959. {
  24960. ASSERT(output[count++] == NULL);
  24961. break;
  24962. }
  24963. }
  24964. if (output[count] == NULL && repeats)
  24965. {
  24966. repeats--;
  24967. count = 0;
  24968. }
  24969. ASSERT(output[count] != NULL);
  24970. unsigned outsize = meta->getRecordSize(next);
  24971. memset(buf, 0, outsize);
  24972. strncpy((char *) buf, output[count++], outsize);
  24973. ASSERT(memcmp(next, buf, outsize) == 0);
  24974. ReleaseRoxieRow(next);
  24975. }
  24976. outStream->stop();
  24977. }
  24978. private:
  24979. IRoxieServerActivity *activity;
  24980. ArrayOf<IFinalRoxieInput *> &outputs;
  24981. char const * const *input;
  24982. char const * const *output;
  24983. unsigned repeat;
  24984. CcdServerTest *parent;
  24985. } afor(this, activity, out, input, output, repeat);
  24986. afor.For(numOutputs, numOutputs);
  24987. ASSERT(in.state == TestInput::STATEstopped);
  24988. for (unsigned i2 = 0; i2 < numOutputs; i2++)
  24989. {
  24990. out.item(i2)->reset();
  24991. }
  24992. ASSERT(in.state == TestInput::STATEreset);
  24993. ctx->queryRowManager().reportLeaks();
  24994. ASSERT(ctx->queryRowManager().numPagesAfterCleanup(true) == 0);
  24995. }
  24996. static int compareFunc(const void *l, const void *r)
  24997. {
  24998. return strcmp(*(char **) l, *(char **) r);
  24999. }
  25000. void testSort(unsigned type)
  25001. {
  25002. init();
  25003. sortAlgorithm = NULL;
  25004. if (type==2)
  25005. sortAlgorithm = "heapSort";
  25006. else
  25007. sortAlgorithm = "quickSort";
  25008. DBGLOG("Testing %s activity", sortAlgorithm);
  25009. Owned<IPropertyTree> dummyNode = createPTree("node");
  25010. Owned <IRoxieServerActivityFactory> factory = createRoxieServerSortActivityFactory(1, 1, *queryFactory, sortActivityTestFactory, TAKsort, *dummyNode);
  25011. Owned <IRoxieServerActivity> activity = factory->createActivity(ctx, NULL);
  25012. const char * test[] = { NULL, NULL };
  25013. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  25014. const char * test54321[] = { "5", "4", "3", "2", "1", NULL, NULL };
  25015. const char * test11111[] = { "1", "1", "1", "1", "1", NULL, NULL };
  25016. const char * test11111_12345[] = { "1", "1", "1", "1", "1", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  25017. const char * test11111_54321[] = { "1", "1", "1", "1", "1", NULL, "5", "4", "3", "2", "1", NULL, NULL };
  25018. const char * test54321_54321[] = { "5", "4", "3", "2", "1", NULL, "5", "4", "3", "2", "1", NULL, NULL };
  25019. const char * test12345_12345[] = { "1", "2", "3", "4", "5", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  25020. testActivity(activity, test, test);
  25021. testActivity(activity, test12345, test12345);
  25022. testActivity(activity, test54321, test12345);
  25023. testActivity(activity, test11111, test11111);
  25024. testActivity(activity, test11111_12345, test11111_12345);
  25025. testActivity(activity, test11111_54321, test11111_12345);
  25026. testActivity(activity, test54321_54321, test12345_12345);
  25027. // A few larger tests
  25028. char *input[2002];
  25029. char *output[2002];
  25030. input[2000] = input[2001] = output[2000] = output[2001] = NULL;
  25031. unsigned i;
  25032. // identical
  25033. for (i=0; i<2000; i++)
  25034. {
  25035. input[i] = new char[11];
  25036. output[i] = new char[11];
  25037. sprintf(input[i], "1");
  25038. sprintf(output[i], "1");
  25039. }
  25040. testActivity(activity, input, output);
  25041. // Ascending
  25042. for (i=0; i<2000; i++)
  25043. {
  25044. sprintf(input[i], "%04d", i);
  25045. sprintf(output[i], "%04d", i);
  25046. }
  25047. testActivity(activity, input, output);
  25048. // Almost sorted
  25049. for (i=0; i<20; i++)
  25050. {
  25051. unsigned h = i*100;
  25052. sprintf(input[h], "%04d", 1900-h);
  25053. }
  25054. testActivity(activity, input, output);
  25055. // Descending
  25056. for (i=0; i<2000; i++)
  25057. {
  25058. sprintf(input[i], "%04d", 1999-i);
  25059. sprintf(output[i], "%04d", i);
  25060. }
  25061. testActivity(activity, input, output);
  25062. // Random
  25063. for (i=0; i<2000; i++)
  25064. {
  25065. unsigned r = rand() % 1500;
  25066. sprintf(input[i], "%04d", r);
  25067. sprintf(output[i], "%04d", r);
  25068. }
  25069. qsort(output, 2000, sizeof(output[0]), compareFunc);
  25070. testActivity(activity, input, output);
  25071. unsigned __int64 us = cycle_to_nanosec(factory->queryLocalCycles()/1000);
  25072. DBGLOG("Simple %s sorts: activity time %u.%u ms", type==2?"Heap" : (type==1 ? "Insertion" : "Quick"), (int)(us/1000), (int)(us%1000));
  25073. factory->resetNodeProgressInfo();
  25074. if (type)
  25075. {
  25076. // Other than quicksort, it's supposed to be stable. Let's check that it is
  25077. // All sort identical
  25078. for (i=0; i<2000; i++)
  25079. {
  25080. sprintf(input[i], "1 %d", i);
  25081. sprintf(output[i], "1 %d", i);
  25082. }
  25083. testActivity(activity, input, output);
  25084. // Already sorted
  25085. for (i=0; i<2000; i++)
  25086. {
  25087. sprintf(input[i], "%04d %d", i / 10, i);
  25088. sprintf(output[i], "%04d %d", i / 10, i);
  25089. }
  25090. testActivity(activity, input, output);
  25091. // Reverse order
  25092. for (i=0; i<2000; i++)
  25093. {
  25094. sprintf(input[i], "%04d %d", 199 - (i / 10), i%10);
  25095. sprintf(output[i], "%04d %d", i / 10, i%10);
  25096. }
  25097. testActivity(activity, input, output);
  25098. }
  25099. for (i=0; i<2000; i++)
  25100. {
  25101. delete [] input[i];
  25102. delete [] output[i];
  25103. }
  25104. DBGLOG("Finished testing %s sort", type==2?"Heap" : (type==1 ? "Insertion" : "Quick"));
  25105. }
  25106. void testQuickSort()
  25107. {
  25108. testSort(0);
  25109. }
  25110. void testHeapSort()
  25111. {
  25112. testSort(2);
  25113. }
  25114. void testMerge()
  25115. {
  25116. DBGLOG("testMerge");
  25117. init();
  25118. Owned<IPropertyTree> splitterNode = createPTree();
  25119. Owned <IRoxieServerActivityFactory> factory = createRoxieServerMergeActivityFactory(1, 1, *queryFactory, mergeActivityTestFactory, TAKmerge, *splitterNode);
  25120. factory->setInput(0,0,0);
  25121. factory->setInput(1,0,0);
  25122. Owned <IRoxieServerActivity> activity = factory->createActivity(ctx, NULL);
  25123. const char * test[] = { NULL, NULL };
  25124. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  25125. const char * test1122334455[] = { "1", "1", "2", "2", "3", "3", "4", "4", "5", "5", NULL, NULL };
  25126. const char * test11111[] = { "1", "1", "1", "1", "1", NULL, NULL };
  25127. const char * test1111111111[] = { "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", NULL, NULL };
  25128. const char * test11111_12345[] = { "1", "1", "1", "1", "1", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  25129. const char * test1111112345[] = { "1", "1", "1", "1", "1", "1", "2", "3", "4", "5", NULL, NULL };
  25130. 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 };
  25131. testActivity(activity, test, test, test);
  25132. testActivity(activity, test12345, test, test12345);
  25133. testActivity(activity, test, test12345, test12345);
  25134. testActivity(activity, test12345, test12345, test1122334455);
  25135. testActivity(activity, test11111, test, test11111);
  25136. testActivity(activity, test, test11111, test11111);
  25137. testActivity(activity, test11111, test11111, test1111111111);
  25138. testActivity(activity, test11111_12345, test, test1111112345);
  25139. testActivity(activity, test11111_12345, test11111_12345, test11111111111122334455);
  25140. // Should really test WHICH side gets kept...
  25141. // Should test with more than 2 inputs...
  25142. DBGLOG("testMerge done");
  25143. }
  25144. void testMergeDedup()
  25145. {
  25146. DBGLOG("testMergeDedup");
  25147. init();
  25148. MergeActivityTest::isDedup = true;
  25149. Owned<IPropertyTree> splitterNode = createPTree();
  25150. Owned <IRoxieServerActivityFactory> factory = createRoxieServerMergeActivityFactory(1, 1, *queryFactory, mergeActivityTestFactory, TAKmerge, *splitterNode);
  25151. factory->setInput(0,0,0);
  25152. factory->setInput(1,0,0);
  25153. Owned <IRoxieServerActivity> activity = factory->createActivity(ctx, NULL);
  25154. const char * test[] = { NULL, NULL };
  25155. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  25156. const char * test11111[] = { "1", "1", "1", "1", "1", NULL, NULL };
  25157. const char * test11111_12345[] = { "1", "1", "1", "1", "1", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  25158. const char * test1111112345[] = { "1", "1", "1", "1", "1", "1", "2", "3", "4", "5", NULL, NULL };
  25159. testActivity(activity, test11111, test, test11111); // No dedup within a stream
  25160. testActivity(activity, test11111, test11111, test11111); // No dedup within a stream
  25161. testActivity(activity, test, test11111, test11111);
  25162. testActivity(activity, test, test, test);
  25163. testActivity(activity, test12345, test, test12345);
  25164. testActivity(activity, test, test12345, test12345);
  25165. testActivity(activity, test12345, test12345, test12345);
  25166. testActivity(activity, test11111_12345, test, test1111112345);
  25167. testActivity(activity, test11111_12345, test11111_12345, test1111112345);
  25168. // Should really test WHICH side gets kept...
  25169. // Should test with more than 2 inputs...
  25170. DBGLOG("testMergeDedup done");
  25171. }
  25172. void doTestSplitter(unsigned numOutputs)
  25173. {
  25174. DBGLOG("testSplit %d", numOutputs);
  25175. init();
  25176. Owned<IPropertyTree> splitterNode = createPTree();
  25177. Owned <IRoxieServerActivityFactory> factory = createRoxieServerThroughSpillActivityFactory(*queryFactory, splitActivityTestFactory, numOutputs, *splitterNode);
  25178. factory->setInput(0,0,0);
  25179. Owned <IRoxieServerActivity> activity = factory->createActivity(ctx, NULL);
  25180. const char * test[] = { NULL, NULL };
  25181. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  25182. unsigned start = msTick();
  25183. testSplitActivity(factory, test, test, numOutputs, 0);
  25184. testSplitActivity(factory, test12345, test12345, numOutputs, 0);
  25185. testSplitActivity(factory, test12345, test12345, numOutputs, 100);
  25186. unsigned elapsed = msTick() - start;
  25187. DBGLOG("testSplit %d done in %dms", numOutputs, elapsed);
  25188. }
  25189. void testSplitter()
  25190. {
  25191. doTestSplitter(1);
  25192. doTestSplitter(2);
  25193. doTestSplitter(3);
  25194. doTestSplitter(10);
  25195. }
  25196. void testMiscellaneous()
  25197. {
  25198. DBGLOG("sizeof(CriticalSection)=%u", (unsigned) sizeof(CriticalSection));
  25199. DBGLOG("sizeof(SpinLock)=%u", (unsigned) sizeof(SpinLock));
  25200. DBGLOG("sizeof(CJoinGroup)=%u", (unsigned) sizeof(CJoinGroup));
  25201. ASSERT(sizeof(CJoinGroup) <= 120);
  25202. }
  25203. };
  25204. CPPUNIT_TEST_SUITE_REGISTRATION( CcdServerTest );
  25205. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( CcdServerTest, "CcdServerTest" );
  25206. #endif