ccdserver.cpp 995 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418
  1. /*##############################################################################
  2. HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems®.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. ############################################################################## */
  13. #include "jmisc.hpp"
  14. #include "jdebug.hpp"
  15. #include "jptree.hpp"
  16. #include "rtlkey.hpp"
  17. #include "jsort.hpp"
  18. #include "jhtree.hpp"
  19. #include "jqueue.tpp"
  20. #include "jisem.hpp"
  21. #include "thorxmlread.hpp"
  22. #include "thorrparse.ipp"
  23. #include "thorxmlwrite.hpp"
  24. #include "thorsoapcall.hpp"
  25. #include "thorcommon.ipp"
  26. #include "thorsort.hpp"
  27. #include "thorstats.hpp"
  28. #include "jlzw.hpp"
  29. #include "javahash.hpp"
  30. #include "javahash.tpp"
  31. #include "thorstep.ipp"
  32. #include "thorpipe.hpp"
  33. #include "thorfile.hpp"
  34. #include "eclhelper.hpp"
  35. #include "eclrtl_imp.hpp"
  36. #include "rtlfield.hpp"
  37. #include "rtlds_imp.hpp"
  38. #include "rtlread_imp.hpp"
  39. #include "rtlcommon.hpp"
  40. #include <algorithm>
  41. #include "dafdesc.hpp"
  42. #include "dautils.hpp"
  43. #include "ftbase.ipp"
  44. #include "eclhelper_base.hpp"
  45. #include "ccd.hpp"
  46. #include "ccdserver.hpp"
  47. #include "ccdcontext.hpp"
  48. #include "ccdactivities.hpp"
  49. #include "ccdquery.hpp"
  50. #include "ccdstate.hpp"
  51. #include "ccdqueue.ipp"
  52. #include "ccdsnmp.hpp"
  53. #include "ccddali.hpp"
  54. #include "jsmartsock.hpp"
  55. #include "dllserver.hpp"
  56. #include "workflow.hpp"
  57. #include "roxiemem.hpp"
  58. #include "roxierowbuff.hpp"
  59. #include "roxiehelper.hpp"
  60. #include "roxielmj.hpp"
  61. #include "roxierow.hpp"
  62. #include "thorplugin.hpp"
  63. #include "keybuild.hpp"
  64. #include "thorstrand.hpp"
  65. #include "rtldynfield.hpp"
  66. #define MAX_HTTP_HEADERSIZE 8000
  67. #define MIN_PAYLOAD_SIZE 800
  68. #pragma warning(disable : 4355)
  69. #define DEFAULT_PARALLEL_LOOP_THREADS 1
  70. #define PROBE
  71. #ifdef _DEBUG
  72. //#define FAKE_EXCEPTIONS
  73. //#define TRACE_JOINGROUPS
  74. //#define TRACE_SPLIT
  75. //#define _CHECK_HEAPSORT
  76. //#undef PARALLEL_EXECUTE
  77. //#define TRACE_SEEK_REQUESTS
  78. #endif
  79. using roxiemem::OwnedRoxieRow;
  80. using roxiemem::OwnedRoxieString;
  81. using roxiemem::OwnedConstRoxieRow;
  82. using roxiemem::IRowManager;
  83. using roxiemem::ReleaseRoxieRows;
  84. // 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...
  85. #if _MSC_VER==1200
  86. #define protected public
  87. #endif
  88. #define TRACE_STARTSTOP // This determines if it is available - it is enabled/disabled by a configuration option
  89. #define TRACE_STRANDS
  90. #define MAX_SENSIBLE_STRANDS 1024 // Architecture dependent...
  91. static const SmartStepExtra dummySmartStepExtra(SSEFreadAhead, NULL);
  92. //=================================================================================
  93. class RestartableThread : public CInterface
  94. {
  95. class MyThread : public Thread
  96. {
  97. Linked<RestartableThread> owner;
  98. public:
  99. MyThread(RestartableThread *_owner, const char *name) : Thread(name), owner(_owner)
  100. {
  101. }
  102. virtual int run()
  103. {
  104. owner->started.signal();
  105. return owner->run();
  106. }
  107. };
  108. friend class MyThread;
  109. Semaphore started;
  110. Owned<MyThread> thread;
  111. CriticalSection crit;
  112. StringAttr name;
  113. public:
  114. RestartableThread(const char *_name) : name(_name)
  115. {
  116. }
  117. virtual void start(const char *namePrefix)
  118. {
  119. StringBuffer s(namePrefix);
  120. s.append(name);
  121. {
  122. CriticalBlock b(crit);
  123. assertex(!thread);
  124. thread.setown(new MyThread(this, s));
  125. thread->start();
  126. }
  127. started.wait();
  128. }
  129. virtual void join()
  130. {
  131. {
  132. Owned<Thread> tthread;
  133. {
  134. CriticalBlock b(crit);
  135. tthread.setown(thread.getClear());
  136. }
  137. if (tthread)
  138. tthread->join();
  139. }
  140. }
  141. virtual int run() = 0;
  142. };
  143. //================================================================================
  144. //The following don't link their arguments because that creates a circular reference
  145. //But I wish there was a better way
  146. class IndirectSlaveContext : implements IRoxieSlaveContext, public CInterface
  147. {
  148. public:
  149. IndirectSlaveContext(IRoxieSlaveContext * _ctx) : ctx(_ctx) {}
  150. IMPLEMENT_IINTERFACE
  151. // void set(IRoxieSlaveContext * _ctx) { ctx = _ctx; }
  152. virtual ICodeContext *queryCodeContext()
  153. {
  154. return ctx->queryCodeContext();
  155. }
  156. virtual void checkAbort()
  157. {
  158. ctx->checkAbort();
  159. }
  160. virtual void notifyAbort(IException *E)
  161. {
  162. ctx->notifyAbort(E);
  163. }
  164. virtual IActivityGraph * queryChildGraph(unsigned id)
  165. {
  166. return ctx->queryChildGraph(id);
  167. }
  168. virtual void noteChildGraph(unsigned id, IActivityGraph *childGraph)
  169. {
  170. ctx->noteChildGraph(id, childGraph) ;
  171. }
  172. virtual IRowManager &queryRowManager()
  173. {
  174. return ctx->queryRowManager();
  175. }
  176. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value) const
  177. {
  178. ctx->noteStatistic(kind, value);
  179. }
  180. virtual void mergeStats(const CRuntimeStatisticCollection &from) const
  181. {
  182. ctx->mergeStats(from);
  183. }
  184. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  185. {
  186. ctx->gatherStats(merged);
  187. }
  188. virtual void CTXLOGva(const char *format, va_list args) const __attribute__((format(printf,2,0)))
  189. {
  190. ctx->CTXLOGva(format, args);
  191. }
  192. virtual void CTXLOGa(TracingCategory category, const char *prefix, const char *text) const
  193. {
  194. ctx->CTXLOGa(category, prefix, text);
  195. }
  196. virtual void logOperatorExceptionVA(IException *E, const char *file, unsigned line, const char *format, va_list args) const __attribute__((format(printf,5,0)))
  197. {
  198. ctx->logOperatorExceptionVA(E, file, line, format, args);
  199. }
  200. 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)))
  201. {
  202. ctx->CTXLOGaeva(E, file, line, prefix, format, args);
  203. }
  204. virtual void CTXLOGl(LogItem *log) const
  205. {
  206. ctx->CTXLOGl(log);
  207. }
  208. virtual StringBuffer &getLogPrefix(StringBuffer &ret) const
  209. {
  210. return ctx->getLogPrefix(ret);
  211. }
  212. virtual unsigned queryTraceLevel() const
  213. {
  214. return ctx->queryTraceLevel();
  215. }
  216. virtual bool isIntercepted() const
  217. {
  218. return ctx->isIntercepted();
  219. }
  220. virtual bool isBlind() const
  221. {
  222. return ctx->isBlind();
  223. }
  224. virtual void setGlobalId(const char *id, SocketEndpoint &ep, unsigned pid)
  225. {
  226. ctx->setGlobalId(id, ep, pid);
  227. }
  228. virtual const char *queryGlobalId() const
  229. {
  230. return ctx->queryGlobalId();
  231. }
  232. virtual const char *queryLocalId() const
  233. {
  234. return ctx->queryLocalId();
  235. }
  236. virtual void setHttpIdHeaders(const char *global, const char *caller)
  237. {
  238. ctx->setHttpIdHeaders(global, caller);
  239. }
  240. virtual const char *queryGlobalIdHttpHeader() const
  241. {
  242. return ctx->queryGlobalIdHttpHeader();
  243. }
  244. virtual const char *queryCallerIdHttpHeader() const
  245. {
  246. return ctx->queryCallerIdHttpHeader();
  247. }
  248. virtual const QueryOptions &queryOptions() const
  249. {
  250. return ctx->queryOptions();
  251. }
  252. virtual void addSlavesReplyLen(unsigned len)
  253. {
  254. ctx->addSlavesReplyLen(len);
  255. }
  256. virtual const char *queryAuthToken()
  257. {
  258. return ctx->queryAuthToken();
  259. }
  260. virtual const IResolvedFile *resolveLFN(const char *filename, bool isOpt)
  261. {
  262. return ctx->resolveLFN(filename, isOpt);
  263. }
  264. virtual IRoxieWriteHandler *createLFN(const char *filename, bool overwrite, bool extend, const StringArray &clusters)
  265. {
  266. return ctx->createLFN(filename, overwrite, extend, clusters);
  267. }
  268. virtual void onFileCallback(const RoxiePacketHeader &header, const char *lfn, bool isOpt, bool isLocal)
  269. {
  270. ctx->onFileCallback(header, lfn, isOpt, isLocal);
  271. }
  272. virtual IActivityGraph *getLibraryGraph(const LibraryCallFactoryExtra &extra, IRoxieServerActivity *parentActivity)
  273. {
  274. return ctx->getLibraryGraph(extra, parentActivity);
  275. }
  276. virtual void noteProcessed(unsigned subgraphId, unsigned activityId, unsigned _idx, unsigned _processed, unsigned _strands) const
  277. {
  278. ctx->noteProcessed(subgraphId, activityId, _idx, _processed, _strands);
  279. }
  280. virtual void mergeActivityStats(const CRuntimeStatisticCollection &fromStats, unsigned subgraphId, unsigned activityId) const
  281. {
  282. ctx->mergeActivityStats(fromStats, subgraphId, activityId);
  283. }
  284. virtual IProbeManager *queryProbeManager() const
  285. {
  286. return ctx->queryProbeManager();
  287. }
  288. virtual IDebuggableContext *queryDebugContext() const
  289. {
  290. return ctx->queryDebugContext();
  291. }
  292. virtual void printResults(IXmlWriter *output, const char *name, unsigned sequence)
  293. {
  294. ctx->printResults(output, name, sequence);
  295. }
  296. virtual void setWUState(WUState state)
  297. {
  298. ctx->setWUState(state);
  299. }
  300. virtual bool checkWuAborted()
  301. {
  302. return ctx->checkWuAborted();
  303. }
  304. virtual IWorkUnit *updateWorkUnit() const
  305. {
  306. return ctx->updateWorkUnit();
  307. }
  308. virtual IConstWorkUnit *queryWorkUnit() const
  309. {
  310. return ctx->queryWorkUnit();
  311. }
  312. virtual IRoxieServerContext *queryServerContext()
  313. {
  314. return ctx->queryServerContext();
  315. }
  316. virtual IWorkUnitRowReader *getWorkunitRowReader(const char *wuid, const char * name, unsigned sequence, IXmlToRowTransformer * xmlTransformer, IEngineRowAllocator *rowAllocator, bool isGrouped)
  317. {
  318. return ctx->getWorkunitRowReader(wuid, name, sequence, xmlTransformer, rowAllocator, isGrouped);
  319. }
  320. virtual IEngineRowAllocator *getRowAllocatorEx(IOutputMetaData * meta, unsigned activityId, roxiemem::RoxieHeapFlags flags) const
  321. {
  322. return ctx->getRowAllocatorEx(meta, activityId, flags);
  323. }
  324. protected:
  325. IRoxieSlaveContext * ctx;
  326. };
  327. //=================================================================================
  328. #define RESULT_FLUSH_THRESHOLD 10000u
  329. #ifdef _DEBUG
  330. #define SOAP_SPLIT_THRESHOLD 100u
  331. #define SOAP_SPLIT_RESERVE 200u
  332. #else
  333. #define SOAP_SPLIT_THRESHOLD 64000u
  334. #define SOAP_SPLIT_RESERVE 65535u
  335. #endif
  336. //=================================================================================
  337. // General activity statistics
  338. static const StatisticsMapping actStatistics({StWhenFirstRow, StTimeElapsed, StTimeLocalExecute, StTimeTotalExecute, StSizeMaxRowSize,
  339. StNumRowsProcessed, StNumSlaves, StNumStarts, StNumStops, StNumStrands,
  340. StNumScansPerRow, StNumAllocations, StNumAllocationScans,
  341. StTimeFirstExecute, StCycleLocalExecuteCycles, StCycleTotalExecuteCycles});
  342. static const StatisticsMapping joinStatistics(&actStatistics, {StNumAtmostTriggered});
  343. static const StatisticsMapping keyedJoinStatistics(&joinStatistics, { StNumServerCacheHits, StNumIndexSeeks, StNumIndexScans, StNumIndexWildSeeks,
  344. StNumIndexSkips, StNumIndexNullSkips, StNumIndexMerges, StNumIndexMergeCompares,
  345. StNumPreFiltered, StNumPostFiltered, StNumIndexAccepted, StNumIndexRejected,
  346. StNumIndexRowsRead, StNumDiskRowsRead, StNumDiskSeeks, StNumDiskAccepted,
  347. StNumBlobCacheHits, StNumLeafCacheHits, StNumNodeCacheHits,
  348. StNumBlobCacheAdds, StNumLeafCacheAdds, StNumNodeCacheAdds,
  349. StNumDiskRejected});
  350. static const StatisticsMapping indexStatistics(&actStatistics, {StNumServerCacheHits, StNumIndexSeeks, StNumIndexScans, StNumIndexWildSeeks,
  351. StNumIndexSkips, StNumIndexNullSkips, StNumIndexMerges, StNumIndexMergeCompares,
  352. StNumPreFiltered, StNumPostFiltered, StNumIndexAccepted, StNumIndexRejected,
  353. StNumBlobCacheHits, StNumLeafCacheHits, StNumNodeCacheHits,
  354. StNumBlobCacheAdds, StNumLeafCacheAdds, StNumNodeCacheAdds,
  355. StNumIndexRowsRead});
  356. static const StatisticsMapping diskStatistics(&actStatistics, {StNumServerCacheHits, StNumDiskRowsRead, StNumDiskSeeks, StNumDiskAccepted,
  357. StNumDiskRejected });
  358. static const StatisticsMapping soapStatistics(&actStatistics, { StTimeSoapcall });
  359. static const StatisticsMapping groupStatistics(&actStatistics, { StNumGroups, StNumGroupMax });
  360. static const StatisticsMapping sortStatistics(&actStatistics, { StTimeSortElapsed });
  361. static const StatisticsMapping indexWriteStatistics(&actStatistics, { StNumDuplicateKeys });
  362. //=================================================================================
  363. const static unsigned minus1U = (0U-1U);
  364. class CRoxieServerActivityFactoryBase : public CActivityFactory, implements IRoxieServerActivityFactory
  365. {
  366. protected:
  367. IntArray dependencies; // things I am dependent on
  368. IntArray dependencyIndexes; // things I am dependent on
  369. IntArray dependencyControlIds; // things I am dependent on
  370. StringArray dependencyEdgeIds; // How to describe them to the debugger
  371. unsigned dependentCount; // things dependent on me
  372. unsigned optParallel = 0; // -1=enable,0=not specified,1=single-threaded,n=<num threads>
  373. bool optStableInput = true; // is the input forced to ordered?
  374. bool optUnstableInput = false; // is the input forced to unordered?
  375. bool optUnordered = false; // is the output specified as unordered?
  376. unsigned heapFlags;
  377. mutable RelaxedAtomic<__int64> processed = {0};
  378. mutable RelaxedAtomic<__int64> started = {0};
  379. public:
  380. IMPLEMENT_IINTERFACE;
  381. CRoxieServerActivityFactoryBase(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  382. : CActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  383. {
  384. dependentCount = 0;
  385. optParallel = _graphNode.getPropInt("att[@name='parallel']/@value", 0);
  386. optUnordered = !_graphNode.getPropBool("att[@name='ordered']/@value", true);
  387. heapFlags = _graphNode.getPropInt("hint[@name='heapflags']/@value", _queryFactory.queryOptions().heapFlags);
  388. }
  389. ~CRoxieServerActivityFactoryBase()
  390. {
  391. }
  392. StringBuffer &toString(StringBuffer &ret) const
  393. {
  394. return ret.appendf("%p", this);
  395. }
  396. virtual void addDependency(unsigned _source, ThorActivityKind _kind, unsigned _sourceIdx, int controlId, const char *edgeId)
  397. {
  398. dependencies.append(_source);
  399. dependencyIndexes.append(_sourceIdx);
  400. dependencyControlIds.append(controlId);
  401. dependencyEdgeIds.append(edgeId);
  402. }
  403. virtual bool isInputOrdered(bool consumerOrdered, unsigned idx) const
  404. {
  405. if (optStableInput)
  406. return true;
  407. if (optUnstableInput)
  408. return false;
  409. if (optUnordered)
  410. return false;
  411. return consumerOrdered;
  412. }
  413. virtual void noteDependent(unsigned target)
  414. {
  415. dependentCount++;
  416. }
  417. virtual IntArray &queryDependencies() { return dependencies; }
  418. virtual IntArray &queryDependencyIndexes() { return dependencyIndexes; }
  419. virtual IntArray &queryDependencyControlIds() { return dependencyControlIds; }
  420. virtual StringArray &queryDependencyEdgeIds() { return dependencyEdgeIds; }
  421. virtual unsigned queryId() const { return id; }
  422. virtual unsigned querySubgraphId() const { return subgraphId; }
  423. virtual ThorActivityKind getKind() const { return kind; }
  424. virtual IOutputMetaData * queryOutputMeta() const
  425. {
  426. return meta;
  427. }
  428. virtual bool isSink() const
  429. {
  430. return false;
  431. }
  432. virtual bool isFunction() const
  433. {
  434. return false;
  435. }
  436. virtual bool isGraphInvariant() const
  437. {
  438. return false;
  439. }
  440. virtual IHThorArg &getHelper() const
  441. {
  442. return *helperFactory();
  443. }
  444. virtual IRoxieServerActivity *createFunction(IHThorArg &arg, IProbeManager *_probeManager) const
  445. {
  446. arg.Release();
  447. throwUnexpected();
  448. }
  449. virtual void mergeStats(const CRuntimeStatisticCollection &from) const
  450. {
  451. CActivityFactory::mergeStats(from);
  452. }
  453. virtual void noteProcessed(unsigned _idx, unsigned _processed) const
  454. {
  455. dbgassertex(!_idx);
  456. if (_processed)
  457. processed += _processed;
  458. }
  459. virtual void noteStarted() const
  460. {
  461. started++;
  462. }
  463. virtual void noteStarted(unsigned idx) const
  464. {
  465. throwUnexpected(); // should be implemented/required by multiOutput cases only
  466. }
  467. virtual void getEdgeProgressInfo(unsigned output, IPropertyTree &edge) const
  468. {
  469. if (output == 0)
  470. {
  471. putStatsValue(&edge, "count", "sum", processed);
  472. auto _started = started.load();
  473. if (_started)
  474. putStatsValue(&edge, "started", "sum", _started);
  475. }
  476. else
  477. ERRLOG("unexpected call to getEdgeProcessInfo for output %d in activity %d", output, queryId());
  478. }
  479. virtual void getNodeProgressInfo(IPropertyTree &node) const
  480. {
  481. CActivityFactory::getNodeProgressInfo(node);
  482. auto _started = started.load();
  483. if (_started)
  484. putStatsValue(&node, "_roxieStarted", "sum", _started);
  485. }
  486. virtual void resetNodeProgressInfo()
  487. {
  488. CActivityFactory::resetNodeProgressInfo();
  489. processed = 0;
  490. started = 0;
  491. }
  492. virtual void getActivityMetrics(StringBuffer &reply) const
  493. {
  494. CActivityFactory::getActivityMetrics(reply);
  495. putStatsValue(reply, "_roxieStarted", "sum", started);
  496. CriticalBlock b(statsCrit);
  497. putStatsValue(reply, "totalTime", "sum", (unsigned) (mystats.getSerialStatisticValue(StTimeTotalExecute)/1000));
  498. putStatsValue(reply, "localTime", "sum", (unsigned) (mystats.getSerialStatisticValue(StTimeLocalExecute)/1000));
  499. }
  500. virtual unsigned __int64 queryLocalTimeNs() const
  501. {
  502. return mystats.getSerialStatisticValue(StTimeLocalExecute);
  503. }
  504. virtual IQueryFactory &queryQueryFactory() const
  505. {
  506. return CActivityFactory::queryQueryFactory();
  507. }
  508. virtual ActivityArray *queryChildQuery(unsigned idx, unsigned &id)
  509. {
  510. return CActivityFactory::queryChildQuery(idx, id);
  511. }
  512. virtual void addChildQuery(unsigned id, ActivityArray *childQuery)
  513. {
  514. CActivityFactory::addChildQuery(id, childQuery);
  515. }
  516. virtual void onCreateChildQueries(IRoxieSlaveContext *ctx, IHThorArg *colocalArg, IArrayOf<IActivityGraph> &childGraphs, IRoxieServerActivity *parentActivity, IProbeManager *_probeManager, const IRoxieContextLogger &_logctx, unsigned numParallel) const
  517. {
  518. ForEachItemIn(idx, childQueries)
  519. {
  520. childGraphs.append(*createActivityGraph(ctx, NULL, childQueryIndexes.item(idx), childQueries.item(idx), parentActivity, _probeManager, _logctx, numParallel));
  521. ctx->noteChildGraph(childQueryIndexes.item(idx), &childGraphs.item(idx));
  522. childGraphs.item(idx).onCreate(colocalArg);
  523. }
  524. }
  525. IActivityGraph * createChildGraph(IRoxieSlaveContext * ctx, IHThorArg *colocalArg, unsigned childId, IRoxieServerActivity *parentActivity, IProbeManager * _probeManager, const IRoxieContextLogger &_logctx) const
  526. {
  527. unsigned match = childQueryIndexes.find(childId);
  528. assertex(match != NotFound);
  529. Owned<IActivityGraph> graph = createActivityGraph(ctx, NULL, childQueryIndexes.item(match), childQueries.item(match), parentActivity, _probeManager, _logctx, 1);
  530. graph->onCreate(colocalArg);
  531. return graph.getClear();
  532. }
  533. virtual IRoxieServerSideCache *queryServerSideCache() const
  534. {
  535. return NULL; // Activities that wish to support server-side caching will need to do better....
  536. }
  537. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  538. {
  539. // Most activities have nothing to say...
  540. }
  541. virtual const StatisticsMapping &queryStatsMapping() const
  542. {
  543. return actStatistics; // Overridden by anyone that needs more
  544. }
  545. virtual roxiemem::RoxieHeapFlags getHeapFlags() const
  546. {
  547. return (roxiemem::RoxieHeapFlags)heapFlags;
  548. }
  549. };
  550. class CRoxieServerMultiInputInfo
  551. {
  552. private:
  553. UnsignedArray inputs;
  554. UnsignedArray inputIndexes;
  555. public:
  556. void set(unsigned idx, unsigned source, unsigned sourceidx)
  557. {
  558. if (idx==inputs.length())
  559. {
  560. inputs.append(source);
  561. inputIndexes.append(sourceidx);
  562. }
  563. else
  564. {
  565. while (!inputs.isItem(idx))
  566. {
  567. inputs.append(0);
  568. inputIndexes.append(0);
  569. }
  570. inputs.replace(source, idx);
  571. inputIndexes.replace(sourceidx, idx);
  572. }
  573. }
  574. unsigned get(unsigned idx, unsigned &sourceidx) const
  575. {
  576. if (inputs.isItem(idx))
  577. {
  578. sourceidx = inputIndexes.item(idx);
  579. return inputs.item(idx);
  580. }
  581. else
  582. return (unsigned) -1;
  583. }
  584. inline unsigned ordinality() const { return inputs.ordinality(); }
  585. };
  586. class CRoxieServerMultiInputFactory : public CRoxieServerActivityFactoryBase
  587. {
  588. private:
  589. CRoxieServerMultiInputInfo inputs;
  590. public:
  591. CRoxieServerMultiInputFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  592. : CRoxieServerActivityFactoryBase(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  593. {
  594. }
  595. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  596. {
  597. inputs.set(idx, source, sourceidx);
  598. }
  599. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  600. {
  601. return inputs.get(idx, sourceidx);
  602. }
  603. virtual unsigned numInputs() const { return inputs.ordinality(); }
  604. };
  605. class DECL_EXCEPTION CWrappedException : implements IException, public CInterface
  606. {
  607. Owned<IException> wrapped;
  608. ThorActivityKind kind;
  609. unsigned queryId;
  610. public:
  611. IMPLEMENT_IINTERFACE;
  612. CWrappedException(IException *_wrapped, ThorActivityKind _kind, unsigned _queryId)
  613. : wrapped(_wrapped), kind(_kind), queryId(_queryId)
  614. {
  615. }
  616. virtual int errorCode() const { return wrapped->errorCode(); }
  617. virtual StringBuffer & errorMessage(StringBuffer &msg) const { return wrapped->errorMessage(msg).appendf(" (in %s %d)", getActivityText(kind), queryId); }
  618. virtual MessageAudience errorAudience() const { return wrapped->errorAudience(); }
  619. };
  620. class CRoxieServerActivityFactory : public CRoxieServerActivityFactoryBase
  621. {
  622. protected:
  623. unsigned input;
  624. unsigned inputidx;
  625. public:
  626. CRoxieServerActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  627. : CRoxieServerActivityFactoryBase(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  628. {
  629. input = (unsigned) -1;
  630. inputidx = 0;
  631. }
  632. inline void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  633. {
  634. if (idx != 0)
  635. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: id = %d : setInput() parameter out of bounds idx = %d at %s(%d)", id, idx, sanitizeSourceFile(__FILE__), __LINE__);
  636. if (input != -1)
  637. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: id = %d : setInput() called twice for input = %d source = %d inputidx = %d sourceidx = %d at %s(%d)", id, input, source, inputidx, sourceidx, sanitizeSourceFile(__FILE__), __LINE__);
  638. input = source;
  639. inputidx = sourceidx;
  640. }
  641. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  642. {
  643. if (!idx)
  644. {
  645. sourceidx = inputidx;
  646. return input;
  647. }
  648. return (unsigned) -1;
  649. }
  650. virtual unsigned numInputs() const { return (input == (unsigned)-1) ? 0 : 1; }
  651. };
  652. class CRoxieServerMultiOutputFactory : public CRoxieServerActivityFactory
  653. {
  654. protected:
  655. unsigned numOutputs = 0;
  656. RelaxedAtomic<__int64> *processedArray = nullptr;
  657. RelaxedAtomic<__int64> *startedArray = nullptr;
  658. CRoxieServerMultiOutputFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  659. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  660. {
  661. }
  662. ~CRoxieServerMultiOutputFactory()
  663. {
  664. delete [] processedArray;
  665. delete [] startedArray;
  666. }
  667. void setNumOutputs(unsigned num)
  668. {
  669. numOutputs = num;
  670. if (!num)
  671. num = 1; // Even sink activities like to track how many records they process
  672. processedArray = new RelaxedAtomic<__int64>[num];
  673. startedArray = new RelaxedAtomic<__int64>[num];
  674. for (unsigned i = 0; i < num; i++)
  675. {
  676. processedArray[i] = 0;
  677. startedArray[i] = 0;
  678. }
  679. }
  680. virtual void getEdgeProgressInfo(unsigned idx, IPropertyTree &edge) const
  681. {
  682. assertex(numOutputs ? idx < numOutputs : idx==0);
  683. putStatsValue(&edge, "count", "sum", processedArray[idx]);
  684. putStatsValue(&edge, "started", "sum", startedArray[idx]);
  685. }
  686. virtual void resetNodeProgressInfo()
  687. {
  688. CRoxieServerActivityFactory::resetNodeProgressInfo();
  689. for (unsigned i = 0; i < numOutputs; i++)
  690. {
  691. processedArray[i] = 0;
  692. startedArray[i] = 0;
  693. }
  694. }
  695. virtual void noteProcessed(unsigned idx, unsigned _processed) const
  696. {
  697. assertex(numOutputs ? idx < numOutputs : idx==0);
  698. processedArray[idx] += _processed;
  699. }
  700. virtual void noteStarted(unsigned idx) const
  701. {
  702. assertex(numOutputs ? idx < numOutputs : idx==0);
  703. startedArray[idx]++;
  704. }
  705. };
  706. class CRoxieServerInternalSinkFactory : public CRoxieServerActivityFactory
  707. {
  708. protected:
  709. bool isInternal;
  710. bool isRoot;
  711. unsigned usageCount;
  712. public:
  713. CRoxieServerInternalSinkFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  714. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  715. {
  716. usageCount = _usageCount;
  717. isRoot = _isRoot;
  718. isInternal = false; // filled in by derived class constructor
  719. }
  720. virtual bool isSink() const
  721. {
  722. //only a sink if a root activity
  723. 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?
  724. }
  725. virtual void getEdgeProgressInfo(unsigned idx, IPropertyTree &edge) const
  726. {
  727. // 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
  728. // Just leave it blank is safest.
  729. }
  730. };
  731. typedef enum { STATEreset, STATEstarted, STATEstopped, STATEstarting } activityState;
  732. const char *queryStateText(activityState state)
  733. {
  734. switch (state)
  735. {
  736. case STATEreset: return "reset";
  737. case STATEstarted: return "started";
  738. case STATEstopped: return "stopped";
  739. case STATEstarting: return "starting";
  740. default: return "unknown";
  741. }
  742. }
  743. typedef ICopyArrayOf<IRoxieServerActivity> IRoxieServerActivityCopyArray;
  744. class CParallelActivityExecutor : public CAsyncFor
  745. {
  746. public:
  747. unsigned parentExtractSize;
  748. const byte * parentExtract;
  749. CParallelActivityExecutor(IRoxieServerActivityCopyArray & _activities, unsigned _parentExtractSize, const byte * _parentExtract) :
  750. activities(_activities), parentExtractSize(_parentExtractSize), parentExtract(_parentExtract) { }
  751. void Do(unsigned i)
  752. {
  753. activities.item(i).execute(parentExtractSize, parentExtract);
  754. }
  755. private:
  756. IRoxieServerActivityCopyArray & activities;
  757. };
  758. extern IEngineRowStream * ensureSingleStream(IRoxieSlaveContext *ctx, PointerArrayOf<IEngineRowStream> & instreams, Owned<IStrandJunction> &junction)
  759. {
  760. if (instreams.length() != 1)
  761. {
  762. assertex(instreams.length());
  763. if (!junction)
  764. junction.setown(createStrandJunction(ctx->queryRowManager(), instreams.length(), 1, ctx->queryOptions().strandBlockSize, false));
  765. ForEachItemIn(stream, instreams)
  766. {
  767. junction->setInput(stream, instreams.item(stream));
  768. }
  769. return junction->queryOutput(0);
  770. }
  771. else
  772. return instreams.item(0);
  773. }
  774. extern IEngineRowStream *connectSingleStream(IRoxieSlaveContext *ctx, IFinalRoxieInput *input, unsigned idx, Owned<IStrandJunction> &junction, bool consumerOrdered)
  775. {
  776. if (input)
  777. {
  778. PointerArrayOf<IEngineRowStream> instreams;
  779. junction.setown(input->getOutputStreams(ctx, idx, instreams, NULL, consumerOrdered, nullptr));
  780. return ensureSingleStream(ctx, instreams, junction);
  781. }
  782. else
  783. return NULL;
  784. }
  785. extern IEngineRowStream *connectSingleStream(IRoxieSlaveContext *ctx, IFinalRoxieInput *input, unsigned idx, bool consumerOrdered)
  786. {
  787. Owned<IStrandJunction> junction;
  788. IEngineRowStream * result = connectSingleStream(ctx, input, idx, junction, consumerOrdered);
  789. assertex(!junction);
  790. return result;
  791. }
  792. class CRoxieServerActivity : implements CInterfaceOf<IRoxieServerActivity>, implements IFinalRoxieInput, implements IEngineRowStream, implements IRoxieContextLogger
  793. {
  794. friend class StrandProcessor;
  795. protected:
  796. IFinalRoxieInput *input;
  797. unsigned sourceIdx;
  798. IEngineRowStream *inputStream;
  799. Owned<IStrandJunction> junction;
  800. IHThorArg &basehelper;
  801. IRoxieSlaveContext *ctx;
  802. class InterceptRegisterTimer : public IndirectCodeContext
  803. {
  804. public:
  805. InterceptRegisterTimer(CRoxieServerActivity &_activity) : activity(_activity) {}
  806. virtual ISectionTimer *registerTimer(unsigned activityId, const char * name)
  807. {
  808. if (activityId == activity.queryId())
  809. return activity.registerTimer(activityId, name);
  810. else
  811. return ctx->registerTimer(activityId, name);
  812. }
  813. private:
  814. CRoxieServerActivity &activity;
  815. } interceptedCtx;
  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. unsigned activityId;
  831. activityState state;
  832. bool createPending;
  833. bool debugging;
  834. bool timeActivities;
  835. bool aborted;
  836. bool connected = false;
  837. IProbeManager *probeManager = NULL;
  838. public:
  839. IMPLEMENT_IINTERFACE_USING(CInterfaceOf<IRoxieServerActivity>)
  840. CRoxieServerActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  841. : ctx(_ctx),
  842. interceptedCtx(*this),
  843. factory(_factory),
  844. basehelper(_factory->getHelper()),
  845. activityId(_factory->queryId()),
  846. stats(_factory->queryStatsMapping()),
  847. probeManager(_probeManager)
  848. {
  849. input = NULL;
  850. sourceIdx = 0;
  851. inputStream = NULL;
  852. meta.set(basehelper.queryOutputMeta());
  853. processed = 0;
  854. state=STATEreset;
  855. rowAllocator = NULL;
  856. debugging = _probeManager != NULL; // Don't want to collect timing stats from debug sessions
  857. colocalParent = NULL;
  858. createPending = true;
  859. timeActivities = defaultTimeActivities;
  860. aborted = false;
  861. }
  862. CRoxieServerActivity(IRoxieSlaveContext *_ctx, IHThorArg & _helper)
  863. : ctx(_ctx),
  864. interceptedCtx(*this),
  865. factory(NULL), basehelper(_helper), stats(allStatistics)
  866. {
  867. activityId = 0;
  868. input = NULL;
  869. sourceIdx = 0;
  870. inputStream = NULL;
  871. ctx = NULL;
  872. meta.set(basehelper.queryOutputMeta());
  873. processed = 0;
  874. state=STATEreset;
  875. rowAllocator = NULL;
  876. debugging = false;
  877. colocalParent = NULL;
  878. createPending = true;
  879. timeActivities = defaultTimeActivities;
  880. aborted = false;
  881. }
  882. ~CRoxieServerActivity()
  883. {
  884. basehelper.Release();
  885. ::Release(rowAllocator);
  886. }
  887. virtual void beforeDispose() override
  888. {
  889. if (traceStartStop)
  890. {
  891. // There was an old comment here stating // Note- CTXLOG may not be safe
  892. // There were problems in the destruction order of graphs that might mean an IndirectSlaveContext
  893. // was released while activities still referenced it.
  894. // However these should now all be fixed
  895. DBGLOG("%p destroy %d state=%s", this, activityId, queryStateText(state));
  896. if (watchActivityId && watchActivityId==activityId)
  897. {
  898. DBGLOG("WATCH: %p destroy %d state=%s", this, activityId, queryStateText(state));
  899. }
  900. }
  901. if (state!=STATEreset)
  902. {
  903. DBGLOG("STATE: Activity %d destroyed but not reset", activityId);
  904. state = STATEreset; // bit pointless but there you go...
  905. }
  906. }
  907. const IResolvedFile *resolveLFNIndex(const char *filename, bool isOpt)
  908. {
  909. const IResolvedFile *ret = resolveLFN(filename, isOpt);
  910. if (ret && !ret->isKey())
  911. throw MakeStringException(0, "Attempting to read flat file as an index: %s", filename);
  912. return ret;
  913. }
  914. const IResolvedFile *resolveLFNFlat(const char *filename, bool isOpt)
  915. {
  916. const IResolvedFile *ret = resolveLFN(filename, isOpt);
  917. if (ret && ret->isKey())
  918. throw MakeStringException(0, "Attempting to read index as a flat file: %s", filename);
  919. return ret;
  920. }
  921. virtual void updateFactoryStatistics() const override
  922. {
  923. CRuntimeStatisticCollection mergedStats(stats.queryMapping());
  924. gatherStats(mergedStats);
  925. if (factory && !debugging)
  926. {
  927. if (processed)
  928. factory->noteProcessed(0, processed);
  929. factory->mergeStats(mergedStats);
  930. }
  931. if (ctx && factory)
  932. {
  933. if (processed)
  934. ctx->noteProcessed(factory->querySubgraphId(), activityId, 0, processed, 0);
  935. ctx->mergeActivityStats(mergedStats, factory->querySubgraphId(), activityId);
  936. }
  937. ForEachItemIn(i, childGraphs)
  938. childGraphs.item(i).updateFactoryStatistics();
  939. }
  940. virtual const IRoxieContextLogger &queryLogCtx()const
  941. {
  942. return *this;
  943. }
  944. inline const StatisticsMapping & queryStatsMapping() const
  945. {
  946. return factory ? factory->queryStatsMapping() : actStatistics;
  947. }
  948. virtual void mergeStats(MemoryBuffer &buf)
  949. {
  950. stats.deserializeMerge(buf);
  951. }
  952. virtual ISectionTimer *registerTimer(unsigned _activityId, const char * name)
  953. {
  954. CriticalBlock b(statscrit); // reuse statscrit to protect functionTimers - it will not be held concurrently
  955. ISectionTimer *timer = functionTimers.getValue(name);
  956. if (!timer)
  957. {
  958. timer = ThorSectionTimer::createTimer(stats, name);
  959. functionTimers.setValue(name, timer);
  960. timer->Release(); // Value returned is not linked
  961. }
  962. return timer;
  963. }
  964. void mergeStrandStats(unsigned strandProcessed, const ActivityTimeAccumulator & strandCycles)
  965. {
  966. CriticalBlock cb(statscrit);
  967. processed += strandProcessed;
  968. totalCycles.merge(strandCycles);
  969. }
  970. inline void ensureRowAllocator()
  971. {
  972. if (!rowAllocator)
  973. rowAllocator = createRowAllocator(meta.queryOriginal());
  974. }
  975. virtual IEngineRowAllocator * createRowAllocator(IOutputMetaData * metadata)
  976. {
  977. return ctx->getRowAllocatorEx(metadata, activityId, factory->getHeapFlags());
  978. }
  979. virtual IEngineRowAllocator * createRowAllocatorEx(IOutputMetaData * metadata, roxiemem::RoxieHeapFlags extraFlags)
  980. {
  981. return ctx->getRowAllocatorEx(metadata, activityId, (roxiemem::RoxieHeapFlags)(factory->getHeapFlags()|extraFlags));
  982. }
  983. inline ICodeContext *queryCodeContext()
  984. {
  985. return ctx->queryCodeContext();
  986. }
  987. // MORE - most of this is copied from ccd.hpp - can't we refactor?
  988. virtual void CTXLOGa(TracingCategory category, const char *prefix, const char *text) const
  989. {
  990. if (ctx)
  991. ctx->CTXLOGa(category, prefix, text);
  992. else
  993. DBGLOG("[%s] %s", prefix, text);
  994. }
  995. 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)))
  996. {
  997. if (ctx)
  998. ctx->CTXLOGaeva(E, file, line, prefix, format, args);
  999. else
  1000. {
  1001. StringBuffer ss;
  1002. ss.appendf("[%s] ERROR", prefix);
  1003. if (E)
  1004. ss.append(": ").append(E->errorCode());
  1005. if (file)
  1006. ss.appendf(": %s(%d) ", file, line);
  1007. if (E)
  1008. E->errorMessage(ss.append(": "));
  1009. if (format)
  1010. {
  1011. ss.append(": ").valist_appendf(format, args);
  1012. }
  1013. LOG(MCoperatorProgress, unknownJob, "%s", ss.str());
  1014. }
  1015. }
  1016. virtual void CTXLOGl(LogItem *log) const
  1017. {
  1018. if (ctx)
  1019. ctx->CTXLOGl(log);
  1020. else
  1021. {
  1022. assert(ctx);
  1023. log->Release(); // Should never happen
  1024. }
  1025. }
  1026. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value) const
  1027. {
  1028. stats.addStatistic(kind, value);
  1029. }
  1030. virtual void mergeStats(const CRuntimeStatisticCollection &from) const
  1031. {
  1032. stats.merge(from);
  1033. }
  1034. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  1035. {
  1036. merged.merge(stats);
  1037. if (rowAllocator)
  1038. rowAllocator->gatherStats(merged);
  1039. totalCycles.addStatistics(merged);
  1040. merged.mergeStatistic(StCycleLocalExecuteCycles, queryLocalCycles());
  1041. }
  1042. virtual StringBuffer &getLogPrefix(StringBuffer &ret) const
  1043. {
  1044. if (ctx)
  1045. ctx->getLogPrefix(ret);
  1046. return ret.append('@').append(activityId);
  1047. }
  1048. virtual bool isIntercepted() const
  1049. {
  1050. return ctx ? ctx->isIntercepted() : false;
  1051. }
  1052. virtual bool isBlind() const
  1053. {
  1054. return ctx ? ctx->isBlind() : blindLogging;
  1055. }
  1056. virtual unsigned queryTraceLevel() const
  1057. {
  1058. if (ctx)
  1059. return ctx->queryTraceLevel();
  1060. else
  1061. return traceLevel;
  1062. }
  1063. virtual void setGlobalId(const char *id, SocketEndpoint&ep, unsigned pid)
  1064. {
  1065. if (ctx)
  1066. ctx->setGlobalId(id, ep, pid);
  1067. }
  1068. virtual const char *queryGlobalId() const
  1069. {
  1070. return ctx ? ctx->queryGlobalId() : nullptr;
  1071. }
  1072. virtual const char *queryLocalId() const
  1073. {
  1074. return ctx ? ctx->queryLocalId() : nullptr;
  1075. }
  1076. virtual void setHttpIdHeaders(const char *global, const char *caller)
  1077. {
  1078. if (ctx)
  1079. ctx->setHttpIdHeaders(global, caller);
  1080. }
  1081. virtual const char *queryGlobalIdHttpHeader() const
  1082. {
  1083. return ctx ? ctx->queryGlobalIdHttpHeader() : "HPCC-Global-Id";
  1084. }
  1085. virtual const char *queryCallerIdHttpHeader() const
  1086. {
  1087. return ctx ? ctx->queryCallerIdHttpHeader() : "HPCC-Caller-Id";
  1088. }
  1089. virtual bool isPassThrough()
  1090. {
  1091. return false;
  1092. }
  1093. virtual const IResolvedFile *resolveLFN(const char *filename, bool isOpt)
  1094. {
  1095. return ctx->resolveLFN(filename, isOpt);
  1096. }
  1097. virtual const IResolvedFile *queryVarFileInfo() const
  1098. {
  1099. throwUnexpected(); // should be implemented in more derived class by anyone that has a remote adaptor
  1100. return NULL;
  1101. }
  1102. virtual void serializeSkipInfo(MemoryBuffer &out, unsigned seekLen, const void *rawSeek, unsigned numFields, const void * seek, const SmartStepExtra &stepExtra) const
  1103. {
  1104. throwUnexpected(); // should be implemented in more derived class wherever needed
  1105. }
  1106. virtual IRoxieSlaveContext *queryContext()
  1107. {
  1108. return ctx;
  1109. }
  1110. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { assertex(whichInput==0); return this; }
  1111. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { assertex(idx==0); return junction; }
  1112. virtual IRoxieServerActivity *queryActivity() { return this; }
  1113. virtual IIndexReadActivityInfo *queryIndexReadActivity() { return NULL; }
  1114. virtual bool needsAllocator() const { return false; }
  1115. void _onCreate(IHThorArg *_colocalParent, unsigned _numParallel)
  1116. {
  1117. colocalParent = _colocalParent;
  1118. createPending = true;
  1119. if (needsAllocator())
  1120. ensureRowAllocator();
  1121. processed = 0;
  1122. if (factory)
  1123. factory->onCreateChildQueries(ctx, &basehelper, childGraphs, this, probeManager, *this, _numParallel);
  1124. if (ctx)
  1125. timeActivities = ctx->queryOptions().timeActivities;
  1126. }
  1127. virtual void onCreate(IHThorArg *_colocalParent)
  1128. {
  1129. _onCreate(_colocalParent, 1);
  1130. }
  1131. virtual void serializeCreateStartContext(MemoryBuffer &out)
  1132. {
  1133. //This should only be called after onStart has been called on the helper
  1134. assertex(!createPending);
  1135. assertex(state==STATEstarted);
  1136. unsigned startlen = out.length();
  1137. basehelper.serializeCreateContext(out);
  1138. basehelper.serializeStartContext(out);
  1139. if (queryTraceLevel() > 10)
  1140. CTXLOG("serializeCreateStartContext for %d added %d bytes", activityId, out.length()-startlen);
  1141. }
  1142. virtual void serializeExtra(MemoryBuffer &out) {}
  1143. inline void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  1144. {
  1145. CriticalBlock cb(statecrit);
  1146. if (state != STATEreset && state != STATEstarting)
  1147. {
  1148. CTXLOG("STATE: Expected state to be reset, but was %s, in activity %d", queryStateText(state), activityId);
  1149. }
  1150. state=STATEstarted;
  1151. #ifdef TRACE_STARTSTOP
  1152. if (traceStartStop)
  1153. {
  1154. CTXLOG("start %p %d", this, activityId);
  1155. if (watchActivityId && watchActivityId==activityId)
  1156. {
  1157. CTXLOG("WATCH: start %p %d", this, activityId);
  1158. }
  1159. }
  1160. #endif
  1161. executeDependencies(parentExtractSize, parentExtract, 0);
  1162. if (input)
  1163. input->start(parentExtractSize, parentExtract, paused);
  1164. ensureCreated();
  1165. basehelper.onStart(parentExtract, NULL);
  1166. if (factory)
  1167. factory->noteStarted();
  1168. startJunction(junction);
  1169. }
  1170. void executeDependencies(unsigned parentExtractSize, const byte *parentExtract, unsigned controlId)
  1171. {
  1172. //MORE: Create a filtered list and then use asyncfor
  1173. ForEachItemIn(idx, dependencies)
  1174. {
  1175. if (dependencyControlIds.item(idx) == controlId)
  1176. dependencies.item(idx).execute(parentExtractSize, parentExtract);
  1177. }
  1178. }
  1179. void stopDependencies(unsigned parentExtractSize, const byte *parentExtract, unsigned controlId)
  1180. {
  1181. ForEachItemIn(idx, dependencies)
  1182. {
  1183. if (dependencyControlIds.item(idx) == controlId)
  1184. dependencies.item(idx).stop();
  1185. }
  1186. }
  1187. virtual unsigned __int64 queryTotalCycles() const
  1188. {
  1189. return totalCycles.totalCycles;
  1190. }
  1191. virtual unsigned __int64 queryLocalCycles() const
  1192. {
  1193. __int64 ret = totalCycles.totalCycles;
  1194. if (input) ret -= input->queryTotalCycles();
  1195. if (ret < 0)
  1196. ret = 0;
  1197. return ret;
  1198. }
  1199. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  1200. {
  1201. if (idx==0)
  1202. return input;
  1203. else
  1204. return NULL;
  1205. }
  1206. inline void ensureCreated()
  1207. {
  1208. if (createPending)
  1209. {
  1210. createPending = false;
  1211. interceptedCtx.set(ctx->queryCodeContext());
  1212. basehelper.onCreate(&interceptedCtx, colocalParent, NULL);
  1213. }
  1214. }
  1215. virtual void stop()
  1216. {
  1217. // NOTE - don't be tempted to skip the stop for activities that are reset - splitters need to see the stops
  1218. if (state != STATEstopped)
  1219. {
  1220. CriticalBlock cb(statecrit);
  1221. if (state != STATEstopped)
  1222. {
  1223. #ifdef TRACE_STARTSTOP
  1224. if (traceStartStop)
  1225. {
  1226. CTXLOG("stop %p %d (state currently %s)", this, activityId, queryStateText(state));
  1227. if (watchActivityId && watchActivityId==activityId)
  1228. {
  1229. CTXLOG("WATCH: stop %p %d", this, activityId);
  1230. }
  1231. }
  1232. #endif
  1233. state=STATEstopped;
  1234. // NOTE - this is needed to ensure that dependencies which were not used are properly stopped
  1235. ForEachItemIn(idx, dependencies)
  1236. {
  1237. if (dependencyControlIds.item(idx) == 0)
  1238. dependencies.item(idx).stopSink(dependencyIndexes.item(idx));
  1239. }
  1240. if (inputStream)
  1241. inputStream->stop();
  1242. }
  1243. }
  1244. }
  1245. virtual void abort()
  1246. {
  1247. aborted = true;
  1248. // MORE - should abort dependencies here?
  1249. stop();
  1250. }
  1251. inline void reset()
  1252. {
  1253. if (state != STATEreset)
  1254. {
  1255. CriticalBlock cb(statecrit);
  1256. if (state != STATEreset)
  1257. {
  1258. if (state==STATEstarted || state==STATEstarting)
  1259. {
  1260. if (ctx->queryOptions().failOnLeaks)
  1261. throw makeStringExceptionV(ROXIE_INTERNAL_ERROR, "STATE: activity %d reset without stop", activityId);
  1262. if (traceStartStop || traceLevel > 2)
  1263. CTXLOG("STATE: activity %d reset without stop", activityId);
  1264. stop();
  1265. }
  1266. state = STATEreset;
  1267. #ifdef TRACE_STARTSTOP
  1268. if (traceStartStop)
  1269. {
  1270. CTXLOG("reset %p %d", this, activityId);
  1271. if (watchActivityId && watchActivityId==activityId)
  1272. {
  1273. CTXLOG("WATCH: reset %p %d", this, activityId);
  1274. }
  1275. }
  1276. #endif
  1277. resetJunction(junction);
  1278. ForEachItemIn(idx, dependencies)
  1279. dependencies.item(idx).reset();
  1280. if (input)
  1281. input->reset();
  1282. }
  1283. }
  1284. aborted = false;
  1285. }
  1286. virtual void addDependency(IRoxieServerActivity &source, unsigned sourceIdx, int controlId)
  1287. {
  1288. dependencies.append(source);
  1289. dependencyIndexes.append(sourceIdx);
  1290. dependencyControlIds.append(controlId);
  1291. }
  1292. virtual void resetEOF()
  1293. {
  1294. //would make more sense if the default implementation (and eof member) were in the base class
  1295. }
  1296. // Sink activities should override this....
  1297. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  1298. {
  1299. throw MakeStringException(ROXIE_SINK, "Internal error: execute() requires a sink");
  1300. }
  1301. virtual void executeChild(size32_t & retSize, void * & ret, unsigned parentExtractSize, const byte * parentExtract)
  1302. {
  1303. throw MakeStringException(ROXIE_SINK, "Internal error: executeChild() requires a suitable sink");
  1304. }
  1305. virtual void stopSink(unsigned idx)
  1306. {
  1307. throw MakeStringException(ROXIE_SINK, "Internal error: stopSink() requires a suitable sink");
  1308. }
  1309. virtual void connectInputStreams(bool consumerOrdered)
  1310. {
  1311. if (input && !inputStream)
  1312. inputStream = connectSingleStream(ctx, input, sourceIdx, junction, isInputOrdered(consumerOrdered, 0));
  1313. if (!connected)
  1314. {
  1315. connectDependencies();
  1316. connected = true;
  1317. }
  1318. }
  1319. void connectDependencies()
  1320. {
  1321. ForEachItemIn(i, dependencies)
  1322. dependencies.item(i).connectInputStreams(true);
  1323. }
  1324. virtual __int64 evaluate()
  1325. {
  1326. throw MakeStringException(ROXIE_SINK, "Internal error: evaluate() requires a function");
  1327. }
  1328. virtual IFinalRoxieInput * querySelectOutput(unsigned id)
  1329. {
  1330. return NULL;
  1331. }
  1332. virtual bool querySetStreamInput(unsigned id, unsigned _sourceIdx, IFinalRoxieInput * _input)
  1333. {
  1334. return false;
  1335. }
  1336. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  1337. {
  1338. assertex(!idx);
  1339. input = _in;
  1340. sourceIdx = _sourceIdx;
  1341. inputStream = NULL;
  1342. }
  1343. bool isInputOrdered(bool consumerOrdered, unsigned idx) const
  1344. {
  1345. if (!factory)
  1346. return true;
  1347. //Grouping implies the stream processing must be ordered - I think this always applies
  1348. IFinalRoxieInput * curInput = queryInput(idx);
  1349. if (curInput && curInput->queryOutputMeta()->isGrouped())
  1350. return true;
  1351. return factory->isInputOrdered(consumerOrdered, idx);
  1352. }
  1353. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  1354. {
  1355. assertex(!idx);
  1356. // By default, activities are assumed NOT to support streams
  1357. bool inputOrdered = isInputOrdered(consumerOrdered, 0);
  1358. connectInputStreams(inputOrdered);
  1359. // Return a single stream
  1360. streams.append(this);
  1361. return NULL;
  1362. }
  1363. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  1364. {
  1365. if (idx == (unsigned) -1)
  1366. idx = 0;
  1367. return idx ? NULL : this;
  1368. }
  1369. virtual IOutputMetaData *queryOutputMeta() const
  1370. {
  1371. return meta.queryOriginal();
  1372. }
  1373. virtual unsigned queryId() const
  1374. {
  1375. return activityId;
  1376. }
  1377. virtual unsigned querySubgraphId() const
  1378. {
  1379. return factory->querySubgraphId();
  1380. }
  1381. virtual void checkAbort()
  1382. {
  1383. ctx->checkAbort();
  1384. }
  1385. IException *makeWrappedException(IException *e)
  1386. {
  1387. StringBuffer msg;
  1388. ThorActivityKind activityKind = factory ? factory->getKind() : TAKnone;
  1389. CTXLOG("makeWrappedException - %s (in %s %d)", e->errorMessage(msg).str(), getActivityText(activityKind), activityId);
  1390. if (QUERYINTERFACE(e, CWrappedException) || QUERYINTERFACE(e, IUserException))
  1391. return e;
  1392. else
  1393. return new CWrappedException(e, activityKind, activityId);
  1394. }
  1395. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract)
  1396. {
  1397. }
  1398. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract, IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes)
  1399. {
  1400. }
  1401. virtual void resetOutputsUsed()
  1402. {
  1403. }
  1404. virtual void noteOutputUsed()
  1405. {
  1406. }
  1407. virtual IRoxieServerSideCache *queryServerSideCache() const
  1408. {
  1409. return factory->queryServerSideCache();
  1410. }
  1411. virtual const IRoxieServerActivityFactory *queryFactory() const
  1412. {
  1413. return factory;
  1414. }
  1415. inline ThorActivityKind getKind() const
  1416. {
  1417. return factory->getKind();
  1418. }
  1419. inline bool isSink() const
  1420. {
  1421. return (factory != NULL) && factory->isSink();
  1422. }
  1423. protected:
  1424. bool skipFileFormatCrcCheck() const
  1425. {
  1426. return factory->queryQueryFactory().queryOptions().skipFileFormatCrcCheck;
  1427. }
  1428. RecordTranslationMode getEnableFieldTranslation() const
  1429. {
  1430. return factory->queryQueryFactory().queryOptions().enableFieldTranslation;
  1431. }
  1432. };
  1433. //=====================================================================================================
  1434. class CRoxieServerLateStartActivity : public CRoxieServerActivity
  1435. {
  1436. protected:
  1437. bool prefiltered;
  1438. bool eof;
  1439. void lateStart(unsigned parentExtractSize, const byte *parentExtract, bool any)
  1440. {
  1441. prefiltered = !any;
  1442. eof = prefiltered;
  1443. if (!prefiltered)
  1444. {
  1445. input->start(parentExtractSize, parentExtract, false);
  1446. startJunction(junction);
  1447. }
  1448. else
  1449. {
  1450. if (traceStartStop)
  1451. CTXLOG("lateStart activity stopping input early as prefiltered");
  1452. inputStream->stop();
  1453. }
  1454. }
  1455. public:
  1456. CRoxieServerLateStartActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  1457. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  1458. {
  1459. prefiltered = false;
  1460. eof = false;
  1461. }
  1462. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  1463. {
  1464. IFinalRoxieInput *saveInput = input;
  1465. Owned<IStrandJunction> saveJunction = junction.getClear();
  1466. input = NULL; // Make sure parent does not start the chain yet
  1467. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  1468. input = saveInput;
  1469. junction.setown(saveJunction.getClear());
  1470. }
  1471. virtual void stop()
  1472. {
  1473. if (!prefiltered)
  1474. {
  1475. inputStream->stop();
  1476. }
  1477. else if (traceStartStop)
  1478. CTXLOG("lateStart activity NOT stopping input late as prefiltered");
  1479. IEngineRowStream *save = inputStream;
  1480. inputStream = NULL; // We already stopped inputStream - prevent parent from doing so again
  1481. CRoxieServerActivity::stop();
  1482. inputStream = save;
  1483. }
  1484. virtual void reset()
  1485. {
  1486. CRoxieServerActivity::reset();
  1487. prefiltered = false;
  1488. }
  1489. };
  1490. //=================================================================================
  1491. class StrandOptions
  1492. {
  1493. // Typically set from hints, common to many stranded activities
  1494. public:
  1495. explicit StrandOptions(IPropertyTree &_graphNode)
  1496. {
  1497. //PARALLEL(1) can be used to explicitly disable parallel processing.
  1498. numStrands = _graphNode.getPropInt("att[@name='parallel']/@value", 0);
  1499. if ((numStrands == minus1U) || (numStrands > MAX_SENSIBLE_STRANDS))
  1500. numStrands = getAffinityCpus();
  1501. blockSize = _graphNode.getPropInt("hint[@name='strandblocksize']/@value", 0);
  1502. }
  1503. StrandOptions(const StrandOptions &from, IRoxieSlaveContext *ctx)
  1504. {
  1505. numStrands = from.numStrands;
  1506. blockSize = from.blockSize;
  1507. if (!blockSize)
  1508. blockSize = ctx->queryOptions().strandBlockSize;
  1509. if (numStrands == 0)
  1510. numStrands = ctx->queryOptions().forceNumStrands;
  1511. }
  1512. public:
  1513. unsigned numStrands = 0; // if 1 it forces single-stranded operations. (Useful for testing.)
  1514. unsigned blockSize = 0;
  1515. };
  1516. class StrandProcessor : public CInterfaceOf<IEngineRowStream>
  1517. {
  1518. protected:
  1519. CRoxieServerActivity &parent;
  1520. IEngineRowAllocator *rowAllocator;
  1521. IEngineRowStream *inputStream;
  1522. ActivityTimeAccumulator totalCycles;
  1523. mutable CRuntimeStatisticCollection stats;
  1524. unsigned processed = 0;
  1525. unsigned numProcessedLastGroup = 0;
  1526. const bool timeActivities;
  1527. bool stopped = false;
  1528. std::atomic<bool> abortRequested;
  1529. public:
  1530. explicit StrandProcessor(CRoxieServerActivity &_parent, IEngineRowStream *_inputStream, bool needsAllocator)
  1531. : parent(_parent), inputStream(_inputStream), stats(parent.queryStatsMapping()), timeActivities(_parent.timeActivities), abortRequested(false)
  1532. {
  1533. if (needsAllocator)
  1534. {
  1535. rowAllocator = parent.createRowAllocatorEx(parent.queryOutputMeta(), roxiemem::RHFunique);
  1536. }
  1537. else
  1538. rowAllocator = NULL;
  1539. }
  1540. ~StrandProcessor()
  1541. {
  1542. ::Release(rowAllocator);
  1543. }
  1544. virtual void start()
  1545. {
  1546. processed = 0;
  1547. numProcessedLastGroup = 0;
  1548. totalCycles.reset();
  1549. }
  1550. virtual void stop()
  1551. {
  1552. if (!stopped)
  1553. {
  1554. if (inputStream)
  1555. inputStream->stop();
  1556. parent.stop();
  1557. //It would be preferrable to move totalCycles (+processed?) to gatherStats(), but because of
  1558. //the way firstRow is associated with startCycles it would require an extra parameter
  1559. //which is not consistent with the other gatherStats() calls, or extra logic in the stats classes.
  1560. parent.mergeStrandStats(processed, totalCycles);
  1561. }
  1562. stopped = true;
  1563. }
  1564. virtual void reset()
  1565. {
  1566. stopped = false;
  1567. abortRequested.store(false, std::memory_order_relaxed);
  1568. }
  1569. virtual void resetEOF()
  1570. {
  1571. inputStream->resetEOF();
  1572. }
  1573. inline void requestAbort() { abortRequested.store(true, std::memory_order_relaxed); }
  1574. inline bool isAborting() { return abortRequested.load(std::memory_order_relaxed); }
  1575. void gatherStats(CRuntimeStatisticCollection & mergedStats) const
  1576. {
  1577. mergedStats.merge(stats);
  1578. if (rowAllocator)
  1579. rowAllocator->gatherStats(mergedStats);
  1580. }
  1581. };
  1582. class CRoxieServerStrandedActivity : public CRoxieServerActivity
  1583. {
  1584. protected:
  1585. StrandOptions strandOptions;
  1586. IArrayOf<StrandProcessor> strands;
  1587. Owned<IStrandBranch> branch;
  1588. Owned<IStrandJunction> splitter;
  1589. Owned<IStrandJunction> sourceJunction; // A junction applied to the output of a source activity
  1590. std::atomic<unsigned> active;
  1591. public:
  1592. CRoxieServerStrandedActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const StrandOptions &_strandOptions)
  1593. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  1594. strandOptions(_strandOptions, ctx)
  1595. {
  1596. active = 0;
  1597. }
  1598. ~CRoxieServerStrandedActivity()
  1599. {
  1600. if (strands.ordinality() > 1)
  1601. {
  1602. if (factory && !debugging)
  1603. factory->noteProcessed(0, processed);
  1604. if (ctx && factory)
  1605. ctx->noteProcessed(factory->querySubgraphId(), activityId, 0, processed, strands.ordinality());
  1606. processed = 0; // To avoid reprocessing in base destructor
  1607. }
  1608. }
  1609. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  1610. {
  1611. CRoxieServerActivity::gatherStats(merged);
  1612. ForEachItemIn(i, strands)
  1613. strands.item(i).gatherStats(merged);
  1614. }
  1615. virtual void onCreate(IHThorArg *_colocalArg)
  1616. {
  1617. CRoxieServerActivity::_onCreate(_colocalArg, strands.ordinality());
  1618. }
  1619. //This function is pure (But also implemented out of line) to force the derived classes to implement it.
  1620. //After calling the base class start method, and initialising any values from the helper they must call onStartStrands(),
  1621. //this must also happen before any rows are read from the strands (e.g., by a source junction)
  1622. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused) = 0;
  1623. virtual void reset()
  1624. {
  1625. assertex(active==0);
  1626. ForEachItemIn(idx, strands)
  1627. strands.item(idx).reset();
  1628. resetJunction(splitter);
  1629. CRoxieServerActivity::reset();
  1630. resetJunction(sourceJunction);
  1631. }
  1632. virtual void stop()
  1633. {
  1634. // Called from the strands... which should ensure that stop is not called more than once per strand
  1635. //The first strand to call
  1636. if (active)
  1637. --active;
  1638. if (!active)
  1639. CRoxieServerActivity::stop();
  1640. }
  1641. void requestAbort()
  1642. {
  1643. ForEachItemIn(idx, strands)
  1644. strands.item(idx).requestAbort();
  1645. }
  1646. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  1647. {
  1648. assertex(idx == 0);
  1649. assertex(strands.empty());
  1650. CRoxieServerActivity::connectDependencies();
  1651. bool inputOrdered = isInputOrdered(consumerOrdered, idx);
  1652. //Note, numStrands == 1 is an explicit request to disable threading
  1653. if (consumerOptions && (consumerOptions->numStrands != 1) && (strandOptions.numStrands != 1))
  1654. {
  1655. //Check to see if the consumer's settings should override
  1656. if (strandOptions.numStrands == 0)
  1657. {
  1658. strandOptions.numStrands = consumerOptions->numStrands;
  1659. strandOptions.blockSize = consumerOptions->blockSize;
  1660. }
  1661. else if (consumerOptions->numStrands > strandOptions.numStrands)
  1662. {
  1663. strandOptions.numStrands = consumerOptions->numStrands;
  1664. }
  1665. }
  1666. Owned <IStrandJunction> recombiner;
  1667. if (input)
  1668. {
  1669. if (strandOptions.numStrands == 1)
  1670. {
  1671. // 1 means explicitly requested single-strand.
  1672. IEngineRowStream *instream = connectSingleStream(ctx, input, sourceIdx, junction, inputOrdered);
  1673. strands.append(*createStrandProcessor(instream));
  1674. }
  1675. else
  1676. {
  1677. PointerArrayOf<IEngineRowStream> instreams;
  1678. recombiner.setown(input->getOutputStreams(ctx, sourceIdx, instreams, &strandOptions, inputOrdered, orderedCallbacks));
  1679. if ((instreams.length() == 1) && (strandOptions.numStrands != 0)) // 0 means did not specify - we should use the strands that our upstream provides
  1680. {
  1681. assertex(recombiner == NULL);
  1682. // Create a splitter to split the input into n... and a recombiner if need to preserve sorting
  1683. if (inputOrdered)
  1684. {
  1685. branch.setown(createStrandBranch(ctx->queryRowManager(), strandOptions.numStrands, strandOptions.blockSize, true, input->queryOutputMeta()->isGrouped(), false, orderedCallbacks));
  1686. splitter.set(branch->queryInputJunction());
  1687. recombiner.set(branch->queryOutputJunction());
  1688. }
  1689. else
  1690. {
  1691. splitter.setown(createStrandJunction(ctx->queryRowManager(), 1, strandOptions.numStrands, strandOptions.blockSize, false));
  1692. }
  1693. splitter->setInput(0, instreams.item(0));
  1694. for (unsigned strandNo = 0; strandNo < strandOptions.numStrands; strandNo++)
  1695. strands.append(*createStrandProcessor(splitter->queryOutput(strandNo)));
  1696. }
  1697. else
  1698. {
  1699. // Ignore my hint and just use the width already split into...
  1700. ForEachItemIn(strandNo, instreams)
  1701. strands.append(*createStrandProcessor(instreams.item(strandNo)));
  1702. }
  1703. }
  1704. }
  1705. else
  1706. {
  1707. unsigned numStrands = strandOptions.numStrands ? strandOptions.numStrands : 1;
  1708. for (unsigned i=0; i < numStrands; i++)
  1709. strands.append(*createStrandSourceProcessor(inputOrdered));
  1710. if (inputOrdered && (numStrands > 1))
  1711. {
  1712. if (consumerOptions)
  1713. {
  1714. //If the output activities are also stranded then need to create a version of the branch
  1715. bool isGrouped = queryOutputMeta()->isGrouped();
  1716. branch.setown(createStrandBranch(ctx->queryRowManager(), strandOptions.numStrands, strandOptions.blockSize, true, isGrouped, true, orderedCallbacks));
  1717. sourceJunction.set(branch->queryInputJunction());
  1718. recombiner.set(branch->queryOutputJunction());
  1719. assertex((orderedCallbacks && !recombiner) || (!orderedCallbacks && recombiner));
  1720. //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
  1721. for (unsigned strandNo = 0; strandNo < strandOptions.numStrands; strandNo++)
  1722. {
  1723. sourceJunction->setInput(strandNo, &strands.item(strandNo));
  1724. streams.append(sourceJunction->queryOutput(strandNo));
  1725. }
  1726. #ifdef TRACE_STRANDS
  1727. if (traceLevel > 2)
  1728. DBGLOG("Executing activity %u with %u strands", activityId, strands.ordinality());
  1729. #endif
  1730. return recombiner.getClear();
  1731. }
  1732. else
  1733. {
  1734. //Feeding into a non threaded activity, so create a M:1 junction to combine the source strands
  1735. recombiner.setown(createStrandJunction(ctx->queryRowManager(), numStrands, 1, strandOptions.blockSize, inputOrdered));
  1736. }
  1737. }
  1738. }
  1739. ForEachItemIn(i, strands)
  1740. streams.append(&strands.item(i));
  1741. #ifdef TRACE_STRANDS
  1742. if (traceLevel > 2)
  1743. DBGLOG("Executing activity %u with %u strands", activityId, strands.ordinality());
  1744. #endif
  1745. return recombiner.getClear();
  1746. }
  1747. virtual StrandProcessor *createStrandProcessor(IEngineRowStream *instream) = 0;
  1748. //MORE: Possibly this class should be split into two for sinks and non sinks...
  1749. virtual StrandProcessor *createStrandSourceProcessor(bool inputOrdered) = 0;
  1750. virtual const void * nextRow()
  1751. {
  1752. throwUnexpected();
  1753. }
  1754. inline unsigned numStrands() const { return strands.ordinality(); }
  1755. protected:
  1756. void onStartStrands()
  1757. {
  1758. ForEachItemIn(idx, strands)
  1759. {
  1760. strands.item(idx).start();
  1761. active++;
  1762. }
  1763. }
  1764. };
  1765. //For some reason gcc doesn't let you specify a function as pure virtual and define it at the same time.
  1766. void CRoxieServerStrandedActivity::start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  1767. {
  1768. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  1769. startJunction(splitter);
  1770. }
  1771. class CRoxieServerStrandedLateStartActivity : public CRoxieServerStrandedActivity
  1772. {
  1773. protected:
  1774. bool prefiltered;
  1775. bool eof;
  1776. void lateStart(unsigned parentExtractSize, const byte *parentExtract, bool any)
  1777. {
  1778. prefiltered = !any;
  1779. eof = prefiltered;
  1780. if (!prefiltered)
  1781. {
  1782. //At this point
  1783. input->start(parentExtractSize, parentExtract, false);
  1784. startJunction(splitter);
  1785. onStartStrands(); // Initialise the strands - the helper will have been correctly initialized by this point.
  1786. startJunction(sourceJunction);
  1787. }
  1788. else
  1789. {
  1790. if (traceStartStop)
  1791. CTXLOG("strandedLateStart activity stopping input early as prefiltered");
  1792. ForEachItemIn(idx, strands)
  1793. strands.item(idx).stop();
  1794. }
  1795. }
  1796. public:
  1797. CRoxieServerStrandedLateStartActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const StrandOptions &_strandOptions)
  1798. : CRoxieServerStrandedActivity(_ctx, _factory, _probeManager, _strandOptions)
  1799. {
  1800. prefiltered = false;
  1801. eof = false;
  1802. }
  1803. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  1804. {
  1805. IFinalRoxieInput *save = input;
  1806. 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)
  1807. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  1808. input = save;
  1809. }
  1810. virtual void reset()
  1811. {
  1812. CRoxieServerStrandedActivity::reset();
  1813. prefiltered = false;
  1814. }
  1815. };
  1816. //=====================================================================================================
  1817. atomic_t nextInstanceId;
  1818. extern unsigned getNextInstanceId()
  1819. {
  1820. return atomic_add_exchange(&nextInstanceId, 1)+1;
  1821. }
  1822. atomic_t nextRuid;
  1823. ruid_t getNextRuid()
  1824. {
  1825. ruid_t ret = atomic_add_exchange(&nextRuid, 1)+1;
  1826. while (ret < RUID_FIRST)
  1827. ret = atomic_add_exchange(&nextRuid, 1)+1; // ruids 0 and 1 are reserved for pings/unwanted discarder.
  1828. return ret;
  1829. }
  1830. void setStartRuid(unsigned restarts)
  1831. {
  1832. atomic_set(&nextRuid, restarts * 0x10000);
  1833. atomic_set(&nextInstanceId, restarts * 10000);
  1834. }
  1835. enum { LimitSkipErrorCode = 0, KeyedLimitSkipErrorCode = 1 };
  1836. class DECL_EXCEPTION LimitSkipException : public IException, public CInterface
  1837. {
  1838. int code;
  1839. public:
  1840. LimitSkipException(int _code) { code = _code; }
  1841. IMPLEMENT_IINTERFACE;
  1842. virtual int errorCode() const { return code; }
  1843. virtual StringBuffer & errorMessage(StringBuffer &msg) const { return msg.append("LimitSkipException"); }
  1844. virtual MessageAudience errorAudience() const { return MSGAUD_internal; }
  1845. };
  1846. IException *makeLimitSkipException(bool isKeyed)
  1847. {
  1848. // We need to make sure what we throw is IException not something derived from it....
  1849. return new LimitSkipException(isKeyed ? KeyedLimitSkipErrorCode : LimitSkipErrorCode);
  1850. }
  1851. //=================================================================================
  1852. interface IRecordPullerCallback : extends IExceptionHandler
  1853. {
  1854. virtual void processRow(const void *row) = 0;
  1855. virtual void processEOG() = 0;
  1856. virtual void processGroup(const ConstPointerArray &rows) = 0;
  1857. virtual void processDone() = 0;
  1858. };
  1859. class RecordPullerThread : public RestartableThread
  1860. {
  1861. protected:
  1862. IFinalRoxieInput *input;
  1863. Owned<IStrandJunction> junction;
  1864. unsigned sourceIdx = 0;
  1865. IEngineRowStream *inputStream;
  1866. IRecordPullerCallback *helper;
  1867. Semaphore started; // MORE: GH->RKC I'm pretty sure this can be deleted, since handled by RestartableThread
  1868. bool groupAtOnce, eof, eog;
  1869. CriticalSection crit;
  1870. public:
  1871. RecordPullerThread(bool _groupAtOnce)
  1872. : RestartableThread("RecordPullerThread"), groupAtOnce(_groupAtOnce)
  1873. {
  1874. input = NULL;
  1875. inputStream = NULL;
  1876. helper = NULL;
  1877. eof = eog = FALSE;
  1878. }
  1879. inline unsigned __int64 queryTotalCycles() const
  1880. {
  1881. return input->queryTotalCycles();
  1882. }
  1883. void setInput(IRecordPullerCallback *_helper, unsigned _sourceIdx, IFinalRoxieInput *_input)
  1884. {
  1885. helper = _helper;
  1886. input = _input;
  1887. sourceIdx = _sourceIdx;
  1888. }
  1889. IFinalRoxieInput *queryInput() const
  1890. {
  1891. return input;
  1892. }
  1893. virtual void connectInputStreams(IRoxieSlaveContext *ctx, bool consumerOrdered)
  1894. {
  1895. inputStream = connectSingleStream(ctx, input, sourceIdx, junction, consumerOrdered);
  1896. }
  1897. IEngineRowStream *queryStream() const
  1898. {
  1899. return inputStream;
  1900. }
  1901. void start(unsigned parentExtractSize, const byte *parentExtract, bool paused, unsigned preload, bool noThread, IRoxieSlaveContext *ctx)
  1902. {
  1903. eof = false;
  1904. eog = false;
  1905. input->start(parentExtractSize, parentExtract, paused);
  1906. startJunction(junction);
  1907. try
  1908. {
  1909. if (preload && !paused)
  1910. {
  1911. if (traceLevel > 4)
  1912. DBGLOG("Preload fetching first %d records", preload);
  1913. if (groupAtOnce)
  1914. pullGroups(preload);
  1915. else
  1916. pullRecords(preload);
  1917. }
  1918. if (eof)
  1919. {
  1920. if (traceLevel > 4)
  1921. DBGLOG("No need to start puller after preload");
  1922. helper->processDone();
  1923. }
  1924. else
  1925. {
  1926. if (!noThread)
  1927. {
  1928. StringBuffer logPrefix("[");
  1929. if (ctx) ctx->getLogPrefix(logPrefix);
  1930. logPrefix.append("] ");
  1931. RestartableThread::start(logPrefix);
  1932. started.wait();
  1933. }
  1934. }
  1935. }
  1936. catch (IException *e)
  1937. {
  1938. helper->fireException(e);
  1939. }
  1940. catch (...)
  1941. {
  1942. helper->fireException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unexpected exception caught in RecordPullerThread::start"));
  1943. }
  1944. }
  1945. void stop()
  1946. {
  1947. if (traceStartStop)
  1948. DBGLOG("RecordPullerThread::stop");
  1949. {
  1950. 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.
  1951. if (inputStream)
  1952. inputStream->stop();
  1953. }
  1954. RestartableThread::join();
  1955. }
  1956. void reset()
  1957. {
  1958. input->reset();
  1959. resetJunction(junction);
  1960. }
  1961. virtual int run()
  1962. {
  1963. started.signal();
  1964. try
  1965. {
  1966. if (groupAtOnce)
  1967. pullGroups((unsigned) -1);
  1968. else
  1969. pullRecords((unsigned) -1);
  1970. helper->processDone();
  1971. }
  1972. catch (IException *e)
  1973. {
  1974. helper->fireException(e);
  1975. }
  1976. catch (...)
  1977. {
  1978. helper->fireException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unexpected exception caught in RecordPullerThread::run"));
  1979. }
  1980. return 0;
  1981. }
  1982. void done()
  1983. {
  1984. helper->processDone();
  1985. }
  1986. bool pullRecords(unsigned preload)
  1987. {
  1988. if (eof)
  1989. return false;
  1990. while (preload)
  1991. {
  1992. const void * row;
  1993. {
  1994. CriticalBlock c(crit); // See comments in stop for why this is needed
  1995. row = inputStream->nextRow();
  1996. }
  1997. if (row)
  1998. {
  1999. eog = false;
  2000. helper->processRow(row);
  2001. }
  2002. else if (!eog)
  2003. {
  2004. helper->processEOG();
  2005. eog = true;
  2006. }
  2007. else
  2008. {
  2009. eof = true;
  2010. return false;
  2011. }
  2012. if (preload != (unsigned) -1)
  2013. preload--;
  2014. }
  2015. return true;
  2016. }
  2017. void pullGroups(unsigned preload)
  2018. {
  2019. ConstPointerArray thisGroup;
  2020. unsigned rowsDone = 0;
  2021. while (preload && !eof)
  2022. {
  2023. const void *row;
  2024. {
  2025. CriticalBlock c(crit);
  2026. row = inputStream->nextRow();
  2027. }
  2028. if (row)
  2029. {
  2030. thisGroup.append(row);
  2031. rowsDone++;
  2032. }
  2033. else if (thisGroup.length())
  2034. {
  2035. helper->processGroup(thisGroup);
  2036. thisGroup.kill();
  2037. if (preload != (unsigned) -1)
  2038. {
  2039. if (preload > rowsDone)
  2040. preload -= rowsDone;
  2041. else
  2042. break;
  2043. }
  2044. rowsDone = 0;
  2045. }
  2046. else
  2047. {
  2048. eof = true;
  2049. break;
  2050. }
  2051. }
  2052. }
  2053. };
  2054. //=================================================================================
  2055. #define READAHEAD_SIZE 1000
  2056. // MORE - this code copied from ThreadedConcat code - may be able to common up some.
  2057. class CRoxieServerReadAheadInput : implements IEngineRowStream, implements IFinalRoxieInput, implements IRecordPullerCallback, public CInterface
  2058. {
  2059. QueueOf<const void, true> buffer;
  2060. InterruptableSemaphore ready;
  2061. InterruptableSemaphore space;
  2062. CriticalSection crit;
  2063. bool eof;
  2064. bool disabled;
  2065. IRoxieSlaveContext *ctx;
  2066. RecordPullerThread puller;
  2067. unsigned preload;
  2068. cycle_t totalCycles;
  2069. bool timeActivities;
  2070. public:
  2071. IMPLEMENT_IINTERFACE;
  2072. CRoxieServerReadAheadInput(IRoxieSlaveContext *_ctx, unsigned _preload) : ctx(_ctx), puller(true), preload(_preload)
  2073. {
  2074. eof = false;
  2075. disabled = (ctx->queryDebugContext() != NULL);
  2076. totalCycles = 0;
  2077. timeActivities = ctx->queryOptions().timeActivities;
  2078. }
  2079. virtual IRoxieServerActivity *queryActivity()
  2080. {
  2081. return puller.queryInput()->queryActivity();
  2082. }
  2083. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  2084. {
  2085. assertex(!idx);
  2086. puller.connectInputStreams(ctx, consumerOrdered);
  2087. streams.append(this);
  2088. return NULL;
  2089. }
  2090. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { return this; }
  2091. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { return nullptr; }
  2092. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  2093. {
  2094. return puller.queryInput()->queryIndexReadActivity();
  2095. }
  2096. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  2097. {
  2098. eof = false;
  2099. if (disabled)
  2100. puller.queryInput()->start(parentExtractSize, parentExtract, paused);
  2101. else
  2102. {
  2103. space.reinit(READAHEAD_SIZE);
  2104. ready.reinit();
  2105. puller.start(parentExtractSize, parentExtract, paused, preload, false, ctx);
  2106. }
  2107. }
  2108. virtual void stop()
  2109. {
  2110. if (disabled)
  2111. puller.queryStream()->stop();
  2112. else
  2113. {
  2114. space.interrupt();
  2115. ready.interrupt();
  2116. puller.stop();
  2117. }
  2118. }
  2119. virtual void reset()
  2120. {
  2121. if (disabled)
  2122. puller.queryInput()->reset();
  2123. else
  2124. {
  2125. puller.reset();
  2126. ForEachItemIn(idx1, buffer)
  2127. ReleaseRoxieRow(buffer.item(idx1));
  2128. buffer.clear();
  2129. }
  2130. }
  2131. virtual void resetEOF()
  2132. {
  2133. throwUnexpected();
  2134. }
  2135. virtual IOutputMetaData * queryOutputMeta() const
  2136. {
  2137. return puller.queryInput()->queryOutputMeta();
  2138. }
  2139. void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  2140. {
  2141. assertex(!idx);
  2142. puller.setInput(this, _sourceIdx, _in);
  2143. }
  2144. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  2145. {
  2146. if (idx==0)
  2147. return puller.queryInput();
  2148. else
  2149. return NULL;
  2150. }
  2151. virtual unsigned __int64 queryTotalCycles() const
  2152. {
  2153. return totalCycles;
  2154. }
  2155. virtual const void * nextRow()
  2156. {
  2157. SimpleActivityTimer t(totalCycles, timeActivities);
  2158. if (disabled)
  2159. return puller.queryStream()->nextRow();
  2160. else
  2161. {
  2162. for (;;)
  2163. {
  2164. {
  2165. CriticalBlock b(crit);
  2166. if (eof && !buffer.ordinality())
  2167. return NULL; // eof
  2168. }
  2169. ready.wait();
  2170. const void *ret;
  2171. {
  2172. CriticalBlock b(crit);
  2173. ret = buffer.dequeue();
  2174. }
  2175. space.signal();
  2176. return ret;
  2177. }
  2178. }
  2179. }
  2180. virtual bool fireException(IException *e)
  2181. {
  2182. // called from puller thread on failure
  2183. ready.interrupt(LINK(e));
  2184. space.interrupt(e);
  2185. return true;
  2186. }
  2187. virtual void processRow(const void *row)
  2188. {
  2189. {
  2190. CriticalBlock b(crit);
  2191. buffer.enqueue(row);
  2192. }
  2193. ready.signal();
  2194. space.wait();
  2195. }
  2196. virtual void processGroup(const ConstPointerArray &rows)
  2197. {
  2198. // NOTE - a bit bizarre in that it waits for the space AFTER using it.
  2199. // But the space semaphore is only there to stop infinite readahead. And otherwise it would deadlock
  2200. // if group was larger than max(space)
  2201. {
  2202. CriticalBlock b(crit);
  2203. ForEachItemIn(idx, rows)
  2204. buffer.enqueue(rows.item(idx));
  2205. buffer.enqueue(NULL);
  2206. }
  2207. for (unsigned i2 = 0; i2 <= rows.length(); i2++) // note - does 1 extra for the null
  2208. {
  2209. ready.signal();
  2210. space.wait();
  2211. }
  2212. }
  2213. virtual void processEOG()
  2214. {
  2215. // Used when output is not grouped - just ignore
  2216. }
  2217. virtual void processDone()
  2218. {
  2219. CriticalBlock b(crit);
  2220. eof = true;
  2221. ready.signal();
  2222. }
  2223. };
  2224. //=================================================================================
  2225. class CRoxieServerTwoInputActivity : public CRoxieServerActivity
  2226. {
  2227. protected:
  2228. IFinalRoxieInput *input1;
  2229. IEngineRowStream *inputStream1;
  2230. Owned<IStrandJunction> junction1;
  2231. unsigned sourceIdx1 = 0;
  2232. Owned<CRoxieServerReadAheadInput> puller;
  2233. public:
  2234. CRoxieServerTwoInputActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  2235. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  2236. {
  2237. input1 = NULL;
  2238. inputStream1 = NULL;
  2239. }
  2240. ~CRoxieServerTwoInputActivity()
  2241. {
  2242. }
  2243. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  2244. {
  2245. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  2246. input1->start(parentExtractSize, parentExtract, paused);
  2247. startJunction(junction1);
  2248. }
  2249. virtual void stop()
  2250. {
  2251. inputStream1->stop();
  2252. CRoxieServerActivity::stop();
  2253. }
  2254. virtual unsigned __int64 queryLocalCycles() const
  2255. {
  2256. __int64 ret;
  2257. __int64 inputCycles = input->queryTotalCycles();
  2258. __int64 input1Cycles = input1->queryTotalCycles();
  2259. if (puller)
  2260. ret = totalCycles.totalCycles - (inputCycles > input1Cycles ? inputCycles : input1Cycles);
  2261. else
  2262. ret = totalCycles.totalCycles - (inputCycles + input1Cycles);
  2263. if (ret < 0)
  2264. ret = 0;
  2265. return ret;
  2266. }
  2267. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  2268. {
  2269. switch (idx)
  2270. {
  2271. case 0:
  2272. return input;
  2273. case 1:
  2274. return input1;
  2275. default:
  2276. return NULL;
  2277. }
  2278. }
  2279. virtual void reset()
  2280. {
  2281. CRoxieServerActivity::reset();
  2282. if (input1)
  2283. input1->reset();
  2284. resetJunction(junction1);
  2285. }
  2286. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  2287. {
  2288. switch(idx)
  2289. {
  2290. case 0:
  2291. CRoxieServerActivity::setInput(idx, _sourceIdx, _in);
  2292. break;
  2293. case 1:
  2294. input1 = _in;
  2295. sourceIdx1 = _sourceIdx;
  2296. break;
  2297. default:
  2298. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
  2299. }
  2300. }
  2301. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  2302. {
  2303. inputStream1 = connectSingleStream(ctx, input1, sourceIdx1, junction1, isInputOrdered(consumerOrdered, 1));
  2304. //Assumes input1 will be stranded if any.
  2305. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
  2306. }
  2307. };
  2308. //=================================================================================
  2309. class CRoxieServerMultiInputBaseActivity : public CRoxieServerActivity
  2310. {
  2311. protected:
  2312. unsigned numInputs;
  2313. unsigned numStreams;
  2314. IFinalRoxieInput **inputArray;
  2315. unsigned *sourceIdxArray;
  2316. IEngineRowStream **streamArray;
  2317. Owned<IStrandJunction> *junctionArray;
  2318. public:
  2319. CRoxieServerMultiInputBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  2320. : CRoxieServerActivity(_ctx, _factory, _probeManager), numInputs(_numInputs)
  2321. {
  2322. numStreams = numInputs;
  2323. inputArray = new IFinalRoxieInput*[numInputs];
  2324. sourceIdxArray = new unsigned[numInputs];
  2325. streamArray = new IEngineRowStream*[numStreams];
  2326. junctionArray = new Owned<IStrandJunction>[numStreams];
  2327. for (unsigned i1 = 0; i1 < numInputs; i1++)
  2328. {
  2329. inputArray[i1] = NULL;
  2330. sourceIdxArray[i1] = 0;
  2331. }
  2332. for (unsigned i2 = 0; i2 < numStreams; i2++)
  2333. streamArray[i2] = NULL;
  2334. }
  2335. ~CRoxieServerMultiInputBaseActivity()
  2336. {
  2337. delete [] inputArray;
  2338. delete [] sourceIdxArray;
  2339. delete [] streamArray;
  2340. delete [] junctionArray;
  2341. }
  2342. virtual unsigned __int64 queryLocalCycles() const
  2343. {
  2344. __int64 localCycles = totalCycles.totalCycles;
  2345. for (unsigned i = 0; i < numInputs; i++)
  2346. localCycles -= inputArray[i]->queryTotalCycles();
  2347. if (localCycles < 0)
  2348. localCycles = 0;
  2349. return localCycles;
  2350. }
  2351. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  2352. {
  2353. if (idx < numInputs)
  2354. return inputArray[idx];
  2355. else
  2356. return NULL;
  2357. }
  2358. virtual IFinalRoxieInput * queryConcreteInput(unsigned idx)
  2359. {
  2360. return queryInput(idx);
  2361. }
  2362. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput)
  2363. {
  2364. if (whichInput < numInputs)
  2365. return streamArray[whichInput];
  2366. else
  2367. return NULL;
  2368. }
  2369. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const
  2370. {
  2371. if (idx < numInputs)
  2372. return junctionArray[idx];
  2373. else
  2374. return NULL;
  2375. }
  2376. virtual void reset()
  2377. {
  2378. for (unsigned i = 0; i < numInputs; i++)
  2379. inputArray[i]->reset();
  2380. for (unsigned iS = 0; iS < numStreams; iS++)
  2381. {
  2382. resetJunction(junctionArray[iS]);
  2383. }
  2384. CRoxieServerActivity::reset();
  2385. }
  2386. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  2387. {
  2388. assertex(idx < numInputs && idx < numStreams);
  2389. inputArray[idx] = _in;
  2390. sourceIdxArray[idx] = _sourceIdx;
  2391. }
  2392. virtual void connectInputStreams(bool consumerOrdered)
  2393. {
  2394. //There could be situations (e.g., NONEMPTY), where you might want to strand the activity.
  2395. connectSingleInputStreams(consumerOrdered);
  2396. CRoxieServerActivity::connectInputStreams(consumerOrdered);
  2397. }
  2398. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  2399. {
  2400. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, NULL, consumerOrdered, nullptr); // The input basesclass does not have an input
  2401. }
  2402. protected:
  2403. void connectSingleInputStreams(bool consumerOrdered)
  2404. {
  2405. for (unsigned i = 0; i < numInputs; i++)
  2406. streamArray[i] = connectSingleStream(ctx, inputArray[i], sourceIdxArray[i], junctionArray[i], consumerOrdered);
  2407. }
  2408. };
  2409. //=================================================================================
  2410. class CRoxieServerMultiInputActivity : public CRoxieServerMultiInputBaseActivity
  2411. {
  2412. public:
  2413. CRoxieServerMultiInputActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  2414. : CRoxieServerMultiInputBaseActivity(_ctx, _factory, _probeManager, _numInputs)
  2415. {
  2416. }
  2417. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  2418. {
  2419. CRoxieServerMultiInputBaseActivity::start(parentExtractSize, parentExtract, paused);
  2420. for (unsigned i = 0; i < numInputs; i++)
  2421. {
  2422. inputArray[i]->start(parentExtractSize, parentExtract, paused);
  2423. }
  2424. for (unsigned iS = 0; iS < numStreams; iS++)
  2425. {
  2426. startJunction(junctionArray[iS]);
  2427. }
  2428. }
  2429. virtual void stop()
  2430. {
  2431. for (unsigned i = 0; i < numStreams; i++)
  2432. {
  2433. streamArray[i]->stop();
  2434. }
  2435. CRoxieServerMultiInputBaseActivity::stop();
  2436. }
  2437. };
  2438. //=====================================================================================================
  2439. class CRoxieServerInternalSinkActivity : public CRoxieServerActivity
  2440. {
  2441. protected:
  2442. unsigned numOutputs;
  2443. bool executed;
  2444. bool *stopped;
  2445. CriticalSection ecrit;
  2446. Owned<IException> exception;
  2447. public:
  2448. CRoxieServerInternalSinkActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  2449. : CRoxieServerActivity(_ctx, _factory, _probeManager), numOutputs(_numOutputs)
  2450. {
  2451. executed = false;
  2452. stopped = new bool[numOutputs];
  2453. for (unsigned s = 0; s < numOutputs; s++)
  2454. stopped[s] = false;
  2455. }
  2456. ~CRoxieServerInternalSinkActivity()
  2457. {
  2458. delete [] stopped;
  2459. }
  2460. virtual void reset()
  2461. {
  2462. for (unsigned s = 0; s < numOutputs; s++)
  2463. stopped[s] = false;
  2464. executed = false;
  2465. exception.clear();
  2466. CRoxieServerActivity::reset();
  2467. }
  2468. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  2469. {
  2470. return NULL;
  2471. }
  2472. virtual void stopSink(unsigned outputIdx)
  2473. {
  2474. if (outputIdx < numOutputs && !stopped[outputIdx]) // Implicit dependencies on DiskWrite activities do not count as outputs
  2475. {
  2476. stopped[outputIdx] = true;
  2477. for (unsigned s = 0; s < numOutputs; s++)
  2478. if (!stopped[s])
  2479. return;
  2480. stop(); // all outputs stopped - stop parent.
  2481. }
  2482. }
  2483. virtual const void *nextRow()
  2484. {
  2485. throwUnexpected(); // I am nobody's input
  2486. }
  2487. virtual void onExecute() = 0;
  2488. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  2489. {
  2490. CriticalBlock b(ecrit);
  2491. if (exception)
  2492. throw exception.getLink();
  2493. if (!executed)
  2494. {
  2495. try
  2496. {
  2497. start(parentExtractSize, parentExtract, false);
  2498. {
  2499. ActivityTimer t(totalCycles, timeActivities); // unfortunately this is not really best place for seeing in debugger.
  2500. onExecute();
  2501. }
  2502. stop();
  2503. executed = true;
  2504. }
  2505. catch (IException *E)
  2506. {
  2507. exception.set(E); // (or maybe makeWrappedException?)
  2508. abort();
  2509. throw;
  2510. }
  2511. catch (...)
  2512. {
  2513. exception.set(MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught at %s:%d", sanitizeSourceFile(__FILE__), __LINE__));
  2514. abort();
  2515. throw;
  2516. }
  2517. }
  2518. }
  2519. };
  2520. //=================================================================================
  2521. class CRoxieServerQueryPacket : implements IRoxieServerQueryPacket, public CInterface
  2522. {
  2523. protected:
  2524. Owned<IMessageResult> result;
  2525. Owned<IRoxieQueryPacket> packet;
  2526. Linked<IRoxieServerQueryPacket> continuation;
  2527. unsigned hash;
  2528. unsigned seq;
  2529. unsigned lastDebugSequence;
  2530. Owned<IRoxieQueryPacket> lastDebugResponse;
  2531. ILRUChain *prev;
  2532. ILRUChain *next;
  2533. bool delayed;
  2534. public:
  2535. IMPLEMENT_IINTERFACE;
  2536. CRoxieServerQueryPacket(IRoxieQueryPacket *p) : packet(p)
  2537. {
  2538. hash = 0;
  2539. seq = 0;
  2540. prev = NULL;
  2541. next = NULL;
  2542. delayed = false;
  2543. lastDebugSequence = 0;
  2544. }
  2545. virtual IRoxieQueryPacket *queryPacket() const
  2546. {
  2547. return packet;
  2548. }
  2549. virtual bool isContinuation() const
  2550. {
  2551. return packet && (packet->queryHeader().continueSequence & ~CONTINUE_SEQUENCE_SKIPTO) != 0;
  2552. }
  2553. virtual bool isDelayed() const
  2554. {
  2555. return delayed;
  2556. }
  2557. virtual bool isEnd() const
  2558. {
  2559. return false;
  2560. }
  2561. virtual bool isLimit(unsigned __int64 &_rowLimit, unsigned __int64 &_keyedLimit, unsigned __int64 &_stopAfter) const
  2562. {
  2563. return false;
  2564. }
  2565. virtual bool hasResult() const
  2566. {
  2567. return result != NULL;
  2568. }
  2569. virtual bool hasContinuation() const
  2570. {
  2571. return continuation != NULL;
  2572. }
  2573. virtual void setDelayed(bool _delayed)
  2574. {
  2575. delayed = _delayed;
  2576. }
  2577. virtual void setPacket(IRoxieQueryPacket *_packet)
  2578. {
  2579. packet.setown(_packet);
  2580. }
  2581. virtual void setSequence(unsigned _seq)
  2582. {
  2583. assertex(!IsShared());
  2584. seq = _seq;
  2585. }
  2586. virtual unsigned getSequence() const
  2587. {
  2588. return seq;
  2589. }
  2590. IMessageResult *getResult()
  2591. {
  2592. return result.getLink();
  2593. }
  2594. IMessageResult *queryResult()
  2595. {
  2596. return result;
  2597. }
  2598. void setResult(IMessageResult *r)
  2599. {
  2600. result.setown(r);
  2601. }
  2602. IRoxieServerQueryPacket *queryContinuation()
  2603. {
  2604. return continuation;
  2605. }
  2606. void setContinuation(IRoxieServerQueryPacket *c)
  2607. {
  2608. continuation.setown(c);
  2609. }
  2610. virtual unsigned queryHash() const
  2611. {
  2612. return hash;
  2613. }
  2614. virtual void setHash(unsigned _hash)
  2615. {
  2616. hash = _hash;
  2617. }
  2618. virtual ILRUChain *queryPrev() const { return prev; }
  2619. virtual ILRUChain *queryNext() const { return next; }
  2620. virtual void setPrev(ILRUChain *p) { prev = p; }
  2621. virtual void setNext(ILRUChain *n) { next = n; }
  2622. virtual void unchain()
  2623. {
  2624. if (prev && next)
  2625. {
  2626. prev->setNext(next);
  2627. next->setPrev(prev);
  2628. }
  2629. next = NULL;
  2630. prev = NULL;
  2631. }
  2632. virtual IRoxieQueryPacket *getDebugResponse(unsigned sequence)
  2633. {
  2634. if (sequence == lastDebugSequence)
  2635. return lastDebugResponse.getLink();
  2636. else if (sequence > lastDebugSequence)
  2637. {
  2638. lastDebugResponse.clear();
  2639. return NULL;
  2640. }
  2641. else
  2642. throwUnexpected();
  2643. }
  2644. virtual void setDebugResponse(unsigned sequence, IRoxieQueryPacket *response)
  2645. {
  2646. lastDebugSequence = sequence;
  2647. lastDebugResponse.set(response);
  2648. }
  2649. };
  2650. class CRoxieServerQueryPacketEndMarker : public CRoxieServerQueryPacket
  2651. {
  2652. public:
  2653. CRoxieServerQueryPacketEndMarker() : CRoxieServerQueryPacket(NULL)
  2654. {
  2655. }
  2656. virtual bool isEnd() const
  2657. {
  2658. return true;
  2659. }
  2660. };
  2661. class CRoxieServerQueryPacketLimitMarker : public CRoxieServerQueryPacket
  2662. {
  2663. unsigned __int64 rowLimit;
  2664. unsigned __int64 keyedLimit;
  2665. unsigned __int64 stopAfter;
  2666. public:
  2667. CRoxieServerQueryPacketLimitMarker(unsigned __int64 _rowLimit, unsigned __int64 _keyedLimit, unsigned __int64 _stopAfter) : CRoxieServerQueryPacket(NULL)
  2668. {
  2669. rowLimit = _rowLimit;
  2670. keyedLimit = _keyedLimit;
  2671. stopAfter = _stopAfter;
  2672. }
  2673. virtual bool isLimit(unsigned __int64 &_rowLimit, unsigned __int64 &_keyedLimit, unsigned __int64 &_stopAfter) const
  2674. {
  2675. _rowLimit = rowLimit;
  2676. _keyedLimit = keyedLimit;
  2677. _stopAfter = stopAfter;
  2678. return true;
  2679. }
  2680. };
  2681. class CRoxieServerSideCache : implements IRoxieServerSideCache, implements ILRUChain
  2682. {
  2683. protected:
  2684. unsigned cacheTableSize;
  2685. unsigned cacheTableSpace;
  2686. IRoxieServerQueryPacket **cacheTable;
  2687. mutable ILRUChain *prev;
  2688. mutable ILRUChain *next;
  2689. mutable CriticalSection crit;
  2690. virtual ILRUChain *queryPrev() const { return prev; }
  2691. virtual ILRUChain *queryNext() const { return next; }
  2692. virtual void setPrev(ILRUChain *p) { prev = p; }
  2693. virtual void setNext(ILRUChain *n) { next = n; }
  2694. virtual void unchain()
  2695. {
  2696. prev->setNext(next);
  2697. next->setPrev(prev);
  2698. next = NULL;
  2699. prev = NULL;
  2700. }
  2701. void moveToHead(IRoxieServerQueryPacket *mru)
  2702. {
  2703. mru->unchain();
  2704. mru->setNext(next);
  2705. next->setPrev(mru);
  2706. mru->setPrev(this);
  2707. next = mru;
  2708. }
  2709. IRoxieServerQueryPacket *removeLRU()
  2710. {
  2711. if (next==this)
  2712. assertex(next != this);
  2713. IRoxieServerQueryPacket *goer = (IRoxieServerQueryPacket *) next;
  2714. goer->unchain(); // NOTE - this will modify the value of next
  2715. return goer;
  2716. }
  2717. void removeEntry(IRoxieServerQueryPacket *goer)
  2718. {
  2719. unsigned v = goer->queryHash() % cacheTableSize;
  2720. for (;;)
  2721. {
  2722. IRoxieServerQueryPacket *found = cacheTable[v];
  2723. assertex(found);
  2724. if (found == goer)
  2725. {
  2726. cacheTable[v] = NULL;
  2727. unsigned vn = v;
  2728. for (;;)
  2729. {
  2730. vn++;
  2731. if (vn==cacheTableSize) vn = 0;
  2732. IRoxieServerQueryPacket *found2 = cacheTable[vn];
  2733. if (!found2)
  2734. break;
  2735. unsigned vm = found2->queryHash() % cacheTableSize;
  2736. if (((vn+cacheTableSize-vm) % cacheTableSize)>=((vn+cacheTableSize-v) % cacheTableSize)) // diff(vn,vm)>=diff(vn,v)
  2737. {
  2738. cacheTable[v] = found2;
  2739. v = vn;
  2740. cacheTable[v] = NULL;
  2741. }
  2742. }
  2743. cacheTableSpace++;
  2744. break;
  2745. }
  2746. v++;
  2747. if (v==cacheTableSize)
  2748. v = 0;
  2749. }
  2750. goer->Release();
  2751. }
  2752. public:
  2753. CRoxieServerSideCache(unsigned _cacheSize)
  2754. {
  2755. cacheTableSize = (_cacheSize*4)/3;
  2756. cacheTable = new IRoxieServerQueryPacket *[cacheTableSize];
  2757. memset(cacheTable, 0, cacheTableSize * sizeof(IRoxieServerQueryPacket *));
  2758. cacheTableSpace = _cacheSize;
  2759. prev = this;
  2760. next = this;
  2761. }
  2762. ~CRoxieServerSideCache()
  2763. {
  2764. for (unsigned i = 0; i < cacheTableSize; i++)
  2765. {
  2766. ::Release(cacheTable[i]);
  2767. }
  2768. delete [] cacheTable;
  2769. }
  2770. virtual IRoxieServerQueryPacket *findCachedResult(const IRoxieContextLogger &logctx, IRoxieQueryPacket *p) const
  2771. {
  2772. unsigned hash = p->hash();
  2773. unsigned et = hash % cacheTableSize;
  2774. if (traceServerSideCache)
  2775. {
  2776. StringBuffer s;
  2777. logctx.CTXLOG("CRoxieServerSideCache::findCachedResult hash %x slot %d %s", hash, et, p->queryHeader().toString(s).str());
  2778. }
  2779. CriticalBlock b(crit);
  2780. for (;;)
  2781. {
  2782. IRoxieServerQueryPacket *found = cacheTable[et];
  2783. if (!found)
  2784. return NULL;
  2785. if (found->queryHash() == hash && found->queryPacket()->cacheMatch(p))
  2786. {
  2787. const_cast<CRoxieServerSideCache *>(this)->moveToHead(found);
  2788. if (traceServerSideCache)
  2789. logctx.CTXLOG("CRoxieServerSideCache::findCachedResult cache hit");
  2790. logctx.noteStatistic(StNumServerCacheHits, 1);
  2791. return NULL;
  2792. // 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....
  2793. //IRoxieServerQueryPacket *ret = new CRoxieServerQueryPacket(p);
  2794. //ret->setResult(found->getResult());
  2795. //return ret;
  2796. }
  2797. et++;
  2798. if (et == cacheTableSize)
  2799. et = 0;
  2800. }
  2801. }
  2802. virtual void noteCachedResult(IRoxieServerQueryPacket *out, IMessageResult *in)
  2803. {
  2804. if (true) //!in->getLength()) // MORE - separate caches for hits and nohits
  2805. {
  2806. unsigned hash = out->queryPacket()->hash();
  2807. out->setHash(hash);
  2808. unsigned et = hash % cacheTableSize;
  2809. if (traceServerSideCache)
  2810. {
  2811. StringBuffer s;
  2812. DBGLOG("CRoxieServerSideCache::noteCachedResult hash %x slot %d %s", hash, et, out->queryPacket()->queryHeader().toString(s).str());
  2813. }
  2814. CriticalBlock b(crit);
  2815. for (;;)
  2816. {
  2817. IRoxieServerQueryPacket *found = cacheTable[et];
  2818. if (!found)
  2819. {
  2820. if (cacheTableSpace)
  2821. {
  2822. out->setResult(LINK(in));
  2823. cacheTable[et] = LINK(out);
  2824. cacheTableSpace--;
  2825. moveToHead(out);
  2826. break;
  2827. }
  2828. else
  2829. {
  2830. IRoxieServerQueryPacket *goer = removeLRU();
  2831. removeEntry(goer);
  2832. et = hash % cacheTableSize;
  2833. continue;
  2834. }
  2835. }
  2836. else if (found->queryHash()==hash && found->queryPacket()->cacheMatch(out->queryPacket()))
  2837. {
  2838. moveToHead(found);
  2839. return; // already in the cache. Because we don't cache until we have result, this can happen where
  2840. // multiple copies of a slave query are in-flight at once.
  2841. }
  2842. et++;
  2843. if (et == cacheTableSize)
  2844. et = 0;
  2845. }
  2846. }
  2847. // MORE - do we need to worry about the attachment between the MessageUnpacker and the current row manager. May all fall out ok...
  2848. // Can I easily spot a null result? Do I want to cache null results separately? only?
  2849. }
  2850. // Note that this caching mechanism (unlike the old keyed-join specific one) does not common up cases where multiple
  2851. // identical queries are in-flight at the same time. But if we can make it persistent between queries that will
  2852. // more than make up for it
  2853. };
  2854. class CRowArrayMessageUnpackCursor : implements IMessageUnpackCursor, public CInterface
  2855. {
  2856. ConstPointerArray &data;
  2857. Linked<IMessageResult> result;
  2858. public:
  2859. IMPLEMENT_IINTERFACE;
  2860. CRowArrayMessageUnpackCursor(ConstPointerArray &_data, IMessageResult *_result)
  2861. : data(_data), result(_result)
  2862. {
  2863. }
  2864. virtual bool atEOF() const
  2865. {
  2866. return data.length()==0;
  2867. }
  2868. virtual bool isSerialized() const
  2869. {
  2870. return false;
  2871. }
  2872. virtual const void * getNext(int length)
  2873. {
  2874. if (!data.length())
  2875. return NULL;
  2876. const void *ret = data.item(0);
  2877. data.remove(0);
  2878. return ret;
  2879. }
  2880. };
  2881. // MORE - should possibly move more over to the lazy version used in indexread?
  2882. class CRowArrayMessageResult : implements IMessageResult, public CInterface
  2883. {
  2884. ConstPointerArray data;
  2885. IRowManager &rowManager;
  2886. bool variableSize;
  2887. public:
  2888. IMPLEMENT_IINTERFACE;
  2889. CRowArrayMessageResult(IRowManager &_rowManager, bool _variableSize) : rowManager(_rowManager), variableSize(_variableSize)
  2890. {
  2891. }
  2892. ~CRowArrayMessageResult()
  2893. {
  2894. ReleaseRoxieRows(data);
  2895. }
  2896. virtual IMessageUnpackCursor *getCursor(IRowManager *rowMgr) const
  2897. {
  2898. CRowArrayMessageResult *_this = (CRowArrayMessageResult *) this;
  2899. return new CRowArrayMessageUnpackCursor(_this->data, _this);
  2900. }
  2901. virtual const void *getMessageHeader(unsigned &length) const
  2902. {
  2903. throwUnexpected(); // should never get called - I don't have a header available
  2904. }
  2905. virtual const void *getMessageMetadata(unsigned &length) const
  2906. {
  2907. length = 0;
  2908. return NULL;
  2909. }
  2910. virtual void discard() const
  2911. {
  2912. throwUnexpected();
  2913. }
  2914. void append(const void *row)
  2915. {
  2916. data.append(row);
  2917. }
  2918. };
  2919. void throwRemoteException(IMessageUnpackCursor *extra)
  2920. {
  2921. RecordLengthType *rowlen = (RecordLengthType *) extra->getNext(sizeof(RecordLengthType));
  2922. if (rowlen)
  2923. {
  2924. char *xml = (char *) extra->getNext(*rowlen);
  2925. ReleaseRoxieRow(rowlen);
  2926. Owned<IPropertyTree> p = createPTreeFromXMLString(xml, ipt_fast);
  2927. ReleaseRoxieRow(xml);
  2928. unsigned code = p->getPropInt("Code", 0);
  2929. const char *msg = p->queryProp("Message");
  2930. if (!msg)
  2931. msg = xml;
  2932. throw MakeStringException(code, "%s", msg);
  2933. }
  2934. throwUnexpected();
  2935. }
  2936. class CRemoteResultAdaptor : implements IEngineRowStream, implements IFinalRoxieInput, implements IExceptionHandler, public CInterface
  2937. {
  2938. friend class CRemoteResultMerger;
  2939. class CRemoteResultMerger
  2940. {
  2941. class HeapEntry : public CInterface
  2942. {
  2943. private:
  2944. CRemoteResultAdaptor &adaptor;
  2945. IMessageUnpackCursor *cursor;
  2946. public:
  2947. const void *current;
  2948. bool isLast;
  2949. bool lastIsComplete;
  2950. IRoxieServerQueryPacket *packet;
  2951. unsigned seq;
  2952. public:
  2953. inline const void *noteResult(IMessageUnpackCursor *_cursor, bool _lastIsComplete)
  2954. {
  2955. cursor = _cursor;
  2956. lastIsComplete = _lastIsComplete;
  2957. return next();
  2958. }
  2959. public:
  2960. HeapEntry(CRemoteResultAdaptor &_adaptor, IRoxieServerQueryPacket *_packet, unsigned _seq) : adaptor(_adaptor), packet(_packet), seq(_seq)
  2961. {
  2962. cursor = NULL;
  2963. current = NULL;
  2964. isLast = false;
  2965. lastIsComplete = true;
  2966. }
  2967. ~HeapEntry()
  2968. {
  2969. ::Release(packet);
  2970. ::Release(cursor);
  2971. ReleaseRoxieRow(current);
  2972. }
  2973. bool isCompleteMatch() const
  2974. {
  2975. if (!isLast || lastIsComplete)
  2976. return true;
  2977. else
  2978. return false;
  2979. }
  2980. const void *next()
  2981. {
  2982. if (cursor)
  2983. {
  2984. ReleaseClearRoxieRow(current);
  2985. current = adaptor.getRow(cursor);
  2986. isLast = cursor->atEOF();
  2987. if (!current)
  2988. {
  2989. cursor->Release();
  2990. cursor = NULL;
  2991. }
  2992. }
  2993. return current;
  2994. }
  2995. unsigned skipTo(IRangeCompare *compare, const void *seek, unsigned numFields, bool requireExactMatch)
  2996. {
  2997. // MORE - This loop should possibly be a binchop... though it's not absolutely clear that is true (depends on term frequencies)
  2998. unsigned skipped = 0;
  2999. for (;;)
  3000. {
  3001. int c = compare->docompare(current, seek, numFields);
  3002. //If larger than the seek values, then we may be allowed to return an inexact match,
  3003. //if equal then it is required to be an exact match,
  3004. if (c > 0)
  3005. {
  3006. if (!requireExactMatch || isCompleteMatch())
  3007. break;
  3008. }
  3009. else if ((c == 0) && isCompleteMatch())
  3010. break;
  3011. skipped++;
  3012. if (!next())
  3013. break;
  3014. }
  3015. return skipped;
  3016. }
  3017. };
  3018. CRemoteResultAdaptor &adaptor;
  3019. CIArrayOf<HeapEntry> heapEntries;
  3020. UnsignedArray heap;
  3021. IRowManager *rowManager;
  3022. unsigned numPending;
  3023. unsigned numFields;
  3024. bool endSeen;
  3025. bool remakePending;
  3026. IRangeCompare *compare;
  3027. bool deferredContinuation;
  3028. inline int doCompare(unsigned l, unsigned r)
  3029. {
  3030. int ret = compare->docompare(heapEntries.item(l).current, heapEntries.item(r).current, numFields);
  3031. if (!ret) ret = heapEntries.item(l).seq - heapEntries.item(r).seq;
  3032. return ret;
  3033. }
  3034. void makeHeap()
  3035. {
  3036. /* Permute blocks to establish the heap property
  3037. For each element p, the children are p*2+1 and p*2+2 (provided these are in range)
  3038. The children of p must both be greater than or equal to p
  3039. The parent of a child c is given by p = (c-1)/2
  3040. */
  3041. unsigned i;
  3042. unsigned n = heap.length();
  3043. unsigned *s = heap.getArray();
  3044. for (i=1; i<n; i++)
  3045. {
  3046. unsigned r = s[i];
  3047. int c = i; /* child */
  3048. while (c > 0)
  3049. {
  3050. int p = (c-1)/2; /* parent */
  3051. if ( doCompare( s[c], s[p] ) >= 0 )
  3052. break;
  3053. s[c] = s[p];
  3054. s[p] = r;
  3055. c = p;
  3056. }
  3057. }
  3058. remakePending = false;
  3059. }
  3060. void remakeHeap()
  3061. {
  3062. /* The row associated with block[0] will have changed
  3063. This code restores the heap property
  3064. */
  3065. unsigned p = 0; /* parent */
  3066. unsigned n = heap.length();
  3067. unsigned *s = heap.getArray();
  3068. while (1)
  3069. {
  3070. unsigned c = p*2 + 1; /* child */
  3071. if ( c >= n )
  3072. break;
  3073. /* Select smaller child */
  3074. if ( c+1 < n && doCompare( s[c+1], s[c] ) < 0 ) c += 1;
  3075. /* If child is greater or equal than parent then we are done */
  3076. if ( doCompare( s[c], s[p] ) >= 0 )
  3077. break;
  3078. /* Swap parent and child */
  3079. unsigned r = s[c];
  3080. s[c] = s[p];
  3081. s[p] = r;
  3082. /* child becomes parent */
  3083. p = c;
  3084. }
  3085. remakePending = false;
  3086. }
  3087. void append(IRoxieServerQueryPacket *p, unsigned seq)
  3088. {
  3089. HeapEntry &h = *new HeapEntry(adaptor, LINK(p), seq);
  3090. IMessageResult *result = p->queryResult();
  3091. assertex(result);
  3092. if (h.noteResult(result->getCursor(rowManager), isCompleteMatchFlag(result)))
  3093. {
  3094. heapEntries.append(h);
  3095. heap.append(heap.ordinality());
  3096. }
  3097. else
  3098. h.Release();
  3099. }
  3100. void removeHeap(unsigned idx)
  3101. {
  3102. heapEntries.remove(idx);
  3103. ForEachItemIn(i, heap)
  3104. {
  3105. unsigned v = heap.item(i);
  3106. assertex(v != idx);
  3107. if (v > idx)
  3108. heap.replace(v-1, i);
  3109. }
  3110. }
  3111. bool isCompleteMatchFlag(IMessageResult *result)
  3112. {
  3113. unsigned metaLen;
  3114. const byte *metaInfo = (const byte *) result->getMessageMetadata(metaLen);
  3115. if (metaLen)
  3116. {
  3117. unsigned short continuationLen = *(unsigned short *) metaInfo;
  3118. if (continuationLen >= sizeof(bool))
  3119. {
  3120. metaInfo += sizeof(unsigned short);
  3121. return *(bool *) metaInfo;
  3122. }
  3123. }
  3124. return true; // if no continuation info, last row was complete.
  3125. }
  3126. public:
  3127. CRemoteResultMerger(CRemoteResultAdaptor &_adaptor) : adaptor(_adaptor)
  3128. {
  3129. init(NULL, NULL);
  3130. }
  3131. void init(ISteppingMeta *meta, IRowManager *_rowManager)
  3132. {
  3133. if (meta)
  3134. {
  3135. numFields = meta->getNumFields();
  3136. compare = meta->queryCompare();
  3137. }
  3138. else
  3139. {
  3140. numFields = 0;
  3141. compare = NULL;
  3142. }
  3143. rowManager = _rowManager;
  3144. numPending = 0;
  3145. endSeen = false;
  3146. remakePending = false;
  3147. deferredContinuation = false;
  3148. }
  3149. void reset()
  3150. {
  3151. heapEntries.kill();
  3152. heap.kill();
  3153. numPending = 0;
  3154. endSeen = false;
  3155. remakePending = false;
  3156. deferredContinuation = false;
  3157. }
  3158. inline bool noteEndSeen()
  3159. {
  3160. bool hadSeen = endSeen;
  3161. if (!endSeen)
  3162. makeHeap();
  3163. endSeen = true;
  3164. return !hadSeen;
  3165. }
  3166. void noteResult(IRoxieServerQueryPacket *p, unsigned seq)
  3167. {
  3168. if (!p->isContinuation())
  3169. append(p, seq);
  3170. else
  3171. {
  3172. ForEachItemIn(idx, heapEntries)
  3173. {
  3174. HeapEntry &h = heapEntries.item(idx);
  3175. if (h.packet == p)
  3176. {
  3177. IMessageResult *result = p->queryResult();
  3178. if (!h.noteResult(result->getCursor(rowManager), isCompleteMatchFlag(result)))
  3179. {
  3180. heap.zap(idx);
  3181. removeHeap(idx);
  3182. }
  3183. numPending--;
  3184. if (!numPending)
  3185. makeHeap();
  3186. return;
  3187. }
  3188. }
  3189. }
  3190. // If we get here it must be a continuation for one that I have not yet consumed... we don't need to do anything.
  3191. return;
  3192. }
  3193. unsigned skipRows(unsigned &idx, const void *seek, const void *rawSeek, unsigned numFields, unsigned seekLen, const SmartStepExtra & stepExtra)
  3194. {
  3195. HeapEntry &entry = heapEntries.item(idx);
  3196. unsigned skipped = entry.current ? entry.skipTo(compare, seek, numFields, !stepExtra.returnMismatches()) : 0;
  3197. if (!entry.current)
  3198. {
  3199. IRoxieServerQueryPacket *continuation = entry.packet->queryContinuation();
  3200. if (continuation)
  3201. {
  3202. continuation->Link();
  3203. entry.packet->Release();
  3204. entry.packet = continuation;
  3205. if (continuation->hasResult())
  3206. {
  3207. IMessageResult *result = continuation->queryResult();
  3208. bool lastIsCompleteMatch = isCompleteMatchFlag(result);
  3209. entry.noteResult(result->getCursor(rowManager), lastIsCompleteMatch);
  3210. }
  3211. else
  3212. {
  3213. if (continuation->isDelayed())
  3214. {
  3215. continuation->setDelayed(false);
  3216. MemoryBuffer serializedSkip;
  3217. adaptor.activity.serializeSkipInfo(serializedSkip, seekLen, rawSeek, numFields, seek, stepExtra);
  3218. continuation->setPacket(continuation->queryPacket()->insertSkipData(serializedSkip.length(), serializedSkip.toByteArray()));
  3219. ROQ->sendPacket(continuation->queryPacket(), adaptor.activity.queryLogCtx());
  3220. adaptor.sentsome.signal();
  3221. }
  3222. numPending++;
  3223. }
  3224. }
  3225. else
  3226. {
  3227. heap.zap(idx);
  3228. removeHeap(idx);
  3229. idx--;
  3230. }
  3231. }
  3232. return skipped;
  3233. }
  3234. const void * nextRowGE(const void * seek, const void *rawSeek, unsigned numFields, unsigned seeklen, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  3235. {
  3236. // We discard all rows < seekval from all entries in heap
  3237. // If this results in additional slave requests, we return NULL so that we can wait for them
  3238. // If not, we rebuild the heap (if any were skipped) and return the first row
  3239. deferredContinuation = false;
  3240. if (heap.length())
  3241. {
  3242. unsigned skipped = 0;
  3243. unsigned idx = 0;
  3244. while(heapEntries.isItem(idx))
  3245. {
  3246. skipped += skipRows(idx, seek, rawSeek, numFields, seeklen, stepExtra);
  3247. idx++;
  3248. }
  3249. if (numPending)
  3250. return NULL; // can't answer yet, need more results from slaves
  3251. else
  3252. {
  3253. if (skipped)
  3254. makeHeap();
  3255. return next(wasCompleteMatch, stepExtra);
  3256. }
  3257. }
  3258. else
  3259. return NULL;
  3260. }
  3261. bool doContinuation(HeapEntry &topEntry, bool canDefer)
  3262. {
  3263. IRoxieServerQueryPacket *continuation = topEntry.packet->queryContinuation();
  3264. if (continuation)
  3265. {
  3266. if (continuation->isDelayed() && canDefer)
  3267. {
  3268. if (adaptor.activity.queryLogCtx().queryTraceLevel() > 10)
  3269. adaptor.activity.queryLogCtx().CTXLOG("Deferring continuation");
  3270. deferredContinuation = true;
  3271. }
  3272. else
  3273. {
  3274. deferredContinuation = false;
  3275. continuation->Link();
  3276. topEntry.packet->Release();
  3277. topEntry.packet = continuation;
  3278. if (continuation->hasResult())
  3279. {
  3280. IMessageResult *result = continuation->queryResult();
  3281. bool lastIsCompleteMatch = isCompleteMatchFlag(result);
  3282. topEntry.noteResult(result->getCursor(rowManager), lastIsCompleteMatch);
  3283. }
  3284. else
  3285. {
  3286. if (continuation->isDelayed()) // has the continuation been requested yet?
  3287. {
  3288. continuation->Link();
  3289. topEntry.packet->Release();
  3290. topEntry.packet = continuation;
  3291. continuation->setDelayed(false);
  3292. if (adaptor.activity.queryLogCtx().queryTraceLevel() > 10)
  3293. adaptor.activity.queryLogCtx().CTXLOG("About to send continuation, from doContinuation");
  3294. ROQ->sendPacket(continuation->queryPacket(), adaptor.activity.queryLogCtx());
  3295. adaptor.sentsome.signal();
  3296. }
  3297. numPending++; // we are waiting for one that is already in flight
  3298. }
  3299. }
  3300. return true; // next not known yet
  3301. }
  3302. else
  3303. return false;
  3304. }
  3305. const void *next(bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  3306. {
  3307. OwnedConstRoxieRow ret;
  3308. if (heap.length())
  3309. {
  3310. if (deferredContinuation)
  3311. {
  3312. unsigned top = heap.item(0);
  3313. HeapEntry &topEntry = heapEntries.item(top);
  3314. doContinuation(topEntry, false);
  3315. return NULL;
  3316. }
  3317. if (remakePending)
  3318. remakeHeap();
  3319. unsigned top = heap.item(0);
  3320. HeapEntry &topEntry = heapEntries.item(top);
  3321. ret.set(topEntry.current);
  3322. wasCompleteMatch = topEntry.isCompleteMatch();
  3323. const void *next = topEntry.next();
  3324. if (!next)
  3325. {
  3326. if (!doContinuation(topEntry, stepExtra.returnMismatches()))
  3327. {
  3328. unsigned last = heap.popGet();
  3329. if (heap.length())
  3330. heap.replace(last, 0);
  3331. removeHeap(top);
  3332. }
  3333. }
  3334. remakePending = true;
  3335. }
  3336. return ret.getClear();
  3337. }
  3338. bool ready()
  3339. {
  3340. return endSeen && numPending == 0;
  3341. }
  3342. };
  3343. IRoxieServerQueryPacket *createRoxieServerQueryPacket(IRoxieQueryPacket *p, bool &cached)
  3344. {
  3345. if (serverSideCache && !debugContext)
  3346. {
  3347. IRoxieServerQueryPacket *ret = serverSideCache->findCachedResult(activity.queryLogCtx(), p);
  3348. if (ret)
  3349. {
  3350. p->Release();
  3351. cached = true;
  3352. return ret;
  3353. }
  3354. }
  3355. cached = false;
  3356. return new CRoxieServerQueryPacket(p);
  3357. }
  3358. #ifdef _DEBUG
  3359. void dumpPending()
  3360. {
  3361. CriticalBlock b(pendingCrit);
  3362. ForEachItemIn(idx, pending)
  3363. {
  3364. IRoxieServerQueryPacket &p = pending.item(idx);
  3365. StringBuffer s;
  3366. unsigned __int64 dummy;
  3367. if (p.isEnd())
  3368. s.append("END");
  3369. else if (p.isLimit(dummy, dummy, dummy))
  3370. s.append("LIMIT");
  3371. else
  3372. {
  3373. IRoxieQueryPacket *i = p.queryPacket();
  3374. s.appendf("%s", p.hasResult() ? "COMPLETE " : "PENDING ");
  3375. if (i)
  3376. {
  3377. RoxiePacketHeader &header = i->queryHeader();
  3378. header.toString(s);
  3379. }
  3380. }
  3381. DBGLOG("Pending %d %s", idx, s.str());
  3382. }
  3383. }
  3384. #endif
  3385. void abortPending()
  3386. {
  3387. CriticalBlock b(pendingCrit);
  3388. ForEachItemIn(idx, pending)
  3389. {
  3390. IRoxieServerQueryPacket &p = pending.item(idx);
  3391. if (!p.hasResult())
  3392. {
  3393. IRoxieQueryPacket *i = p.queryPacket();
  3394. if (i)
  3395. {
  3396. RoxiePacketHeader &header = i->queryHeader();
  3397. ROQ->sendAbort(header, activity.queryLogCtx());
  3398. }
  3399. }
  3400. }
  3401. pending.kill();
  3402. }
  3403. void checkDelayed()
  3404. {
  3405. if (ctx->queryDebugContext() && ctx->queryDebugContext()->getExecuteSequentially())
  3406. {
  3407. bool allDelayed = true;
  3408. CriticalBlock b(pendingCrit);
  3409. unsigned sendIdx = (unsigned) -1;
  3410. ForEachItemIn(idx, pending)
  3411. {
  3412. IRoxieServerQueryPacket &p = pending.item(idx);
  3413. if (p.queryPacket())
  3414. {
  3415. if (p.isDelayed())
  3416. {
  3417. if (sendIdx == (unsigned) -1)
  3418. sendIdx = idx;
  3419. }
  3420. else if (!p.hasResult())
  3421. {
  3422. allDelayed = false;
  3423. break;
  3424. }
  3425. }
  3426. }
  3427. if (allDelayed && sendIdx != (unsigned) -1)
  3428. {
  3429. if (activity.queryLogCtx().queryTraceLevel() > 10)
  3430. activity.queryLogCtx().CTXLOG("About to send debug-deferred from next");
  3431. pending.item(sendIdx).setDelayed(false);
  3432. ROQ->sendPacket(pending.item(sendIdx).queryPacket(), activity.queryLogCtx());
  3433. sentsome.signal();
  3434. }
  3435. }
  3436. else if (deferredStart)
  3437. {
  3438. CriticalBlock b(pendingCrit);
  3439. ForEachItemIn(idx, pending)
  3440. {
  3441. IRoxieServerQueryPacket &p = pending.item(idx);
  3442. if (p.isDelayed())
  3443. {
  3444. if (activity.queryLogCtx().queryTraceLevel() > 10)
  3445. activity.queryLogCtx().CTXLOG("About to send deferred start from next");
  3446. p.setDelayed(false);
  3447. ROQ->sendPacket(p.queryPacket(), activity.queryLogCtx());
  3448. sentsome.signal();
  3449. }
  3450. }
  3451. deferredStart = false;
  3452. }
  3453. }
  3454. void retryPending()
  3455. {
  3456. CriticalBlock b(pendingCrit);
  3457. checkDelayed();
  3458. ForEachItemIn(idx, pending)
  3459. {
  3460. IRoxieServerQueryPacket &p = pending.item(idx);
  3461. if (!p.hasResult() && !p.isDelayed())
  3462. {
  3463. IRoxieQueryPacket *i = p.queryPacket();
  3464. if (i)
  3465. {
  3466. if (!i->queryHeader().retry())
  3467. {
  3468. StringBuffer s;
  3469. 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());
  3470. activity.queryLogCtx().logOperatorException(E, __FILE__, __LINE__, "CRemoteResultAdaptor::retry");
  3471. throw E;
  3472. }
  3473. if (!localSlave)
  3474. {
  3475. ROQ->sendPacket(i, activity.queryLogCtx());
  3476. retriesSent++;
  3477. }
  3478. }
  3479. }
  3480. }
  3481. }
  3482. class ChannelBuffer
  3483. {
  3484. protected:
  3485. unsigned bufferLeft;
  3486. MemoryBuffer buffer;
  3487. char *nextBuf;
  3488. unsigned overflowSequence;
  3489. unsigned channel; // == bonded channel
  3490. bool needsFlush;
  3491. InterruptableSemaphore flowController;
  3492. const CRemoteResultAdaptor &owner;
  3493. CriticalSection crit;
  3494. public:
  3495. ChannelBuffer(const CRemoteResultAdaptor &_owner, unsigned _channel) : owner(_owner), channel(_channel), flowController(perChannelFlowLimit)
  3496. {
  3497. overflowSequence = 0;
  3498. needsFlush = false;
  3499. bufferLeft = 0;
  3500. nextBuf = NULL;
  3501. }
  3502. void init(unsigned minSize)
  3503. {
  3504. assertex(!buffer.length());
  3505. if (minSize < MIN_PAYLOAD_SIZE)
  3506. minSize = MIN_PAYLOAD_SIZE;
  3507. unsigned headerSize = sizeof(RoxiePacketHeader)+owner.headerLength();
  3508. unsigned bufferSize = headerSize+minSize;
  3509. if (bufferSize < mtu_size)
  3510. bufferSize = mtu_size;
  3511. buffer.reserveTruncate(bufferSize);
  3512. bufferLeft = bufferSize - headerSize;
  3513. assertex(buffer.toByteArray());
  3514. nextBuf = (char *) buffer.toByteArray() + headerSize;
  3515. needsFlush = false;
  3516. }
  3517. inline IRoxieQueryPacket *flush()
  3518. {
  3519. CriticalBlock cb(crit);
  3520. Owned<IRoxieQueryPacket> ret;
  3521. if (needsFlush)
  3522. {
  3523. buffer.setLength(nextBuf - buffer.toByteArray());
  3524. RoxiePacketHeader *h = (RoxiePacketHeader *) buffer.toByteArray();
  3525. h->init(owner.remoteId, owner.ruid, channel, overflowSequence);
  3526. //patch logPrefix, cachedContext and parent extract into the place reserved in the message buffer
  3527. byte * tgt = (byte*)(h+1);
  3528. owner.copyHeader(tgt, channel);
  3529. ret.setown(createRoxiePacket(buffer));
  3530. if (overflowSequence == OVERFLOWSEQUENCE_MAX)
  3531. overflowSequence = 1; // don't wrap to 0 - that is a bit special
  3532. else
  3533. overflowSequence++;
  3534. needsFlush = false;
  3535. bufferLeft = 0;
  3536. if (owner.flowControlled)
  3537. {
  3538. CriticalUnblock cub(crit);
  3539. while (!flowController.wait(1000))
  3540. {
  3541. StringBuffer s;
  3542. owner.activity.queryLogCtx().CTXLOG("Channel %d blocked by flow control: %s", channel, h->toString(s).str());
  3543. }
  3544. }
  3545. }
  3546. return ret.getClear();
  3547. }
  3548. inline void signal()
  3549. {
  3550. if (owner.flowControlled)
  3551. flowController.signal();
  3552. }
  3553. inline void interrupt(IException *e)
  3554. {
  3555. flowController.interrupt(e);
  3556. }
  3557. inline void *getBuffer(unsigned size)
  3558. {
  3559. CriticalBlock cb(crit);
  3560. if (bufferLeft >= size)
  3561. {
  3562. needsFlush = true;
  3563. void * ret = nextBuf;
  3564. nextBuf += size;
  3565. bufferLeft -= size;
  3566. return ret;
  3567. }
  3568. else if (!needsFlush)
  3569. {
  3570. init(size);
  3571. return getBuffer(size);
  3572. }
  3573. else if (owner.mergeOrder)
  3574. {
  3575. return buffer.reserve(size); // whole query needs to go as single packet if we are to merge
  3576. }
  3577. else
  3578. return NULL; // will force it to flush and start a new packet
  3579. }
  3580. };
  3581. private:
  3582. friend class CRemoteResultMerger;
  3583. bool allread;
  3584. bool contextCached;
  3585. bool preserveOrder;
  3586. bool eogSent = false;
  3587. InterruptableSemaphore sentsome;
  3588. Owned <IMessageCollator> mc;
  3589. Owned<IMessageUnpackCursor> mu;
  3590. Owned<IMessageResult> mr;
  3591. ChannelBuffer **buffers;
  3592. IHThorArg &helper;
  3593. unsigned __int64 stopAfter;
  3594. unsigned resendSequence;
  3595. IHThorArg *colocalArg;
  3596. IArrayOf<IRoxieServerQueryPacket> pending;
  3597. CriticalSection pendingCrit;
  3598. IRoxieServerSideCache *serverSideCache;
  3599. unsigned sentSequence;
  3600. Owned<IOutputRowDeserializer> deserializer;
  3601. Owned<IEngineRowAllocator> rowAllocator;
  3602. CRemoteResultMerger merger;
  3603. // this is only used to avoid recreating a bufferStream for each row. A better solution may be needed
  3604. MemoryBuffer tempRowBuffer;
  3605. Owned<ISerialStream> bufferStream;
  3606. CThorStreamDeserializerSource rowSource;
  3607. protected:
  3608. IRowManager *rowManager;
  3609. unsigned __int64 rowLimit;
  3610. unsigned __int64 keyedLimit;
  3611. IRoxieServerErrorHandler *errorHandler;
  3612. CachedOutputMetaData meta;
  3613. public:
  3614. ISteppingMeta *mergeOrder;
  3615. IRoxieSlaveContext *ctx;
  3616. IDebuggableContext *debugContext;
  3617. IRoxieServerActivity &activity;
  3618. unsigned parentExtractSize;
  3619. const byte * parentExtract;
  3620. bool flowControlled;
  3621. bool deferredStart;
  3622. MemoryBuffer logInfo;
  3623. MemoryBuffer cachedContext;
  3624. const RemoteActivityId &remoteId;
  3625. ruid_t ruid;
  3626. mutable CriticalSection buffersCrit;
  3627. unsigned processed;
  3628. cycle_t totalCycles;
  3629. bool timeActivities;
  3630. //private: //vc6 doesn't like this being private yet accessed by nested class...
  3631. const void *getRow(IMessageUnpackCursor *mu)
  3632. {
  3633. if (!mu->isSerialized() || (meta.isFixedSize() && !deserializer))
  3634. return mu->getNext(meta.getFixedSize());
  3635. else
  3636. {
  3637. RecordLengthType *rowlen = (RecordLengthType *) mu->getNext(sizeof(RecordLengthType));
  3638. if (rowlen)
  3639. {
  3640. RecordLengthType len = *rowlen;
  3641. ReleaseRoxieRow(rowlen);
  3642. const void *slaveRec = mu->getNext(len);
  3643. if (deserializer && mu->isSerialized())
  3644. {
  3645. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  3646. tempRowBuffer.setBuffer(len, const_cast<void *>(slaveRec), false);
  3647. size_t outsize = deserializer->deserialize(rowBuilder, rowSource);
  3648. ReleaseRoxieRow(slaveRec);
  3649. return rowBuilder.finalizeRowClear(outsize);
  3650. }
  3651. else
  3652. return slaveRec;
  3653. }
  3654. else
  3655. return NULL;
  3656. }
  3657. }
  3658. private:
  3659. ChannelBuffer *queryChannelBuffer(unsigned channel, bool force=false)
  3660. {
  3661. CriticalBlock cb(buffersCrit);
  3662. ChannelBuffer *b = buffers[channel];
  3663. if (!b && force)
  3664. {
  3665. if (!contextCached)
  3666. {
  3667. logInfo.clear();
  3668. unsigned char loggingFlags = LOGGING_FLAGSPRESENT | LOGGING_TRACELEVELSET;
  3669. unsigned char ctxTraceLevel = activity.queryLogCtx().queryTraceLevel() + 1; // Avoid passing a 0
  3670. const QueryOptions &options = ctx->queryOptions();
  3671. if (activity.queryLogCtx().isIntercepted())
  3672. loggingFlags |= LOGGING_INTERCEPTED;
  3673. if (options.timeActivities)
  3674. loggingFlags |= LOGGING_TIMEACTIVITIES;
  3675. if (activity.queryLogCtx().isBlind())
  3676. loggingFlags |= LOGGING_BLIND;
  3677. if (options.checkingHeap)
  3678. loggingFlags |= LOGGING_CHECKINGHEAP;
  3679. if (ctx->queryWorkUnit())
  3680. loggingFlags |= LOGGING_WUID;
  3681. if (debugContext)
  3682. {
  3683. loggingFlags |= LOGGING_DEBUGGERACTIVE;
  3684. logInfo.append(loggingFlags).append(ctxTraceLevel);
  3685. MemoryBuffer bpInfo;
  3686. debugContext->serialize(bpInfo);
  3687. bpInfo.append((__uint64)(memsize_t) &activity);
  3688. logInfo.append((unsigned short) bpInfo.length());
  3689. logInfo.append(bpInfo.length(), bpInfo.toByteArray());
  3690. }
  3691. else
  3692. logInfo.append(loggingFlags).append(ctxTraceLevel);
  3693. StringBuffer logPrefix;
  3694. activity.queryLogCtx().getLogPrefix(logPrefix);
  3695. logInfo.append(logPrefix);
  3696. activity.serializeCreateStartContext(cachedContext.clear());
  3697. activity.serializeExtra(cachedContext);
  3698. if (activity.queryVarFileInfo())
  3699. {
  3700. activity.queryVarFileInfo()->queryTimeStamp().serialize(cachedContext);
  3701. cachedContext.append(activity.queryVarFileInfo()->queryCheckSum());
  3702. }
  3703. contextCached = true;
  3704. }
  3705. b = buffers[channel] = new ChannelBuffer(*this, channel);
  3706. }
  3707. return b;
  3708. }
  3709. void processRow(const void *got)
  3710. {
  3711. processed++;
  3712. if (processed > rowLimit)
  3713. {
  3714. ReleaseRoxieRow(got);
  3715. errorHandler->onLimitExceeded(false); // NOTE - should throw exception
  3716. throwUnexpected();
  3717. }
  3718. else if (processed > keyedLimit)
  3719. {
  3720. ReleaseRoxieRow(got);
  3721. errorHandler->onLimitExceeded(true); // NOTE - should throw exception
  3722. throwUnexpected();
  3723. }
  3724. }
  3725. public:
  3726. IMPLEMENT_IINTERFACE;
  3727. CRemoteResultAdaptor(IRoxieSlaveContext *_ctx, IRoxieServerErrorHandler *_errorHandler, const RemoteActivityId &_remoteId, IOutputMetaData *_meta, IHThorArg &_helper, IRoxieServerActivity &_activity, bool _preserveOrder, bool _flowControlled)
  3728. : remoteId(_remoteId), meta(_meta), activity(_activity), helper(_helper), preserveOrder(_preserveOrder), flowControlled(_flowControlled), merger(*this)
  3729. {
  3730. ctx = _ctx;
  3731. errorHandler = _errorHandler;
  3732. colocalArg = NULL;
  3733. allread = false;
  3734. ruid = 0;
  3735. rowLimit = (unsigned __int64) -1;
  3736. keyedLimit = (unsigned __int64) -1;
  3737. contextCached = false;
  3738. stopAfter = I64C(0x7FFFFFFFFFFFFFFF);
  3739. buffers = new ChannelBuffer*[numChannels+1];
  3740. memset(buffers, 0, (numChannels+1)*sizeof(ChannelBuffer *));
  3741. parentExtractSize = 0;
  3742. rowManager = NULL;
  3743. parentExtract = NULL;
  3744. debugContext = NULL;
  3745. mergeOrder = NULL;
  3746. deferredStart = false;
  3747. processed = 0;
  3748. sentSequence = 0;
  3749. resendSequence = 0;
  3750. totalCycles = 0;
  3751. serverSideCache = activity.queryServerSideCache();
  3752. bufferStream.setown(createMemoryBufferSerialStream(tempRowBuffer));
  3753. rowSource.setStream(bufferStream);
  3754. timeActivities = defaultTimeActivities;
  3755. }
  3756. ~CRemoteResultAdaptor()
  3757. {
  3758. if (mc)
  3759. {
  3760. ROQ->queryReceiveManager()->detachCollator(mc);
  3761. mc.clear();
  3762. }
  3763. for (unsigned channel = 0; channel <= numChannels; channel++)
  3764. {
  3765. delete(buffers[channel]);
  3766. }
  3767. delete [] buffers;
  3768. }
  3769. void setMeta(IOutputMetaData *newmeta)
  3770. {
  3771. meta.set(newmeta);
  3772. }
  3773. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { assertex(whichInput==0); return this; }
  3774. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { assertex(idx==0); return nullptr; }
  3775. virtual IRoxieServerActivity *queryActivity()
  3776. {
  3777. return &activity;
  3778. }
  3779. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  3780. {
  3781. return NULL;
  3782. }
  3783. void setMergeInfo(ISteppingMeta *_mergeOrder)
  3784. {
  3785. mergeOrder = _mergeOrder;
  3786. deferredStart = true;
  3787. }
  3788. void send(IRoxieQueryPacket *p)
  3789. {
  3790. if (p)
  3791. {
  3792. Linked<IRoxieQueryPacket> saver(p); // avoids a race with abortPending, without keeping pendingCrit locked over the send which we might prefer not to
  3793. assertex(p->queryHeader().uid==ruid);
  3794. // MORE: Maybe we should base the fastlane flag on some other
  3795. // criteria !! (i.e A Roxie server prediction based on the
  3796. // activity type/activity behaviour/expected reply size .. etc).
  3797. //
  3798. // Currently (code below) based on high priority, seq=0, and none-child activity.
  3799. // But this could still cause too many reply packets on the fatlane
  3800. // (higher priority output Q), which may cause the activities on the
  3801. // low priority output Q to not get service on time.
  3802. if ((colocalArg == 0) && // not a child query activity??
  3803. (p->queryHeader().activityId & (ROXIE_SLA_PRIORITY | ROXIE_HIGH_PRIORITY)) &&
  3804. (p->queryHeader().overflowSequence == 0) &&
  3805. (p->queryHeader().continueSequence & ~CONTINUE_SEQUENCE_SKIPTO)==0)
  3806. p->queryHeader().retries |= ROXIE_FASTLANE;
  3807. if (p->queryHeader().channel)
  3808. {
  3809. bool cached = false;
  3810. IRoxieServerQueryPacket *rsqp = createRoxieServerQueryPacket(p, cached);
  3811. if (deferredStart)
  3812. rsqp->setDelayed(true);
  3813. rsqp->setSequence(sentSequence++);
  3814. {
  3815. CriticalBlock b(pendingCrit);
  3816. pending.append(*rsqp);
  3817. }
  3818. if (!deferredStart)
  3819. {
  3820. if (!cached)
  3821. ROQ->sendPacket(p, activity.queryLogCtx());
  3822. sentsome.signal();
  3823. }
  3824. }
  3825. else
  3826. {
  3827. // 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
  3828. // Need to add first, then send
  3829. unsigned i;
  3830. bool allCached = true;
  3831. for (i = 1; i <= numChannels; i++)
  3832. {
  3833. IRoxieQueryPacket *q = p->clonePacket(i);
  3834. bool thisChannelCached;
  3835. IRoxieServerQueryPacket *rsqp = createRoxieServerQueryPacket(q, thisChannelCached);
  3836. if (!thisChannelCached)
  3837. allCached = false;
  3838. rsqp->setSequence(sentSequence++);
  3839. if (deferredStart)
  3840. {
  3841. rsqp->setDelayed(true);
  3842. }
  3843. {
  3844. CriticalBlock b(pendingCrit);
  3845. pending.append(*rsqp);
  3846. }
  3847. if (!deferredStart)
  3848. sentsome.signal();
  3849. }
  3850. if (!allCached && !deferredStart)
  3851. ROQ->sendPacket(p, activity.queryLogCtx());
  3852. buffers[0]->signal(); // since replies won't come back on that channel...
  3853. p->Release();
  3854. }
  3855. }
  3856. }
  3857. void *getMem(unsigned partNo, unsigned fileNo, unsigned size)
  3858. {
  3859. unsigned channel = partNo ? getBondedChannel(partNo) : 0;
  3860. size += sizeof(PartNoType);
  3861. ChannelBuffer *b = queryChannelBuffer(channel, true);
  3862. char *buffer = (char *) b->getBuffer(size);
  3863. if (!buffer)
  3864. {
  3865. send(b->flush());
  3866. buffer = (char *) b->getBuffer(size);
  3867. }
  3868. PartNoType sp;
  3869. sp.partNo = partNo;
  3870. sp.fileNo = fileNo;
  3871. memcpy(buffer, &sp, sizeof(sp));
  3872. buffer += sizeof(sp);
  3873. return buffer;
  3874. }
  3875. void injectResult(IMessageResult *result)
  3876. {
  3877. IRoxieServerQueryPacket *f = new CRoxieServerQueryPacket(NULL);
  3878. f->setSequence(sentSequence++);
  3879. f->setResult(result);
  3880. CriticalBlock b(pendingCrit);
  3881. pending.append(*f);
  3882. sentsome.signal(); // MORE - arguably should only send if there is any point waking up the listener thread, to save context swicth
  3883. }
  3884. void flush()
  3885. {
  3886. for (unsigned channel = 0; channel <= numChannels; channel++)
  3887. {
  3888. ChannelBuffer *b = queryChannelBuffer(channel, false);
  3889. if (b)
  3890. send(b->flush());
  3891. }
  3892. }
  3893. void interruptBuffers(IException *e)
  3894. {
  3895. for (unsigned channel = 0; channel <= numChannels; channel++)
  3896. {
  3897. ChannelBuffer *b = queryChannelBuffer(channel, false);
  3898. if (b)
  3899. b->interrupt(LINK(e));
  3900. }
  3901. }
  3902. void senddone()
  3903. {
  3904. CriticalBlock b(pendingCrit);
  3905. pending.append(*new CRoxieServerQueryPacketEndMarker);
  3906. sentsome.signal();
  3907. }
  3908. bool fireException(IException *e)
  3909. {
  3910. {
  3911. CriticalBlock b(pendingCrit);
  3912. pending.append(*new CRoxieServerQueryPacketEndMarker);
  3913. }
  3914. interruptBuffers(e);
  3915. if (mc)
  3916. mc->interrupt(LINK(e));
  3917. sentsome.interrupt(e);
  3918. return true;
  3919. }
  3920. virtual void onCreate(IHThorArg *_colocalArg)
  3921. {
  3922. debugContext = ctx->queryDebugContext();
  3923. colocalArg = _colocalArg;
  3924. if (meta.needsSerializeDisk())
  3925. {
  3926. deserializer.setown(meta.createDiskDeserializer(ctx->queryCodeContext(), activity.queryId()));
  3927. rowAllocator.setown(activity.createRowAllocator(meta.queryOriginal()));
  3928. }
  3929. if (ctx->queryDebugContext() && ctx->queryDebugContext()->getExecuteSequentially())
  3930. deferredStart = true;
  3931. timeActivities = ctx->queryOptions().timeActivities;
  3932. }
  3933. virtual void onStart(unsigned _parentExtractSize, const byte * _parentExtract)
  3934. {
  3935. #ifdef TRACE_STARTSTOP
  3936. if (traceStartStop)
  3937. activity.queryLogCtx().CTXLOG("RRAonstart");
  3938. #endif
  3939. sentsome.reinit();
  3940. ruid = getNextRuid();
  3941. rowManager = &ctx->queryRowManager();
  3942. if (mergeOrder)
  3943. merger.init(mergeOrder, rowManager);
  3944. if (mc)
  3945. {
  3946. ROQ->queryReceiveManager()->detachCollator(mc); // Should never happen - implies someone forgot to call onReset!
  3947. }
  3948. mc.setown(ROQ->queryReceiveManager()->createMessageCollator(rowManager, ruid));
  3949. allread = false;
  3950. mu.clear();
  3951. contextCached = false;
  3952. processed = 0;
  3953. resendSequence = 0;
  3954. sentSequence = 0;
  3955. for (unsigned channel = 0; channel <= numChannels; channel++)
  3956. {
  3957. delete(buffers[channel]);
  3958. buffers[channel] = NULL;
  3959. }
  3960. flush();
  3961. parentExtractSize = _parentExtractSize;
  3962. parentExtract = _parentExtract;
  3963. }
  3964. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  3965. {
  3966. #ifdef TRACE_STARTSTOP
  3967. if (traceStartStop)
  3968. activity.queryLogCtx().CTXLOG("RRAstart");
  3969. #endif
  3970. activity.start(parentExtractSize, parentExtract, paused);
  3971. }
  3972. void setLimits(unsigned __int64 _rowLimit, unsigned __int64 _keyedLimit, unsigned __int64 _stopAfter)
  3973. {
  3974. if (ctx->queryProbeManager())
  3975. {
  3976. if (_rowLimit != (unsigned __int64) -1) ctx->queryProbeManager()->setNodePropertyInt(&activity, "rowLimit", _rowLimit);
  3977. if (_keyedLimit != (unsigned __int64) -1) ctx->queryProbeManager()->setNodePropertyInt(&activity, "keyedLimit", _keyedLimit);
  3978. if (_stopAfter != I64C(0x7FFFFFFFFFFFFFFF)) ctx->queryProbeManager()->setNodePropertyInt(&activity, "choosenLimit", _stopAfter);
  3979. }
  3980. {
  3981. CriticalBlock b(pendingCrit);
  3982. if (pending.length())
  3983. {
  3984. #ifdef _DEBUG
  3985. dumpPending(); // MORE - only defined in debug build - could have put the ifdef inside the dumpPending method
  3986. #endif
  3987. assertex(pending.length()==0);
  3988. }
  3989. pending.append(*new CRoxieServerQueryPacketLimitMarker(_rowLimit, _keyedLimit, _stopAfter));
  3990. }
  3991. sentsome.signal();
  3992. rowLimit = _rowLimit;
  3993. keyedLimit = _keyedLimit;
  3994. stopAfter = _stopAfter;
  3995. }
  3996. virtual void stop()
  3997. {
  3998. #ifdef TRACE_STARTSTOP
  3999. if (traceStartStop)
  4000. activity.queryLogCtx().CTXLOG("RRAstop");
  4001. #endif
  4002. onStop();
  4003. activity.stop();
  4004. }
  4005. void onStop()
  4006. {
  4007. #ifdef TRACE_STARTSTOP
  4008. if (traceStartStop)
  4009. activity.queryLogCtx().CTXLOG("RRAonstop");
  4010. #endif
  4011. abortPending();
  4012. interruptBuffers(NULL);
  4013. sentsome.interrupt();
  4014. if (mc) // May not be set if start() chain threw exception
  4015. mc->interrupt();
  4016. }
  4017. virtual void reset()
  4018. {
  4019. #ifdef TRACE_STARTSTOP
  4020. if (traceStartStop)
  4021. activity.queryLogCtx().CTXLOG("RRAreset");
  4022. #endif
  4023. activity.reset();
  4024. onReset();
  4025. }
  4026. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  4027. {
  4028. // Make sure parent activity calls up the tree
  4029. PointerArrayOf<IEngineRowStream> instreams;
  4030. IStrandJunction *junction = activity.getOutputStreams(ctx, idx, instreams, consumerOptions, consumerOrdered, orderedCallbacks);
  4031. assertex (junction == NULL);
  4032. // I return a single strand (we could change that sometime I guess...)
  4033. streams.append(this);
  4034. return NULL;
  4035. }
  4036. virtual void resetEOF()
  4037. {
  4038. throwUnexpected();
  4039. }
  4040. virtual void onReset()
  4041. {
  4042. #ifdef TRACE_STARTSTOP
  4043. if (traceStartStop)
  4044. activity.queryLogCtx().CTXLOG("RRAonreset");
  4045. #endif
  4046. if (mc)
  4047. ROQ->queryReceiveManager()->detachCollator(mc);
  4048. merger.reset();
  4049. pending.kill();
  4050. if (mc && ctx)
  4051. ctx->addSlavesReplyLen(mc->queryBytesReceived());
  4052. mc.clear(); // Or we won't free memory for graphs that get recreated
  4053. mu.clear(); //ditto
  4054. deferredStart = false;
  4055. // NOTE: do NOT clear mergeOrder - this is set at create time not per child query
  4056. }
  4057. virtual IOutputMetaData * queryOutputMeta() const
  4058. {
  4059. return helper.queryOutputMeta();
  4060. }
  4061. virtual unsigned __int64 queryTotalCycles() const
  4062. {
  4063. return totalCycles;
  4064. }
  4065. void gatherStats(CRuntimeStatisticCollection & merged) const
  4066. {
  4067. if (rowAllocator)
  4068. rowAllocator->gatherStats(merged);
  4069. }
  4070. const void * nextRowGE(const void *seek, const void *rawSeek, unsigned numFields, unsigned seekLen, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  4071. {
  4072. if (activity.queryLogCtx().queryTraceLevel() > 20)
  4073. {
  4074. StringBuffer recstr;
  4075. unsigned i;
  4076. for (i = 0; i < seekLen; i++)
  4077. {
  4078. recstr.appendf("%02x ", ((unsigned char *) rawSeek)[i]);
  4079. }
  4080. activity.queryLogCtx().CTXLOG("CRemoteResultAdaptor::nextRowGE(rawSeek=%s numFields=%d, seeklen=%d, returnMismatches=%d)", recstr.str(), numFields, seekLen, stepExtra.returnMismatches());
  4081. }
  4082. assertex(mergeOrder);
  4083. if (deferredStart)
  4084. {
  4085. CriticalBlock b(pendingCrit);
  4086. ForEachItemIn(idx, pending)
  4087. {
  4088. IRoxieServerQueryPacket &p = pending.item(idx);
  4089. if (p.isDelayed())
  4090. {
  4091. p.setDelayed(false);
  4092. if (activity.queryLogCtx().queryTraceLevel() > 10)
  4093. activity.queryLogCtx().CTXLOG("About to send deferred start from nextRowGE, setting requireExact to %d", !stepExtra.returnMismatches());
  4094. MemoryBuffer serializedSkip;
  4095. activity.serializeSkipInfo(serializedSkip, seekLen, rawSeek, numFields, seek, stepExtra);
  4096. p.setPacket(p.queryPacket()->insertSkipData(serializedSkip.length(), serializedSkip.toByteArray()));
  4097. ROQ->sendPacket(p.queryPacket(), activity.queryLogCtx());
  4098. sentsome.signal();
  4099. }
  4100. }
  4101. deferredStart = false;
  4102. }
  4103. SimpleActivityTimer t(totalCycles, timeActivities);
  4104. if (processed==stopAfter)
  4105. return NULL;
  4106. if (allread)
  4107. return NULL;
  4108. for (;;)
  4109. {
  4110. if (merger.ready())
  4111. {
  4112. const void *got = merger.nextRowGE(seek, rawSeek, numFields, seekLen, wasCompleteMatch, stepExtra);
  4113. if (got)
  4114. {
  4115. processRow(got);
  4116. return got;
  4117. }
  4118. }
  4119. if (!reload()) // MORE - should pass the seek info here...
  4120. return NULL;
  4121. }
  4122. }
  4123. virtual const void *nextRow()
  4124. {
  4125. // If we are merging then we need to do a heapsort on all
  4126. SimpleActivityTimer t(totalCycles, timeActivities);
  4127. if (activity.queryLogCtx().queryTraceLevel() > 10)
  4128. {
  4129. activity.queryLogCtx().CTXLOG("CRemoteResultAdaptor::nextRow()");
  4130. }
  4131. for (;;)
  4132. {
  4133. checkDelayed();
  4134. if (processed==stopAfter)
  4135. return NULL;
  4136. if (allread)
  4137. return NULL;
  4138. // If we can still consume from the merger or the most recently retrieved mu, do so.
  4139. const void *got = NULL;
  4140. if (mergeOrder && merger.ready())
  4141. {
  4142. bool matched = true;
  4143. got = merger.next(matched, dummySmartStepExtra);
  4144. }
  4145. else if (mu)
  4146. {
  4147. got = getRow(mu);
  4148. if (!got && meta.isGrouped() && !eogSent)
  4149. {
  4150. eogSent = true;
  4151. return NULL;
  4152. }
  4153. }
  4154. if (got)
  4155. {
  4156. processRow(got);
  4157. return got;
  4158. }
  4159. eogSent = false;
  4160. if (!reload())
  4161. return NULL;
  4162. }
  4163. }
  4164. bool reload()
  4165. {
  4166. // Wait for something to be returned from a slave....
  4167. mu.clear();
  4168. sentsome.wait();
  4169. // must be at least an endMarker on the queue since sentsome was signalled
  4170. {
  4171. CriticalBlock b(pendingCrit);
  4172. IRoxieServerQueryPacket &top = pending.item(0);
  4173. if (top.isLimit(rowLimit, keyedLimit, stopAfter)) // This is really a start marker...
  4174. {
  4175. pending.remove(0);
  4176. return true;
  4177. }
  4178. else if (top.isEnd())
  4179. {
  4180. pending.remove(0);
  4181. allread = true;
  4182. if (activity.queryLogCtx().queryTraceLevel() > 5)
  4183. activity.queryLogCtx().CTXLOG("All read on ruid %x", ruid);
  4184. return false;
  4185. }
  4186. else if (mergeOrder)
  4187. {
  4188. unsigned idx = 0;
  4189. bool added = false;
  4190. while (pending.isItem(idx))
  4191. {
  4192. IRoxieServerQueryPacket &item = pending.item(idx);
  4193. if (item.isEnd())
  4194. {
  4195. if (merger.noteEndSeen())
  4196. {
  4197. sentsome.signal(); // Because we waited, yet didn't actually consume anything
  4198. added = true;
  4199. }
  4200. break;
  4201. }
  4202. else if (item.hasResult())
  4203. {
  4204. merger.noteResult(&item, item.getSequence());
  4205. pending.remove(idx);
  4206. added = true;
  4207. }
  4208. else if (item.isContinuation())
  4209. idx++;
  4210. else
  4211. break;
  4212. }
  4213. if (added)
  4214. return true;
  4215. }
  4216. else if (top.hasResult())
  4217. {
  4218. mr.setown(pending.item(0).getResult());
  4219. mu.setown(mr->getCursor(rowManager));
  4220. pending.remove(0);
  4221. return true;
  4222. }
  4223. }
  4224. getNextUnpacker();
  4225. return true;
  4226. }
  4227. void getNextUnpacker()
  4228. {
  4229. mu.clear();
  4230. unsigned ctxTraceLevel = activity.queryLogCtx().queryTraceLevel();
  4231. for (;;)
  4232. {
  4233. checkDelayed();
  4234. unsigned timeout = remoteId.isSLAPriority() ? slaTimeout : (remoteId.isHighPriority() ? highTimeout : lowTimeout);
  4235. activity.queryContext()->checkAbort();
  4236. bool anyActivity;
  4237. if (ctxTraceLevel > 5)
  4238. activity.queryLogCtx().CTXLOG("Calling getNextUnpacker(%d)", timeout);
  4239. mr.setown(mc->getNextResult(timeout, anyActivity));
  4240. if (ctxTraceLevel > 6)
  4241. activity.queryLogCtx().CTXLOG("Called getNextUnpacker(%d), activity=%d", timeout, anyActivity);
  4242. activity.queryContext()->checkAbort();
  4243. if (mr)
  4244. {
  4245. unsigned roxieHeaderLen;
  4246. const RoxiePacketHeader &header = *(const RoxiePacketHeader *) mr->getMessageHeader(roxieHeaderLen);
  4247. #ifdef _DEBUG
  4248. assertex(roxieHeaderLen == sizeof(RoxiePacketHeader));
  4249. #endif
  4250. if (ctxTraceLevel > 5)
  4251. {
  4252. StringBuffer s;
  4253. activity.queryLogCtx().CTXLOG("getNextUnpacker got packet %s", header.toString(s).str());
  4254. }
  4255. CriticalBlock b(pendingCrit);
  4256. unsigned idx = 0;
  4257. IRoxieServerQueryPacket *original = NULL;
  4258. IRoxieQueryPacket *op;
  4259. while (pending.isItem(idx))
  4260. {
  4261. original = &pending.item(idx);
  4262. op = original->queryPacket();
  4263. if (op && header.matchPacket(op->queryHeader()))
  4264. break;
  4265. original = NULL;
  4266. idx++;
  4267. }
  4268. if (!original || original->hasResult())
  4269. {
  4270. switch (header.activityId)
  4271. {
  4272. case ROXIE_FILECALLBACK:
  4273. {
  4274. // tell slave to abort
  4275. //if (ctxTraceLevel > 5)
  4276. {
  4277. StringBuffer s;
  4278. activity.queryLogCtx().CTXLOG("Redundant callback on query %s", header.toString(s).str());
  4279. }
  4280. Owned<IMessageUnpackCursor> callbackData = mr->getCursor(rowManager);
  4281. OwnedConstRoxieRow len = callbackData->getNext(sizeof(RecordLengthType));
  4282. if (len)
  4283. {
  4284. RecordLengthType *rowlen = (RecordLengthType *) len.get();
  4285. OwnedConstRoxieRow row = callbackData->getNext(*rowlen);
  4286. const char *rowdata = (const char *) row.get();
  4287. // bool isOpt = * (bool *) rowdata;
  4288. // bool isLocal = * (bool *) (rowdata+1);
  4289. ROQ->sendAbortCallback(header, rowdata+2, activity.queryLogCtx());
  4290. }
  4291. else
  4292. throwUnexpected();
  4293. break;
  4294. }
  4295. // MORE - ROXIE_ALIVE perhaps should go here too
  4296. default:
  4297. if (ctxTraceLevel > 3)
  4298. activity.queryLogCtx().CTXLOG("Discarding packet %p %x - original %p is NULL or has result already", mr.get(), header.activityId, original);
  4299. mr->discard();
  4300. break;
  4301. }
  4302. mr.clear();
  4303. }
  4304. else
  4305. {
  4306. resultsReceived++;
  4307. switch (header.activityId)
  4308. {
  4309. case ROXIE_DEBUGCALLBACK:
  4310. {
  4311. Owned<IMessageUnpackCursor> callbackData = mr->getCursor(rowManager);
  4312. OwnedConstRoxieRow len = callbackData->getNext(sizeof(RecordLengthType));
  4313. if (len)
  4314. {
  4315. RecordLengthType *rowlen = (RecordLengthType *) len.get();
  4316. OwnedConstRoxieRow row = callbackData->getNext(*rowlen);
  4317. char *rowdata = (char *) row.get();
  4318. if (ctxTraceLevel > 5)
  4319. {
  4320. StringBuffer s;
  4321. activity.queryLogCtx().CTXLOG("Callback on query %s for debug", header.toString(s).str());
  4322. }
  4323. MemoryBuffer slaveInfo;
  4324. slaveInfo.setBuffer(*rowlen, rowdata, false);
  4325. unsigned debugSequence;
  4326. slaveInfo.read(debugSequence);
  4327. Owned<IRoxieQueryPacket> reply = original->getDebugResponse(debugSequence);
  4328. if (!reply)
  4329. reply.setown(activity.queryContext()->queryDebugContext()->onDebugCallback(header, *rowlen, rowdata));
  4330. if (reply)
  4331. {
  4332. original->setDebugResponse(debugSequence, reply);
  4333. ROQ->sendPacket(reply, activity.queryLogCtx());
  4334. }
  4335. }
  4336. else
  4337. throwUnexpected();
  4338. // MORE - somehow we need to make sure slave gets a reply even if I'm not waiting (in udp layer)
  4339. // Leave original message on pending queue in original location - this is not a reply to it.
  4340. break;
  4341. }
  4342. case ROXIE_FILECALLBACK:
  4343. {
  4344. // we need to send back to the slave a message containing the file info requested.
  4345. Owned<IMessageUnpackCursor> callbackData = mr->getCursor(rowManager);
  4346. OwnedConstRoxieRow len = callbackData->getNext(sizeof(RecordLengthType));
  4347. if (len)
  4348. {
  4349. RecordLengthType *rowlen = (RecordLengthType *) len.get();
  4350. OwnedConstRoxieRow row = callbackData->getNext(*rowlen);
  4351. const char *rowdata = (const char *) row.get();
  4352. bool isOpt = * (bool *) rowdata;
  4353. bool isLocal = * (bool *) (rowdata+1);
  4354. const char *lfn = rowdata+2;
  4355. if (ctxTraceLevel > 5)
  4356. {
  4357. StringBuffer s;
  4358. activity.queryLogCtx().CTXLOG("Callback on query %s file %s", header.toString(s).str(),(const char *) lfn);
  4359. }
  4360. activity.queryContext()->onFileCallback(header, lfn, isOpt, isLocal);
  4361. }
  4362. else
  4363. throwUnexpected();
  4364. // MORE - somehow we need to make sure slave gets a reply even if I'm not waiting (in udp layer)
  4365. // Leave original message on pending queue in original location - this is not a reply to it.
  4366. break;
  4367. }
  4368. case ROXIE_KEYEDLIMIT_EXCEEDED:
  4369. activity.queryLogCtx().CTXLOG("ROXIE_KEYEDLIMIT_EXCEEDED");
  4370. errorHandler->onLimitExceeded(true); // NOTE - should throw exception!
  4371. throwUnexpected();
  4372. case ROXIE_LIMIT_EXCEEDED:
  4373. activity.queryLogCtx().CTXLOG("ROXIE_LIMIT_EXCEEDED");
  4374. errorHandler->onLimitExceeded(false); // NOTE - should throw exception!
  4375. throwUnexpected();
  4376. case ROXIE_TRACEINFO:
  4377. {
  4378. Owned<IMessageUnpackCursor> extra = mr->getCursor(rowManager);
  4379. for (;;)
  4380. {
  4381. RecordLengthType *rowlen = (RecordLengthType *) extra->getNext(sizeof(RecordLengthType));
  4382. if (rowlen)
  4383. {
  4384. char *logInfo = (char *) extra->getNext(*rowlen);
  4385. MemoryBuffer buf;
  4386. buf.setBuffer(*rowlen, logInfo, false);
  4387. switch ((TracingCategory) *logInfo)
  4388. {
  4389. case LOG_TRACING:
  4390. case LOG_ERROR:
  4391. activity.queryLogCtx().CTXLOGl(new LogItem(buf));
  4392. break;
  4393. case LOG_STATVALUES:
  4394. buf.skip(1);
  4395. activity.mergeStats(buf);
  4396. break;
  4397. case LOG_CHILDCOUNT:
  4398. case LOG_CHILDSTATS:
  4399. unsigned graphId, childId;
  4400. buf.skip(1);
  4401. buf.read(graphId);
  4402. buf.read(childId);
  4403. if (*logInfo == LOG_CHILDCOUNT)
  4404. {
  4405. unsigned idx;
  4406. unsigned childProcessed;
  4407. unsigned childStrands;
  4408. buf.read(idx);
  4409. buf.read(childProcessed);
  4410. buf.read(childStrands);
  4411. if (traceLevel > 5)
  4412. activity.queryLogCtx().CTXLOG("Processing ChildCount %d idx %d strands %d for child %d subgraph %d", childProcessed, idx, childStrands, childId, graphId);
  4413. activity.queryContext()->noteProcessed(graphId, childId, idx, childProcessed, childStrands);
  4414. }
  4415. else
  4416. {
  4417. CRuntimeStatisticCollection childStats(allStatistics);
  4418. childStats.deserialize(buf);
  4419. if (traceLevel > 5)
  4420. {
  4421. StringBuffer s;
  4422. activity.queryLogCtx().CTXLOG("Processing ChildStats for child %d subgraph %d: %s", childId, graphId, childStats.toStr(s).str());
  4423. }
  4424. activity.queryContext()->mergeActivityStats(childStats, graphId, childId);
  4425. }
  4426. }
  4427. ReleaseRoxieRow(rowlen);
  4428. ReleaseRoxieRow(logInfo);
  4429. }
  4430. else
  4431. break;
  4432. }
  4433. break;
  4434. }
  4435. case ROXIE_EXCEPTION:
  4436. if (ctxTraceLevel > 1)
  4437. {
  4438. StringBuffer s;
  4439. activity.queryLogCtx().CTXLOG("Exception on query %s", header.toString(s).str());
  4440. }
  4441. op->queryHeader().noteException(header.retries);
  4442. if (op->queryHeader().allChannelsFailed())
  4443. {
  4444. activity.queryLogCtx().CTXLOG("Multiple exceptions on query - aborting");
  4445. Owned<IMessageUnpackCursor> exceptionData = mr->getCursor(rowManager);
  4446. throwRemoteException(exceptionData);
  4447. }
  4448. // Leave it on pending queue in original location
  4449. break;
  4450. case ROXIE_ALIVE:
  4451. if (ctxTraceLevel > 4)
  4452. {
  4453. StringBuffer s;
  4454. activity.queryLogCtx().CTXLOG("ROXIE_ALIVE: %s", header.toString(s).str());
  4455. }
  4456. op->queryHeader().noteAlive(header.retries & ROXIE_RETRIES_MASK);
  4457. // Leave it on pending queue in original location
  4458. break;
  4459. default:
  4460. if (header.retries & ROXIE_RETRIES_MASK)
  4461. retriesNeeded++;
  4462. unsigned metaLen;
  4463. const void *metaData = mr->getMessageMetadata(metaLen);
  4464. if (metaLen)
  4465. {
  4466. // We got back first chunk but there is more.
  4467. // resend the packet, with the cursor info provided.
  4468. // MORE - if smart-stepping, we don't want to send the continuation immediately. Other cases it's not clear that we do.
  4469. if (ctxTraceLevel > 1)
  4470. {
  4471. StringBuffer s;
  4472. activity.queryLogCtx().CTXLOG("Additional data size %d on query %s mergeOrder %p", metaLen, header.toString(s).str(), mergeOrder);
  4473. }
  4474. if (*((unsigned short *) metaData) + sizeof(unsigned short) != metaLen)
  4475. {
  4476. StringBuffer s;
  4477. activity.queryLogCtx().CTXLOG("Additional data size %d on query %s mergeOrder %p", metaLen, header.toString(s).str(), mergeOrder);
  4478. activity.queryLogCtx().CTXLOG("Additional data is corrupt");
  4479. throwUnexpected();
  4480. }
  4481. MemoryBuffer nextQuery;
  4482. nextQuery.append(sizeof(RoxiePacketHeader), &header);
  4483. nextQuery.append(metaLen, metaData);
  4484. nextQuery.append(op->getTraceLength(), op->queryTraceInfo());
  4485. nextQuery.append(op->getContextLength(), op->queryContextData());
  4486. if (resendSequence == CONTINUESEQUENCE_MAX)
  4487. {
  4488. activity.queryLogCtx().CTXLOG("ERROR: Continuation sequence wrapped"); // shouldn't actually matter.... but suggests a very iffy query!
  4489. resendSequence = 1;
  4490. }
  4491. else
  4492. resendSequence++;
  4493. RoxiePacketHeader *newHeader = (RoxiePacketHeader *) nextQuery.toByteArray();
  4494. newHeader->continueSequence = resendSequence; // NOTE - we clear the skipTo flag since continuation of a skip is NOT a skip...
  4495. newHeader->retries &= ~ROXIE_RETRIES_MASK;
  4496. IRoxieQueryPacket *resend = createRoxiePacket(nextQuery);
  4497. CRoxieServerQueryPacket *fqp = new CRoxieServerQueryPacket(resend);
  4498. fqp->setSequence(original->getSequence());
  4499. pending.add(*fqp, idx+1); // note that pending takes ownership. sendPacket does not release.
  4500. original->setContinuation(LINK(fqp));
  4501. if (mergeOrder)
  4502. fqp->setDelayed(true);
  4503. else
  4504. {
  4505. ROQ->sendPacket(resend, activity.queryLogCtx());
  4506. sentsome.signal();
  4507. }
  4508. // Note that we don't attempt to cache results that have continuation records - too tricky !
  4509. }
  4510. else
  4511. {
  4512. if (serverSideCache)
  4513. serverSideCache->noteCachedResult(original, mr);
  4514. }
  4515. unsigned channel = header.channel;
  4516. {
  4517. ChannelBuffer *b = queryChannelBuffer(channel); // If not something is wrong, or we sent out on channel 0?
  4518. if (b)
  4519. b->signal();
  4520. }
  4521. original->setResult(mr.getClear());
  4522. sentsome.signal();
  4523. return;
  4524. }
  4525. }
  4526. }
  4527. else
  4528. {
  4529. if (!anyActivity && !localSlave)
  4530. {
  4531. activity.queryLogCtx().CTXLOG("Input has stalled - retry required?");
  4532. retryPending();
  4533. }
  4534. }
  4535. }
  4536. }
  4537. inline unsigned headerLength() const
  4538. {
  4539. return logInfo.length() + cachedContext.length() + sizeof(unsigned) + parentExtractSize;
  4540. }
  4541. void copyHeader(byte *tgt, unsigned channel) const
  4542. {
  4543. unsigned len = logInfo.length();
  4544. memcpy(tgt, logInfo.toByteArray(), len);
  4545. tgt += len;
  4546. *(unsigned *) tgt = parentExtractSize;
  4547. tgt += sizeof(unsigned);
  4548. memcpy(tgt, parentExtract, parentExtractSize);
  4549. tgt += parentExtractSize;
  4550. memcpy(tgt, cachedContext.toByteArray(), cachedContext.length());
  4551. tgt += cachedContext.length();
  4552. }
  4553. };
  4554. class CSkippableRemoteResultAdaptor : public CRemoteResultAdaptor
  4555. {
  4556. Owned <IException> exception;
  4557. bool skipping;
  4558. ConstPointerArray buff;
  4559. unsigned index;
  4560. bool pulled;
  4561. void pullInput()
  4562. {
  4563. try
  4564. {
  4565. if (exception)
  4566. throw exception.getClear();
  4567. unsigned __int64 count = 0;
  4568. for (;;)
  4569. {
  4570. const void * next = CRemoteResultAdaptor::nextRow();
  4571. if (next == NULL)
  4572. {
  4573. next = CRemoteResultAdaptor::nextRow();
  4574. if(next == NULL)
  4575. break;
  4576. buff.append(NULL);
  4577. }
  4578. count++;
  4579. if (count > rowLimit)
  4580. {
  4581. ReleaseRoxieRow(next);
  4582. ReleaseRoxieRows(buff);
  4583. errorHandler->onLimitExceeded(false); // throws an exception - user or LimitSkipException
  4584. throwUnexpected();
  4585. }
  4586. else if (count > keyedLimit)
  4587. {
  4588. ReleaseRoxieRow(next);
  4589. ReleaseRoxieRows(buff);
  4590. errorHandler->onLimitExceeded(true); // throws an exception - user or LimitSkipException
  4591. throwUnexpected();
  4592. }
  4593. buff.append(next);
  4594. }
  4595. }
  4596. catch (IException *E)
  4597. {
  4598. if (QUERYINTERFACE(E, LimitSkipException))
  4599. {
  4600. Owned<IException> cleanup = E;
  4601. ReleaseRoxieRows(buff);
  4602. const void *onfail = errorHandler->createLimitFailRow(E->errorCode() == KeyedLimitSkipErrorCode);
  4603. if (onfail)
  4604. buff.append(onfail);
  4605. }
  4606. else
  4607. throw;
  4608. }
  4609. pulled = true;
  4610. }
  4611. public:
  4612. CSkippableRemoteResultAdaptor(IRoxieSlaveContext *_ctx, IRoxieServerErrorHandler *_errorHandler, const RemoteActivityId &_remoteId, IOutputMetaData *_meta, IHThorArg &_helper, IRoxieServerActivity &_activity, bool _preserveOrder, bool _flowControlled, bool _skipping) :
  4613. CRemoteResultAdaptor(_ctx, _errorHandler, _remoteId, _meta, _helper, _activity, _preserveOrder, _flowControlled)
  4614. {
  4615. skipping = _skipping;
  4616. index = 0;
  4617. pulled = false;
  4618. }
  4619. void setException(IException *E)
  4620. {
  4621. exception.setown(E);
  4622. }
  4623. virtual void onReset()
  4624. {
  4625. roxiemem::ReleaseRoxieRowRange(buff.getArray(), index, buff.ordinality());
  4626. buff.kill();
  4627. index = 0;
  4628. pulled = false;
  4629. exception.clear();
  4630. CRemoteResultAdaptor::onReset();
  4631. }
  4632. void onStart(unsigned _parentExtractSize, const byte * _parentExtract)
  4633. {
  4634. index = 0;
  4635. pulled = false;
  4636. CRemoteResultAdaptor::onStart(_parentExtractSize, _parentExtract);
  4637. }
  4638. virtual const void * nextRowGE(const void *seek, const void *rawSeek, unsigned numFields, unsigned seeklen, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  4639. {
  4640. // 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
  4641. if (exception)
  4642. throw exception.getClear();
  4643. return CRemoteResultAdaptor::nextRowGE(seek, rawSeek, numFields, seeklen, wasCompleteMatch, stepExtra);
  4644. }
  4645. virtual const void *nextRow()
  4646. {
  4647. if (skipping)
  4648. {
  4649. if(!pulled)
  4650. pullInput();
  4651. if(buff.isItem(index))
  4652. {
  4653. const void * next = buff.item(index++);
  4654. if(next)
  4655. processed++;
  4656. return next;
  4657. }
  4658. return NULL;
  4659. }
  4660. else
  4661. {
  4662. if (exception)
  4663. throw exception.getClear();
  4664. return CRemoteResultAdaptor::nextRow();
  4665. }
  4666. }
  4667. };
  4668. //=================================================================================
  4669. class CRoxieServerApplyActivity : public CRoxieServerInternalSinkActivity
  4670. {
  4671. IHThorApplyArg &helper;
  4672. public:
  4673. CRoxieServerApplyActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4674. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, 0), helper((IHThorApplyArg &) basehelper)
  4675. {
  4676. }
  4677. virtual void onExecute()
  4678. {
  4679. helper.start();
  4680. for (;;)
  4681. {
  4682. const void * next = inputStream->ungroupedNextRow();
  4683. if (!next)
  4684. break;
  4685. helper.apply(next);
  4686. ReleaseRoxieRow(next);
  4687. }
  4688. helper.end();
  4689. }
  4690. };
  4691. class CRoxieServerApplyActivityFactory : public CRoxieServerActivityFactory
  4692. {
  4693. bool isRoot;
  4694. public:
  4695. CRoxieServerApplyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  4696. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  4697. {
  4698. }
  4699. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  4700. {
  4701. return new CRoxieServerApplyActivity(_ctx, this, _probeManager);
  4702. }
  4703. virtual bool isSink() const
  4704. {
  4705. return isRoot;
  4706. }
  4707. };
  4708. IRoxieServerActivityFactory *createRoxieServerApplyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  4709. {
  4710. return new CRoxieServerApplyActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  4711. }
  4712. //=================================================================================
  4713. class CRoxieServerNullActivity : public CRoxieServerActivity
  4714. {
  4715. public:
  4716. CRoxieServerNullActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4717. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  4718. {
  4719. }
  4720. virtual const void *nextRow()
  4721. {
  4722. return NULL;
  4723. }
  4724. };
  4725. IRoxieServerActivity * createRoxieServerNullActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4726. {
  4727. return new CRoxieServerNullActivity(_ctx, _factory, _probeManager);
  4728. }
  4729. class CRoxieServerNullActivityFactory : public CRoxieServerActivityFactory
  4730. {
  4731. public:
  4732. CRoxieServerNullActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4733. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  4734. {
  4735. }
  4736. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  4737. {
  4738. return new CRoxieServerNullActivity(_ctx, this, _probeManager);
  4739. }
  4740. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  4741. {
  4742. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for null activity");
  4743. }
  4744. };
  4745. IRoxieServerActivityFactory *createRoxieServerNullActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4746. {
  4747. return new CRoxieServerNullActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  4748. }
  4749. //=================================================================================
  4750. class CRoxieServerPassThroughActivity : public CRoxieServerActivity
  4751. {
  4752. public:
  4753. CRoxieServerPassThroughActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4754. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  4755. {
  4756. }
  4757. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  4758. {
  4759. return input->gatherConjunctions(collector);
  4760. }
  4761. virtual void resetEOF()
  4762. {
  4763. inputStream->resetEOF();
  4764. }
  4765. virtual const void *nextRow()
  4766. {
  4767. const void * next = inputStream->nextRow();
  4768. if (next)
  4769. processed++;
  4770. return next;
  4771. }
  4772. virtual bool isPassThrough()
  4773. {
  4774. return true;
  4775. }
  4776. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  4777. {
  4778. ActivityTimer t(totalCycles, timeActivities);
  4779. const void * next = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  4780. if (next)
  4781. processed++;
  4782. return next;
  4783. }
  4784. IInputSteppingMeta * querySteppingMeta()
  4785. {
  4786. return input->querySteppingMeta();
  4787. }
  4788. };
  4789. IRoxieServerActivity * createRoxieServerPassThroughActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4790. {
  4791. return new CRoxieServerPassThroughActivity(_ctx, _factory, _probeManager);
  4792. }
  4793. //=================================================================================
  4794. class CRoxieServerChildBaseActivity : public CRoxieServerActivity
  4795. {
  4796. protected:
  4797. bool eof;
  4798. bool first;
  4799. public:
  4800. CRoxieServerChildBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4801. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  4802. {
  4803. eof = false;
  4804. first = true;
  4805. }
  4806. ~CRoxieServerChildBaseActivity()
  4807. {
  4808. }
  4809. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4810. {
  4811. eof = false;
  4812. first = true;
  4813. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  4814. }
  4815. };
  4816. class CRoxieServerChildBaseActivityFactory : public CRoxieServerActivityFactory
  4817. {
  4818. public:
  4819. CRoxieServerChildBaseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4820. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  4821. {
  4822. }
  4823. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  4824. {
  4825. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  4826. }
  4827. };
  4828. //=================================================================================
  4829. class CRoxieServerChildIteratorActivity : public CRoxieServerChildBaseActivity
  4830. {
  4831. IHThorChildIteratorArg &helper;
  4832. public:
  4833. CRoxieServerChildIteratorActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4834. : CRoxieServerChildBaseActivity(_ctx, _factory, _probeManager), helper((IHThorChildIteratorArg &) basehelper)
  4835. {
  4836. }
  4837. virtual bool needsAllocator() const { return true; }
  4838. virtual const void *nextRow()
  4839. {
  4840. ActivityTimer t(totalCycles, timeActivities);
  4841. if (eof)
  4842. return NULL;
  4843. bool ok;
  4844. if (first)
  4845. {
  4846. ok = helper.first();
  4847. first = false;
  4848. }
  4849. else
  4850. ok = helper.next();
  4851. try
  4852. {
  4853. while (ok)
  4854. {
  4855. processed++;
  4856. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  4857. unsigned outSize = helper.transform(rowBuilder);
  4858. if (outSize)
  4859. return rowBuilder.finalizeRowClear(outSize);
  4860. ok = helper.next();
  4861. }
  4862. }
  4863. catch (IException *E)
  4864. {
  4865. throw makeWrappedException(E);
  4866. }
  4867. eof = true;
  4868. return NULL;
  4869. }
  4870. };
  4871. class CRoxieServerChildIteratorActivityFactory : public CRoxieServerChildBaseActivityFactory
  4872. {
  4873. public:
  4874. CRoxieServerChildIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4875. : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  4876. {
  4877. }
  4878. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  4879. {
  4880. return new CRoxieServerChildIteratorActivity(_ctx, this, _probeManager);
  4881. }
  4882. };
  4883. IRoxieServerActivityFactory *createRoxieServerChildIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4884. {
  4885. return new CRoxieServerChildIteratorActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  4886. }
  4887. //=================================================================================
  4888. class CRoxieServerChildNormalizeActivity : public CRoxieServerChildBaseActivity
  4889. {
  4890. IHThorChildNormalizeArg &helper;
  4891. public:
  4892. CRoxieServerChildNormalizeActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4893. : CRoxieServerChildBaseActivity(_ctx, _factory, _probeManager), helper((IHThorChildNormalizeArg &) basehelper)
  4894. {
  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. bool ok;
  4903. if (first)
  4904. {
  4905. ok = helper.first();
  4906. first = false;
  4907. }
  4908. else
  4909. ok = helper.next();
  4910. if (ok)
  4911. {
  4912. try
  4913. {
  4914. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  4915. do {
  4916. unsigned outSize = helper.transform(rowBuilder);
  4917. if (outSize)
  4918. {
  4919. processed++;
  4920. return rowBuilder.finalizeRowClear(outSize);
  4921. }
  4922. ok = helper.next();
  4923. }
  4924. while (ok);
  4925. }
  4926. catch (IException *E)
  4927. {
  4928. throw makeWrappedException(E);
  4929. }
  4930. }
  4931. eof = true;
  4932. return NULL;
  4933. }
  4934. };
  4935. class CRoxieServerChildNormalizeActivityFactory : public CRoxieServerChildBaseActivityFactory
  4936. {
  4937. public:
  4938. CRoxieServerChildNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4939. : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  4940. {
  4941. }
  4942. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  4943. {
  4944. return new CRoxieServerChildNormalizeActivity(_ctx, this, _probeManager);
  4945. }
  4946. };
  4947. IRoxieServerActivityFactory *createRoxieServerNewChildNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4948. {
  4949. return new CRoxieServerChildNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  4950. }
  4951. //=================================================================================
  4952. class CRoxieServerChildAggregateActivity : public CRoxieServerChildBaseActivity
  4953. {
  4954. IHThorChildAggregateArg &helper;
  4955. public:
  4956. CRoxieServerChildAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4957. : CRoxieServerChildBaseActivity(_ctx, _factory, _probeManager), helper((IHThorChildAggregateArg &) basehelper)
  4958. {
  4959. }
  4960. virtual bool needsAllocator() const { return true; }
  4961. virtual const void *nextRow()
  4962. {
  4963. ActivityTimer t(totalCycles, timeActivities);
  4964. if (eof)
  4965. return NULL;
  4966. eof = true;
  4967. processed++;
  4968. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  4969. helper.clearAggregate(rowBuilder);
  4970. helper.processRows(rowBuilder);
  4971. size32_t finalSize = meta.getRecordSize(rowBuilder.getSelf());
  4972. return rowBuilder.finalizeRowClear(finalSize);
  4973. }
  4974. };
  4975. class CRoxieServerChildAggregateActivityFactory : public CRoxieServerChildBaseActivityFactory
  4976. {
  4977. public:
  4978. CRoxieServerChildAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4979. : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  4980. {
  4981. }
  4982. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  4983. {
  4984. return new CRoxieServerChildAggregateActivity(_ctx, this, _probeManager);
  4985. }
  4986. };
  4987. IRoxieServerActivityFactory *createRoxieServerNewChildAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4988. {
  4989. return new CRoxieServerChildAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  4990. }
  4991. //=================================================================================
  4992. class CRoxieServerChildGroupAggregateActivity : public CRoxieServerChildBaseActivity, public IHThorGroupAggregateCallback
  4993. {
  4994. IHThorChildGroupAggregateArg &helper;
  4995. RowAggregator aggregated;
  4996. public:
  4997. IMPLEMENT_IINTERFACE_USING(CRoxieServerChildBaseActivity)
  4998. CRoxieServerChildGroupAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4999. : CRoxieServerChildBaseActivity(_ctx, _factory, _probeManager), helper((IHThorChildGroupAggregateArg &) basehelper),
  5000. aggregated(helper, helper)
  5001. {
  5002. }
  5003. void processRow(const void * next)
  5004. {
  5005. aggregated.addRow(next);
  5006. }
  5007. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5008. {
  5009. CRoxieServerChildBaseActivity::start(parentExtractSize, parentExtract, paused);
  5010. aggregated.start(rowAllocator, ctx->queryCodeContext(), activityId);
  5011. }
  5012. virtual void reset()
  5013. {
  5014. aggregated.reset();
  5015. CRoxieServerChildBaseActivity::reset();
  5016. }
  5017. virtual bool needsAllocator() const { return true; }
  5018. virtual const void *nextRow()
  5019. {
  5020. ActivityTimer t(totalCycles, timeActivities);
  5021. if (eof)
  5022. return NULL;
  5023. if (first)
  5024. {
  5025. helper.processRows(this);
  5026. first = false;
  5027. }
  5028. Owned<AggregateRowBuilder> next = aggregated.nextResult();
  5029. if (next)
  5030. {
  5031. processed++;
  5032. return next->finalizeRowClear();
  5033. }
  5034. eof = true;
  5035. return NULL;
  5036. }
  5037. };
  5038. class CRoxieServerChildGroupAggregateActivityFactory : public CRoxieServerChildBaseActivityFactory
  5039. {
  5040. public:
  5041. CRoxieServerChildGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5042. : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  5043. {
  5044. }
  5045. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  5046. {
  5047. return new CRoxieServerChildGroupAggregateActivity(_ctx, this, _probeManager);
  5048. }
  5049. };
  5050. IRoxieServerActivityFactory *createRoxieServerNewChildGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5051. {
  5052. return new CRoxieServerChildGroupAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  5053. }
  5054. //=================================================================================
  5055. class CRoxieServerChildThroughNormalizeActivity : public CRoxieServerChildBaseActivity
  5056. {
  5057. IHThorChildThroughNormalizeArg &helper;
  5058. const void * lastInput;
  5059. unsigned numProcessedLastGroup;
  5060. bool ok;
  5061. public:
  5062. CRoxieServerChildThroughNormalizeActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5063. : CRoxieServerChildBaseActivity(_ctx, _factory, _probeManager), helper((IHThorChildThroughNormalizeArg &) basehelper)
  5064. {
  5065. lastInput = NULL;
  5066. numProcessedLastGroup = 0;
  5067. ok = false;
  5068. }
  5069. virtual void stop()
  5070. {
  5071. CRoxieServerChildBaseActivity::stop();
  5072. ReleaseRoxieRow(lastInput);
  5073. lastInput = NULL;
  5074. }
  5075. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5076. {
  5077. CRoxieServerChildBaseActivity::start(parentExtractSize, parentExtract, paused);
  5078. numProcessedLastGroup = processed;
  5079. ok = false;
  5080. }
  5081. virtual bool needsAllocator() const { return true; }
  5082. virtual const void *nextRow()
  5083. {
  5084. ActivityTimer t(totalCycles, timeActivities);
  5085. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  5086. for (;;)
  5087. {
  5088. if (ok)
  5089. ok = helper.next();
  5090. while (!ok)
  5091. {
  5092. ReleaseRoxieRow(lastInput);
  5093. lastInput = inputStream->nextRow();
  5094. if (!lastInput)
  5095. {
  5096. if (numProcessedLastGroup != processed)
  5097. {
  5098. numProcessedLastGroup = processed;
  5099. return NULL;
  5100. }
  5101. lastInput = inputStream->nextRow();
  5102. if (!lastInput)
  5103. return NULL;
  5104. }
  5105. ok = helper.first(lastInput);
  5106. }
  5107. try
  5108. {
  5109. do
  5110. {
  5111. unsigned outSize = helper.transform(rowBuilder);
  5112. if (outSize)
  5113. {
  5114. processed++;
  5115. return rowBuilder.finalizeRowClear(outSize);
  5116. }
  5117. ok = helper.next();
  5118. } while (ok);
  5119. }
  5120. catch (IException *E)
  5121. {
  5122. throw makeWrappedException(E);
  5123. }
  5124. }
  5125. }
  5126. };
  5127. class CRoxieServerChildThroughNormalizeActivityFactory : public CRoxieServerActivityFactory
  5128. {
  5129. public:
  5130. CRoxieServerChildThroughNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5131. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  5132. {
  5133. }
  5134. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  5135. {
  5136. return new CRoxieServerChildThroughNormalizeActivity(_ctx, this, _probeManager);
  5137. }
  5138. };
  5139. IRoxieServerActivityFactory *createRoxieServerNewChildThroughNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5140. {
  5141. return new CRoxieServerChildThroughNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  5142. }
  5143. //=================================================================================
  5144. class CRoxieServerDistributionActivity : public CRoxieServerInternalSinkActivity
  5145. {
  5146. IHThorDistributionArg &helper;
  5147. public:
  5148. CRoxieServerDistributionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5149. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, 0), helper((IHThorDistributionArg &)basehelper)
  5150. {
  5151. }
  5152. virtual void onExecute()
  5153. {
  5154. MemoryAttr ma;
  5155. IDistributionTable * * accumulator = (IDistributionTable * *)ma.allocate(helper.queryInternalRecordSize()->getMinRecordSize());
  5156. helper.clearAggregate(accumulator);
  5157. OwnedConstRoxieRow nextrec(inputStream->nextRow());
  5158. for (;;)
  5159. {
  5160. if (!nextrec)
  5161. {
  5162. nextrec.setown(inputStream->nextRow());
  5163. if (!nextrec)
  5164. break;
  5165. }
  5166. helper.process(accumulator, nextrec);
  5167. nextrec.setown(inputStream->nextRow());
  5168. }
  5169. StringBuffer result;
  5170. result.append("<XML>");
  5171. helper.gatherResult(accumulator, result);
  5172. result.append("</XML>");
  5173. helper.sendResult(result.length(), result.str());
  5174. helper.destruct(accumulator);
  5175. }
  5176. };
  5177. class CRoxieServerDistributionActivityFactory : public CRoxieServerActivityFactory
  5178. {
  5179. bool isRoot;
  5180. public:
  5181. CRoxieServerDistributionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  5182. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  5183. {
  5184. }
  5185. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  5186. {
  5187. return new CRoxieServerDistributionActivity(_ctx, this, _probeManager);
  5188. }
  5189. virtual bool isSink() const
  5190. {
  5191. return isRoot;
  5192. }
  5193. };
  5194. IRoxieServerActivityFactory *createRoxieServerDistributionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  5195. {
  5196. return new CRoxieServerDistributionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  5197. }
  5198. //=================================================================================
  5199. class CRoxieServerLinkedRawIteratorActivity : public CRoxieServerActivity
  5200. {
  5201. IHThorLinkedRawIteratorArg &helper;
  5202. public:
  5203. CRoxieServerLinkedRawIteratorActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5204. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorLinkedRawIteratorArg &) basehelper)
  5205. {
  5206. }
  5207. virtual const void *nextRow()
  5208. {
  5209. ActivityTimer t(totalCycles, timeActivities);
  5210. const void *ret =helper.next();
  5211. if (ret)
  5212. {
  5213. LinkRoxieRow(ret);
  5214. processed++;
  5215. }
  5216. return ret;
  5217. }
  5218. };
  5219. class CRoxieServerLinkedRawIteratorActivityFactory : public CRoxieServerActivityFactory
  5220. {
  5221. public:
  5222. CRoxieServerLinkedRawIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5223. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  5224. {
  5225. }
  5226. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  5227. {
  5228. return new CRoxieServerLinkedRawIteratorActivity(_ctx, this, _probeManager);
  5229. }
  5230. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  5231. {
  5232. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  5233. }
  5234. };
  5235. IRoxieServerActivityFactory *createRoxieServerLinkedRawIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5236. {
  5237. return new CRoxieServerLinkedRawIteratorActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  5238. }
  5239. //=================================================================================
  5240. class CRoxieServerDatasetResultActivity : public CRoxieServerActivity
  5241. {
  5242. public:
  5243. CRoxieServerDatasetResultActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5244. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  5245. {
  5246. }
  5247. virtual const void *nextRow()
  5248. {
  5249. throwUnexpected();
  5250. }
  5251. virtual void executeChild(size32_t & retSize, void * & ret, unsigned parentExtractSize, const byte * parentExtract)
  5252. {
  5253. try
  5254. {
  5255. start(parentExtractSize, parentExtract, false);
  5256. {
  5257. ActivityTimer t(totalCycles, timeActivities);
  5258. MemoryBuffer result;
  5259. IRecordSize * inputMeta = input->queryOutputMeta();
  5260. for (;;)
  5261. {
  5262. const void *nextrec = inputStream->ungroupedNextRow();
  5263. if (!nextrec)
  5264. break;
  5265. result.append(inputMeta->getRecordSize(nextrec), nextrec);
  5266. ReleaseRoxieRow(nextrec);
  5267. }
  5268. retSize = result.length();
  5269. ret = result.detach();
  5270. }
  5271. stop();
  5272. reset();
  5273. }
  5274. catch(IException *E)
  5275. {
  5276. ctx->notifyAbort(E);
  5277. abort();
  5278. reset();
  5279. throw;
  5280. }
  5281. catch(...)
  5282. {
  5283. Owned<IException> E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught at %s:%d", sanitizeSourceFile(__FILE__), __LINE__);
  5284. ctx->notifyAbort(E);
  5285. abort();
  5286. reset();
  5287. throw;
  5288. }
  5289. }
  5290. };
  5291. class CRoxieServerDatasetResultActivityFactory : public CRoxieServerActivityFactory
  5292. {
  5293. bool isRoot;
  5294. public:
  5295. CRoxieServerDatasetResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  5296. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  5297. {
  5298. }
  5299. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  5300. {
  5301. return new CRoxieServerDatasetResultActivity(_ctx, this, _probeManager);
  5302. }
  5303. virtual bool isSink() const
  5304. {
  5305. return isRoot;
  5306. }
  5307. };
  5308. IRoxieServerActivityFactory *createRoxieServerDatasetResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  5309. {
  5310. return new CRoxieServerDatasetResultActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  5311. }
  5312. //=================================================================================
  5313. class CRoxieServerInlineTableActivity : public CRoxieServerActivity
  5314. {
  5315. IHThorInlineTableArg &helper;
  5316. __uint64 curRow;
  5317. __uint64 numRows;
  5318. public:
  5319. CRoxieServerInlineTableActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5320. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorInlineTableArg &) basehelper)
  5321. {
  5322. curRow = 0;
  5323. numRows = 0;
  5324. }
  5325. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5326. {
  5327. curRow = 0;
  5328. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5329. numRows = helper.numRows();
  5330. }
  5331. virtual bool needsAllocator() const { return true; }
  5332. virtual const void *nextRow()
  5333. {
  5334. ActivityTimer t(totalCycles, timeActivities);
  5335. // Filtering empty rows, returns the next valid row
  5336. while (curRow < numRows)
  5337. {
  5338. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  5339. unsigned outSize = helper.getRow(rowBuilder, curRow++);
  5340. if (outSize)
  5341. {
  5342. processed++;
  5343. return rowBuilder.finalizeRowClear(outSize);
  5344. }
  5345. }
  5346. return NULL;
  5347. }
  5348. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  5349. {
  5350. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  5351. }
  5352. };
  5353. class CRoxieServerStrandedInlineTableActivity : public CRoxieServerStrandedActivity
  5354. {
  5355. IHThorInlineTableArg &helper;
  5356. __uint64 numRows;
  5357. //An inline table that isn't stranded
  5358. class InlineTableSimpleProcessor : public StrandProcessor
  5359. {
  5360. protected:
  5361. IHThorInlineTableArg &helper;
  5362. __uint64 curRow;
  5363. __uint64 maxRows;
  5364. public:
  5365. InlineTableSimpleProcessor(CRoxieServerActivity &_parent, IHThorInlineTableArg &_helper)
  5366. : StrandProcessor(_parent, NULL, true), helper(_helper), curRow(0), maxRows(0)
  5367. {
  5368. }
  5369. virtual void start() override
  5370. {
  5371. StrandProcessor::start();
  5372. curRow = 0;
  5373. maxRows = queryParent().numRows;
  5374. }
  5375. virtual const void * nextRow()
  5376. {
  5377. ActivityTimer t(totalCycles, timeActivities);
  5378. //Return rows while the current section is active
  5379. while (curRow < maxRows)
  5380. {
  5381. RtlDynamicRowBuilder rowBuilder(*rowAllocator);
  5382. unsigned outSize = helper.getRow(rowBuilder, curRow++);
  5383. if (outSize)
  5384. {
  5385. processed++;
  5386. return rowBuilder.finalizeRowClear(outSize);
  5387. }
  5388. }
  5389. return NULL;
  5390. }
  5391. CRoxieServerStrandedInlineTableActivity & queryParent() { return static_cast<CRoxieServerStrandedInlineTableActivity&>(parent); }
  5392. };
  5393. class InlineTableStrandProcessor : public StrandProcessor
  5394. {
  5395. protected:
  5396. IHThorInlineTableArg &helper;
  5397. unsigned whichStrand;
  5398. unsigned numStrands = 0;
  5399. __uint64 sectionSize;
  5400. __uint64 curRow = 0;
  5401. __uint64 sectionMaxRows = 0;
  5402. __uint64 maxRows = 0;
  5403. bool isOrdered;
  5404. bool eosPending;
  5405. public:
  5406. InlineTableStrandProcessor(CRoxieServerActivity &_parent, IHThorInlineTableArg &_helper, unsigned _whichStrand, bool _isOrdered)
  5407. : StrandProcessor(_parent, NULL, true), helper(_helper), whichStrand(_whichStrand), isOrdered(_isOrdered)
  5408. {
  5409. sectionSize = queryParent().strandOptions.blockSize;
  5410. eosPending = false;
  5411. }
  5412. virtual void start() override
  5413. {
  5414. StrandProcessor::start();
  5415. numStrands = queryParent().numStrands();
  5416. maxRows = queryParent().numRows;
  5417. curRow = std::min(whichStrand * sectionSize, maxRows);
  5418. sectionMaxRows = std::min(curRow + sectionSize, maxRows);
  5419. eosPending = isOrdered && (curRow != maxRows);
  5420. }
  5421. virtual const void * nextRow()
  5422. {
  5423. ActivityTimer t(totalCycles, timeActivities);
  5424. for (;;)
  5425. {
  5426. //Return rows while the current section is active
  5427. while (curRow < sectionMaxRows)
  5428. {
  5429. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  5430. unsigned outSize = helper.getRow(rowBuilder, curRow++);
  5431. if (outSize)
  5432. {
  5433. processed++;
  5434. return rowBuilder.finalizeRowClear(outSize);
  5435. }
  5436. }
  5437. if (curRow == maxRows)
  5438. return NULL;
  5439. //Update current position to the next section
  5440. curRow += (numStrands - 1) * sectionSize;
  5441. if (curRow > maxRows)
  5442. curRow = maxRows;
  5443. sectionMaxRows = std::min(curRow + sectionSize, maxRows);
  5444. //If we have output a block of rows, then send the block as a unit - results now come from the next strand
  5445. if (eosPending)
  5446. {
  5447. //If there is another block, then second an end of section marker after it, otherwise make sure NULL is returned next.
  5448. eosPending = isOrdered && (curRow != maxRows);
  5449. return queryEndOfSectionMarker();
  5450. }
  5451. }
  5452. }
  5453. CRoxieServerStrandedInlineTableActivity & queryParent() { return static_cast<CRoxieServerStrandedInlineTableActivity&>(parent); }
  5454. };
  5455. public:
  5456. CRoxieServerStrandedInlineTableActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const StrandOptions &_strandOptions)
  5457. : CRoxieServerStrandedActivity(_ctx, _factory, _probeManager, _strandOptions), helper((IHThorInlineTableArg &) basehelper)
  5458. {
  5459. numRows = 0;
  5460. }
  5461. virtual StrandProcessor *createStrandProcessor(IEngineRowStream *instream) { throwUnexpected(); }
  5462. virtual StrandProcessor *createStrandSourceProcessor(bool inputOrdered)
  5463. {
  5464. if (strandOptions.numStrands <= 1)
  5465. return new InlineTableSimpleProcessor(*this, helper);
  5466. return new InlineTableStrandProcessor(*this, helper, strands.ordinality(), inputOrdered);
  5467. }
  5468. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5469. {
  5470. CRoxieServerStrandedActivity::start(parentExtractSize, parentExtract, paused);
  5471. numRows = helper.numRows();
  5472. onStartStrands();
  5473. startJunction(sourceJunction); // This must be started *after* all the strands have been initialised
  5474. }
  5475. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  5476. {
  5477. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  5478. }
  5479. };
  5480. class CRoxieServerInlineTableActivityFactory : public CRoxieServerActivityFactory
  5481. {
  5482. StrandOptions strandOptions;
  5483. public:
  5484. CRoxieServerInlineTableActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5485. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), strandOptions(_graphNode)
  5486. {
  5487. optStableInput = false; // do not force the output to be ordered
  5488. }
  5489. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  5490. {
  5491. return new CRoxieServerStrandedInlineTableActivity(_ctx, this, _probeManager, strandOptions);
  5492. }
  5493. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  5494. {
  5495. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for InlineTable activity");
  5496. }
  5497. };
  5498. IRoxieServerActivityFactory *createRoxieServerInlineTableActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5499. {
  5500. return new CRoxieServerInlineTableActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  5501. }
  5502. //=================================================================================
  5503. class CRoxieServerWorkUnitReadActivity : public CRoxieServerActivity
  5504. {
  5505. IHThorWorkunitReadArg &helper;
  5506. CriticalSection readerCrit;
  5507. Owned<IWorkUnitRowReader> wuReader;
  5508. public:
  5509. CRoxieServerWorkUnitReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5510. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorWorkunitReadArg &)basehelper)
  5511. {
  5512. }
  5513. virtual void onCreate(IHThorArg *_colocalParent)
  5514. {
  5515. CRoxieServerActivity::onCreate(_colocalParent);
  5516. if (!ctx->queryServerContext())
  5517. {
  5518. throw MakeStringException(ROXIE_INTERNAL_ERROR, "Workunit read activity cannot be executed in slave context");
  5519. }
  5520. }
  5521. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5522. {
  5523. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5524. IXmlToRowTransformer * xmlTransformer = helper.queryXmlTransformer();
  5525. OwnedRoxieString fromWuid(helper.getWUID());
  5526. wuReader.setown(ctx->getWorkunitRowReader(fromWuid, helper.queryName(), helper.querySequence(), xmlTransformer, rowAllocator, meta.isGrouped()));
  5527. // MORE _ should that be in onCreate?
  5528. }
  5529. virtual void reset()
  5530. {
  5531. {
  5532. CriticalBlock b(readerCrit);
  5533. wuReader.clear();
  5534. }
  5535. CRoxieServerActivity::reset();
  5536. };
  5537. virtual bool needsAllocator() const { return true; }
  5538. virtual const void *nextRow()
  5539. {
  5540. ActivityTimer t(totalCycles, timeActivities);
  5541. Linked<IWorkUnitRowReader> useReader;
  5542. {
  5543. CriticalBlock b(readerCrit);
  5544. if (!wuReader)
  5545. return NULL;
  5546. useReader.set(wuReader);
  5547. }
  5548. const void *ret = useReader->nextRow();
  5549. if (ret)
  5550. processed++;
  5551. return ret;
  5552. }
  5553. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  5554. {
  5555. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  5556. }
  5557. };
  5558. class CRoxieServerWorkUnitReadActivityFactory : public CRoxieServerActivityFactory
  5559. {
  5560. public:
  5561. CRoxieServerWorkUnitReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5562. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  5563. {
  5564. }
  5565. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  5566. {
  5567. return new CRoxieServerWorkUnitReadActivity(_ctx, this, _probeManager);
  5568. }
  5569. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  5570. {
  5571. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for WorkUnitRead activity");
  5572. }
  5573. };
  5574. IRoxieServerActivityFactory *createRoxieServerWorkUnitReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5575. {
  5576. return new CRoxieServerWorkUnitReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  5577. }
  5578. //=================================================================================
  5579. interface ILocalGraphEx : public IEclGraphResults
  5580. {
  5581. public:
  5582. virtual void setResult(unsigned id, IGraphResult * result) = 0;
  5583. virtual IEngineRowStream * createResultIterator(unsigned id) = 0;
  5584. virtual void setGraphLoopResult(IGraphResult * result) = 0;
  5585. virtual IEngineRowStream * createGraphLoopResultIterator(unsigned id) = 0;
  5586. };
  5587. class CSafeRoxieInput : implements IEngineRowStream, implements IFinalRoxieInput, public CInterface
  5588. {
  5589. public:
  5590. CSafeRoxieInput(unsigned _sourceIdx, IFinalRoxieInput * _input) : input(_input), inputStream(NULL), sourceIdx(_sourceIdx) {}
  5591. IMPLEMENT_IINTERFACE
  5592. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  5593. {
  5594. connectInputStreams(ctx, consumerOrdered);
  5595. streams.append(this);
  5596. return NULL;
  5597. }
  5598. void connectInputStreams(IRoxieSlaveContext *ctx, bool consumerOrdered)
  5599. {
  5600. inputStream.set(connectSingleStream(ctx, input, sourceIdx, junction, consumerOrdered));
  5601. }
  5602. virtual IOutputMetaData * queryOutputMeta() const
  5603. {
  5604. return input->queryOutputMeta();
  5605. }
  5606. virtual unsigned __int64 queryTotalCycles() const
  5607. {
  5608. return input->queryTotalCycles();
  5609. }
  5610. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { assertex(whichInput==0); return this; }
  5611. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { assertex(idx==0); return nullptr; }
  5612. virtual IRoxieServerActivity *queryActivity()
  5613. {
  5614. return input->queryActivity();
  5615. }
  5616. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  5617. {
  5618. return input->queryIndexReadActivity();
  5619. }
  5620. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5621. {
  5622. CriticalBlock procedure(cs);
  5623. input->start(parentExtractSize, parentExtract, paused);
  5624. startJunction(junction);
  5625. }
  5626. virtual void stop()
  5627. {
  5628. CriticalBlock procedure(cs);
  5629. inputStream->stop();
  5630. }
  5631. virtual void reset()
  5632. {
  5633. CriticalBlock procedure(cs);
  5634. input->reset();
  5635. resetJunction(junction);
  5636. }
  5637. virtual void resetEOF()
  5638. {
  5639. CriticalBlock procedure(cs);
  5640. inputStream->resetEOF();
  5641. }
  5642. virtual const void *nextRow()
  5643. {
  5644. CriticalBlock procedure(cs);
  5645. return inputStream->nextRow();
  5646. }
  5647. virtual bool nextGroup(ConstPointerArray & group)
  5648. {
  5649. CriticalBlock procedure(cs);
  5650. return inputStream->nextGroup(group);
  5651. }
  5652. private:
  5653. CriticalSection cs;
  5654. Linked<IFinalRoxieInput> input;
  5655. Linked<IEngineRowStream> inputStream;
  5656. Owned<IStrandJunction> junction;
  5657. unsigned sourceIdx;
  5658. };
  5659. //=================================================================================
  5660. class CPseudoRoxieInput : implements IEngineRowStream, implements IFinalRoxieInput, public CInterface
  5661. {
  5662. public:
  5663. IMPLEMENT_IINTERFACE;
  5664. CPseudoRoxieInput()
  5665. {
  5666. }
  5667. virtual unsigned __int64 queryTotalCycles() const
  5668. {
  5669. return 0;
  5670. }
  5671. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { assertex(whichInput==0); return this; }
  5672. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { assertex(idx==0); return nullptr; }
  5673. virtual IRoxieServerActivity *queryActivity()
  5674. {
  5675. throwUnexpected();
  5676. }
  5677. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  5678. {
  5679. throwUnexpected();
  5680. }
  5681. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  5682. {
  5683. assertex(!idx);
  5684. streams.append(this);
  5685. return NULL;
  5686. }
  5687. virtual IOutputMetaData * queryOutputMeta() const { throwUnexpected(); }
  5688. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused) { }
  5689. virtual void stop() { }
  5690. virtual void reset() { }
  5691. virtual void checkAbort() { }
  5692. virtual void resetEOF() { }
  5693. };
  5694. class CIndirectRoxieInput : public CPseudoRoxieInput
  5695. {
  5696. public:
  5697. CIndirectRoxieInput() : input(NULL)
  5698. {
  5699. stream = NULL;
  5700. sourceIdx = 0;
  5701. }
  5702. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5703. {
  5704. input->start(parentExtractSize, parentExtract, paused);
  5705. startJunction(junction);
  5706. }
  5707. virtual void stop()
  5708. {
  5709. stream->stop();
  5710. }
  5711. virtual void reset()
  5712. {
  5713. input->reset();
  5714. resetJunction(junction);
  5715. }
  5716. virtual const void * nextRow()
  5717. {
  5718. return stream->nextRow();
  5719. }
  5720. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  5721. {
  5722. return stream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  5723. }
  5724. virtual unsigned __int64 queryTotalCycles() const
  5725. {
  5726. return input->queryTotalCycles();
  5727. }
  5728. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  5729. {
  5730. return input->gatherConjunctions(collector);
  5731. }
  5732. virtual void resetEOF()
  5733. {
  5734. stream->resetEOF();
  5735. }
  5736. virtual unsigned numConcreteOutputs() const
  5737. {
  5738. return input->numConcreteOutputs();
  5739. }
  5740. virtual IFinalRoxieInput * queryConcreteInput(unsigned idx)
  5741. {
  5742. return input->queryConcreteInput(idx);
  5743. }
  5744. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput)
  5745. {
  5746. return input->queryConcreteOutputStream(whichInput);
  5747. }
  5748. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const
  5749. {
  5750. return input->queryConcreteOutputJunction(idx);
  5751. }
  5752. virtual IOutputMetaData * queryOutputMeta() const
  5753. {
  5754. return input->queryOutputMeta();
  5755. }
  5756. virtual IRoxieServerActivity *queryActivity()
  5757. {
  5758. return input->queryActivity();
  5759. }
  5760. inline void setInput(unsigned _sourceIdx, IFinalRoxieInput * _input)
  5761. {
  5762. input = _input;
  5763. sourceIdx = _sourceIdx;
  5764. }
  5765. inline void connectInputStreams(IRoxieSlaveContext *ctx, bool consumerOrdered)
  5766. {
  5767. stream = connectSingleStream(ctx, input, sourceIdx, junction, consumerOrdered);
  5768. }
  5769. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  5770. {
  5771. assertex(idx == 0);
  5772. connectInputStreams(ctx, consumerOrdered);
  5773. streams.append(this);
  5774. return NULL;
  5775. }
  5776. inline IFinalRoxieInput *queryInput() const
  5777. {
  5778. return input;
  5779. }
  5780. protected:
  5781. unsigned sourceIdx;
  5782. IFinalRoxieInput *input;
  5783. IEngineRowStream *stream;
  5784. Owned<IStrandJunction> junction;
  5785. };
  5786. class CExtractMapperInput : public CIndirectRoxieInput
  5787. {
  5788. unsigned savedParentExtractSize;
  5789. const byte * savedParentExtract;
  5790. public:
  5791. CExtractMapperInput()
  5792. {
  5793. savedParentExtractSize = 0;
  5794. savedParentExtract = NULL;
  5795. }
  5796. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5797. {
  5798. CIndirectRoxieInput::start(savedParentExtractSize, savedParentExtract, paused);
  5799. }
  5800. void setParentExtract(unsigned _savedParentExtractSize, const byte * _savedParentExtract)
  5801. {
  5802. savedParentExtractSize = _savedParentExtractSize;
  5803. savedParentExtract = _savedParentExtract;
  5804. }
  5805. };
  5806. class CGraphResult : implements IGraphResult, public CInterface
  5807. {
  5808. CriticalSection cs;
  5809. const byte **rowset;
  5810. size32_t count;
  5811. bool complete;
  5812. void clear()
  5813. {
  5814. CriticalBlock func(cs);
  5815. rtlReleaseRowset(count, rowset);
  5816. rowset = NULL;
  5817. count = 0;
  5818. complete = false;
  5819. }
  5820. public:
  5821. IMPLEMENT_IINTERFACE
  5822. CGraphResult()
  5823. {
  5824. complete = false; // dummy result is not supposed to be used...
  5825. rowset = NULL;
  5826. count = 0;
  5827. }
  5828. CGraphResult(size32_t _count, const byte **_rowset)
  5829. : count(_count), rowset(_rowset)
  5830. {
  5831. complete = true;
  5832. }
  5833. ~CGraphResult()
  5834. {
  5835. clear();
  5836. }
  5837. // interface IGraphResult
  5838. virtual IEngineRowStream * createIterator()
  5839. {
  5840. if (!complete)
  5841. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Internal Error: Reading uninitialised graph result");
  5842. return new CGraphResultIterator(this);
  5843. }
  5844. virtual void getLinkedResult(unsigned & countResult, const byte * * & result) override
  5845. {
  5846. if (!complete)
  5847. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Internal Error: Reading uninitialised graph result");
  5848. result = rtlLinkRowset(rowset);
  5849. countResult = count;
  5850. }
  5851. virtual const void * getLinkedRowResult()
  5852. {
  5853. if (!complete)
  5854. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Internal Error: Reading uninitialised graph result");
  5855. if (count != 1)
  5856. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Internal Error: Expected a single row result");
  5857. const void * ret = rowset[0];
  5858. LinkRoxieRow(ret);
  5859. return ret;
  5860. }
  5861. //other
  5862. const void * getRow(unsigned i)
  5863. {
  5864. CriticalBlock func(cs);
  5865. if (i >= count)
  5866. return NULL;
  5867. const void * ret = rowset[i];
  5868. if (ret) LinkRoxieRow(ret);
  5869. return ret;
  5870. }
  5871. protected:
  5872. class CGraphResultIterator : public CInterfaceOf<IEngineRowStream>
  5873. {
  5874. unsigned i;
  5875. Linked<CGraphResult> result;
  5876. public:
  5877. CGraphResultIterator(CGraphResult * _result) : result(_result) { i = 0; }
  5878. public:
  5879. virtual const void * nextRow()
  5880. {
  5881. return result->getRow(i++);
  5882. }
  5883. virtual void stop()
  5884. {
  5885. }
  5886. virtual void resetEOF()
  5887. {
  5888. throwUnexpected();
  5889. }
  5890. };
  5891. };
  5892. //=================================================================================
  5893. class CRoxieServerLocalResultReadActivity : public CRoxieServerActivity
  5894. {
  5895. IHThorLocalResultReadArg &helper;
  5896. CriticalSection iterCrit;
  5897. Owned<IEngineRowStream> iter;
  5898. ILocalGraphEx * graph;
  5899. unsigned graphId;
  5900. unsigned sequence;
  5901. public:
  5902. CRoxieServerLocalResultReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId)
  5903. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorLocalResultReadArg &)basehelper), graphId(_graphId)
  5904. {
  5905. graph = NULL;
  5906. sequence = 0;
  5907. }
  5908. virtual void onCreate(IHThorArg *_colocalParent)
  5909. {
  5910. CRoxieServerActivity::onCreate(_colocalParent);
  5911. graph = static_cast<ILocalGraphEx *>(ctx->queryCodeContext()->resolveLocalQuery(graphId));
  5912. sequence = helper.querySequence();
  5913. }
  5914. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5915. {
  5916. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5917. iter.setown(graph->createResultIterator(sequence));
  5918. }
  5919. virtual void reset()
  5920. {
  5921. {
  5922. CriticalBlock b(iterCrit);
  5923. iter.clear();
  5924. }
  5925. CRoxieServerActivity::reset();
  5926. };
  5927. virtual const void *nextRow()
  5928. {
  5929. ActivityTimer t(totalCycles, timeActivities);
  5930. Linked<IEngineRowStream> useIter;
  5931. {
  5932. CriticalBlock b(iterCrit);
  5933. if (!iter)
  5934. return NULL;
  5935. useIter.set(iter);
  5936. }
  5937. const void * next = useIter->nextRow();
  5938. if (next)
  5939. {
  5940. processed++;
  5941. rowsIn++;
  5942. }
  5943. return next;
  5944. }
  5945. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  5946. {
  5947. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  5948. }
  5949. };
  5950. class CRoxieServerLocalResultReadActivityFactory : public CRoxieServerActivityFactory
  5951. {
  5952. unsigned graphId;
  5953. public:
  5954. CRoxieServerLocalResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _graphId)
  5955. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), graphId(_graphId)
  5956. {
  5957. }
  5958. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  5959. {
  5960. return new CRoxieServerLocalResultReadActivity(_ctx, this, _probeManager, graphId);
  5961. }
  5962. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  5963. {
  5964. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for LocalResultRead activity");
  5965. }
  5966. };
  5967. IRoxieServerActivityFactory *createRoxieServerLocalResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned graphId)
  5968. {
  5969. return new CRoxieServerLocalResultReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, graphId);
  5970. }
  5971. //=================================================================================
  5972. class CRoxieServerLocalResultStreamReadActivity : public CRoxieServerActivity
  5973. {
  5974. IHThorLocalResultReadArg &helper;
  5975. unsigned sequence;
  5976. public:
  5977. CRoxieServerLocalResultStreamReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5978. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorLocalResultReadArg &)basehelper)
  5979. {
  5980. sequence = 0;
  5981. }
  5982. virtual void onCreate(IHThorArg *_colocalParent)
  5983. {
  5984. CRoxieServerActivity::onCreate(_colocalParent);
  5985. sequence = helper.querySequence();
  5986. }
  5987. virtual const void *nextRow()
  5988. {
  5989. ActivityTimer t(totalCycles, timeActivities);
  5990. const void * next = inputStream->nextRow();
  5991. if (next)
  5992. {
  5993. processed++;
  5994. rowsIn++;
  5995. }
  5996. return next;
  5997. }
  5998. virtual bool querySetStreamInput(unsigned id, unsigned _sourceIdx, IFinalRoxieInput * _input)
  5999. {
  6000. if (id == sequence)
  6001. {
  6002. CRoxieServerActivity::setInput(0, _sourceIdx, _input);
  6003. connectInputStreams(true);
  6004. return true;
  6005. }
  6006. return false;
  6007. }
  6008. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  6009. {
  6010. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  6011. }
  6012. };
  6013. class CRoxieServerLocalResultStreamReadActivityFactory : public CRoxieServerActivityFactory
  6014. {
  6015. public:
  6016. CRoxieServerLocalResultStreamReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  6017. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  6018. {
  6019. }
  6020. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  6021. {
  6022. return new CRoxieServerLocalResultStreamReadActivity(_ctx, this, _probeManager);
  6023. }
  6024. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  6025. {
  6026. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for LocalResultRead activity");
  6027. }
  6028. };
  6029. IRoxieServerActivityFactory *createRoxieServerLocalResultStreamReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  6030. {
  6031. return new CRoxieServerLocalResultStreamReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  6032. }
  6033. //=====================================================================================================
  6034. class CRoxieServerLocalResultWriteActivity : public CRoxieServerInternalSinkActivity
  6035. {
  6036. IHThorLocalResultWriteArg &helper;
  6037. ILocalGraphEx * graph;
  6038. unsigned graphId;
  6039. public:
  6040. CRoxieServerLocalResultWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId, unsigned _numOutputs)
  6041. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _numOutputs), helper((IHThorLocalResultWriteArg &)basehelper), graphId(_graphId)
  6042. {
  6043. graph = NULL;
  6044. }
  6045. virtual bool needsAllocator() const { return true; }
  6046. virtual void onCreate(IHThorArg *_colocalParent)
  6047. {
  6048. CRoxieServerInternalSinkActivity::onCreate(_colocalParent);
  6049. graph = static_cast<ILocalGraphEx *>(ctx->queryCodeContext()->resolveLocalQuery(graphId));
  6050. }
  6051. virtual void onExecute()
  6052. {
  6053. RtlLinkedDatasetBuilder builder(rowAllocator);
  6054. inputStream->readAll(builder);
  6055. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  6056. graph->setResult(helper.querySequence(), result);
  6057. }
  6058. virtual const void *nextRow()
  6059. {
  6060. return inputStream->nextRow(); // I can act as a passthrough input
  6061. }
  6062. IFinalRoxieInput * querySelectOutput(unsigned id)
  6063. {
  6064. if (id == helper.querySequence())
  6065. {
  6066. executed = true; // Ensure that we don't try to pull as a sink as well as via the passthrough
  6067. return LINK(this);
  6068. }
  6069. return NULL;
  6070. }
  6071. };
  6072. class CRoxieServerLocalResultWriteActivityFactory : public CRoxieServerInternalSinkFactory
  6073. {
  6074. unsigned graphId;
  6075. public:
  6076. CRoxieServerLocalResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, unsigned _graphId, bool _isRoot)
  6077. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot), graphId(_graphId)
  6078. {
  6079. isInternal = true;
  6080. Owned<IHThorLocalResultWriteArg> helper = (IHThorLocalResultWriteArg *) helperFactory();
  6081. }
  6082. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  6083. {
  6084. return new CRoxieServerLocalResultWriteActivity(_ctx, this, _probeManager, graphId, usageCount);
  6085. }
  6086. };
  6087. IRoxieServerActivityFactory *createRoxieServerLocalResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, unsigned _graphId, bool _isRoot)
  6088. {
  6089. return new CRoxieServerLocalResultWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _graphId, _isRoot);
  6090. }
  6091. //=====================================================================================================
  6092. class CRoxieServerDictionaryResultWriteActivity : public CRoxieServerInternalSinkActivity
  6093. {
  6094. IHThorDictionaryResultWriteArg &helper;
  6095. ILocalGraphEx * graph;
  6096. unsigned graphId;
  6097. public:
  6098. CRoxieServerDictionaryResultWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _usageCount, unsigned _graphId)
  6099. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _usageCount), helper((IHThorDictionaryResultWriteArg &)basehelper), graphId(_graphId)
  6100. {
  6101. graph = NULL;
  6102. }
  6103. virtual bool needsAllocator() const { return true; }
  6104. virtual void onCreate(IHThorArg *_colocalParent)
  6105. {
  6106. CRoxieServerInternalSinkActivity::onCreate(_colocalParent);
  6107. graph = static_cast<ILocalGraphEx *>(ctx->queryCodeContext()->resolveLocalQuery(graphId));
  6108. }
  6109. virtual void onExecute()
  6110. {
  6111. unsigned sequence = helper.querySequence();
  6112. RtlLinkedDictionaryBuilder builder(rowAllocator, helper.queryHashLookupInfo());
  6113. for (;;)
  6114. {
  6115. const void *row = inputStream->ungroupedNextRow();
  6116. if (!row)
  6117. break;
  6118. builder.appendOwn(row);
  6119. processed++;
  6120. }
  6121. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  6122. graph->setResult(helper.querySequence(), result);
  6123. }
  6124. virtual const void *nextRow()
  6125. {
  6126. return inputStream->nextRow(); // I can act as a passthrough input
  6127. }
  6128. IFinalRoxieInput * querySelectOutput(unsigned id)
  6129. {
  6130. if (id == helper.querySequence())
  6131. {
  6132. executed = true; // Ensure that we don't try to pull as a sink as well as via the passthrough
  6133. return LINK(this);
  6134. }
  6135. return NULL;
  6136. }
  6137. };
  6138. class CRoxieServerDictionaryResultWriteActivityFactory : public CRoxieServerInternalSinkFactory
  6139. {
  6140. unsigned graphId;
  6141. public:
  6142. CRoxieServerDictionaryResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, unsigned _graphId, bool _isRoot)
  6143. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot), graphId(_graphId)
  6144. {
  6145. isInternal = true;
  6146. }
  6147. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  6148. {
  6149. return new CRoxieServerDictionaryResultWriteActivity(_ctx, this, _probeManager, usageCount, graphId);
  6150. }
  6151. };
  6152. IRoxieServerActivityFactory *createRoxieServerDictionaryResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, unsigned _graphId, bool _isRoot)
  6153. {
  6154. return new CRoxieServerDictionaryResultWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _graphId, _isRoot);
  6155. }
  6156. //=================================================================================
  6157. class CRoxieServerGraphLoopResultReadActivity : public CRoxieServerActivity
  6158. {
  6159. protected:
  6160. IHThorGraphLoopResultReadArg &helper;
  6161. CriticalSection iterCrit;
  6162. Owned<IFinalRoxieInput> iterInput;
  6163. Owned<IEngineRowStream> iterStream;
  6164. Owned<IStrandJunction> iterJunction;
  6165. ILocalGraphEx * graph;
  6166. unsigned graphId;
  6167. unsigned sequence;
  6168. public:
  6169. CRoxieServerGraphLoopResultReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId)
  6170. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorGraphLoopResultReadArg &)basehelper), graphId(_graphId)
  6171. {
  6172. graph = NULL;
  6173. sequence = 0;
  6174. }
  6175. virtual void onCreate(IHThorArg *_colocalParent)
  6176. {
  6177. CRoxieServerActivity::onCreate(_colocalParent);
  6178. graph = static_cast<ILocalGraphEx *>(ctx->queryCodeContext()->resolveLocalQuery(graphId));
  6179. }
  6180. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6181. {
  6182. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6183. if (iterInput)
  6184. iterInput->start(parentExtractSize, parentExtract, paused);
  6185. else
  6186. {
  6187. sequence = helper.querySequence();
  6188. if ((int)sequence >= 0)
  6189. {
  6190. try
  6191. {
  6192. iterStream.setown(graph->createGraphLoopResultIterator(sequence));
  6193. iterInput.clear();
  6194. }
  6195. catch (IException * E)
  6196. {
  6197. throw makeWrappedException(E);
  6198. }
  6199. }
  6200. }
  6201. startJunction(iterJunction);
  6202. }
  6203. virtual void stop()
  6204. {
  6205. if (iterStream)
  6206. iterStream->stop();
  6207. CRoxieServerActivity::stop();
  6208. }
  6209. virtual void reset()
  6210. {
  6211. {
  6212. CriticalBlock b(iterCrit);
  6213. if (iterInput)
  6214. iterInput->reset();
  6215. resetJunction(iterJunction);
  6216. iterInput.clear();
  6217. iterStream.clear();
  6218. iterJunction.clear();
  6219. }
  6220. CRoxieServerActivity::reset();
  6221. };
  6222. virtual const void *nextRow()
  6223. {
  6224. ActivityTimer t(totalCycles, timeActivities);
  6225. Linked<IEngineRowStream> useStream;
  6226. {
  6227. CriticalBlock b(iterCrit);
  6228. if (!iterStream)
  6229. return NULL;
  6230. useStream.set(iterStream);
  6231. }
  6232. const void * next = useStream->nextRow();
  6233. if (next)
  6234. {
  6235. processed++;
  6236. rowsIn++;
  6237. }
  6238. return next;
  6239. }
  6240. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  6241. {
  6242. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  6243. }
  6244. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract)
  6245. {
  6246. ensureCreated();
  6247. basehelper.onStart(parentExtract, NULL);
  6248. processor.noteUseIteration(helper.querySequence());
  6249. }
  6250. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract, IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes)
  6251. {
  6252. //helper already initialised from the gatherIterationUsage() call.
  6253. CRoxieServerActivity::connectInputStreams(true);
  6254. iterInput.set(processor.connectIterationOutput(helper.querySequence(), probeManager, probes, this, 0));
  6255. iterStream.set(connectSingleStream(ctx, iterInput, 0, iterJunction, true));
  6256. }
  6257. virtual IInputSteppingMeta * querySteppingMeta()
  6258. {
  6259. assertex(iterInput);
  6260. return iterInput->querySteppingMeta();
  6261. }
  6262. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  6263. {
  6264. assertex(iterStream);
  6265. return iterStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  6266. }
  6267. };
  6268. //variety of CRoxieServerGraphLoopResultReadActivity created internally with a predefined sequence number
  6269. class CRoxieServerInternalGraphLoopResultReadActivity : public CRoxieServerGraphLoopResultReadActivity
  6270. {
  6271. public:
  6272. CRoxieServerInternalGraphLoopResultReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId, unsigned _sequence)
  6273. : CRoxieServerGraphLoopResultReadActivity(_ctx, _factory, _probeManager, _graphId)
  6274. {
  6275. sequence = _sequence;
  6276. }
  6277. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6278. {
  6279. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6280. if ((int)sequence >= 0)
  6281. {
  6282. try
  6283. {
  6284. iterStream.setown(graph->createGraphLoopResultIterator(sequence));
  6285. iterInput.clear();
  6286. }
  6287. catch (IException * E)
  6288. {
  6289. throw makeWrappedException(E);
  6290. }
  6291. }
  6292. }
  6293. };
  6294. class CRoxieServerGraphLoopResultReadActivityFactory : public CRoxieServerActivityFactory
  6295. {
  6296. unsigned graphId;
  6297. public:
  6298. CRoxieServerGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _graphId)
  6299. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), graphId(_graphId)
  6300. {
  6301. }
  6302. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  6303. {
  6304. return new CRoxieServerGraphLoopResultReadActivity(_ctx, this, _probeManager, graphId);
  6305. }
  6306. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  6307. {
  6308. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for GraphLoopResultRead activity");
  6309. }
  6310. };
  6311. IRoxieServerActivityFactory *createRoxieServerGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned graphId)
  6312. {
  6313. return new CRoxieServerGraphLoopResultReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, graphId);
  6314. }
  6315. //=====================================================================================================
  6316. class CRoxieServerGraphLoopResultWriteActivity : public CRoxieServerInternalSinkActivity
  6317. {
  6318. IHThorGraphLoopResultWriteArg &helper;
  6319. ILocalGraphEx * graph;
  6320. unsigned graphId;
  6321. public:
  6322. CRoxieServerGraphLoopResultWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId, unsigned _numOutputs)
  6323. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _numOutputs), helper((IHThorGraphLoopResultWriteArg &)basehelper), graphId(_graphId)
  6324. {
  6325. graph = NULL;
  6326. }
  6327. virtual bool needsAllocator() const { return true; }
  6328. virtual void onCreate(IHThorArg *_colocalParent)
  6329. {
  6330. CRoxieServerInternalSinkActivity::onCreate(_colocalParent);
  6331. graph = static_cast<ILocalGraphEx *>(ctx->queryCodeContext()->resolveLocalQuery(graphId));
  6332. }
  6333. virtual void onExecute()
  6334. {
  6335. RtlLinkedDatasetBuilder builder(rowAllocator);
  6336. inputStream->readAll(builder);
  6337. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  6338. graph->setGraphLoopResult(result);
  6339. }
  6340. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  6341. {
  6342. if (idx==0)
  6343. return this;
  6344. else
  6345. return NULL;
  6346. }
  6347. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  6348. {
  6349. return input->gatherConjunctions(collector);
  6350. }
  6351. virtual void resetEOF()
  6352. {
  6353. inputStream->resetEOF();
  6354. }
  6355. virtual const void *nextRow()
  6356. {
  6357. const void * next = inputStream->nextRow();
  6358. if (next)
  6359. processed++;
  6360. return next;
  6361. }
  6362. virtual bool isPassThrough()
  6363. {
  6364. return true;
  6365. }
  6366. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  6367. {
  6368. ActivityTimer t(totalCycles, timeActivities);
  6369. const void * next = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  6370. if (next)
  6371. processed++;
  6372. return next;
  6373. }
  6374. IInputSteppingMeta * querySteppingMeta()
  6375. {
  6376. return input->querySteppingMeta();
  6377. }
  6378. virtual IOutputMetaData * queryOutputMeta() const
  6379. {
  6380. return input->queryOutputMeta();
  6381. }
  6382. };
  6383. class CRoxieServerGraphLoopResultWriteActivityFactory : public CRoxieServerInternalSinkFactory
  6384. {
  6385. unsigned graphId;
  6386. public:
  6387. CRoxieServerGraphLoopResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, unsigned _graphId)
  6388. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, true), graphId(_graphId)
  6389. {
  6390. isInternal = true;
  6391. Owned<IHThorGraphLoopResultWriteArg> helper = (IHThorGraphLoopResultWriteArg *) helperFactory();
  6392. }
  6393. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  6394. {
  6395. return new CRoxieServerGraphLoopResultWriteActivity(_ctx, this, _probeManager, graphId, usageCount);
  6396. }
  6397. };
  6398. IRoxieServerActivityFactory *createRoxieServerGraphLoopResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, unsigned _graphId)
  6399. {
  6400. return new CRoxieServerGraphLoopResultWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _graphId);
  6401. }
  6402. //=================================================================================
  6403. class CRoxieServerDedupActivity : public CRoxieServerActivity
  6404. {
  6405. protected:
  6406. IHThorDedupArg &helper;
  6407. unsigned numKept;
  6408. unsigned numToKeep;
  6409. public:
  6410. CRoxieServerDedupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6411. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorDedupArg &)basehelper)
  6412. {
  6413. numKept = 0;
  6414. numToKeep = 0;
  6415. }
  6416. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6417. {
  6418. numKept = 0;
  6419. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6420. numToKeep = helper.numToKeep();
  6421. }
  6422. };
  6423. class CRoxieServerDedupKeepLeftActivity : public CRoxieServerDedupActivity
  6424. {
  6425. IRangeCompare * stepCompare;
  6426. const void *prev;
  6427. public:
  6428. CRoxieServerDedupKeepLeftActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6429. : CRoxieServerDedupActivity(_ctx, _factory, _probeManager)
  6430. {
  6431. prev = NULL;
  6432. stepCompare = NULL;
  6433. }
  6434. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6435. {
  6436. prev = NULL;
  6437. CRoxieServerDedupActivity::start(parentExtractSize, parentExtract, paused);
  6438. IInputSteppingMeta * stepMeta = input->querySteppingMeta();
  6439. stepCompare = NULL;
  6440. if (stepMeta)
  6441. stepCompare = stepMeta->queryCompare();
  6442. }
  6443. virtual void reset()
  6444. {
  6445. ReleaseClearRoxieRow(prev);
  6446. CRoxieServerDedupActivity::reset();
  6447. }
  6448. virtual const void * nextRow()
  6449. {
  6450. ActivityTimer t(totalCycles, timeActivities);
  6451. const void * next;
  6452. for (;;)
  6453. {
  6454. next = inputStream->nextRow();
  6455. if (!prev || !next || !helper.matches(prev,next))
  6456. {
  6457. numKept = 0;
  6458. break;
  6459. }
  6460. if (numKept < numToKeep-1)
  6461. {
  6462. numKept++;
  6463. break;
  6464. }
  6465. ReleaseRoxieRow(next);
  6466. }
  6467. ReleaseRoxieRow(prev);
  6468. prev = next;
  6469. if (next)
  6470. {
  6471. LinkRoxieRow(next);
  6472. processed++;
  6473. }
  6474. return next;
  6475. }
  6476. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  6477. {
  6478. ActivityTimer t(totalCycles, timeActivities);
  6479. const void * next;
  6480. for (;;)
  6481. {
  6482. next = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  6483. //If the record was an in-exact match from the index then return it immediately
  6484. //and don't cause it to dedup following legal records.
  6485. if (!wasCompleteMatch)
  6486. {
  6487. assertex(stepExtra.returnMismatches());
  6488. return next;
  6489. }
  6490. if (!prev || !next || !helper.matches(prev,next))
  6491. {
  6492. numKept = 0;
  6493. break;
  6494. }
  6495. if (numKept < numToKeep-1)
  6496. {
  6497. numKept++;
  6498. break;
  6499. }
  6500. //Unusual - deduping by x,y stepped on x,y,z - still want any record back as soon as possible.
  6501. if (stepExtra.returnMismatches())
  6502. {
  6503. //If asked to return mismatches we are only interested in mismatches that will force the stepped
  6504. //condition to advance
  6505. if (stepCompare->docompare(next, seek, numFields) != 0)
  6506. {
  6507. wasCompleteMatch = false;
  6508. break;
  6509. }
  6510. }
  6511. ReleaseRoxieRow(next);
  6512. }
  6513. ReleaseRoxieRow(prev);
  6514. prev = next;
  6515. if (next)
  6516. {
  6517. LinkRoxieRow(next);
  6518. processed++;
  6519. }
  6520. return next;
  6521. }
  6522. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  6523. {
  6524. return input->gatherConjunctions(collector);
  6525. }
  6526. virtual void resetEOF()
  6527. {
  6528. inputStream->resetEOF();
  6529. }
  6530. IInputSteppingMeta * querySteppingMeta()
  6531. {
  6532. return input->querySteppingMeta();
  6533. }
  6534. };
  6535. //=================================================================================
  6536. class CRoxieServerDedupKeepRightActivity : public CRoxieServerDedupActivity
  6537. {
  6538. const void *kept;
  6539. bool first;
  6540. ICompare * compareBest;
  6541. public:
  6542. CRoxieServerDedupKeepRightActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6543. : CRoxieServerDedupActivity(_ctx, _factory, _probeManager), compareBest(nullptr)
  6544. {
  6545. kept = nullptr;
  6546. first = true;
  6547. if (helper.keepBest())
  6548. compareBest = helper.queryCompareBest();
  6549. }
  6550. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6551. {
  6552. first = true;
  6553. kept = nullptr;
  6554. CRoxieServerDedupActivity::start(parentExtractSize, parentExtract, paused);
  6555. if (numToKeep>1)
  6556. throw MakeStringException(ROXIE_UNIMPLEMENTED_ERROR, "DEDUP with RIGHT and NumToKeep>1 not supported");
  6557. }
  6558. virtual void reset()
  6559. {
  6560. ReleaseClearRoxieRow(kept);
  6561. CRoxieServerActivity::reset();
  6562. }
  6563. virtual const void * nextRow()
  6564. {
  6565. ActivityTimer t(totalCycles, timeActivities);
  6566. if (first)
  6567. {
  6568. kept = inputStream->nextRow();
  6569. first = false;
  6570. }
  6571. const void * next;
  6572. for (;;)
  6573. {
  6574. next = inputStream->nextRow();
  6575. if (!kept || !next || !helper.matches(kept,next))
  6576. break;
  6577. if (compareBest && compareBest->docompare(kept,next) <= 0)
  6578. continue;
  6579. ReleaseRoxieRow(kept);
  6580. kept = next;
  6581. }
  6582. const void * ret = kept;
  6583. kept = next;
  6584. // CTXLOG("dedup returns %p", ret);
  6585. if (ret) processed++;
  6586. return ret;
  6587. }
  6588. };
  6589. class CRoxieServerDedupAllActivity : public CRoxieServerActivity
  6590. {
  6591. IHThorDedupArg &helper;
  6592. unsigned survivorIndex;
  6593. ConstPointerArray survivors;
  6594. bool keepLeft;
  6595. bool eof;
  6596. bool first;
  6597. ICompare *primaryCompare;
  6598. public:
  6599. CRoxieServerDedupAllActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _keepLeft)
  6600. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorDedupArg &)basehelper)
  6601. {
  6602. keepLeft = _keepLeft;
  6603. primaryCompare = helper.queryComparePrimary();
  6604. eof = false;
  6605. first = true;
  6606. survivorIndex = 0;
  6607. }
  6608. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6609. {
  6610. eof = false;
  6611. first = true;
  6612. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6613. }
  6614. virtual void reset()
  6615. {
  6616. while (survivors.isItem(survivorIndex))
  6617. {
  6618. ReleaseRoxieRow(survivors.item(survivorIndex++));
  6619. }
  6620. survivors.kill();
  6621. eof = false;
  6622. first = true;
  6623. CRoxieServerActivity::reset();
  6624. }
  6625. void dedupRange(unsigned first, unsigned last, ConstPointerArray & group)
  6626. {
  6627. for (unsigned idxL = first; idxL < last; idxL++)
  6628. {
  6629. const void * left = group.item(idxL);
  6630. if (left)
  6631. {
  6632. for (unsigned idxR = first; idxR < last; idxR++)
  6633. {
  6634. const void * right = group.item(idxR);
  6635. if ((idxL != idxR) && right)
  6636. {
  6637. if (helper.matches(left, right))
  6638. {
  6639. if (keepLeft)
  6640. {
  6641. group.replace(NULL, idxR);
  6642. ReleaseRoxieRow(right);
  6643. }
  6644. else
  6645. {
  6646. group.replace(NULL, idxL);
  6647. ReleaseRoxieRow(left);
  6648. break;
  6649. }
  6650. }
  6651. }
  6652. }
  6653. }
  6654. }
  6655. }
  6656. void dedupRange(unsigned first, unsigned last, void ** rows)
  6657. {
  6658. for (unsigned idxL = first; idxL < last; idxL++)
  6659. {
  6660. void * left = rows[idxL];
  6661. if (left)
  6662. {
  6663. for (unsigned idxR = first; idxR < last; idxR++)
  6664. {
  6665. void * right = rows[idxR];
  6666. if ((idxL != idxR) && right)
  6667. {
  6668. if (helper.matches(left, right))
  6669. {
  6670. if (keepLeft)
  6671. {
  6672. rows[idxR] = NULL;
  6673. ReleaseRoxieRow(right);
  6674. }
  6675. else
  6676. {
  6677. rows[idxL] = NULL;
  6678. ReleaseRoxieRow(left);
  6679. break;
  6680. }
  6681. }
  6682. }
  6683. }
  6684. }
  6685. }
  6686. }
  6687. bool calcNextDedupAll()
  6688. {
  6689. survivors.kill();
  6690. survivorIndex = 0;
  6691. ConstPointerArray group;
  6692. if (eof || !inputStream->nextGroup(group))
  6693. {
  6694. eof = true;
  6695. return false;
  6696. }
  6697. unsigned max = group.ordinality();
  6698. if (primaryCompare)
  6699. {
  6700. //hard, if not impossible, to hit this code once optimisations in place
  6701. MemoryAttr indexbuff(max*sizeof(void *));
  6702. void ** temp = (void **)indexbuff.bufferBase();
  6703. void * *rows = const_cast<void * *>(group.getArray());
  6704. msortvecstableinplace(rows, max, *primaryCompare, temp);
  6705. unsigned first = 0;
  6706. for (unsigned idx = 1; idx < max; idx++)
  6707. {
  6708. if (primaryCompare->docompare(rows[first], rows[idx]) != 0)
  6709. {
  6710. dedupRange(first, idx, rows);
  6711. first = idx;
  6712. }
  6713. }
  6714. dedupRange(first, max, rows);
  6715. for(unsigned idx2=0; idx2<max; ++idx2)
  6716. {
  6717. void * cur = rows[idx2];
  6718. if(cur)
  6719. survivors.append(cur);
  6720. }
  6721. }
  6722. else
  6723. {
  6724. dedupRange(0, max, group);
  6725. for(unsigned idx=0; idx<max; ++idx)
  6726. {
  6727. const void * cur = group.item(idx);
  6728. if(cur)
  6729. survivors.append(cur);
  6730. }
  6731. }
  6732. return true;
  6733. }
  6734. virtual const void *nextRow()
  6735. {
  6736. ActivityTimer t(totalCycles, timeActivities);
  6737. if (first)
  6738. {
  6739. calcNextDedupAll();
  6740. first = false;
  6741. }
  6742. while (survivors.isItem(survivorIndex))
  6743. {
  6744. const void *ret = survivors.item(survivorIndex++);
  6745. if (ret)
  6746. {
  6747. processed++;
  6748. return ret;
  6749. }
  6750. }
  6751. calcNextDedupAll();
  6752. return NULL;
  6753. }
  6754. };
  6755. class CRoxieServerDedupActivityFactory : public CRoxieServerActivityFactory
  6756. {
  6757. bool compareAll;
  6758. bool keepLeft;
  6759. bool keepBest;
  6760. public:
  6761. CRoxieServerDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  6762. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  6763. {
  6764. Owned<IHThorDedupArg> helper = (IHThorDedupArg *) helperFactory();
  6765. compareAll = helper->compareAll();
  6766. keepLeft = helper->keepLeft();
  6767. keepBest = helper->keepBest();
  6768. }
  6769. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  6770. {
  6771. if (compareAll)
  6772. return new CRoxieServerDedupAllActivity(_ctx, this, _probeManager, keepLeft);
  6773. else if (keepLeft && !keepBest)
  6774. return new CRoxieServerDedupKeepLeftActivity(_ctx, this, _probeManager);
  6775. else
  6776. return new CRoxieServerDedupKeepRightActivity(_ctx, this, _probeManager);
  6777. }
  6778. };
  6779. IRoxieServerActivityFactory *createRoxieServerDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  6780. {
  6781. return new CRoxieServerDedupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  6782. }
  6783. //=================================================================================
  6784. class CRoxieServerHashDedupActivity : public CRoxieServerActivity
  6785. {
  6786. bool eof;
  6787. IHThorHashDedupArg &helper;
  6788. class HashDedupElement
  6789. {
  6790. public:
  6791. HashDedupElement(unsigned _hash, const void *_keyRow)
  6792. : hash(_hash), keyRow(_keyRow)
  6793. {
  6794. }
  6795. ~HashDedupElement()
  6796. {
  6797. ReleaseRoxieRow(keyRow);
  6798. }
  6799. inline unsigned queryHash() const
  6800. {
  6801. return hash;
  6802. }
  6803. inline const void *queryRow() const
  6804. {
  6805. return keyRow;
  6806. }
  6807. inline const void *getRowClear()
  6808. {
  6809. const void * row = keyRow;
  6810. keyRow = nullptr;
  6811. return row;
  6812. }
  6813. private:
  6814. unsigned hash;
  6815. const void *keyRow;
  6816. };
  6817. static CClassMeta<HashDedupElement> hashDedupElementMeta;
  6818. class HashDedupTable : public SuperHashTable
  6819. {
  6820. public:
  6821. HashDedupTable(IHThorHashDedupArg & _helper, CRoxieServerHashDedupActivity & _activity)
  6822. : helper(_helper),
  6823. activity(_activity),
  6824. keySize(helper.queryKeySize())
  6825. {
  6826. bestCompare=helper.queryCompareBest();
  6827. }
  6828. virtual ~HashDedupTable()
  6829. {
  6830. //elementRowAllocator is a unique allocator, so all rows can be freed in a single call
  6831. elementRowAllocator->releaseAllRows();
  6832. tablecount = 0;
  6833. }
  6834. virtual unsigned getHashFromElement(const void *et) const
  6835. {
  6836. const HashDedupElement *element = reinterpret_cast<const HashDedupElement *>(et);
  6837. return element->queryHash();
  6838. }
  6839. virtual unsigned getHashFromFindParam(const void *fp) const { throwUnexpected(); }
  6840. virtual const void * getFindParam(const void *et) const { throwUnexpected(); }
  6841. virtual bool matchesElement(const void *et, const void *searchET) const { throwUnexpected(); }
  6842. virtual bool matchesFindParam(const void *et, const void *key, unsigned fphash) const
  6843. {
  6844. const HashDedupElement *element = reinterpret_cast<const HashDedupElement *>(et);
  6845. if (fphash != element->queryHash())
  6846. return false;
  6847. return (helper.queryKeyCompare()->docompare(element->queryRow(), key) == 0);
  6848. }
  6849. virtual void onAdd(void *et) {}
  6850. virtual void onRemove(void *et)
  6851. {
  6852. ReleaseRoxieRow(et);
  6853. }
  6854. void onCreate(IRoxieSlaveContext *ctx)
  6855. {
  6856. keyRowAllocator.setown(activity.createRowAllocator(keySize.queryOriginal()));
  6857. elementRowAllocator.setown(activity.createRowAllocatorEx(&hashDedupElementMeta, roxiemem::RHFunique|roxiemem::RHFscanning|roxiemem::RHFdelayrelease));
  6858. }
  6859. void reset()
  6860. {
  6861. kill();
  6862. }
  6863. bool insert(const void * row)
  6864. {
  6865. unsigned hash = helper.queryHash()->hash(row);
  6866. RtlDynamicRowBuilder keyRowBuilder(keyRowAllocator, true);
  6867. size32_t thisKeySize = helper.recordToKey(keyRowBuilder, row);
  6868. OwnedConstRoxieRow keyRow = keyRowBuilder.finalizeRowClear(thisKeySize);
  6869. if (find(hash, keyRow.get()))
  6870. return false;
  6871. addNew(createElement(hash, keyRow.getClear()), hash);
  6872. return true;
  6873. }
  6874. bool insertBest(const void * nextrow)
  6875. {
  6876. unsigned hash = helper.queryHash()->hash(nextrow);
  6877. const void *et = find(hash, nextrow);
  6878. if (et)
  6879. {
  6880. const HashDedupElement *element = reinterpret_cast<const HashDedupElement *>(et);
  6881. const void * row = element->queryRow();
  6882. if (bestCompare->docompare(row,nextrow) <= 0)
  6883. return false;
  6884. removeExact( const_cast<void *>(et));
  6885. // drop-through to add new row
  6886. }
  6887. addNew(createElement(hash, nextrow), hash);
  6888. return true;
  6889. }
  6890. void gatherStats(CRuntimeStatisticCollection & merged) const
  6891. {
  6892. if (keyRowAllocator)
  6893. keyRowAllocator->gatherStats(merged);
  6894. }
  6895. private:
  6896. inline void *createElement(unsigned hash, const void *row)
  6897. {
  6898. return elementRowAllocator->finalizeRow(sizeof(HashDedupElement), new (elementRowAllocator->createRow()) HashDedupElement(hash, row), sizeof(HashDedupElement));
  6899. }
  6900. IHThorHashDedupArg & helper;
  6901. CachedOutputMetaData keySize;
  6902. Owned<IEngineRowAllocator> keyRowAllocator;
  6903. Owned<IEngineRowAllocator> elementRowAllocator;
  6904. CRoxieServerHashDedupActivity & activity;
  6905. ICompare * bestCompare;
  6906. } table;
  6907. public:
  6908. CRoxieServerHashDedupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6909. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorHashDedupArg &)basehelper), table(helper, *this), hashTableFilled(false), hashDedupTableIter(table)
  6910. {
  6911. eof = false;
  6912. keepBest = helper.keepBest();
  6913. }
  6914. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6915. {
  6916. eof = false;
  6917. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6918. }
  6919. virtual void onCreate(IHThorArg *_colocalParent)
  6920. {
  6921. CRoxieServerActivity::onCreate(colocalParent);
  6922. table.onCreate(ctx);
  6923. }
  6924. virtual void reset()
  6925. {
  6926. table.reset();
  6927. eof = false;
  6928. CRoxieServerActivity::reset();
  6929. hashTableFilled = false;
  6930. }
  6931. virtual const void *nextRow()
  6932. {
  6933. ActivityTimer t(totalCycles, timeActivities);
  6934. if (keepBest)
  6935. {
  6936. if (eof)
  6937. return NULL;
  6938. // Populate hash table with best rows
  6939. if (!hashTableFilled)
  6940. {
  6941. const void * next = inputStream->nextRow();
  6942. while(next)
  6943. {
  6944. if (!table.insertBest(next))
  6945. ReleaseRoxieRow(next);
  6946. next = inputStream->nextRow();
  6947. }
  6948. if (table.count() == 0)
  6949. eof = true;
  6950. hashTableFilled = true;
  6951. hashDedupTableIter.first();
  6952. }
  6953. // Iterate throw hash table returning rows
  6954. if (hashDedupTableIter.isValid())
  6955. {
  6956. HashDedupElement &el = hashDedupTableIter.query();
  6957. const void * row = el.getRowClear();
  6958. hashDedupTableIter.next();
  6959. return row;
  6960. }
  6961. table.reset();
  6962. hashTableFilled = false;
  6963. return NULL;
  6964. }
  6965. else
  6966. {
  6967. while(!eof)
  6968. {
  6969. const void * next = inputStream->nextRow();
  6970. if(!next)
  6971. {
  6972. if (table.count() == 0)
  6973. eof = true;
  6974. table.reset();
  6975. return NULL;
  6976. }
  6977. if(table.insert(next))
  6978. return next;
  6979. else
  6980. ReleaseRoxieRow(next);
  6981. }
  6982. return NULL;
  6983. }
  6984. }
  6985. private:
  6986. bool keepBest;
  6987. bool hashTableFilled;
  6988. SuperHashIteratorOf<HashDedupElement> hashDedupTableIter;
  6989. };
  6990. CClassMeta<CRoxieServerHashDedupActivity::HashDedupElement> CRoxieServerHashDedupActivity::hashDedupElementMeta;
  6991. class CRoxieServerHashDedupActivityFactory : public CRoxieServerActivityFactory
  6992. {
  6993. public:
  6994. CRoxieServerHashDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  6995. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  6996. {
  6997. }
  6998. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  6999. {
  7000. return new CRoxieServerHashDedupActivity(_ctx, this, _probeManager);
  7001. }
  7002. };
  7003. IRoxieServerActivityFactory *createRoxieServerHashDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7004. {
  7005. return new CRoxieServerHashDedupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  7006. }
  7007. //=================================================================================
  7008. class CRoxieServerRollupActivity : public CRoxieServerActivity
  7009. {
  7010. IHThorRollupArg &helper;
  7011. OwnedConstRoxieRow left;
  7012. OwnedConstRoxieRow prev;
  7013. OwnedConstRoxieRow right;
  7014. bool readFirstRow;
  7015. public:
  7016. CRoxieServerRollupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  7017. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorRollupArg &)basehelper)
  7018. {
  7019. readFirstRow = false;
  7020. }
  7021. ~CRoxieServerRollupActivity()
  7022. {
  7023. }
  7024. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7025. {
  7026. readFirstRow = false;
  7027. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7028. }
  7029. virtual void reset()
  7030. {
  7031. left.clear();
  7032. prev.clear();
  7033. right.clear();
  7034. CRoxieServerActivity::reset();
  7035. }
  7036. virtual bool needsAllocator() const { return true; }
  7037. virtual const void * nextRow()
  7038. {
  7039. ActivityTimer t(totalCycles, timeActivities);
  7040. if (!readFirstRow)
  7041. {
  7042. left.setown(inputStream->nextRow());
  7043. prev.set(left);
  7044. readFirstRow = true;
  7045. }
  7046. for (;;)
  7047. {
  7048. right.setown(inputStream->nextRow());
  7049. if(!prev || !right || !helper.matches(prev,right))
  7050. {
  7051. const void * ret = left.getClear();
  7052. if(ret)
  7053. processed++;
  7054. left.setown(right.getClear());
  7055. prev.set(left);
  7056. return ret;
  7057. }
  7058. try
  7059. {
  7060. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  7061. unsigned outSize = helper.transform(rowBuilder, left, right);
  7062. if (outSize)
  7063. left.setown(rowBuilder.finalizeRowClear(outSize));
  7064. if (helper.getFlags() & RFrolledismatchleft)
  7065. prev.set(left);
  7066. else
  7067. prev.set(right);
  7068. }
  7069. catch(IException * E)
  7070. {
  7071. throw makeWrappedException(E);
  7072. }
  7073. }
  7074. }
  7075. };
  7076. class CRoxieServerRollupActivityFactory : public CRoxieServerActivityFactory
  7077. {
  7078. public:
  7079. CRoxieServerRollupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7080. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  7081. {
  7082. }
  7083. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  7084. {
  7085. return new CRoxieServerRollupActivity(_ctx, this, _probeManager);
  7086. }
  7087. };
  7088. IRoxieServerActivityFactory *createRoxieServerRollupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7089. {
  7090. return new CRoxieServerRollupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  7091. }
  7092. //=================================================================================
  7093. class CRoxieServerNormalizeActivity : public CRoxieServerActivity
  7094. {
  7095. IHThorNormalizeArg &helper;
  7096. unsigned numThisRow;
  7097. unsigned curRow;
  7098. const void *buffer;
  7099. unsigned numProcessedLastGroup;
  7100. public:
  7101. CRoxieServerNormalizeActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  7102. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorNormalizeArg &)basehelper)
  7103. {
  7104. buffer = NULL;
  7105. numThisRow = 0;
  7106. curRow = 0;
  7107. numProcessedLastGroup = 0;
  7108. }
  7109. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7110. {
  7111. numThisRow = 0;
  7112. curRow = 0;
  7113. numProcessedLastGroup = 0;
  7114. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7115. }
  7116. virtual void reset()
  7117. {
  7118. ReleaseClearRoxieRow(buffer);
  7119. CRoxieServerActivity::reset();
  7120. }
  7121. virtual bool needsAllocator() const { return true; }
  7122. virtual const void * nextRow()
  7123. {
  7124. ActivityTimer t(totalCycles, timeActivities);
  7125. for (;;)
  7126. {
  7127. while (curRow == numThisRow)
  7128. {
  7129. if (buffer)
  7130. ReleaseClearRoxieRow(buffer);
  7131. buffer = inputStream->nextRow();
  7132. if (!buffer && (processed == numProcessedLastGroup))
  7133. buffer = inputStream->nextRow();
  7134. if (!buffer)
  7135. {
  7136. numProcessedLastGroup = processed;
  7137. return NULL;
  7138. }
  7139. curRow = 0;
  7140. numThisRow = helper.numExpandedRows(buffer);
  7141. }
  7142. try
  7143. {
  7144. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  7145. unsigned actualSize = helper.transform(rowBuilder, buffer, ++curRow);
  7146. if (actualSize != 0)
  7147. {
  7148. processed++;
  7149. return rowBuilder.finalizeRowClear(actualSize);
  7150. }
  7151. }
  7152. catch (IException *E)
  7153. {
  7154. throw makeWrappedException(E);
  7155. }
  7156. }
  7157. }
  7158. };
  7159. class CRoxieServerNormalizeActivityFactory : public CRoxieServerActivityFactory
  7160. {
  7161. public:
  7162. CRoxieServerNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7163. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  7164. {
  7165. }
  7166. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  7167. {
  7168. return new CRoxieServerNormalizeActivity(_ctx, this, _probeManager);
  7169. }
  7170. };
  7171. IRoxieServerActivityFactory *createRoxieServerNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7172. {
  7173. return new CRoxieServerNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  7174. }
  7175. //=================================================================================
  7176. class CRoxieServerNormalizeChildActivity : public CRoxieServerActivity
  7177. {
  7178. IHThorNormalizeChildArg &helper;
  7179. unsigned numThisRow;
  7180. unsigned curRow;
  7181. const void *buffer;
  7182. unsigned numProcessedLastGroup;
  7183. INormalizeChildIterator * cursor;
  7184. const void * curChildRow;
  7185. bool advanceInput()
  7186. {
  7187. for (;;)
  7188. {
  7189. ReleaseClearRoxieRow(buffer);
  7190. buffer = inputStream->nextRow();
  7191. if (!buffer && (processed == numProcessedLastGroup))
  7192. buffer = inputStream->nextRow();
  7193. if (!buffer)
  7194. {
  7195. numProcessedLastGroup = processed;
  7196. return false;
  7197. }
  7198. curChildRow = cursor->first(buffer);
  7199. if (curChildRow)
  7200. {
  7201. curRow = 0;
  7202. return true;
  7203. }
  7204. }
  7205. }
  7206. public:
  7207. CRoxieServerNormalizeChildActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  7208. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorNormalizeChildArg &)basehelper)
  7209. {
  7210. buffer = NULL;
  7211. cursor = NULL;
  7212. numThisRow = 0;
  7213. curRow = 0;
  7214. numProcessedLastGroup = 0;
  7215. curChildRow = NULL;
  7216. }
  7217. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7218. {
  7219. numThisRow = 0;
  7220. curRow = 0;
  7221. numProcessedLastGroup = 0;
  7222. curChildRow = NULL;
  7223. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7224. cursor = helper.queryIterator();
  7225. }
  7226. virtual void stop()
  7227. {
  7228. CRoxieServerActivity::stop();
  7229. }
  7230. virtual void reset()
  7231. {
  7232. cursor = NULL;
  7233. ReleaseClearRoxieRow(buffer);
  7234. CRoxieServerActivity::reset();
  7235. }
  7236. virtual bool needsAllocator() const { return true; }
  7237. const void *nextRow()
  7238. {
  7239. ActivityTimer t(totalCycles, timeActivities);
  7240. for (;;)
  7241. {
  7242. if (!buffer)
  7243. {
  7244. if (!advanceInput())
  7245. return NULL;
  7246. }
  7247. try
  7248. {
  7249. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  7250. size32_t outSize = helper.transform(rowBuilder, buffer, curChildRow, ++curRow);
  7251. curChildRow = cursor->next();
  7252. if (!curChildRow)
  7253. ReleaseClearRoxieRow(buffer);
  7254. if (outSize != 0)
  7255. {
  7256. processed++;
  7257. return rowBuilder.finalizeRowClear(outSize);
  7258. }
  7259. }
  7260. catch (IException *E)
  7261. {
  7262. throw makeWrappedException(E);
  7263. }
  7264. }
  7265. }
  7266. };
  7267. class CRoxieServerNormalizeChildActivityFactory : public CRoxieServerActivityFactory
  7268. {
  7269. public:
  7270. CRoxieServerNormalizeChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7271. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  7272. {
  7273. }
  7274. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  7275. {
  7276. return new CRoxieServerNormalizeChildActivity(_ctx, this, _probeManager);
  7277. }
  7278. };
  7279. IRoxieServerActivityFactory *createRoxieServerNormalizeChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7280. {
  7281. return new CRoxieServerNormalizeChildActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  7282. }
  7283. //=================================================================================
  7284. class CRoxieServerNormalizeLinkedChildActivity : public CRoxieServerActivity
  7285. {
  7286. IHThorNormalizeLinkedChildArg &helper;
  7287. OwnedConstRoxieRow curParent;
  7288. OwnedConstRoxieRow curChild;
  7289. unsigned numProcessedLastGroup;
  7290. bool advanceInput()
  7291. {
  7292. for (;;)
  7293. {
  7294. curParent.setown(inputStream->nextRow());
  7295. if (!curParent && (processed == numProcessedLastGroup))
  7296. curParent.setown(inputStream->nextRow());
  7297. if (!curParent)
  7298. {
  7299. numProcessedLastGroup = processed;
  7300. return false;
  7301. }
  7302. curChild.set(helper.first(curParent));
  7303. if (curChild)
  7304. return true;
  7305. }
  7306. }
  7307. public:
  7308. CRoxieServerNormalizeLinkedChildActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  7309. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorNormalizeLinkedChildArg &)basehelper)
  7310. {
  7311. numProcessedLastGroup = 0;
  7312. }
  7313. ~CRoxieServerNormalizeLinkedChildActivity()
  7314. {
  7315. }
  7316. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7317. {
  7318. numProcessedLastGroup = 0;
  7319. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7320. }
  7321. virtual void reset()
  7322. {
  7323. curParent.clear();
  7324. curChild.clear();
  7325. CRoxieServerActivity::reset();
  7326. }
  7327. const void *nextRow()
  7328. {
  7329. ActivityTimer t(totalCycles, timeActivities);
  7330. for (;;)
  7331. {
  7332. if (!curParent)
  7333. {
  7334. if (!advanceInput())
  7335. return NULL;
  7336. }
  7337. try
  7338. {
  7339. const void *ret = curChild.getClear();
  7340. curChild.set(helper.next());
  7341. if (!curChild)
  7342. curParent.clear();
  7343. if (ret)
  7344. {
  7345. processed++;
  7346. return ret;
  7347. }
  7348. }
  7349. catch (IException *E)
  7350. {
  7351. throw makeWrappedException(E);
  7352. }
  7353. }
  7354. }
  7355. };
  7356. class CRoxieServerNormalizeLinkedChildActivityFactory : public CRoxieServerActivityFactory
  7357. {
  7358. public:
  7359. CRoxieServerNormalizeLinkedChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7360. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  7361. {
  7362. }
  7363. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  7364. {
  7365. return new CRoxieServerNormalizeLinkedChildActivity(_ctx, this, _probeManager);
  7366. }
  7367. };
  7368. IRoxieServerActivityFactory *createRoxieServerNormalizeLinkedChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7369. {
  7370. return new CRoxieServerNormalizeLinkedChildActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  7371. }
  7372. //=================================================================================
  7373. class CRoxieServerSortActivity : public CRoxieServerActivity
  7374. {
  7375. protected:
  7376. IHThorSortArg &helper;
  7377. ICompare *compare;
  7378. Owned<ISortAlgorithm> sorter;
  7379. bool readInput;
  7380. RoxieSortAlgorithm sortAlgorithm;
  7381. unsigned sortFlags;
  7382. public:
  7383. CRoxieServerSortActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, RoxieSortAlgorithm _sortAlgorithm, unsigned _sortFlags)
  7384. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorSortArg &)basehelper), sortAlgorithm(_sortAlgorithm), sortFlags(_sortFlags)
  7385. {
  7386. compare = helper.queryCompare();
  7387. readInput = false;
  7388. }
  7389. virtual void onCreate(IHThorArg *_colocalParent)
  7390. {
  7391. CRoxieServerActivity::onCreate(_colocalParent);
  7392. if (sortAlgorithm==unknownSortAlgorithm)
  7393. sorter.clear();
  7394. else
  7395. sorter.setown(createSortAlgorithm(sortAlgorithm, compare, ctx->queryRowManager(), meta, ctx->queryCodeContext(), tempDirectory, activityId));
  7396. }
  7397. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7398. {
  7399. assertex(!readInput);
  7400. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7401. }
  7402. virtual void reset()
  7403. {
  7404. if (sorter)
  7405. sorter->reset();
  7406. readInput = false;
  7407. CRoxieServerActivity::reset();
  7408. }
  7409. static RoxieSortAlgorithm useAlgorithm(const char *algorithmName, unsigned sortFlags)
  7410. {
  7411. RoxieSortAlgorithm sortAlgorithm = unknownSortAlgorithm;
  7412. if (!algorithmName)
  7413. algorithmName = "";
  7414. if (stricmp(algorithmName, "quicksort")==0)
  7415. {
  7416. switch (sortFlags & (TAFstable|TAFspill))
  7417. {
  7418. case 0: sortAlgorithm = quickSortAlgorithm; break;
  7419. case TAFstable: sortAlgorithm = stableQuickSortAlgorithm; break;
  7420. case TAFspill: sortAlgorithm = spillingQuickSortAlgorithm; break;
  7421. case TAFstable|TAFspill: sortAlgorithm = stableSpillingQuickSortAlgorithm; break;
  7422. }
  7423. }
  7424. else if (stricmp(algorithmName, "parquicksort")==0)
  7425. {
  7426. switch (sortFlags & TAFstable)
  7427. {
  7428. case 0: sortAlgorithm = parallelQuickSortAlgorithm; break;
  7429. case TAFstable: sortAlgorithm = parallelStableQuickSortAlgorithm; break;
  7430. default: throwUnexpected();
  7431. }
  7432. }
  7433. else if (stricmp(algorithmName, "heapsort")==0)
  7434. sortAlgorithm = heapSortAlgorithm; // NOTE - we do allow UNSTABLE('heapsort') in order to facilitate runtime selection. Also explicit selection of heapsort overrides request to spill
  7435. else if (stricmp(algorithmName, "mergesort")==0)
  7436. sortAlgorithm = (sortFlags & TAFspill) ? spillingMergeSortAlgorithm : mergeSortAlgorithm;
  7437. else if (stricmp(algorithmName, "parmergesort")==0)
  7438. sortAlgorithm = (sortFlags & TAFspill) ? spillingParallelMergeSortAlgorithm : parallelMergeSortAlgorithm;
  7439. else if (stricmp(algorithmName, "tbbqsort")==0)
  7440. sortAlgorithm = tbbQuickSortAlgorithm;
  7441. else if (stricmp(algorithmName, "tbbstableqsort")==0)
  7442. sortAlgorithm = tbbStableQuickSortAlgorithm;
  7443. else
  7444. {
  7445. if (*algorithmName)
  7446. WARNLOG(ROXIE_UNKNOWN_ALGORITHM, "Ignoring unsupported sort order algorithm '%s', using default", algorithmName);
  7447. if (sortFlags & TAFspill)
  7448. sortAlgorithm = ((sortFlags & TAFunstable) != 0) ? spillingQuickSortAlgorithm : stableSpillingQuickSortAlgorithm;
  7449. else if (sortFlags & TAFunstable)
  7450. sortAlgorithm = quickSortAlgorithm;
  7451. else
  7452. sortAlgorithm = heapSortAlgorithm;
  7453. }
  7454. return sortAlgorithm;
  7455. }
  7456. virtual const void * nextRow()
  7457. {
  7458. ActivityTimer t(totalCycles, timeActivities);
  7459. if (!readInput)
  7460. {
  7461. if (sortAlgorithm == unknownSortAlgorithm)
  7462. {
  7463. sorter.clear();
  7464. OwnedRoxieString algorithmName(helper.getAlgorithm());
  7465. sortAlgorithm = useAlgorithm(algorithmName, sortFlags);
  7466. sorter.setown(createSortAlgorithm(sortAlgorithm, compare, ctx->queryRowManager(), meta, ctx->queryCodeContext(), tempDirectory, activityId));
  7467. }
  7468. sorter->prepare(inputStream);
  7469. noteStatistic(StTimeSortElapsed, cycle_to_nanosec(sorter->getElapsedCycles(true)));
  7470. readInput = true;
  7471. }
  7472. const void *ret = sorter->next();
  7473. if (ret)
  7474. processed++;
  7475. else
  7476. {
  7477. sorter->reset();
  7478. readInput = false; // ready for next group
  7479. }
  7480. return ret;
  7481. }
  7482. };
  7483. class CRoxieServerSortActivityFactory : public CRoxieServerActivityFactory
  7484. {
  7485. RoxieSortAlgorithm sortAlgorithm;
  7486. unsigned sortFlags;
  7487. public:
  7488. CRoxieServerSortActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7489. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  7490. {
  7491. Owned<IHThorSortArg> sortHelper = (IHThorSortArg *) helperFactory();
  7492. const char *algorithmName = NULL;
  7493. sortFlags = sortHelper->getAlgorithmFlags();
  7494. if (sortFlags & TAFconstant)
  7495. algorithmName = sortHelper->getAlgorithm();
  7496. bool forceSpill = _queryFactory.queryOptions().allSortsMaySpill || _graphNode.getPropBool("hint[@name='spill']/@value", false);
  7497. if (forceSpill)
  7498. sortFlags |= TAFspill;
  7499. if (!(sortFlags & TAFunstable))
  7500. sortFlags |= TAFstable; // Assume stable unless specifically requested otherwise
  7501. if (sortFlags & TAFconstant)
  7502. sortAlgorithm = CRoxieServerSortActivity::useAlgorithm(algorithmName, sortFlags);
  7503. else
  7504. sortAlgorithm = unknownSortAlgorithm;
  7505. }
  7506. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  7507. {
  7508. return new CRoxieServerSortActivity(_ctx, this, _probeManager, sortAlgorithm, sortFlags);
  7509. }
  7510. virtual const StatisticsMapping &queryStatsMapping() const
  7511. {
  7512. return sortStatistics;
  7513. }
  7514. };
  7515. IRoxieServerActivityFactory *createRoxieServerSortActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7516. {
  7517. return new CRoxieServerSortActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  7518. }
  7519. //=====================================================================================================
  7520. static int compareUint64(const void * _left, const void * _right)
  7521. {
  7522. const unsigned __int64 left = *static_cast<const unsigned __int64 *>(_left);
  7523. const unsigned __int64 right = *static_cast<const unsigned __int64 *>(_right);
  7524. if (left < right)
  7525. return -1;
  7526. if (left > right)
  7527. return -1;
  7528. return 0;
  7529. }
  7530. class CRoxieServerQuantileActivity : public CRoxieServerActivity
  7531. {
  7532. protected:
  7533. Owned<ISortAlgorithm> sorter;
  7534. IHThorQuantileArg &helper;
  7535. ConstPointerArray sorted;
  7536. ICompare *compare;
  7537. unsigned flags;
  7538. double skew;
  7539. unsigned __int64 numDivisions;
  7540. bool rangeIsAll;
  7541. size32_t rangeSize;
  7542. rtlDataAttr rangeValues;
  7543. bool calculated;
  7544. bool processedAny;
  7545. bool anyThisGroup;
  7546. bool eof;
  7547. unsigned curQuantile;
  7548. unsigned curIndex;
  7549. unsigned curIndexExtra;
  7550. unsigned skipSize;
  7551. unsigned skipExtra;
  7552. unsigned prevIndex;
  7553. public:
  7554. CRoxieServerQuantileActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _flags)
  7555. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorQuantileArg &)basehelper), flags(_flags)
  7556. {
  7557. compare = helper.queryCompare();
  7558. skew = 0.0;
  7559. numDivisions = 0;
  7560. calculated = false;
  7561. processedAny = false;
  7562. anyThisGroup = false;
  7563. eof = false;
  7564. rangeIsAll = true;
  7565. rangeSize = 0;
  7566. curQuantile = 0;
  7567. prevIndex = 0;
  7568. curIndex = 0;
  7569. curIndexExtra = 0;
  7570. skipSize = 0;
  7571. skipExtra = 0;
  7572. if (flags & TQFunstable)
  7573. sorter.setown(createQuickSortAlgorithm(compare));
  7574. else
  7575. sorter.setown(createMergeSortAlgorithm(compare));
  7576. }
  7577. virtual void reset()
  7578. {
  7579. sorter->reset();
  7580. calculated = false;
  7581. processedAny = false;
  7582. anyThisGroup = false;
  7583. ReleaseRoxieRows(sorted);
  7584. CRoxieServerActivity::reset();
  7585. }
  7586. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7587. {
  7588. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7589. skew = helper.getSkew();
  7590. numDivisions = helper.getNumDivisions();
  7591. //Check for -ve integer values and treat as out of range
  7592. if ((__int64)numDivisions < 1)
  7593. numDivisions = 1;
  7594. if (flags & TQFhasrange)
  7595. helper.getRange(rangeIsAll, rangeSize, rangeValues.refdata());
  7596. else
  7597. {
  7598. rangeIsAll = true;
  7599. rangeSize = 0;
  7600. }
  7601. if (rangeSize)
  7602. {
  7603. //Sort the range items into order to allow quick comparison
  7604. qsort(rangeValues.getdata(), rangeSize / sizeof(unsigned __int64), sizeof(unsigned __int64), compareUint64);
  7605. }
  7606. calculated = false;
  7607. processedAny = false;
  7608. anyThisGroup = false;
  7609. eof = false;
  7610. curQuantile = 0;
  7611. prevIndex = 0;
  7612. curIndex = 0;
  7613. curIndexExtra = 0;
  7614. }
  7615. virtual bool needsAllocator() const { return true; }
  7616. virtual const void * nextRow()
  7617. {
  7618. ActivityTimer t(totalCycles, timeActivities);
  7619. if (eof)
  7620. return NULL;
  7621. const void * ret = NULL;
  7622. for(;;)
  7623. {
  7624. if (!calculated)
  7625. {
  7626. if (flags & TQFlocalsorted)
  7627. {
  7628. for (;;)
  7629. {
  7630. const void * next = inputStream->nextRow();
  7631. if (!next)
  7632. break;
  7633. sorted.append(next);
  7634. }
  7635. }
  7636. else
  7637. {
  7638. sorter->prepare(inputStream);
  7639. sorter->getSortedGroup(sorted);
  7640. }
  7641. if (sorted.ordinality() == 0)
  7642. {
  7643. if (processedAny)
  7644. {
  7645. eof = true;
  7646. return NULL;
  7647. }
  7648. //Unusual case 0 rows - add a default row instead
  7649. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  7650. size32_t thisSize = helper.createDefault(rowBuilder);
  7651. sorted.append(rowBuilder.finalizeRowClear(thisSize));
  7652. }
  7653. calculated = true;
  7654. processedAny = true;
  7655. anyThisGroup = false;
  7656. curQuantile = 0;
  7657. curIndex = 0;
  7658. curIndexExtra = (unsigned)((numDivisions-1) / 2); // to ensure correctly rounded up
  7659. prevIndex = curIndex-1; // Ensure it doesn't match
  7660. skipSize = (unsigned)(sorted.ordinality() / numDivisions);
  7661. skipExtra = (unsigned)(sorted.ordinality() % numDivisions);
  7662. }
  7663. if (isQuantileIncluded(curQuantile))
  7664. {
  7665. if (!(flags & TQFdedup) || (prevIndex != curIndex))
  7666. {
  7667. const void * lhs = sorted.item(curIndex);
  7668. if (flags & TQFneedtransform)
  7669. {
  7670. unsigned outSize;
  7671. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  7672. try
  7673. {
  7674. outSize = helper.transform(rowBuilder, lhs, curQuantile);
  7675. }
  7676. catch (IException *E)
  7677. {
  7678. throw makeWrappedException(E);
  7679. }
  7680. if (outSize)
  7681. ret = rowBuilder.finalizeRowClear(outSize);
  7682. }
  7683. else
  7684. {
  7685. LinkRoxieRow(lhs);
  7686. ret = lhs;
  7687. }
  7688. prevIndex = curIndex; // even if output was skipped?
  7689. }
  7690. }
  7691. curIndex += skipSize;
  7692. curIndexExtra += skipExtra;
  7693. if (curIndexExtra >= numDivisions)
  7694. {
  7695. curIndex++;
  7696. curIndexExtra -= numDivisions;
  7697. }
  7698. //Ensure the current index always stays valid.
  7699. if (curIndex >= sorted.ordinality())
  7700. curIndex = sorted.ordinality()-1;
  7701. curQuantile++;
  7702. if (curQuantile > numDivisions)
  7703. {
  7704. ReleaseRoxieRows(sorted);
  7705. sorter->reset();
  7706. calculated = false; // ready for next group
  7707. }
  7708. if (ret)
  7709. {
  7710. anyThisGroup = true;
  7711. processed++;
  7712. return ret;
  7713. }
  7714. if (curQuantile > numDivisions)
  7715. {
  7716. if (anyThisGroup)
  7717. return NULL;
  7718. }
  7719. }
  7720. }
  7721. bool isQuantileIncluded(unsigned quantile) const
  7722. {
  7723. if (quantile == 0)
  7724. return (flags & TQFfirst) != 0;
  7725. if (quantile == numDivisions)
  7726. return (flags & TQFlast) != 0;
  7727. if (rangeIsAll)
  7728. return true;
  7729. //Compare against the list of ranges provided
  7730. //MORE: Since the list is sorted should only need to compare the next (and allow for dups)
  7731. unsigned rangeNum = rangeSize / sizeof(unsigned __int64);
  7732. const unsigned __int64 * ranges = static_cast<const unsigned __int64 *>(rangeValues.getdata());
  7733. for (unsigned i = 0; i < rangeNum; i++)
  7734. {
  7735. if (ranges[i] == quantile)
  7736. return true;
  7737. }
  7738. return false;
  7739. }
  7740. };
  7741. class CRoxieServerQuantileActivityFactory : public CRoxieServerActivityFactory
  7742. {
  7743. unsigned flags;
  7744. public:
  7745. CRoxieServerQuantileActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7746. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  7747. {
  7748. Owned<IHThorQuantileArg> quantileHelper = (IHThorQuantileArg *) helperFactory();
  7749. flags = quantileHelper->getFlags();
  7750. }
  7751. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  7752. {
  7753. return new CRoxieServerQuantileActivity(_ctx, this, _probeManager, flags);
  7754. }
  7755. };
  7756. IRoxieServerActivityFactory *createRoxieServerQuantileActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7757. {
  7758. return new CRoxieServerQuantileActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  7759. }
  7760. //=====================================================================================================
  7761. class CRoxieServerSortedActivity : public CRoxieServerActivity
  7762. {
  7763. IHThorSortedArg &helper;
  7764. ICompare * compare;
  7765. const void *prev;
  7766. IRangeCompare * stepCompare;
  7767. public:
  7768. CRoxieServerSortedActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  7769. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorSortedArg &)basehelper)
  7770. {
  7771. prev = NULL;
  7772. compare = helper.queryCompare();
  7773. stepCompare = NULL;
  7774. }
  7775. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7776. {
  7777. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7778. IInputSteppingMeta * stepMeta = input->querySteppingMeta();
  7779. if (stepMeta)
  7780. stepCompare = stepMeta->queryCompare();
  7781. prev = NULL;
  7782. }
  7783. virtual void reset()
  7784. {
  7785. ReleaseClearRoxieRow(prev);
  7786. CRoxieServerActivity::reset();
  7787. }
  7788. virtual const void * nextRow()
  7789. {
  7790. ActivityTimer t(totalCycles, timeActivities);
  7791. const void *ret = inputStream->nextRow();
  7792. if (ret && prev && compare->docompare(prev, ret) > 0)
  7793. {
  7794. // MORE - better to give mismatching rows that indexes?
  7795. throw MakeStringException(ROXIE_NOT_SORTED, "SORTED(%u) detected incorrectly sorted rows (row %d, %d))", activityId, processed, processed+1);
  7796. }
  7797. ReleaseRoxieRow(prev);
  7798. prev = ret;
  7799. if (ret)
  7800. {
  7801. LinkRoxieRow(prev);
  7802. processed++;
  7803. }
  7804. return ret;
  7805. }
  7806. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  7807. {
  7808. ActivityTimer t(totalCycles, timeActivities);
  7809. const void *ret = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  7810. if (ret && prev && compare->docompare(prev, ret) > 0)
  7811. {
  7812. // MORE - better to give mismatching rows that indexes?
  7813. throw MakeStringException(ROXIE_NOT_SORTED, "SORTED(%u) detected incorrectly sorted rows (row %d, %d))", activityId, processed, processed+1);
  7814. }
  7815. ReleaseRoxieRow(prev);
  7816. prev = ret;
  7817. if (ret)
  7818. {
  7819. LinkRoxieRow(prev);
  7820. processed++;
  7821. }
  7822. return ret;
  7823. }
  7824. IInputSteppingMeta * querySteppingMeta()
  7825. {
  7826. return input->querySteppingMeta();
  7827. }
  7828. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  7829. {
  7830. return input->gatherConjunctions(collector);
  7831. }
  7832. virtual void resetEOF()
  7833. {
  7834. inputStream->resetEOF();
  7835. }
  7836. };
  7837. class CRoxieServerSortedActivityFactory : public CRoxieServerActivityFactory
  7838. {
  7839. public:
  7840. CRoxieServerSortedActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7841. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  7842. {
  7843. }
  7844. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  7845. {
  7846. return new CRoxieServerSortedActivity(_ctx, this, _probeManager);
  7847. }
  7848. };
  7849. IRoxieServerActivityFactory *createRoxieServerSortedActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7850. {
  7851. return new CRoxieServerSortedActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  7852. }
  7853. //=====================================================================================================
  7854. class CRoxieServerThroughSpillActivity : public CRoxieServerActivity
  7855. {
  7856. /*
  7857. BE VERY CAREFUL - this code is tricky.
  7858. Note that starts and stops (and resets) can occur in strange orders
  7859. The FIRST start OR stop must initialize the activity but only the first START should call the upstream start.
  7860. The last stop should call the upstream stop.
  7861. The first reset should call the upstream reset.
  7862. 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
  7863. not yet had start or stop called - for this to happen init() is called on all outputs on the first start or stop.
  7864. Some outputs may be completely pruned away when used in a GRAPH - these outputs should not receive any start/stop/reset and should be
  7865. ignored in the minIndex calculation
  7866. */
  7867. public:
  7868. IHThorArg &helper;
  7869. unsigned activeOutputs;
  7870. unsigned numOutputs;
  7871. unsigned numOriginalOutputs;
  7872. QueueOf<const void, true> buffer;
  7873. CriticalSection crit;
  7874. CriticalSection crit2;
  7875. unsigned tailIdx;
  7876. unsigned headIdx;
  7877. Owned<IException> error;
  7878. class OutputAdaptor : implements IEngineRowStream, implements IFinalRoxieInput, public CInterface
  7879. {
  7880. bool eof, eofpending, stopped;
  7881. public:
  7882. CRoxieServerThroughSpillActivity *parent;
  7883. unsigned idx;
  7884. unsigned oid;
  7885. unsigned processed;
  7886. cycle_t totalCycles; // We track this per output so that the pullers get a meaningful value to use when calculating their localtime
  7887. public:
  7888. IMPLEMENT_IINTERFACE;
  7889. OutputAdaptor()
  7890. {
  7891. parent = NULL;
  7892. oid = 0;
  7893. idx = 0;
  7894. processed = 0;
  7895. totalCycles = 0;
  7896. eofpending = false;
  7897. eof = false;
  7898. stopped = false;
  7899. }
  7900. ~OutputAdaptor()
  7901. {
  7902. if (traceStartStop)
  7903. DBGLOG("%p ~OutputAdaptor %d", this, oid);
  7904. if (processed && parent && parent->factory)
  7905. {
  7906. parent->factory->noteProcessed(oid, processed);
  7907. if (parent->ctx)
  7908. parent->ctx->noteProcessed(parent->querySubgraphId(), parent->activityId, oid, processed, 0);
  7909. }
  7910. }
  7911. void init()
  7912. {
  7913. if (traceStartStop)
  7914. DBGLOG("%p init Input adaptor %d", this, oid);
  7915. idx = 0;
  7916. processed = 0;
  7917. eofpending = false;
  7918. eof = false;
  7919. stopped = false;
  7920. }
  7921. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { assertex(idx==0); return this; }
  7922. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { assertex(idx==0); return nullptr; }
  7923. virtual IRoxieServerActivity *queryActivity()
  7924. {
  7925. return parent;
  7926. }
  7927. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  7928. {
  7929. return parent->queryIndexReadActivity();
  7930. }
  7931. virtual unsigned __int64 queryTotalCycles() const
  7932. {
  7933. return totalCycles;
  7934. }
  7935. virtual const void * nextRow()
  7936. {
  7937. SimpleActivityTimer t(totalCycles, parent->timeActivities);
  7938. if (eof)
  7939. return NULL;
  7940. const void *ret = parent->readBuffered(idx, oid);
  7941. #ifdef TRACE_SPLIT
  7942. parent->CTXLOG("Adaptor %d got back %p for record %d", oid, ret, idx);
  7943. #endif
  7944. if (ret)
  7945. {
  7946. processed++;
  7947. eofpending = false;
  7948. }
  7949. else if (eofpending)
  7950. eof = true;
  7951. else
  7952. eofpending = true;
  7953. return ret;
  7954. }
  7955. virtual IOutputMetaData * queryOutputMeta() const
  7956. {
  7957. return parent->queryOutputMeta();
  7958. }
  7959. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7960. {
  7961. // NOTE: it is tempting to move the init() of all output adaptors here. However that is not a good idea,
  7962. // since adaptors that have not yet started or stopped (but are going to) still need to have been init()'ed
  7963. // for minIndex to give the correct answers
  7964. // therefore, we call init() on all adaptors on receipt of the first start() or stop()
  7965. if (traceStartStop)
  7966. parent->CTXLOG("%p start Input adaptor %d stopped = %d", this, oid, stopped);
  7967. parent->start(oid, parentExtractSize, parentExtract, paused);
  7968. }
  7969. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  7970. {
  7971. parent->connectInputStreams(consumerOrdered);
  7972. streams.append(this);
  7973. return NULL;
  7974. }
  7975. virtual void stop()
  7976. {
  7977. if (traceStartStop)
  7978. parent->CTXLOG("%p stop Input adaptor %d stopped = %d", this, oid, stopped);
  7979. if (!stopped)
  7980. {
  7981. parent->stop(oid, idx); // NOTE - may call init()
  7982. stopped = true; // parent code relies on stop being called exactly once per adaptor, so make sure it is!
  7983. }
  7984. };
  7985. virtual void reset()
  7986. {
  7987. if (traceStartStop)
  7988. parent->CTXLOG("%p reset Input adaptor %d stopped = %d", this, oid, stopped);
  7989. parent->reset(oid);
  7990. idx = 0; // value should not be relevant really but this is the safest...
  7991. stopped = false;
  7992. };
  7993. virtual void resetEOF()
  7994. {
  7995. parent->resetEOF();
  7996. }
  7997. virtual void checkAbort()
  7998. {
  7999. parent->checkAbort();
  8000. }
  8001. } *adaptors;
  8002. bool *used;
  8003. unsigned nextFreeOutput()
  8004. {
  8005. unsigned i = numOutputs;
  8006. while (i)
  8007. {
  8008. i--;
  8009. if (!used[i])
  8010. return i;
  8011. }
  8012. throwUnexpected();
  8013. }
  8014. unsigned minIndex(unsigned exceptOid)
  8015. {
  8016. // MORE - yukky code (and slow). Could keep them heapsorted by idx or something
  8017. // this is trying to determine whether any of the adaptors will in the future read a given record
  8018. unsigned minIdx = (unsigned) -1;
  8019. for (unsigned i = 0; i < numOutputs; i++)
  8020. {
  8021. if (i != exceptOid && used[i] && adaptors[i].idx < minIdx)
  8022. minIdx = adaptors[i].idx;
  8023. }
  8024. return minIdx;
  8025. }
  8026. inline bool isLastTailReader(unsigned exceptOid)
  8027. {
  8028. for (unsigned i = 0; i < numOutputs; i++)
  8029. {
  8030. if (i != exceptOid && adaptors[i].idx == tailIdx && used[i])
  8031. return false;
  8032. }
  8033. return true;
  8034. }
  8035. void initOutputs()
  8036. {
  8037. activeOutputs = numOutputs;
  8038. for (unsigned i = 0; i < numOriginalOutputs; i++)
  8039. if (used[i])
  8040. adaptors[i].init();
  8041. state = STATEstarting;
  8042. }
  8043. public:
  8044. CRoxieServerThroughSpillActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  8045. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper(basehelper), numOutputs(_numOutputs)
  8046. {
  8047. numOriginalOutputs = numOutputs;
  8048. adaptors = new OutputAdaptor[numOutputs];
  8049. used = new bool[numOutputs];
  8050. for (unsigned i = 0; i < numOutputs; i++)
  8051. {
  8052. adaptors[i].parent = this;
  8053. adaptors[i].oid = i;
  8054. used[i] = false;
  8055. }
  8056. tailIdx = 0;
  8057. headIdx = 0;
  8058. activeOutputs = numOutputs;
  8059. }
  8060. ~CRoxieServerThroughSpillActivity()
  8061. {
  8062. delete [] adaptors;
  8063. delete [] used;
  8064. }
  8065. const void *readBuffered(unsigned &idx, unsigned oid)
  8066. {
  8067. //False positives are fine, false negatives are not.. so headIdx must only be updated when a row will be available.
  8068. const unsigned curIdx = idx;
  8069. if (curIdx == headIdx) // test once without getting the crit2 sec
  8070. {
  8071. CriticalBlock b2(crit2); // but only one puller gets to read the head
  8072. if (curIdx == headIdx) // test again now that we have it
  8073. {
  8074. 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
  8075. if (error)
  8076. throw error.getLink();
  8077. try
  8078. {
  8079. const void *row = inputStream->nextRow();
  8080. if (activeOutputs==1)
  8081. {
  8082. #ifdef TRACE_SPLIT
  8083. CTXLOG("spill %d optimised return of %p", activityId, row);
  8084. #endif
  8085. headIdx++;
  8086. idx++;
  8087. return row; // optimization for the case where only one output still active.
  8088. }
  8089. CriticalBlock b(crit);
  8090. headIdx++;
  8091. idx++;
  8092. if (activeOutputs==1)
  8093. return row; // optimization for the case where only one output still active.
  8094. buffer.enqueue(row);
  8095. if (row) LinkRoxieRow(row);
  8096. return row;
  8097. }
  8098. catch (IException *E)
  8099. {
  8100. #ifdef TRACE_SPLIT
  8101. CTXLOG("spill %d caught exception", activityId);
  8102. #endif
  8103. error.set(E);
  8104. throw;
  8105. }
  8106. catch (...)
  8107. {
  8108. IException *E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught in CRoxieServerThroughSpillActivity::readBuffered");
  8109. error.set(E);
  8110. throw E;
  8111. }
  8112. }
  8113. }
  8114. CriticalBlock b(crit);
  8115. 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
  8116. unsigned lidx = curIdx - tailIdx;
  8117. idx++;
  8118. if (!lidx)
  8119. {
  8120. // The numOutputs <= 2 check optimizes slightly the common case of 2-way splitters.
  8121. // 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
  8122. if (numOutputs <= 2 || isLastTailReader(oid)) // NOTE - this includes the case where minIndex returns (unsigned) -1, meaning no other active pullers
  8123. {
  8124. tailIdx++;
  8125. const void *ret = buffer.dequeue(); // no need to link - last puller
  8126. #ifdef TRACE_SPLIT
  8127. CTXLOG("last puller return of %p", ret);
  8128. #endif
  8129. return ret;
  8130. }
  8131. }
  8132. const void *ret = buffer.item(lidx);
  8133. if (ret) LinkRoxieRow(ret);
  8134. #ifdef TRACE_SPLIT
  8135. CTXLOG("standard return of %p", ret);
  8136. #endif
  8137. return ret;
  8138. }
  8139. virtual void start(unsigned oid, unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8140. {
  8141. CriticalBlock b(crit);
  8142. if (error)
  8143. throw error.getLink();
  8144. if (factory)
  8145. factory->noteStarted(oid);
  8146. if (traceStartStop)
  8147. CTXLOG("SPLIT %p: start %d child %d activeOutputs %d numOutputs %d numOriginalOutputs %d state %s", this, activityId, oid, activeOutputs, numOutputs, numOriginalOutputs, queryStateText(state));
  8148. if (state != STATEstarted)
  8149. {
  8150. if (state != STATEstarting)
  8151. initOutputs();
  8152. tailIdx = 0;
  8153. headIdx = 0;
  8154. error.clear();
  8155. try
  8156. {
  8157. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8158. }
  8159. catch (IException *E)
  8160. {
  8161. #ifdef TRACE_SPLIT
  8162. CTXLOG("spill %d caught exception in start", activityId);
  8163. #endif
  8164. error.set(E);
  8165. throw;
  8166. }
  8167. catch (...)
  8168. {
  8169. IException *E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught in CRoxieServerThroughSpillActivity::start");
  8170. error.set(E);
  8171. throw E;
  8172. }
  8173. }
  8174. }
  8175. void stop(unsigned oid, unsigned & idx)
  8176. {
  8177. // Note that OutputAdaptor code ensures that stop is not called more than once per adaptor
  8178. CriticalBlock b(crit);
  8179. #ifdef TRACE_STARTSTOP
  8180. if (traceStartStop)
  8181. {
  8182. CTXLOG("SPLIT %p: stop %d child %d activeOutputs %d numOutputs %d numOriginalOutputs %d state %s", this, activityId, oid, activeOutputs, numOutputs, numOriginalOutputs, queryStateText(state));
  8183. if (watchActivityId && watchActivityId==activityId)
  8184. {
  8185. CTXLOG("WATCH: stop %d", activityId);
  8186. }
  8187. }
  8188. #endif
  8189. if (state != STATEstarting && state != STATEstarted)
  8190. initOutputs();
  8191. if (activeOutputs > 1)
  8192. {
  8193. if (tailIdx==idx)
  8194. {
  8195. // Discard all buffered rows that are there purely for this adaptor to read them
  8196. unsigned min = minIndex(oid);
  8197. if (min != (unsigned) -1)
  8198. // what does -1 signify?? No-one wants anything? In which case can't we kill all rows??
  8199. // Should never happen though if there are still some active.
  8200. // there may be a small window where adaptors are blocked on the semaphore...
  8201. {
  8202. #ifdef TRACE_SPLIT
  8203. CTXLOG("%p: Discarding buffered rows from %d to %d for oid %x (%d outputs active)", this, idx, min, oid, activeOutputs);
  8204. #endif
  8205. while (tailIdx < min)
  8206. {
  8207. ReleaseRoxieRow(buffer.dequeue());
  8208. tailIdx++;
  8209. }
  8210. }
  8211. }
  8212. activeOutputs--;
  8213. idx = (unsigned) -1; // causes minIndex not to save rows for me...
  8214. return;
  8215. }
  8216. #ifdef TRACE_SPLIT
  8217. CTXLOG("%p: All outputs done", this);
  8218. #endif
  8219. activeOutputs = numOutputs;
  8220. CRoxieServerActivity::stop();
  8221. };
  8222. void reset(unsigned oid)
  8223. {
  8224. if (traceStartStop)
  8225. CTXLOG("SPLIT %p: reset %d child %d activeOutputs %d numOutputs %d numOriginalOutputs %d state %s", this, activityId, oid, activeOutputs, numOutputs, numOriginalOutputs, queryStateText(state));
  8226. activeOutputs = numOutputs;
  8227. while (buffer.ordinality())
  8228. ReleaseRoxieRow(buffer.dequeue());
  8229. error.clear();
  8230. if (state != STATEreset) // make sure input is only reset once
  8231. CRoxieServerActivity::reset();
  8232. };
  8233. void connectInputStreams(bool consumerOrdered)
  8234. {
  8235. if (!inputStream)
  8236. CRoxieServerActivity::connectInputStreams(consumerOrdered);
  8237. }
  8238. virtual const void *nextRow()
  8239. {
  8240. throwUnexpected(); // Internal logic error - we are not anybody's input
  8241. }
  8242. virtual IOutputMetaData * queryOutputMeta() const
  8243. {
  8244. // if (outputMeta)
  8245. // return outputMeta;
  8246. // else
  8247. return input->queryOutputMeta(); // not always known (e.g. disk write - though Gavin _could_ fill it in)
  8248. }
  8249. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  8250. {
  8251. if (idx==(unsigned)-1)
  8252. idx = nextFreeOutput(); // MORE - what is this used for?
  8253. assertex(idx < numOriginalOutputs);
  8254. assertex(!used[idx]);
  8255. used[idx] = true;
  8256. return &adaptors[idx];
  8257. }
  8258. virtual void resetOutputsUsed()
  8259. {
  8260. numOutputs = 1;
  8261. activeOutputs = 1;
  8262. // MORE RKC->GH should we be clearing the used array here? anywhere?
  8263. }
  8264. virtual void noteOutputUsed()
  8265. {
  8266. assertex(numOutputs < numOriginalOutputs);
  8267. numOutputs++;
  8268. activeOutputs = numOutputs;
  8269. }
  8270. virtual bool isPassThrough()
  8271. {
  8272. return numOutputs==1;
  8273. }
  8274. };
  8275. class CRoxieServerThroughSpillActivityFactory : public CRoxieServerMultiOutputFactory
  8276. {
  8277. public:
  8278. CRoxieServerThroughSpillActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8279. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  8280. {
  8281. Owned<IHThorSpillArg> helper = (IHThorSpillArg *) helperFactory();
  8282. setNumOutputs(helper->getTempUsageCount() + 1);
  8283. }
  8284. CRoxieServerThroughSpillActivityFactory(IQueryFactory &_queryFactory, HelperFactory *_helperFactory, unsigned _numOutputs, IPropertyTree &_graphNode)
  8285. : CRoxieServerMultiOutputFactory(0, 0, _queryFactory, _helperFactory, TAKsplit, _graphNode)
  8286. {
  8287. setNumOutputs(_numOutputs);
  8288. }
  8289. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  8290. {
  8291. return new CRoxieServerThroughSpillActivity(_ctx, this, _probeManager, numOutputs);
  8292. }
  8293. };
  8294. IRoxieServerActivityFactory *createRoxieServerThroughSpillActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8295. {
  8296. return new CRoxieServerThroughSpillActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  8297. }
  8298. IRoxieServerActivityFactory *createRoxieServerThroughSpillActivityFactory(IQueryFactory &_queryFactory, HelperFactory *_factory, unsigned _numOutputs, IPropertyTree &_graphNode)
  8299. {
  8300. return new CRoxieServerThroughSpillActivityFactory(_queryFactory, _factory, _numOutputs, _graphNode);
  8301. }
  8302. //----------------------------------------------------------------------------------------------
  8303. class CRoxieServerSplitActivityFactory : public CRoxieServerMultiOutputFactory
  8304. {
  8305. public:
  8306. CRoxieServerSplitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8307. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  8308. {
  8309. Owned<IHThorSplitArg> helper = (IHThorSplitArg *) helperFactory();
  8310. setNumOutputs(helper->numBranches());
  8311. }
  8312. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  8313. {
  8314. return new CRoxieServerThroughSpillActivity(_ctx, this, _probeManager, numOutputs);
  8315. }
  8316. };
  8317. IRoxieServerActivityFactory *createRoxieServerSplitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8318. {
  8319. return new CRoxieServerSplitActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  8320. }
  8321. //=====================================================================================================
  8322. #define PIPE_BUFSIZE 0x8000
  8323. static IException *createPipeFailureException(const char *cmd, unsigned retcode, IPipeProcess *pipe)
  8324. {
  8325. StringBuffer msg;
  8326. if(pipe->hasError())
  8327. {
  8328. try
  8329. {
  8330. char error[512];
  8331. size32_t sz = pipe->readError(sizeof(error), error);
  8332. if(sz && sz!=(size32_t)-1)
  8333. msg.append(", stderr: '").append(sz, error).append("'");
  8334. }
  8335. catch (IException *e)
  8336. {
  8337. EXCLOG(e, "Error reading pipe stderr");
  8338. e->Release();
  8339. }
  8340. }
  8341. return MakeStringException(ROXIE_PIPE_ERROR, "Pipe process %s returned error %u%s", cmd, retcode, msg.str());
  8342. }
  8343. class CRoxieServerPipeReadActivity : public CRoxieServerActivity
  8344. {
  8345. IHThorPipeReadArg &helper;
  8346. Owned<IPipeProcess> pipe;
  8347. StringAttr pipeCommand;
  8348. Owned<IOutputRowDeserializer> rowDeserializer;
  8349. Owned<IReadRowStream> readTransformer;
  8350. bool groupSignalled;
  8351. public:
  8352. CRoxieServerPipeReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8353. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorPipeReadArg &)basehelper)
  8354. {
  8355. groupSignalled = true;
  8356. }
  8357. virtual bool needsAllocator() const { return true; }
  8358. virtual void onCreate(IHThorArg *_colocalParent)
  8359. {
  8360. CRoxieServerActivity::onCreate(_colocalParent);
  8361. rowDeserializer.setown(rowAllocator->createDiskDeserializer(ctx->queryCodeContext()));
  8362. }
  8363. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8364. {
  8365. groupSignalled = true; // i.e. don't start with a NULL row
  8366. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8367. if (!readTransformer)
  8368. {
  8369. OwnedRoxieString xmlIteratorPath(helper.getXmlIteratorPath());
  8370. readTransformer.setown(createReadRowStream(rowAllocator, rowDeserializer, helper.queryXmlTransformer(), helper.queryCsvTransformer(), xmlIteratorPath, helper.getPipeFlags()));
  8371. }
  8372. OwnedRoxieString pipeProgram(helper.getPipeProgram());
  8373. openPipe(pipeProgram);
  8374. }
  8375. virtual void stop()
  8376. {
  8377. CRoxieServerActivity::stop();
  8378. pipe.clear();
  8379. readTransformer->setStream(NULL);
  8380. }
  8381. virtual const void *nextRow()
  8382. {
  8383. ActivityTimer t(totalCycles, timeActivities);
  8384. while (!waitForPipe())
  8385. {
  8386. if (!pipe)
  8387. return NULL;
  8388. if (helper.getPipeFlags() & TPFgroupeachrow)
  8389. {
  8390. if (!groupSignalled)
  8391. {
  8392. groupSignalled = true;
  8393. return NULL;
  8394. }
  8395. }
  8396. }
  8397. const void *ret = readTransformer->next();
  8398. assertex(ret != NULL); // if ret can ever be NULL then we need to recode this logic
  8399. processed++;
  8400. groupSignalled = false;
  8401. return ret;
  8402. }
  8403. protected:
  8404. bool waitForPipe()
  8405. {
  8406. if (!pipe)
  8407. return false; // done
  8408. if (!readTransformer->eos())
  8409. return true;
  8410. verifyPipe();
  8411. return false;
  8412. }
  8413. void openPipe(char const * cmd)
  8414. {
  8415. pipeCommand.setown(cmd);
  8416. pipe.setown(createPipeProcess());
  8417. if(!pipe->run(NULL, cmd, ".", false, true, true, 0x10000))
  8418. throw MakeStringException(ROXIE_PIPE_ERROR, "Could not run pipe process %s", cmd);
  8419. Owned<ISimpleReadStream> pipeReader = pipe->getOutputStream();
  8420. readTransformer->setStream(pipeReader.get());
  8421. }
  8422. void verifyPipe()
  8423. {
  8424. if (pipe)
  8425. {
  8426. unsigned err = pipe->wait();
  8427. if(err && !(helper.getPipeFlags() & TPFnofail))
  8428. {
  8429. throw createPipeFailureException(pipeCommand.get(), err, pipe);
  8430. }
  8431. pipe.clear();
  8432. }
  8433. }
  8434. };
  8435. class CRoxieServerPipeThroughActivity : public CRoxieServerActivity, implements IRecordPullerCallback
  8436. {
  8437. IHThorPipeThroughArg &helper;
  8438. RecordPullerThread puller;
  8439. Owned<IPipeProcess> pipe;
  8440. StringAttr pipeCommand;
  8441. InterruptableSemaphore pipeVerified;
  8442. InterruptableSemaphore pipeOpened;
  8443. CachedOutputMetaData inputMeta;
  8444. Owned<IOutputRowSerializer> rowSerializer;
  8445. Owned<IOutputRowDeserializer> rowDeserializer;
  8446. Owned<IPipeWriteXformHelper> writeTransformer;
  8447. Owned<IReadRowStream> readTransformer;
  8448. bool firstRead;
  8449. bool recreate;
  8450. bool inputExhausted;
  8451. bool groupSignalled;
  8452. public:
  8453. CRoxieServerPipeThroughActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8454. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorPipeThroughArg &)basehelper), puller(false)
  8455. {
  8456. recreate = helper.recreateEachRow();
  8457. groupSignalled = true;
  8458. firstRead = false;
  8459. inputExhausted = false;
  8460. }
  8461. virtual bool needsAllocator() const { return true; }
  8462. virtual void onCreate(IHThorArg *_colocalParent)
  8463. {
  8464. CRoxieServerActivity::onCreate(_colocalParent);
  8465. rowSerializer.setown(inputMeta.createDiskSerializer(ctx->queryCodeContext(), activityId));
  8466. rowDeserializer.setown(rowAllocator->createDiskDeserializer(ctx->queryCodeContext()));
  8467. writeTransformer.setown(createPipeWriteXformHelper(helper.getPipeFlags(), helper.queryXmlOutput(), helper.queryCsvOutput(), rowSerializer));
  8468. }
  8469. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8470. {
  8471. firstRead = true;
  8472. inputExhausted = false;
  8473. groupSignalled = true; // i.e. don't start with a NULL row
  8474. pipeVerified.reinit();
  8475. pipeOpened.reinit();
  8476. writeTransformer->ready();
  8477. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8478. if (!readTransformer)
  8479. {
  8480. OwnedRoxieString xmlIterator(helper.getXmlIteratorPath());
  8481. readTransformer.setown(createReadRowStream(rowAllocator, rowDeserializer, helper.queryXmlTransformer(), helper.queryCsvTransformer(), xmlIterator, helper.getPipeFlags()));
  8482. }
  8483. if(!recreate)
  8484. {
  8485. OwnedRoxieString pipeProgram(helper.getPipeProgram());
  8486. openPipe(pipeProgram);
  8487. }
  8488. puller.start(parentExtractSize, parentExtract, paused, 0, false, ctx); // Pipe does not support preload presently - locks up
  8489. }
  8490. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  8491. {
  8492. if (idx)
  8493. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
  8494. puller.setInput(this, _sourceIdx, _in);
  8495. inputMeta.set(_in->queryOutputMeta());
  8496. }
  8497. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  8498. {
  8499. puller.connectInputStreams(ctx, consumerOrdered);
  8500. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
  8501. }
  8502. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  8503. {
  8504. if (idx==0)
  8505. return puller.queryInput();
  8506. else
  8507. return NULL;
  8508. }
  8509. virtual void stop()
  8510. {
  8511. pipeVerified.interrupt(NULL);
  8512. pipeOpened.interrupt(NULL);
  8513. puller.stop();
  8514. CRoxieServerActivity::stop();
  8515. pipe.clear();
  8516. if (readTransformer)
  8517. readTransformer->setStream(NULL);
  8518. }
  8519. virtual void reset()
  8520. {
  8521. puller.reset();
  8522. CRoxieServerActivity::reset();
  8523. }
  8524. virtual const void *nextRow()
  8525. {
  8526. ActivityTimer t(totalCycles, timeActivities);
  8527. while (!waitForPipe())
  8528. {
  8529. if (!pipe)
  8530. return NULL;
  8531. if (helper.getPipeFlags() & TPFgroupeachrow)
  8532. {
  8533. if (!groupSignalled)
  8534. {
  8535. groupSignalled = true;
  8536. return NULL;
  8537. }
  8538. }
  8539. }
  8540. const void *ret = readTransformer->next();
  8541. assertex(ret != NULL); // if ret can ever be NULL then we need to recode this logic
  8542. processed++;
  8543. groupSignalled = false;
  8544. return ret;
  8545. }
  8546. virtual void processRow(const void *row)
  8547. {
  8548. // called from puller thread
  8549. if(recreate)
  8550. openPipe(helper.getNameFromRow(row));
  8551. writeTransformer->writeTranslatedText(row, pipe);
  8552. ReleaseRoxieRow(row);
  8553. if(recreate)
  8554. {
  8555. closePipe();
  8556. pipeVerified.wait();
  8557. }
  8558. }
  8559. virtual void processDone()
  8560. {
  8561. // called from puller thread
  8562. if(recreate)
  8563. {
  8564. inputExhausted = true;
  8565. pipeOpened.signal();
  8566. }
  8567. else
  8568. {
  8569. closePipe();
  8570. pipeVerified.wait();
  8571. }
  8572. }
  8573. virtual void processEOG()
  8574. {
  8575. }
  8576. void processGroup(const ConstPointerArray &)
  8577. {
  8578. throwUnexpected();
  8579. }
  8580. virtual bool fireException(IException *e)
  8581. {
  8582. pipeOpened.interrupt(LINK(e));
  8583. pipeVerified.interrupt(e);
  8584. return true;
  8585. }
  8586. private:
  8587. bool waitForPipe()
  8588. {
  8589. if (firstRead)
  8590. {
  8591. pipeOpened.wait();
  8592. firstRead = false;
  8593. }
  8594. if (!pipe)
  8595. return false; // done
  8596. if (!readTransformer->eos())
  8597. return true;
  8598. verifyPipe();
  8599. if (recreate && !inputExhausted)
  8600. pipeOpened.wait();
  8601. return false;
  8602. }
  8603. void openPipe(char const * cmd)
  8604. {
  8605. pipeCommand.setown(cmd);
  8606. pipe.setown(createPipeProcess());
  8607. if(!pipe->run(NULL, cmd, ".", true, true, true, 0x10000))
  8608. throw MakeStringException(ROXIE_PIPE_ERROR, "Could not run pipe process %s", cmd);
  8609. writeTransformer->writeHeader(pipe);
  8610. Owned<ISimpleReadStream> pipeReader = pipe->getOutputStream();
  8611. readTransformer->setStream(pipeReader.get());
  8612. pipeOpened.signal();
  8613. }
  8614. void closePipe()
  8615. {
  8616. writeTransformer->writeFooter(pipe);
  8617. pipe->closeInput();
  8618. }
  8619. void verifyPipe()
  8620. {
  8621. if (pipe)
  8622. {
  8623. unsigned err = pipe->wait();
  8624. if(err && !(helper.getPipeFlags() & TPFnofail))
  8625. {
  8626. throw createPipeFailureException(pipeCommand.get(), err, pipe);
  8627. }
  8628. pipe.clear();
  8629. pipeVerified.signal();
  8630. }
  8631. }
  8632. };
  8633. class CRoxieServerPipeWriteActivity : public CRoxieServerInternalSinkActivity
  8634. {
  8635. IHThorPipeWriteArg &helper;
  8636. Owned<IPipeProcess> pipe;
  8637. StringAttr pipeCommand;
  8638. CachedOutputMetaData inputMeta;
  8639. Owned<IOutputRowSerializer> rowSerializer;
  8640. Owned<IPipeWriteXformHelper> writeTransformer;
  8641. bool firstRead;
  8642. bool recreate;
  8643. bool inputExhausted;
  8644. public:
  8645. CRoxieServerPipeWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  8646. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _numOutputs), helper((IHThorPipeWriteArg &)basehelper)
  8647. {
  8648. recreate = helper.recreateEachRow();
  8649. firstRead = false;
  8650. inputExhausted = false;
  8651. }
  8652. virtual bool needsAllocator() const { return true; }
  8653. virtual void onCreate(IHThorArg *_colocalParent)
  8654. {
  8655. CRoxieServerActivity::onCreate(_colocalParent);
  8656. inputMeta.set(input->queryOutputMeta());
  8657. rowSerializer.setown(inputMeta.createDiskSerializer(ctx->queryCodeContext(), activityId));
  8658. writeTransformer.setown(createPipeWriteXformHelper(helper.getPipeFlags(), helper.queryXmlOutput(), helper.queryCsvOutput(), rowSerializer));
  8659. }
  8660. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8661. {
  8662. firstRead = true;
  8663. inputExhausted = false;
  8664. writeTransformer->ready();
  8665. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8666. if(!recreate)
  8667. {
  8668. OwnedRoxieString pipeProgram(helper.getPipeProgram());
  8669. openPipe(pipeProgram);
  8670. }
  8671. }
  8672. virtual void stop()
  8673. {
  8674. if (!aborted && helper.getSequence() >= 0)
  8675. {
  8676. WorkunitUpdate wu = ctx->updateWorkUnit();
  8677. if (wu)
  8678. {
  8679. Owned<IWUResult> result = wu->updateResultBySequence(helper.getSequence());
  8680. if (result)
  8681. {
  8682. result->setResultTotalRowCount(processed);
  8683. result->setResultStatus(ResultStatusCalculated);
  8684. }
  8685. }
  8686. }
  8687. CRoxieServerActivity::stop();
  8688. pipe.clear();
  8689. }
  8690. virtual void onExecute()
  8691. {
  8692. for (;;)
  8693. {
  8694. const void *row = inputStream->ungroupedNextRow();
  8695. if (!row)
  8696. break;
  8697. processed++;
  8698. if(recreate)
  8699. openPipe(helper.getNameFromRow(row));
  8700. writeTransformer->writeTranslatedText(row, pipe);
  8701. ReleaseRoxieRow(row);
  8702. if(recreate)
  8703. closePipe();
  8704. }
  8705. closePipe();
  8706. }
  8707. private:
  8708. void openPipe(char const * cmd)
  8709. {
  8710. pipeCommand.setown(cmd);
  8711. pipe.setown(createPipeProcess());
  8712. if(!pipe->run(NULL, cmd, ".", true, false, true, 0x10000))
  8713. throw MakeStringException(ROXIE_PIPE_ERROR, "Could not run pipe process %s", cmd);
  8714. writeTransformer->writeHeader(pipe);
  8715. }
  8716. void closePipe()
  8717. {
  8718. writeTransformer->writeFooter(pipe);
  8719. pipe->closeInput();
  8720. unsigned err = pipe->wait();
  8721. if(err && !(helper.getPipeFlags() & TPFnofail))
  8722. {
  8723. throw createPipeFailureException(pipeCommand.get(), err, pipe);
  8724. }
  8725. pipe.clear();
  8726. }
  8727. };
  8728. class CRoxieServerPipeReadActivityFactory : public CRoxieServerActivityFactory
  8729. {
  8730. public:
  8731. CRoxieServerPipeReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8732. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  8733. {
  8734. }
  8735. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  8736. {
  8737. return new CRoxieServerPipeReadActivity(_ctx, this, _probeManager);
  8738. }
  8739. };
  8740. class CRoxieServerPipeThroughActivityFactory : public CRoxieServerActivityFactory
  8741. {
  8742. public:
  8743. CRoxieServerPipeThroughActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8744. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  8745. {
  8746. }
  8747. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  8748. {
  8749. return new CRoxieServerPipeThroughActivity(_ctx, this, _probeManager);
  8750. }
  8751. };
  8752. class CRoxieServerPipeWriteActivityFactory : public CRoxieServerInternalSinkFactory
  8753. {
  8754. public:
  8755. CRoxieServerPipeWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  8756. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot)
  8757. {
  8758. }
  8759. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  8760. {
  8761. return new CRoxieServerPipeWriteActivity(_ctx, this, _probeManager, usageCount);
  8762. }
  8763. };
  8764. IRoxieServerActivityFactory *createRoxieServerPipeReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8765. {
  8766. return new CRoxieServerPipeReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  8767. }
  8768. IRoxieServerActivityFactory *createRoxieServerPipeThroughActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8769. {
  8770. return new CRoxieServerPipeThroughActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  8771. }
  8772. IRoxieServerActivityFactory *createRoxieServerPipeWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  8773. {
  8774. return new CRoxieServerPipeWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot);
  8775. }
  8776. //=====================================================================================================
  8777. class CRoxieServerStreamedIteratorActivity : public CRoxieServerActivity
  8778. {
  8779. IHThorStreamedIteratorArg &helper;
  8780. Owned<IRowStream> rows;
  8781. public:
  8782. CRoxieServerStreamedIteratorActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8783. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorStreamedIteratorArg &)basehelper)
  8784. {
  8785. }
  8786. ~CRoxieServerStreamedIteratorActivity()
  8787. {
  8788. }
  8789. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8790. {
  8791. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8792. rows.setown(helper.createInput());
  8793. }
  8794. virtual void stop()
  8795. {
  8796. if (rows)
  8797. {
  8798. rows->stop();
  8799. rows.clear();
  8800. }
  8801. CRoxieServerActivity::stop();
  8802. }
  8803. virtual const void *nextRow()
  8804. {
  8805. ActivityTimer t(totalCycles, timeActivities);
  8806. assertex(rows != NULL);
  8807. const void * next = rows->nextRow();
  8808. if (next)
  8809. processed++;
  8810. return next;
  8811. }
  8812. };
  8813. class CRoxieServerStreamedIteratorActivityFactory : public CRoxieServerActivityFactory
  8814. {
  8815. public:
  8816. CRoxieServerStreamedIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8817. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  8818. {
  8819. }
  8820. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  8821. {
  8822. return new CRoxieServerStreamedIteratorActivity(_ctx, this, _probeManager);
  8823. }
  8824. };
  8825. IRoxieServerActivityFactory *createRoxieServerStreamedIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8826. {
  8827. return new CRoxieServerStreamedIteratorActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  8828. }
  8829. //=====================================================================================================
  8830. class CRoxieServerFilterActivity : public CRoxieServerLateStartActivity
  8831. {
  8832. IHThorFilterArg &helper;
  8833. bool anyThisGroup;
  8834. IRangeCompare * stepCompare;
  8835. public:
  8836. CRoxieServerFilterActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8837. : CRoxieServerLateStartActivity(_ctx, _factory, _probeManager), helper((IHThorFilterArg &)basehelper)
  8838. {
  8839. anyThisGroup = false;
  8840. stepCompare = NULL;
  8841. }
  8842. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8843. {
  8844. anyThisGroup = false;
  8845. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  8846. lateStart(parentExtractSize, parentExtract, helper.canMatchAny());
  8847. stepCompare = NULL;
  8848. if (!eof)
  8849. {
  8850. IInputSteppingMeta * stepMeta = input->querySteppingMeta();
  8851. if (stepMeta)
  8852. stepCompare = stepMeta->queryCompare();
  8853. }
  8854. }
  8855. virtual const void * nextRow()
  8856. {
  8857. ActivityTimer t(totalCycles, timeActivities);
  8858. if (eof)
  8859. return NULL;
  8860. for (;;)
  8861. {
  8862. OwnedConstRoxieRow ret(inputStream->nextRow());
  8863. if (!ret)
  8864. {
  8865. //stop returning two NULLs in a row.
  8866. if (anyThisGroup)
  8867. {
  8868. anyThisGroup = false;
  8869. return NULL;
  8870. }
  8871. ret.setown(inputStream->nextRow());
  8872. if (!ret)
  8873. {
  8874. eof = true;
  8875. return NULL; // eof...
  8876. }
  8877. }
  8878. if (helper.isValid(ret))
  8879. {
  8880. anyThisGroup = true;
  8881. processed++;
  8882. return ret.getClear();
  8883. }
  8884. }
  8885. }
  8886. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  8887. {
  8888. //Could assert that this isn't grouped
  8889. // MORE - will need rethinking once we rethink the nextRowGE interface for global smart-stepping.
  8890. ActivityTimer t(totalCycles, timeActivities);
  8891. if (eof)
  8892. return NULL;
  8893. for (;;)
  8894. {
  8895. OwnedConstRoxieRow ret(inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra));
  8896. if (!ret)
  8897. {
  8898. eof = true;
  8899. return NULL;
  8900. }
  8901. if (!wasCompleteMatch)
  8902. {
  8903. anyThisGroup = false; // RKC->GH - is this right??
  8904. return ret.getClear();
  8905. }
  8906. if (helper.isValid(ret))
  8907. {
  8908. anyThisGroup = true;
  8909. processed++;
  8910. return ret.getClear();
  8911. }
  8912. if (!stepExtra.returnMismatches())
  8913. {
  8914. ret.clear();
  8915. return nextRow();
  8916. }
  8917. //If asked to return mismatches we are only interested in mismatches that will force the stepped
  8918. //condition to advance
  8919. if (stepCompare->docompare(ret, seek, numFields) != 0)
  8920. {
  8921. wasCompleteMatch = false;
  8922. anyThisGroup = false; // WHY?
  8923. return ret.getClear();
  8924. }
  8925. }
  8926. }
  8927. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  8928. {
  8929. return input->gatherConjunctions(collector);
  8930. }
  8931. virtual void resetEOF()
  8932. {
  8933. eof = prefiltered;
  8934. anyThisGroup = false;
  8935. inputStream->resetEOF();
  8936. }
  8937. IInputSteppingMeta * querySteppingMeta()
  8938. {
  8939. return input->querySteppingMeta();
  8940. }
  8941. };
  8942. class CRoxieServerFilterActivityFactory : public CRoxieServerActivityFactory
  8943. {
  8944. public:
  8945. CRoxieServerFilterActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8946. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  8947. {
  8948. optStableInput = false;
  8949. }
  8950. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  8951. {
  8952. return new CRoxieServerFilterActivity(_ctx, this, _probeManager);
  8953. }
  8954. };
  8955. IRoxieServerActivityFactory *createRoxieServerFilterActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8956. {
  8957. return new CRoxieServerFilterActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  8958. }
  8959. //=====================================================================================================
  8960. class CRoxieServerFilterGroupActivity : public CRoxieServerLateStartActivity
  8961. {
  8962. IHThorFilterGroupArg &helper;
  8963. unsigned curIndex;
  8964. ConstPointerArray gathered;
  8965. IRangeCompare * stepCompare;
  8966. public:
  8967. CRoxieServerFilterGroupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8968. : CRoxieServerLateStartActivity(_ctx, _factory, _probeManager), helper((IHThorFilterGroupArg &)basehelper)
  8969. {
  8970. curIndex = 0;
  8971. stepCompare = NULL;
  8972. }
  8973. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8974. {
  8975. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  8976. lateStart(parentExtractSize, parentExtract, helper.canMatchAny());//sets eof
  8977. assertex(eof == !helper.canMatchAny());
  8978. curIndex = 0;
  8979. stepCompare = NULL;
  8980. if (!eof)
  8981. {
  8982. IInputSteppingMeta * inputStepping = input->querySteppingMeta();
  8983. if (inputStepping)
  8984. stepCompare = inputStepping->queryCompare();
  8985. }
  8986. }
  8987. virtual void reset()
  8988. {
  8989. releaseGathered();
  8990. CRoxieServerLateStartActivity::reset();
  8991. }
  8992. inline void releaseGathered()
  8993. {
  8994. roxiemem::ReleaseRoxieRowRange(gathered.getArray(), curIndex, gathered.ordinality());
  8995. gathered.kill();
  8996. curIndex = 0;
  8997. }
  8998. virtual const void * nextRow()
  8999. {
  9000. ActivityTimer t(totalCycles, timeActivities);
  9001. for (;;)
  9002. {
  9003. if (eof)
  9004. return NULL;
  9005. if (gathered.ordinality())
  9006. {
  9007. if (gathered.isItem(curIndex))
  9008. {
  9009. const void * ret = gathered.item(curIndex++);
  9010. processed++;
  9011. return ret;
  9012. }
  9013. curIndex = 0;
  9014. gathered.kill();
  9015. return NULL;
  9016. }
  9017. const void * ret = inputStream->nextRow();
  9018. while (ret)
  9019. {
  9020. gathered.append(ret);
  9021. ret = inputStream->nextRow();
  9022. }
  9023. unsigned num = gathered.ordinality();
  9024. if (num != 0)
  9025. {
  9026. if (!helper.isValid(num, (const void * *)gathered.getArray()))
  9027. ReleaseRoxieRows(gathered); // read next group
  9028. }
  9029. else
  9030. eof = true;
  9031. }
  9032. }
  9033. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  9034. {
  9035. ActivityTimer t(totalCycles, timeActivities);
  9036. if (eof)
  9037. return NULL;
  9038. if (gathered.ordinality())
  9039. {
  9040. while (gathered.isItem(curIndex))
  9041. {
  9042. const void * ret = gathered.item(curIndex++);
  9043. if (stepCompare->docompare(ret, seek, numFields) >= 0)
  9044. {
  9045. processed++;
  9046. return ret;
  9047. }
  9048. ReleaseRoxieRow(ret);
  9049. }
  9050. curIndex = 0;
  9051. gathered.kill();
  9052. //nextRowGE never returns an end of group marker.
  9053. }
  9054. //Not completely sure about this - it could lead the the start of a group being skipped,
  9055. //so the group filter could potentially work on a different group. If so, we'd need to check the
  9056. //next fields were a subset of the grouping fields - more an issue for the group activity.
  9057. //MORE: What do we do with wasCompleteMatch? something like the following????
  9058. #if 0
  9059. for (;;)
  9060. {
  9061. const void * ret;
  9062. if (stepExtra.returnMismatches())
  9063. {
  9064. bool matchedCompletely = true;
  9065. ret = input->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  9066. if (!wasCompleteMatch)
  9067. return ret;
  9068. }
  9069. else
  9070. ret = input->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  9071. #endif
  9072. const void * ret = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  9073. while (ret)
  9074. {
  9075. gathered.append(ret);
  9076. ret = inputStream->nextRow();
  9077. }
  9078. unsigned num = gathered.ordinality();
  9079. if (num != 0)
  9080. {
  9081. if (!helper.isValid(num, (const void * *)gathered.getArray()))
  9082. ReleaseRoxieRows(gathered); // read next group
  9083. }
  9084. else
  9085. eof = true;
  9086. return IEngineRowStream::ungroupedNextRow();
  9087. }
  9088. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  9089. {
  9090. return input->gatherConjunctions(collector);
  9091. }
  9092. virtual void resetEOF()
  9093. {
  9094. eof = false;
  9095. releaseGathered();
  9096. inputStream->resetEOF();
  9097. }
  9098. IInputSteppingMeta * querySteppingMeta()
  9099. {
  9100. return input->querySteppingMeta();
  9101. }
  9102. };
  9103. class CRoxieServerFilterGroupActivityFactory : public CRoxieServerActivityFactory
  9104. {
  9105. public:
  9106. CRoxieServerFilterGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9107. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  9108. {
  9109. }
  9110. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9111. {
  9112. return new CRoxieServerFilterGroupActivity(_ctx, this, _probeManager);
  9113. }
  9114. };
  9115. IRoxieServerActivityFactory *createRoxieServerFilterGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9116. {
  9117. return new CRoxieServerFilterGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9118. }
  9119. //=================================================================================
  9120. class CRoxieServerSideEffectActivity : public CRoxieServerActivity
  9121. {
  9122. IHThorSideEffectArg &helper;
  9123. CriticalSection ecrit;
  9124. Owned<IException> exception;
  9125. bool executed;
  9126. public:
  9127. CRoxieServerSideEffectActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9128. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorSideEffectArg &)basehelper)
  9129. {
  9130. executed = false;
  9131. }
  9132. virtual const void * nextRow()
  9133. {
  9134. ActivityTimer t(totalCycles, timeActivities);
  9135. CriticalBlock b(ecrit);
  9136. if (exception)
  9137. throw(exception.getLink());
  9138. if (!executed)
  9139. {
  9140. try
  9141. {
  9142. executed = true;
  9143. helper.action();
  9144. }
  9145. catch(IException *E)
  9146. {
  9147. exception.set(E);
  9148. throw;
  9149. }
  9150. }
  9151. return NULL;
  9152. }
  9153. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  9154. {
  9155. CriticalBlock b(ecrit);
  9156. if (exception)
  9157. throw(exception.getLink());
  9158. if (!executed)
  9159. {
  9160. try
  9161. {
  9162. ActivityTimer t(totalCycles, timeActivities);
  9163. executed = true;
  9164. start(parentExtractSize, parentExtract, false);
  9165. helper.action();
  9166. stop();
  9167. }
  9168. catch(IException *E)
  9169. {
  9170. ctx->notifyAbort(E);
  9171. abort();
  9172. exception.set(E);
  9173. throw;
  9174. }
  9175. }
  9176. }
  9177. virtual void reset()
  9178. {
  9179. executed = false;
  9180. exception.clear();
  9181. CRoxieServerActivity::reset();
  9182. }
  9183. };
  9184. class CRoxieServerSideEffectActivityFactory : public CRoxieServerActivityFactory
  9185. {
  9186. bool isRoot;
  9187. public:
  9188. CRoxieServerSideEffectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  9189. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  9190. {
  9191. }
  9192. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9193. {
  9194. return new CRoxieServerSideEffectActivity(_ctx, this, _probeManager);
  9195. }
  9196. virtual bool isSink() const
  9197. {
  9198. return isRoot && !meta.queryOriginal();
  9199. }
  9200. };
  9201. IRoxieServerActivityFactory *createRoxieServerSideEffectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  9202. {
  9203. return new CRoxieServerSideEffectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  9204. }
  9205. //=================================================================================
  9206. class CRoxieServerActionActivity : public CRoxieServerInternalSinkActivity
  9207. {
  9208. IHThorActionArg &helper;
  9209. public:
  9210. CRoxieServerActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  9211. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _numOutputs), helper((IHThorActionArg &)basehelper)
  9212. {
  9213. }
  9214. virtual void onExecute()
  9215. {
  9216. helper.action();
  9217. }
  9218. };
  9219. class CRoxieServerActionActivityFactory : public CRoxieServerInternalSinkFactory
  9220. {
  9221. public:
  9222. CRoxieServerActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  9223. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot)
  9224. {
  9225. }
  9226. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9227. {
  9228. return new CRoxieServerActionActivity(_ctx, this, _probeManager, usageCount);
  9229. }
  9230. };
  9231. IRoxieServerActivityFactory *createRoxieServerActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  9232. {
  9233. return new CRoxieServerActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot);
  9234. }
  9235. //=================================================================================
  9236. class CRoxieServerSampleActivity : public CRoxieServerActivity
  9237. {
  9238. IHThorSampleArg &helper;
  9239. unsigned numSamples;
  9240. unsigned numToSkip;
  9241. unsigned whichSample;
  9242. bool anyThisGroup;
  9243. bool eof;
  9244. public:
  9245. CRoxieServerSampleActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9246. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorSampleArg &)basehelper)
  9247. {
  9248. numSamples = 0;
  9249. numToSkip = 0;
  9250. whichSample = 0;
  9251. anyThisGroup = false;
  9252. eof = false;
  9253. }
  9254. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9255. {
  9256. anyThisGroup = false;
  9257. eof = false;
  9258. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9259. numSamples = helper.getProportion();
  9260. whichSample = helper.getSampleNumber();
  9261. numToSkip = (whichSample ? whichSample-1 : 0);
  9262. }
  9263. virtual const void * nextRow()
  9264. {
  9265. ActivityTimer t(totalCycles, timeActivities);
  9266. if (eof)
  9267. return NULL;
  9268. for (;;)
  9269. {
  9270. const void * ret = inputStream->nextRow();
  9271. if (!ret)
  9272. {
  9273. //this does work with groups - may or may not be useful...
  9274. //reset the sample for each group.... probably best.
  9275. numToSkip = (whichSample ? whichSample-1 : 0);
  9276. if (anyThisGroup)
  9277. {
  9278. anyThisGroup = false;
  9279. return NULL;
  9280. }
  9281. ret = inputStream->nextRow();
  9282. if (!ret)
  9283. {
  9284. eof = true;
  9285. return NULL; // eof...
  9286. }
  9287. }
  9288. if (numToSkip == 0)
  9289. {
  9290. anyThisGroup = true;
  9291. numToSkip = numSamples-1;
  9292. processed++;
  9293. return ret;
  9294. }
  9295. numToSkip--;
  9296. ReleaseRoxieRow(ret);
  9297. }
  9298. }
  9299. };
  9300. class CRoxieServerSampleActivityFactory : public CRoxieServerActivityFactory
  9301. {
  9302. public:
  9303. CRoxieServerSampleActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9304. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  9305. {
  9306. }
  9307. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9308. {
  9309. return new CRoxieServerSampleActivity(_ctx, this, _probeManager);
  9310. }
  9311. };
  9312. IRoxieServerActivityFactory *createRoxieServerSampleActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9313. {
  9314. return new CRoxieServerSampleActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9315. }
  9316. //=================================================================================
  9317. class CRoxieServerChooseSetsActivity : public CRoxieServerActivity
  9318. {
  9319. IHThorChooseSetsArg &helper;
  9320. unsigned numSets;
  9321. unsigned * setCounts;
  9322. bool done;
  9323. public:
  9324. CRoxieServerChooseSetsActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9325. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorChooseSetsArg &)basehelper)
  9326. {
  9327. setCounts = NULL;
  9328. numSets = 0;
  9329. done = false;
  9330. }
  9331. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9332. {
  9333. done = false;
  9334. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9335. numSets = helper.getNumSets();
  9336. setCounts = new unsigned[numSets];
  9337. memset(setCounts, 0, sizeof(unsigned)*numSets);
  9338. helper.setCounts(setCounts);
  9339. }
  9340. virtual void reset()
  9341. {
  9342. delete [] setCounts;
  9343. setCounts = NULL;
  9344. CRoxieServerActivity::reset();
  9345. }
  9346. virtual const void * nextRow()
  9347. {
  9348. ActivityTimer t(totalCycles, timeActivities);
  9349. if (done)
  9350. return NULL;
  9351. for (;;)
  9352. {
  9353. const void * ret = inputStream->ungroupedNextRow();
  9354. if (!ret)
  9355. {
  9356. done = true;
  9357. return NULL;
  9358. }
  9359. processed++;
  9360. switch (helper.getRecordAction(ret))
  9361. {
  9362. case 2:
  9363. done = true;
  9364. return ret;
  9365. case 1:
  9366. return ret;
  9367. }
  9368. ReleaseRoxieRow(ret);
  9369. }
  9370. }
  9371. };
  9372. class CRoxieServerChooseSetsActivityFactory : public CRoxieServerActivityFactory
  9373. {
  9374. public:
  9375. CRoxieServerChooseSetsActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9376. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  9377. {
  9378. }
  9379. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9380. {
  9381. return new CRoxieServerChooseSetsActivity(_ctx, this, _probeManager);
  9382. }
  9383. };
  9384. IRoxieServerActivityFactory *createRoxieServerChooseSetsActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9385. {
  9386. return new CRoxieServerChooseSetsActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9387. }
  9388. //=================================================================================
  9389. class CRoxieServerChooseSetsExActivity : public CRoxieServerActivity
  9390. {
  9391. protected:
  9392. IHThorChooseSetsExArg &helper;
  9393. unsigned numSets;
  9394. unsigned curIndex;
  9395. unsigned * setCounts;
  9396. count_t * limits;
  9397. bool done;
  9398. ConstPointerArray gathered;
  9399. virtual bool includeRow(const void * row) = 0;
  9400. virtual void calculateSelection() = 0;
  9401. public:
  9402. CRoxieServerChooseSetsExActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9403. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorChooseSetsExArg &)basehelper)
  9404. {
  9405. setCounts = NULL;
  9406. limits = NULL;
  9407. done = false;
  9408. curIndex = 0;
  9409. numSets = 0;
  9410. }
  9411. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9412. {
  9413. done = false;
  9414. curIndex = 0;
  9415. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9416. numSets = helper.getNumSets();
  9417. setCounts = new unsigned[numSets];
  9418. memset(setCounts, 0, sizeof(unsigned)*numSets);
  9419. limits = (count_t *)calloc(sizeof(count_t), numSets);
  9420. helper.getLimits(limits);
  9421. }
  9422. virtual void reset()
  9423. {
  9424. delete [] setCounts;
  9425. setCounts = NULL;
  9426. free(limits);
  9427. limits = NULL;
  9428. roxiemem::ReleaseRoxieRowRange(gathered.getArray(), curIndex, gathered.ordinality());
  9429. gathered.kill();
  9430. curIndex = 0;
  9431. CRoxieServerActivity::reset();
  9432. }
  9433. virtual const void * nextRow()
  9434. {
  9435. ActivityTimer t(totalCycles, timeActivities);
  9436. if (gathered.ordinality() == 0)
  9437. {
  9438. curIndex = 0;
  9439. if (!inputStream->nextGroup(gathered))
  9440. {
  9441. done = true;
  9442. return NULL;
  9443. }
  9444. ForEachItemIn(idx1, gathered)
  9445. {
  9446. unsigned category = helper.getCategory(gathered.item(idx1));
  9447. if (category)
  9448. setCounts[category-1]++;
  9449. }
  9450. calculateSelection();
  9451. }
  9452. while (gathered.isItem(curIndex))
  9453. {
  9454. const void * row = gathered.item(curIndex);
  9455. gathered.replace(NULL, curIndex);
  9456. curIndex++;
  9457. if (includeRow(row))
  9458. {
  9459. processed++;
  9460. return row;
  9461. }
  9462. ReleaseRoxieRow(row);
  9463. }
  9464. gathered.kill();
  9465. return NULL;
  9466. }
  9467. };
  9468. class CRoxieServerChooseSetsLastActivity : public CRoxieServerChooseSetsExActivity
  9469. {
  9470. unsigned * numToSkip;
  9471. public:
  9472. CRoxieServerChooseSetsLastActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager) : CRoxieServerChooseSetsExActivity(_ctx, _factory, _probeManager)
  9473. {
  9474. numToSkip = NULL;
  9475. }
  9476. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9477. {
  9478. CRoxieServerChooseSetsExActivity::start(parentExtractSize, parentExtract, paused);
  9479. numToSkip = (unsigned *)calloc(sizeof(unsigned), numSets);
  9480. }
  9481. virtual void reset()
  9482. {
  9483. free(numToSkip);
  9484. numToSkip = NULL;
  9485. CRoxieServerChooseSetsExActivity::reset();
  9486. }
  9487. protected:
  9488. virtual void calculateSelection()
  9489. {
  9490. for (unsigned idx=0; idx < numSets; idx++)
  9491. {
  9492. if (setCounts[idx] < limits[idx])
  9493. numToSkip[idx] = 0;
  9494. else
  9495. numToSkip[idx] = (unsigned)(setCounts[idx] - limits[idx]);
  9496. }
  9497. }
  9498. virtual bool includeRow(const void * row)
  9499. {
  9500. unsigned category = helper.getCategory(row);
  9501. if (category)
  9502. {
  9503. if (numToSkip[category-1] == 0)
  9504. return true;
  9505. numToSkip[category-1]--;
  9506. }
  9507. return false;
  9508. }
  9509. };
  9510. class CRoxieServerChooseSetsEnthActivity : public CRoxieServerChooseSetsExActivity
  9511. {
  9512. count_t * counter;
  9513. public:
  9514. CRoxieServerChooseSetsEnthActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager) : CRoxieServerChooseSetsExActivity(_ctx, _factory, _probeManager)
  9515. {
  9516. counter = NULL;
  9517. }
  9518. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9519. {
  9520. CRoxieServerChooseSetsExActivity::start(parentExtractSize, parentExtract, paused);
  9521. counter = (count_t *)calloc(sizeof(count_t), numSets);
  9522. }
  9523. virtual void reset()
  9524. {
  9525. free(counter);
  9526. counter = NULL;
  9527. CRoxieServerChooseSetsExActivity::reset();
  9528. }
  9529. protected:
  9530. virtual void calculateSelection()
  9531. {
  9532. }
  9533. virtual bool includeRow(const void * row)
  9534. {
  9535. unsigned category = helper.getCategory(row);
  9536. if (category)
  9537. {
  9538. assertex(category <= numSets);
  9539. counter[category-1] += limits[category-1];
  9540. if(counter[category-1] >= setCounts[category-1])
  9541. {
  9542. counter[category-1] -= setCounts[category-1];
  9543. return true;
  9544. }
  9545. }
  9546. return false;
  9547. }
  9548. };
  9549. class CRoxieServerChooseSetsEnthActivityFactory : public CRoxieServerActivityFactory
  9550. {
  9551. public:
  9552. CRoxieServerChooseSetsEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9553. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  9554. {
  9555. }
  9556. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9557. {
  9558. return new CRoxieServerChooseSetsEnthActivity(_ctx, this, _probeManager);
  9559. }
  9560. };
  9561. IRoxieServerActivityFactory *createRoxieServerChooseSetsEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9562. {
  9563. return new CRoxieServerChooseSetsEnthActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9564. }
  9565. class CRoxieServerChooseSetsLastActivityFactory : public CRoxieServerActivityFactory
  9566. {
  9567. public:
  9568. CRoxieServerChooseSetsLastActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9569. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  9570. {
  9571. }
  9572. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9573. {
  9574. return new CRoxieServerChooseSetsLastActivity(_ctx, this, _probeManager);
  9575. }
  9576. };
  9577. IRoxieServerActivityFactory *createRoxieServerChooseSetsLastActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9578. {
  9579. return new CRoxieServerChooseSetsLastActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9580. }
  9581. //=================================================================================
  9582. class CRoxieServerEnthActivity : public CRoxieServerActivity
  9583. {
  9584. IHThorEnthArg &helper;
  9585. unsigned __int64 numerator;
  9586. unsigned __int64 denominator;
  9587. unsigned __int64 counter;
  9588. bool eof;
  9589. public:
  9590. CRoxieServerEnthActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9591. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorEnthArg &)basehelper)
  9592. {
  9593. eof = false;
  9594. numerator = denominator = counter = 0;
  9595. }
  9596. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9597. {
  9598. eof = false;
  9599. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9600. numerator = helper.getProportionNumerator();
  9601. denominator = helper.getProportionDenominator();
  9602. if(denominator == 0) denominator = 1; //MORE: simplest way to avoid disaster in this case
  9603. counter = (helper.getSampleNumber()-1) * greatestCommonDivisor(numerator, denominator);
  9604. if (counter >= denominator)
  9605. counter %= denominator;
  9606. }
  9607. inline bool wanted()
  9608. {
  9609. counter += numerator;
  9610. if(counter >= denominator)
  9611. {
  9612. counter -= denominator;
  9613. return true;
  9614. }
  9615. return false;
  9616. }
  9617. virtual const void * nextRow()
  9618. {
  9619. ActivityTimer t(totalCycles, timeActivities);
  9620. if (eof)
  9621. return NULL;
  9622. const void * ret;
  9623. for (;;)
  9624. {
  9625. ret = inputStream->ungroupedNextRow();
  9626. if (!ret) //eof
  9627. {
  9628. eof = true;
  9629. return ret;
  9630. }
  9631. if (wanted())
  9632. return ret;
  9633. ReleaseRoxieRow(ret);
  9634. }
  9635. }
  9636. };
  9637. class CRoxieServerEnthActivityFactory : public CRoxieServerActivityFactory
  9638. {
  9639. public:
  9640. CRoxieServerEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9641. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  9642. {
  9643. }
  9644. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9645. {
  9646. return new CRoxieServerEnthActivity(_ctx, this, _probeManager);
  9647. }
  9648. };
  9649. IRoxieServerActivityFactory *createRoxieServerEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9650. {
  9651. return new CRoxieServerEnthActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9652. }
  9653. //=================================================================================
  9654. class CRoxieServerAggregateActivity : public CRoxieServerActivity
  9655. {
  9656. IHThorAggregateArg &helper;
  9657. bool eof;
  9658. bool isInputGrouped;
  9659. bool abortEarly;
  9660. public:
  9661. CRoxieServerAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9662. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorAggregateArg &)basehelper)
  9663. {
  9664. eof = false;
  9665. isInputGrouped = false;
  9666. abortEarly = false;
  9667. }
  9668. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9669. {
  9670. eof = false;
  9671. isInputGrouped = input->queryOutputMeta()->isGrouped(); // could be done earlier, in setInput?
  9672. abortEarly = !isInputGrouped && (factory->getKind() == TAKexistsaggregate); // ditto
  9673. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9674. }
  9675. virtual bool needsAllocator() const { return true; }
  9676. virtual const void * nextRow()
  9677. {
  9678. ActivityTimer t(totalCycles, timeActivities);
  9679. if (eof)
  9680. return NULL;
  9681. const void * next = inputStream->nextRow();
  9682. if (!next && isInputGrouped)
  9683. {
  9684. eof = true;
  9685. return NULL;
  9686. }
  9687. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  9688. size32_t finalSize = helper.clearAggregate(rowBuilder);
  9689. if (next)
  9690. {
  9691. finalSize = helper.processFirst(rowBuilder, next);
  9692. ReleaseRoxieRow(next);
  9693. if (!abortEarly)
  9694. {
  9695. for (;;)
  9696. {
  9697. next = inputStream->nextRow();
  9698. if (!next)
  9699. break;
  9700. finalSize = helper.processNext(rowBuilder, next);
  9701. ReleaseRoxieRow(next);
  9702. }
  9703. }
  9704. }
  9705. if (!isInputGrouped) // either read all, or aborted early
  9706. eof = true;
  9707. processed++;
  9708. return rowBuilder.finalizeRowClear(finalSize);
  9709. }
  9710. };
  9711. class CRoxieServerStrandedAggregateActivity : public CRoxieServerStrandedActivity, implements IOrderedCallbackCollection
  9712. {
  9713. class AggregateProcessor : public StrandProcessor, implements IStrandThreaded, implements IOrderedOutputCallback
  9714. {
  9715. protected:
  9716. IHThorAggregateArg &helper;
  9717. OwnedConstRoxieRow result;
  9718. bool eof = false;
  9719. bool isInputGrouped = false;
  9720. bool abortEarly = false;
  9721. public:
  9722. AggregateProcessor(CRoxieServerActivity &_parent, IEngineRowStream *_inputStream, IHThorAggregateArg &_helper, bool _isInputGrouped, bool _abortEarly)
  9723. : StrandProcessor(_parent, _inputStream, true), helper(_helper), isInputGrouped(_isInputGrouped), abortEarly(_abortEarly)
  9724. {
  9725. }
  9726. virtual const void * nextRow() override
  9727. {
  9728. ActivityTimer t(totalCycles, timeActivities);
  9729. if (eof || isAborting())
  9730. return NULL;
  9731. const void * next = inputStream->nextRow();
  9732. if (!next && isInputGrouped)
  9733. {
  9734. eof = true;
  9735. return NULL;
  9736. }
  9737. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  9738. size32_t finalSize = helper.clearAggregate(rowBuilder);
  9739. if (next)
  9740. {
  9741. finalSize = helper.processFirst(rowBuilder, next);
  9742. ReleaseRoxieRow(next);
  9743. if (!abortEarly)
  9744. {
  9745. for (;;)
  9746. {
  9747. next = inputStream->nextRow();
  9748. if (!next)
  9749. break;
  9750. finalSize = helper.processNext(rowBuilder, next);
  9751. ReleaseRoxieRow(next);
  9752. if (isAborting())
  9753. break;
  9754. }
  9755. }
  9756. }
  9757. if (!isInputGrouped) // either read all, or aborted early
  9758. eof = true;
  9759. processed++;
  9760. return rowBuilder.finalizeRowClear(finalSize);
  9761. }
  9762. virtual void threadmain() override
  9763. {
  9764. isInputGrouped = true; // gather no row if there are no input rows.
  9765. result.setown(nextRow());
  9766. queryActivity().noteStrandFinished(inputStream);
  9767. }
  9768. virtual void reset() override
  9769. {
  9770. StrandProcessor::reset();
  9771. result.clear();
  9772. eof = false;
  9773. }
  9774. //interface IOutputOutputCallback
  9775. virtual bool noteEndOfInputChunk() { return true; }
  9776. virtual void noteEndOfInput() {}
  9777. virtual void stopStream()
  9778. {
  9779. inputStream->stop();
  9780. }
  9781. const void * queryResult() const { return result; }
  9782. CRoxieServerStrandedAggregateActivity & queryActivity() { return static_cast<CRoxieServerStrandedAggregateActivity &>(parent); }
  9783. };
  9784. //This class is only used when a single aggregate is being calculated.
  9785. class AggregateCombiner : public CInterfaceOf<IEngineRowStream>
  9786. {
  9787. public:
  9788. explicit AggregateCombiner(CRoxieServerStrandedAggregateActivity & _parent) : parent(_parent)
  9789. {
  9790. }
  9791. virtual const void *nextRow()
  9792. {
  9793. return parent.getCombinedAggregate();
  9794. }
  9795. virtual void stop()
  9796. {
  9797. parent.outputStopped();
  9798. }
  9799. virtual void resetEOF()
  9800. {
  9801. throwUnexpected();
  9802. }
  9803. protected:
  9804. CRoxieServerStrandedAggregateActivity & parent;
  9805. } combiner;
  9806. class NullCallback : implements IOrderedOutputCallback
  9807. {
  9808. public:
  9809. virtual bool noteEndOfInputChunk() { return true; }
  9810. virtual void noteEndOfInput() {}
  9811. } nullCallback;
  9812. public:
  9813. CRoxieServerStrandedAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const StrandOptions &_strandOptions)
  9814. : CRoxieServerStrandedActivity(_ctx, _factory, _probeManager, _strandOptions), helper((IHThorAggregateArg &)basehelper), combiner(*this)
  9815. {
  9816. isInputGrouped = false;
  9817. abortEarly = false;
  9818. }
  9819. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  9820. {
  9821. CRoxieServerStrandedActivity::setInput(idx, _sourceIdx, _in);
  9822. isInputGrouped = input->queryOutputMeta()->isGrouped(); // could be done earlier, in setInput?
  9823. abortEarly = !isInputGrouped && (factory->getKind() == TAKexistsaggregate); // ditto
  9824. //For EXISTS(), and aggregates that rely on the input order, force to execute single threaded
  9825. //MORE: Ordered should be able to process a block at a time and then merge them, similar to disk write processing.
  9826. if (abortEarly || (!isInputGrouped && queryFactory()->isInputOrdered(false, 0)))
  9827. strandOptions.numStrands = 1;
  9828. else if (!isInputGrouped)
  9829. combineStreams = true;
  9830. }
  9831. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  9832. {
  9833. PointerArrayOf<IEngineRowStream> localStreams;
  9834. //If streams are being combined, this class should be notified of end of sections, otherwise grouped aggregates can inform a downstream activity.
  9835. IOrderedCallbackCollection * callbacks = combineStreams ? static_cast<IOrderedCallbackCollection *>(this) : orderedCallbacks;
  9836. Owned<IStrandJunction> outJunction = CRoxieServerStrandedActivity::getOutputStreams(ctx, idx, localStreams, consumerOptions, consumerOrdered, callbacks);
  9837. if (localStreams.ordinality() == 1)
  9838. combineStreams = false; // Select a more efficient/simpler code path
  9839. if (combineStreams)
  9840. {
  9841. assertex(!outJunction); // this needs more thought!
  9842. streams.append(&combiner);
  9843. }
  9844. else
  9845. {
  9846. streams.swapWith(localStreams);
  9847. }
  9848. return outJunction.getClear();
  9849. }
  9850. virtual StrandProcessor *createStrandProcessor(IEngineRowStream *instream)
  9851. {
  9852. if (traceLevel > 4)
  9853. DBGLOG("Create aggregate strand processor %u", strandOptions.numStrands);
  9854. return new AggregateProcessor(*this, instream, (IHThorAggregateArg &) basehelper, isInputGrouped && !combineStreams, abortEarly);
  9855. }
  9856. virtual StrandProcessor *createStrandSourceProcessor(bool inputOrdered) { throwUnexpected(); }
  9857. virtual bool needsAllocator() const { return true; }
  9858. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused) override
  9859. {
  9860. CRoxieServerStrandedActivity::start(parentExtractSize, parentExtract, paused);
  9861. if (combineStreams)
  9862. {
  9863. barrier.setown(createStrandBarrier());
  9864. ForEachItemIn(i, strands)
  9865. barrier->startStrand(queryAggregate(i));
  9866. active.store(1);
  9867. }
  9868. else
  9869. active.store(0);
  9870. }
  9871. virtual void reset() override
  9872. {
  9873. CRoxieServerStrandedActivity::reset();
  9874. barrier.clear();
  9875. calculated = false;
  9876. }
  9877. //Helper functions for the single aggregate case
  9878. const void * getCombinedAggregate()
  9879. {
  9880. if (calculated)
  9881. return NULL;
  9882. calculated= true;
  9883. barrier->waitForStrands();
  9884. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  9885. size32_t finalSize = helper.clearAggregate(rowBuilder);
  9886. bool isFirst = true;
  9887. for (unsigned i=0; i < numStrands(); i++)
  9888. {
  9889. const void * next = queryAggregate(i).queryResult();
  9890. if (next)
  9891. {
  9892. if (isFirst)
  9893. {
  9894. finalSize = cloneRow(rowBuilder, next, helper.queryOutputMeta());
  9895. isFirst = false;
  9896. }
  9897. else
  9898. finalSize = helper.mergeAggregate(rowBuilder, next);
  9899. }
  9900. }
  9901. return rowBuilder.finalizeRowClear(finalSize);
  9902. }
  9903. void outputStopped()
  9904. {
  9905. //only called if generating a single result.
  9906. assertex(combineStreams);
  9907. if (barrier)
  9908. {
  9909. requestAbort(); // if strands are still running, abort them
  9910. barrier->waitForStrands();
  9911. }
  9912. else
  9913. {
  9914. ForEachItemIn(i, strands)
  9915. queryAggregate(i).stopStream();
  9916. }
  9917. CRoxieServerStrandedActivity::stop();
  9918. }
  9919. void noteStrandFinished(IRowStream * stream)
  9920. {
  9921. barrier->noteStrandFinished(stream);
  9922. }
  9923. virtual IOrderedOutputCallback * queryCallback(unsigned i)
  9924. {
  9925. //The non-ordered aggregate does not need to process the ordered call back information.
  9926. //If the ordered single aggregate was implemented then it would need to be processed instead of ignored,
  9927. //however it needs some care since the strands are not yet created. So cannot return strand(i).
  9928. return &nullCallback;
  9929. }
  9930. inline AggregateProcessor & queryAggregate(unsigned i)
  9931. {
  9932. return static_cast<AggregateProcessor &>(strands.item(i));
  9933. }
  9934. protected:
  9935. IHThorAggregateArg &helper;
  9936. Owned<IStrandBarrier> barrier;
  9937. IEngineRowStream * combinedStream = nullptr;
  9938. bool isInputGrouped;
  9939. bool abortEarly;
  9940. bool combineStreams = false;
  9941. bool calculated = false;
  9942. };
  9943. class CRoxieServerAggregateActivityFactory : public CRoxieServerActivityFactory
  9944. {
  9945. StrandOptions strandOptions;
  9946. public:
  9947. CRoxieServerAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9948. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), strandOptions(_graphNode)
  9949. {
  9950. Owned<IHThorAggregateArg> helper = (IHThorAggregateArg *) helperFactory();
  9951. if (!(helper->getAggregateFlags() & TAForderedmerge))
  9952. optStableInput = false;
  9953. }
  9954. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9955. {
  9956. return new CRoxieServerStrandedAggregateActivity(_ctx, this, _probeManager, strandOptions);
  9957. }
  9958. };
  9959. IRoxieServerActivityFactory *createRoxieServerAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9960. {
  9961. return new CRoxieServerAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9962. }
  9963. //=================================================================================
  9964. typedef unsigned t_hashPrefix;
  9965. class CRoxieServerHashAggregateActivity : public CRoxieServerActivity
  9966. {
  9967. IHThorHashAggregateArg &helper;
  9968. RowAggregator aggregated;
  9969. bool eof;
  9970. bool gathered;
  9971. bool isGroupedAggregate;
  9972. public:
  9973. CRoxieServerHashAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, bool _isGroupedAggregate, IProbeManager *_probeManager)
  9974. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorHashAggregateArg &)basehelper),
  9975. isGroupedAggregate(_isGroupedAggregate),
  9976. aggregated(helper, helper)
  9977. {
  9978. eof = false;
  9979. gathered = false;
  9980. }
  9981. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9982. {
  9983. eof = false;
  9984. gathered = false;
  9985. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9986. }
  9987. virtual void reset()
  9988. {
  9989. aggregated.reset();
  9990. CRoxieServerActivity::reset();
  9991. }
  9992. virtual bool needsAllocator() const { return true; }
  9993. virtual const void * nextRow()
  9994. {
  9995. ActivityTimer t(totalCycles, timeActivities);
  9996. if (eof)
  9997. return NULL;
  9998. if (!gathered)
  9999. {
  10000. aggregated.start(rowAllocator, ctx->queryCodeContext(), activityId);
  10001. bool eog = true;
  10002. for (;;)
  10003. {
  10004. const void * next = inputStream->nextRow();
  10005. if (!next)
  10006. {
  10007. if (isGroupedAggregate)
  10008. {
  10009. if (eog)
  10010. eof = true;
  10011. break;
  10012. }
  10013. next = inputStream->nextRow();
  10014. if (!next)
  10015. break;
  10016. }
  10017. eog = false;
  10018. aggregated.addRow(next);
  10019. ReleaseRoxieRow(next);
  10020. }
  10021. gathered = true;
  10022. }
  10023. Owned<AggregateRowBuilder> next = aggregated.nextResult();
  10024. if (next)
  10025. {
  10026. processed++;
  10027. return next->finalizeRowClear();
  10028. }
  10029. if (!isGroupedAggregate)
  10030. eof = true;
  10031. aggregated.reset();
  10032. gathered = false;
  10033. return NULL;
  10034. }
  10035. };
  10036. class CRoxieServerHashAggregateActivityFactory : public CRoxieServerActivityFactory
  10037. {
  10038. public:
  10039. CRoxieServerHashAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  10040. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  10041. {
  10042. isGroupedAggregate = _graphNode.getPropBool("att[@name='grouped']/@value");
  10043. }
  10044. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  10045. {
  10046. return new CRoxieServerHashAggregateActivity(_ctx, this, isGroupedAggregate, _probeManager);
  10047. }
  10048. protected:
  10049. bool isGroupedAggregate;
  10050. };
  10051. IRoxieServerActivityFactory *createRoxieServerHashAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  10052. {
  10053. return new CRoxieServerHashAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  10054. }
  10055. //=================================================================================
  10056. class CRoxieServerDegroupActivity : public CRoxieServerActivity
  10057. {
  10058. IHThorDegroupArg &helper;
  10059. bool eof;
  10060. public:
  10061. CRoxieServerDegroupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  10062. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorDegroupArg &)basehelper)
  10063. {
  10064. eof = false;
  10065. }
  10066. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10067. {
  10068. eof = false;
  10069. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  10070. }
  10071. virtual const void * nextRow()
  10072. {
  10073. ActivityTimer t(totalCycles, timeActivities);
  10074. if (eof)
  10075. return NULL;
  10076. const void * ret = inputStream->ungroupedNextRow();
  10077. if (ret)
  10078. processed++;
  10079. else
  10080. eof = true;
  10081. return ret;
  10082. }
  10083. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  10084. {
  10085. ActivityTimer t(totalCycles, timeActivities);
  10086. if (eof)
  10087. return NULL;
  10088. const void * ret = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  10089. if (ret)
  10090. processed++;
  10091. else
  10092. eof = true;
  10093. return ret;
  10094. }
  10095. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  10096. {
  10097. return input->gatherConjunctions(collector);
  10098. }
  10099. virtual void resetEOF()
  10100. {
  10101. eof = false;
  10102. inputStream->resetEOF();
  10103. }
  10104. IInputSteppingMeta * querySteppingMeta()
  10105. {
  10106. return input->querySteppingMeta();
  10107. }
  10108. };
  10109. class CRoxieServerDegroupActivityFactory : public CRoxieServerActivityFactory
  10110. {
  10111. public:
  10112. CRoxieServerDegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  10113. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  10114. {
  10115. }
  10116. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  10117. {
  10118. return new CRoxieServerDegroupActivity(_ctx, this, _probeManager);
  10119. }
  10120. };
  10121. IRoxieServerActivityFactory *createRoxieServerDegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  10122. {
  10123. return new CRoxieServerDegroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  10124. }
  10125. //=================================================================================
  10126. class CRoxieServerSpillReadActivity : public CRoxieServerActivity
  10127. {
  10128. IHThorDiskReadArg &helper;
  10129. bool needTransform;
  10130. bool eof;
  10131. bool anyThisGroup;
  10132. unsigned __int64 rowLimit;
  10133. unsigned __int64 choosenLimit;
  10134. public:
  10135. CRoxieServerSpillReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  10136. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorDiskReadArg &)basehelper)
  10137. {
  10138. needTransform = helper.needTransform();
  10139. rowLimit = (unsigned __int64) -1;
  10140. choosenLimit = 0;
  10141. eof = false;
  10142. anyThisGroup = false;
  10143. }
  10144. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10145. {
  10146. anyThisGroup = false;
  10147. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  10148. if (helper.canMatchAny())
  10149. eof = false;
  10150. else
  10151. eof = true;
  10152. choosenLimit = helper.getChooseNLimit();
  10153. rowLimit = helper.getRowLimit();
  10154. helper.setCallback(NULL); // members should not be called - change if they are
  10155. }
  10156. virtual bool needsAllocator() const { return true; }
  10157. virtual const void * nextRow()
  10158. {
  10159. ActivityTimer t(totalCycles, timeActivities);
  10160. if (eof)
  10161. return NULL;
  10162. if (processed==choosenLimit)
  10163. {
  10164. eof = true;
  10165. return NULL;
  10166. }
  10167. if (needTransform)
  10168. {
  10169. for (;;)
  10170. {
  10171. const void *in = inputStream->nextRow();
  10172. if (!in)
  10173. {
  10174. if (anyThisGroup)
  10175. {
  10176. anyThisGroup = false;
  10177. return NULL;
  10178. }
  10179. in = inputStream->nextRow();
  10180. if (!in)
  10181. {
  10182. eof = true;
  10183. return NULL; // eof...
  10184. }
  10185. }
  10186. unsigned outSize;
  10187. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  10188. try
  10189. {
  10190. outSize = helper.transform(rowBuilder, in);
  10191. ReleaseRoxieRow(in);
  10192. }
  10193. catch (IException *E)
  10194. {
  10195. throw makeWrappedException(E);
  10196. }
  10197. if (outSize)
  10198. {
  10199. anyThisGroup = true;
  10200. processed++;
  10201. if (processed==rowLimit)
  10202. {
  10203. if (traceLevel > 4)
  10204. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  10205. helper.onLimitExceeded();
  10206. }
  10207. return rowBuilder.finalizeRowClear(outSize);
  10208. }
  10209. }
  10210. }
  10211. else
  10212. {
  10213. const void *ret = inputStream->nextRow();
  10214. if (ret)
  10215. {
  10216. processed++;
  10217. if (processed==rowLimit)
  10218. {
  10219. if (traceLevel > 4)
  10220. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  10221. ReleaseClearRoxieRow(ret);
  10222. helper.onLimitExceeded(); // should not return
  10223. throwUnexpected();
  10224. }
  10225. }
  10226. return ret;
  10227. }
  10228. }
  10229. };
  10230. class CRoxieServerSpillReadActivityFactory : public CRoxieServerActivityFactory
  10231. {
  10232. public:
  10233. CRoxieServerSpillReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  10234. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  10235. {
  10236. }
  10237. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  10238. {
  10239. return new CRoxieServerSpillReadActivity(_ctx, this, _probeManager);
  10240. }
  10241. virtual void addDependency(unsigned source, ThorActivityKind sourceKind, unsigned sourceIdx, int controlId, const char *edgeId)
  10242. {
  10243. if (sourceKind==TAKspill || sourceKind==TAKdiskwrite || sourceKind==TAKspillwrite) // Bit of a hack - codegen probably should differentiate
  10244. setInput(0, source, sourceIdx);
  10245. else
  10246. CRoxieServerActivityFactory::addDependency(source, kind, sourceIdx, controlId, edgeId);
  10247. }
  10248. };
  10249. IRoxieServerActivityFactory *createRoxieServerSpillReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  10250. {
  10251. return new CRoxieServerSpillReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  10252. }
  10253. //=================================================================================
  10254. class CRoxieServerSpillWriteActivity : public CRoxieServerActivity
  10255. {
  10256. public:
  10257. CRoxieServerSpillWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  10258. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  10259. {
  10260. }
  10261. ~CRoxieServerSpillWriteActivity()
  10262. {
  10263. }
  10264. virtual const void *nextRow()
  10265. {
  10266. ActivityTimer t(totalCycles, timeActivities);
  10267. return inputStream->nextRow();
  10268. }
  10269. };
  10270. //==================================================================================
  10271. class CRoxieServerDiskWriteActivity : public CRoxieServerInternalSinkActivity, implements IRoxiePublishCallback
  10272. {
  10273. protected:
  10274. Owned<IExtRowWriter> outSeq;
  10275. Owned<IOutputRowSerializer> rowSerializer;
  10276. Linked<IFileIOStream> diskout;
  10277. bool blockcompressed;
  10278. bool extend;
  10279. bool overwrite;
  10280. bool encrypted;
  10281. bool grouped;
  10282. IHThorDiskWriteArg &helper;
  10283. Owned<IRecordSize> diskmeta;
  10284. Owned<IRoxieWriteHandler> writer;
  10285. bool tallycrc;
  10286. unsigned __int64 uncompressedBytesWritten;
  10287. CRC32 crc;
  10288. void updateWorkUnitResult(unsigned __int64 reccount)
  10289. {
  10290. assertex(writer);
  10291. // MORE - a lot of this is common with hthor
  10292. WorkunitUpdate wu = ctx->updateWorkUnit();
  10293. if (wu)
  10294. {
  10295. OwnedRoxieString rawLogicalName = helper.getFileName();
  10296. StringBuffer lfn; // logical filename
  10297. expandLogicalFilename(lfn, rawLogicalName, wu, false, false);
  10298. if (lfn.length())
  10299. {
  10300. unsigned flags = helper.getFlags();
  10301. WUFileKind fileKind;
  10302. if (TDXtemporary & flags)
  10303. fileKind = WUFileTemporary;
  10304. else if(TDXjobtemp & flags)
  10305. fileKind = WUFileJobOwned;
  10306. else if(TDWowned & flags)
  10307. fileKind = WUFileOwned;
  10308. else
  10309. fileKind = WUFileStandard;
  10310. StringArray clusters;
  10311. writer->getClusters(clusters);
  10312. wu->addFile(lfn.str(), &clusters, helper.getTempUsageCount(), fileKind, NULL);
  10313. if (!(flags & TDXtemporary) && helper.getSequence() >= 0)
  10314. {
  10315. Owned<IWUResult> result = wu->updateResultBySequence(helper.getSequence());
  10316. if (result)
  10317. {
  10318. result->setResultTotalRowCount(reccount);
  10319. result->setResultStatus(ResultStatusCalculated);
  10320. if (helper.getFlags() & TDWresult)
  10321. result->setResultFilename(lfn.str());
  10322. else
  10323. result->setResultLogicalName(lfn.str());
  10324. }
  10325. }
  10326. }
  10327. }
  10328. }
  10329. void resolve()
  10330. {
  10331. OwnedRoxieString rawLogicalName = helper.getFileName();
  10332. assertex(rawLogicalName);
  10333. assertex((helper.getFlags() & TDXtemporary) == 0);
  10334. StringArray clusters;
  10335. unsigned clusterIdx = 0;
  10336. while(true)
  10337. {
  10338. OwnedRoxieString cluster(helper.getCluster(clusterIdx));
  10339. if(!cluster)
  10340. break;
  10341. clusters.append(cluster);
  10342. clusterIdx++;
  10343. }
  10344. if (clusters.length())
  10345. {
  10346. if (extend)
  10347. throw MakeStringException(0, "Cannot combine EXTEND and CLUSTER flags on disk write of file %s", rawLogicalName.get());
  10348. }
  10349. else
  10350. {
  10351. if (roxieName.length())
  10352. clusters.append(roxieName.str());
  10353. else
  10354. clusters.append(".");
  10355. }
  10356. writer.setown(ctx->createLFN(rawLogicalName, overwrite, extend, clusters));
  10357. // MORE - need to check somewhere that single part if it's an existing file or an external one...
  10358. }
  10359. public:
  10360. CRoxieServerDiskWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  10361. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, 0), helper((IHThorDiskWriteArg &) basehelper)
  10362. {
  10363. extend = ((helper.getFlags() & TDWextend) != 0);
  10364. overwrite = ((helper.getFlags() & TDWoverwrite) != 0);
  10365. grouped = (helper.getFlags() & TDXgrouped) != 0;
  10366. diskmeta.set(helper.queryDiskRecordSize()->querySerializedDiskMeta());
  10367. if (grouped)
  10368. diskmeta.setown(createDeltaRecordSize(diskmeta, +1));
  10369. blockcompressed = (((helper.getFlags() & TDWnewcompress) != 0) || (((helper.getFlags() & TDXcompress) != 0) && (diskmeta->getFixedSize() >= MIN_ROWCOMPRESS_RECSIZE))); //always use new compression
  10370. encrypted = false; // set later
  10371. tallycrc = true;
  10372. uncompressedBytesWritten = 0;
  10373. }
  10374. ~CRoxieServerDiskWriteActivity()
  10375. {
  10376. }
  10377. virtual bool needsAllocator() const
  10378. {
  10379. return true;
  10380. }
  10381. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10382. {
  10383. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  10384. resolve();
  10385. Owned<IFileIO> io;
  10386. void *ekey;
  10387. size32_t ekeylen;
  10388. helper.getEncryptKey(ekeylen, ekey);
  10389. Owned<ICompressor> ecomp;
  10390. if (ekeylen!=0)
  10391. {
  10392. ecomp.setown(createAESCompressor256(ekeylen,ekey));
  10393. memset(ekey,0,ekeylen);
  10394. rtlFree(ekey);
  10395. encrypted = true;
  10396. blockcompressed = true;
  10397. }
  10398. if (blockcompressed)
  10399. io.setown(createCompressedFileWriter(writer->queryFile(), (diskmeta->isFixedSize() ? diskmeta->getFixedSize() : 0), extend, true, ecomp));
  10400. else
  10401. io.setown(writer->queryFile()->open(extend ? IFOwrite : IFOcreate));
  10402. if (!io)
  10403. throw MakeStringException(errno, "Failed to create%s file %s for writing", (encrypted ? " encrypted" : (blockcompressed ? " compressed" : "")), writer->queryFile()->queryFilename());
  10404. diskout.setown(createBufferedIOStream(io));
  10405. if (extend)
  10406. diskout->seek(0, IFSend);
  10407. tallycrc = !(helper.getFlags() & TDRnocrccheck) && !blockcompressed;
  10408. Owned<IRowInterfaces> rowIf = createRowInterfaces(input->queryOutputMeta(), activityId, factory->getHeapFlags(), ctx->queryCodeContext());
  10409. rowSerializer.set(rowIf->queryRowSerializer());
  10410. unsigned rwFlags = rw_autoflush;
  10411. if(grouped)
  10412. rwFlags |= rw_grouped;
  10413. if(tallycrc)
  10414. rwFlags |= rw_crc;
  10415. outSeq.setown(createRowWriter(diskout, rowIf, rwFlags));
  10416. }
  10417. virtual void stop()
  10418. {
  10419. if (aborted)
  10420. {
  10421. if (writer)
  10422. writer->finish(false, this);
  10423. }
  10424. else
  10425. {
  10426. if (outSeq)
  10427. outSeq->flush(&crc);
  10428. if (outSeq)
  10429. uncompressedBytesWritten = outSeq->getPosition();
  10430. outSeq.clear();
  10431. diskout.clear(); // Make sure file is properly closed or date may not match published info
  10432. if (writer)
  10433. {
  10434. updateWorkUnitResult(processed);
  10435. writer->finish(true, this);
  10436. }
  10437. }
  10438. writer.clear();
  10439. CRoxieServerActivity::stop();
  10440. }
  10441. virtual void reset()
  10442. {
  10443. CRoxieServerActivity::reset();
  10444. diskout.clear();
  10445. outSeq.clear();
  10446. writer.clear();
  10447. uncompressedBytesWritten = 0;
  10448. crc.reset();
  10449. }
  10450. virtual void onExecute()
  10451. {
  10452. for (;;)
  10453. {
  10454. const void *row = inputStream->nextRow();
  10455. if (!row)
  10456. {
  10457. row = inputStream->nextRow();
  10458. if (!row)
  10459. break;
  10460. if (grouped)
  10461. outSeq->putRow(NULL);
  10462. }
  10463. processed++;
  10464. outSeq->putRow(row);
  10465. }
  10466. }
  10467. virtual void setFileProperties(IFileDescriptor *desc) const
  10468. {
  10469. IPropertyTree &partProps = desc->queryPart(0)->queryProperties(); //properties of the first file part.
  10470. IPropertyTree &fileProps = desc->queryProperties(); // properties of the logical file
  10471. if (blockcompressed)
  10472. {
  10473. // caller has already set @size from file size...
  10474. fileProps.setPropBool("@blockCompressed", true);
  10475. fileProps.setPropInt64("@compressedSize", partProps.getPropInt64("@size", 0));
  10476. partProps.setPropInt64("@compressedSize", partProps.getPropInt64("@size", 0));
  10477. fileProps.setPropInt64("@size", uncompressedBytesWritten);
  10478. partProps.setPropInt64("@size", uncompressedBytesWritten);
  10479. }
  10480. else if (tallycrc && crc.get())
  10481. partProps.setPropInt64("@fileCrc", crc.get());
  10482. if (encrypted)
  10483. fileProps.setPropBool("@encrypted", true);
  10484. fileProps.setPropInt64("@recordCount", processed);
  10485. unsigned flags = helper.getFlags();
  10486. if (flags & TDWpersist)
  10487. fileProps.setPropBool("@persistent", true);
  10488. if (grouped)
  10489. fileProps.setPropBool("@grouped", true);
  10490. if (flags & (TDWowned|TDXjobtemp|TDXtemporary))
  10491. fileProps.setPropBool("@owned", true);
  10492. if (flags & TDWresult)
  10493. fileProps.setPropBool("@result", true);
  10494. IConstWorkUnit *workUnit = ctx->queryWorkUnit();
  10495. if (workUnit)
  10496. {
  10497. fileProps.setProp("@owner", workUnit->queryUser());
  10498. fileProps.setProp("@workunit", workUnit->queryWuid());
  10499. fileProps.setProp("@job", workUnit->queryJobName());
  10500. }
  10501. if (flags & TDWexpires)
  10502. setExpiryTime(fileProps, helper.getExpiryDays());
  10503. if (flags & TDWupdate)
  10504. {
  10505. unsigned eclCRC;
  10506. unsigned __int64 totalCRC;
  10507. helper.getUpdateCRCs(eclCRC, totalCRC);
  10508. fileProps.setPropInt("@eclCRC", eclCRC);
  10509. fileProps.setPropInt64("@totalCRC", totalCRC);
  10510. }
  10511. fileProps.setPropInt("@formatCrc", helper.getFormatCrc());
  10512. IRecordSize * inputMeta = input->queryOutputMeta();
  10513. if ((inputMeta->isFixedSize()) && !isOutputTransformed())
  10514. fileProps.setPropInt("@recordSize", inputMeta->getFixedSize() + (grouped ? 1 : 0));
  10515. const char *recordECL = helper.queryRecordECL();
  10516. if (recordECL && *recordECL)
  10517. fileProps.setProp("ECL", recordECL);
  10518. setRtlFormat(fileProps, helper.queryDiskRecordSize());
  10519. fileProps.setProp("@kind", "flat"); // default, derivitives may override
  10520. }
  10521. virtual IUserDescriptor *queryUserDescriptor() const
  10522. {
  10523. IConstWorkUnit *workUnit = ctx->queryWorkUnit();
  10524. if (workUnit)
  10525. return workUnit->queryUserDescriptor();//ad-hoc mode
  10526. else
  10527. {
  10528. Owned<IRoxieDaliHelper> daliHelper = connectToDali(false);
  10529. if (daliHelper)
  10530. return daliHelper->queryUserDescriptor();//predeployed query mode
  10531. }
  10532. return NULL;
  10533. }
  10534. virtual bool isOutputTransformed() const { return false; }
  10535. };
  10536. //=================================================================================
  10537. class CRoxieServerCsvWriteActivity : public CRoxieServerDiskWriteActivity
  10538. {
  10539. IHThorCsvWriteArg &csvHelper;
  10540. CSVOutputStream csvOutput;
  10541. public:
  10542. CRoxieServerCsvWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  10543. : CRoxieServerDiskWriteActivity(_ctx, _factory, _probeManager), csvHelper(static_cast<IHThorCsvWriteArg &>(helper))
  10544. {
  10545. csvOutput.init(csvHelper.queryCsvParameters(), false);
  10546. }
  10547. virtual void onExecute()
  10548. {
  10549. OwnedRoxieString header(csvHelper.queryCsvParameters()->getHeader());
  10550. if (header)
  10551. {
  10552. csvOutput.beginLine();
  10553. csvOutput.writeHeaderLn(strlen(header), header);
  10554. diskout->write(csvOutput.length(), csvOutput.str());
  10555. }
  10556. for (;;)
  10557. {
  10558. const void *nextrec = inputStream->ungroupedNextRow();
  10559. if (!nextrec)
  10560. break;
  10561. processed++;
  10562. csvOutput.beginLine();
  10563. csvHelper.writeRow((const byte *)nextrec, &csvOutput);
  10564. csvOutput.endLine();
  10565. diskout->write(csvOutput.length(), csvOutput.str());
  10566. ReleaseRoxieRow(nextrec);
  10567. }
  10568. OwnedRoxieString footer(csvHelper.queryCsvParameters()->getFooter());
  10569. if (footer)
  10570. {
  10571. csvOutput.beginLine();
  10572. csvOutput.writeHeaderLn(strlen(footer), footer);
  10573. diskout->write(csvOutput.length(), csvOutput.str());
  10574. }
  10575. }
  10576. virtual void setFileProperties(IFileDescriptor *desc) const
  10577. {
  10578. CRoxieServerDiskWriteActivity::setFileProperties(desc);
  10579. IPropertyTree &props = desc->queryProperties();
  10580. props.setProp("@format","utf8n");
  10581. ICsvParameters *csvParameters = csvHelper.queryCsvParameters();
  10582. StringBuffer separator;
  10583. OwnedRoxieString rs(csvParameters->getSeparator(0));
  10584. const char *s = rs;
  10585. while (s && *s)
  10586. {
  10587. if (',' == *s)
  10588. separator.append("\\,");
  10589. else
  10590. separator.append(*s);
  10591. ++s;
  10592. }
  10593. props.setProp("@csvSeparate", separator.str());
  10594. props.setProp("@csvQuote", rs.setown(csvParameters->getQuote(0)));
  10595. props.setProp("@csvTerminate", rs.setown(csvParameters->getTerminator(0)));
  10596. props.setProp("@csvEscape", rs.setown(csvParameters->getEscape(0)));
  10597. props.setProp("@kind", "csv");
  10598. }
  10599. virtual bool isOutputTransformed() const { return true; }
  10600. };
  10601. class CRoxieServerXmlWriteActivity : public CRoxieServerDiskWriteActivity
  10602. {
  10603. IHThorXmlWriteArg &xmlHelper;
  10604. StringAttr rowTag;
  10605. ThorActivityKind kind;
  10606. unsigned headerLength;
  10607. unsigned footerLength;
  10608. public:
  10609. CRoxieServerXmlWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, ThorActivityKind _kind)
  10610. : CRoxieServerDiskWriteActivity(_ctx, _factory, _probeManager), xmlHelper(static_cast<IHThorXmlWriteArg &>(helper)), kind(_kind), headerLength(0), footerLength(0)
  10611. {
  10612. }
  10613. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10614. {
  10615. CRoxieServerDiskWriteActivity::start(parentExtractSize, parentExtract, paused);
  10616. OwnedRoxieString xmlpath(xmlHelper.getXmlIteratorPath());
  10617. if (!xmlpath)
  10618. rowTag.set(DEFAULTXMLROWTAG);
  10619. else
  10620. {
  10621. const char *path = xmlpath;
  10622. if (*path == '/') path++;
  10623. if (strchr(path, '/')) UNIMPLEMENTED; // more what do we do with /mydata/row
  10624. rowTag.set(path);
  10625. }
  10626. }
  10627. virtual void onExecute()
  10628. {
  10629. StringBuffer header;
  10630. OwnedRoxieString suppliedHeader(xmlHelper.getHeader());
  10631. if (kind==TAKjsonwrite)
  10632. buildJsonHeader(header, suppliedHeader, rowTag);
  10633. else if (suppliedHeader)
  10634. header.set(suppliedHeader);
  10635. else
  10636. header.append(DEFAULTXMLHEADER).newline();
  10637. headerLength = header.length();
  10638. diskout->write(header.length(), header.str());
  10639. Owned<IXmlWriterExt> writer = createIXmlWriterExt(xmlHelper.getXmlFlags(), 0, NULL, (kind==TAKjsonwrite) ? WTJSON : WTStandard);
  10640. writer->outputBeginArray(rowTag); //need to set this
  10641. writer->clear(); //but not output it
  10642. for (;;)
  10643. {
  10644. OwnedConstRoxieRow nextrec = inputStream->ungroupedNextRow();
  10645. if (!nextrec)
  10646. break;
  10647. processed++;
  10648. writer->clear().outputBeginNested(rowTag, false);
  10649. xmlHelper.toXML((const byte *)nextrec.get(), *writer);
  10650. writer->outputEndNested(rowTag);
  10651. diskout->write(writer->length(), writer->str());
  10652. }
  10653. OwnedRoxieString suppliedFooter(xmlHelper.getFooter());
  10654. StringBuffer footer;
  10655. if (kind==TAKjsonwrite)
  10656. buildJsonFooter(footer.newline(), suppliedFooter, rowTag);
  10657. else if (suppliedFooter)
  10658. footer.append(suppliedFooter);
  10659. else
  10660. footer.append(DEFAULTXMLFOOTER);
  10661. footerLength=footer.length();
  10662. diskout->write(footer.length(), footer);
  10663. }
  10664. virtual void reset()
  10665. {
  10666. CRoxieServerDiskWriteActivity::reset();
  10667. rowTag.clear();
  10668. }
  10669. virtual void setFileProperties(IFileDescriptor *desc) const
  10670. {
  10671. CRoxieServerDiskWriteActivity::setFileProperties(desc);
  10672. desc->queryProperties().setProp("@format","utf8n");
  10673. desc->queryProperties().setProp("@rowTag",rowTag.get());
  10674. desc->queryProperties().setProp("@kind", (kind==TAKjsonwrite) ? "json" : "xml");
  10675. desc->queryProperties().setPropInt(FPheaderLength, headerLength);
  10676. desc->queryProperties().setPropInt(FPfooterLength, footerLength);
  10677. }
  10678. virtual bool isOutputTransformed() const { return true; }
  10679. };
  10680. class CRoxieServerDiskWriteActivityFactory : public CRoxieServerMultiOutputFactory
  10681. {
  10682. bool isRoot;
  10683. bool isTemp;
  10684. public:
  10685. CRoxieServerDiskWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  10686. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  10687. {
  10688. Owned<IHThorDiskWriteArg> helper = (IHThorDiskWriteArg *) helperFactory();
  10689. isTemp = (helper->getFlags() & TDXtemporary) != 0;
  10690. setNumOutputs(helper->getTempUsageCount());
  10691. if (_kind != TAKspillwrite)
  10692. assertex(numOutputs == 0);
  10693. }
  10694. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  10695. {
  10696. switch (numOutputs)
  10697. {
  10698. case 0:
  10699. switch (kind)
  10700. {
  10701. case TAKdiskwrite: return new CRoxieServerDiskWriteActivity(_ctx, this, _probeManager);
  10702. case TAKcsvwrite: return new CRoxieServerCsvWriteActivity(_ctx, this, _probeManager);
  10703. case TAKxmlwrite:
  10704. case TAKjsonwrite:
  10705. return new CRoxieServerXmlWriteActivity(_ctx, this, _probeManager, kind);
  10706. };
  10707. throwUnexpected();
  10708. case 1:
  10709. return new CRoxieServerSpillWriteActivity(_ctx, this, _probeManager);
  10710. default:
  10711. return new CRoxieServerThroughSpillActivity(_ctx, this, _probeManager, numOutputs);
  10712. }
  10713. }
  10714. virtual bool isSink() const
  10715. {
  10716. return numOutputs == 0 && !isTemp; // MORE - check with Gavin if this is right if not a temp but reread in same job...
  10717. }
  10718. };
  10719. IRoxieServerActivityFactory *createRoxieServerDiskWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  10720. {
  10721. return new CRoxieServerDiskWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  10722. }
  10723. //=================================================================================
  10724. class CRoxieServerIndexWriteActivity : public CRoxieServerInternalSinkActivity, implements IRoxiePublishCallback
  10725. {
  10726. IHThorIndexWriteArg &helper;
  10727. bool overwrite;
  10728. Owned<ClusterWriteHandler> clusterHandler;
  10729. Owned<IRoxieWriteHandler> writer;
  10730. unsigned __int64 reccount;
  10731. unsigned int fileCrc;
  10732. StringBuffer filename;
  10733. unsigned __int64 duplicateKeyCount = 0;
  10734. unsigned __int64 cummulativeDuplicateKeyCount = 0;
  10735. void updateWorkUnitResult()
  10736. {
  10737. // MORE - a lot of this is common with hthor
  10738. WorkunitUpdate wu = ctx->updateWorkUnit();
  10739. if (wu)
  10740. {
  10741. OwnedRoxieString rawLogicalName = helper.getFileName();
  10742. StringBuffer lfn; // logical filename
  10743. expandLogicalFilename(lfn, rawLogicalName, wu, false, false);
  10744. if (lfn.length())
  10745. {
  10746. if (helper.getSequence() >= 0)
  10747. {
  10748. Owned<IWUResult> result = wu->updateResultBySequence(helper.getSequence());
  10749. if (result)
  10750. {
  10751. result->setResultTotalRowCount(reccount);
  10752. result->setResultStatus(ResultStatusCalculated);
  10753. result->setResultLogicalName(lfn.str());
  10754. }
  10755. }
  10756. if(clusterHandler)
  10757. clusterHandler->finish(writer->queryFile());
  10758. CTXLOG("Created roxie index file %s", lfn.str());
  10759. }
  10760. }
  10761. }
  10762. virtual void resolve()
  10763. {
  10764. StringArray clusters;
  10765. unsigned clusterIdx = 0;
  10766. while(true)
  10767. {
  10768. OwnedRoxieString cluster(helper.getCluster(clusterIdx));
  10769. if(!cluster)
  10770. break;
  10771. clusters.append(cluster);
  10772. clusterIdx++;
  10773. }
  10774. if (roxieName.length())
  10775. clusters.append(roxieName.str());
  10776. else
  10777. clusters.append(".");
  10778. OwnedRoxieString fname(helper.getFileName());
  10779. writer.setown(ctx->createLFN(fname, overwrite, false, clusters)); // MORE - if there's a workunit, use if for scope.
  10780. filename.set(writer->queryFile()->queryFilename());
  10781. if (writer->queryFile()->exists())
  10782. {
  10783. if (overwrite)
  10784. {
  10785. CTXLOG("Removing existing %s from DFS",filename.str());
  10786. writer->queryFile()->remove();
  10787. }
  10788. else
  10789. throw MakeStringException(99, "Cannot write index file %s, file already exists (missing OVERWRITE attribute?)", filename.str());
  10790. }
  10791. }
  10792. void buildUserMetadata(Owned<IPropertyTree> & metadata)
  10793. {
  10794. size32_t nameLen;
  10795. char * nameBuff;
  10796. size32_t valueLen;
  10797. char * valueBuff;
  10798. unsigned idx = 0;
  10799. while(helper.getIndexMeta(nameLen, nameBuff, valueLen, valueBuff, idx++))
  10800. {
  10801. StringBuffer name(nameLen, nameBuff);
  10802. StringBuffer value(valueLen, valueBuff);
  10803. if(*nameBuff == '_' && strcmp(name, "_nodeSize") != 0)
  10804. {
  10805. OwnedRoxieString fname(helper.getFileName());
  10806. throw MakeStringException(0, "Invalid name %s in user metadata for index %s (names beginning with underscore are reserved)", name.str(), fname.get());
  10807. }
  10808. if(!validateXMLTag(name.str()))
  10809. {
  10810. OwnedRoxieString fname(helper.getFileName());
  10811. throw MakeStringException(0, "Invalid name %s in user metadata for index %s (not legal XML element name)", name.str(), fname.get());
  10812. }
  10813. if(!metadata)
  10814. metadata.setown(createPTree("metadata", ipt_fast));
  10815. metadata->setProp(name.str(), value.str());
  10816. }
  10817. }
  10818. void buildLayoutMetadata(Owned<IPropertyTree> & metadata)
  10819. {
  10820. if(!metadata)
  10821. metadata.setown(createPTree("metadata", ipt_fast));
  10822. metadata->setProp("_record_ECL", helper.queryRecordECL());
  10823. setRtlFormat(*metadata, helper.queryDiskRecordSize());
  10824. }
  10825. public:
  10826. CRoxieServerIndexWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  10827. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, 0), helper(static_cast<IHThorIndexWriteArg &>(basehelper))
  10828. {
  10829. overwrite = ((helper.getFlags() & TIWoverwrite) != 0);
  10830. reccount = 0;
  10831. fileCrc = 0;
  10832. }
  10833. ~CRoxieServerIndexWriteActivity()
  10834. {
  10835. }
  10836. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10837. {
  10838. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  10839. resolve();
  10840. }
  10841. virtual void onExecute()
  10842. {
  10843. bool isVariable = helper.queryDiskRecordSize()->isVariableSize();
  10844. size32_t fileposSize = hasTrailingFileposition(helper.queryDiskRecordSize()->queryTypeInfo()) ? sizeof(offset_t) : 0;
  10845. size32_t maxDiskRecordSize;
  10846. if (isVariable)
  10847. {
  10848. if (helper.getFlags() & TIWmaxlength)
  10849. maxDiskRecordSize = helper.getMaxKeySize();
  10850. else
  10851. maxDiskRecordSize = KEYBUILD_MAXLENGTH; // Current default behaviour, could be improved in the future
  10852. }
  10853. else
  10854. maxDiskRecordSize = helper.queryDiskRecordSize()->getFixedSize()-fileposSize;
  10855. if (maxDiskRecordSize > KEYBUILD_MAXLENGTH)
  10856. throw MakeStringException(99, "Index maximum record length (%d) exceeds 32k internal limit", maxDiskRecordSize);
  10857. OwnedMalloc<char> rowBuffer(maxDiskRecordSize, true);
  10858. fileCrc = -1;
  10859. {
  10860. Owned<IFileIO> io;
  10861. try
  10862. {
  10863. io.setown(writer->queryFile()->open(IFOcreate));
  10864. }
  10865. catch(IException * e)
  10866. {
  10867. e->Release();
  10868. clearKeyStoreCache(false);
  10869. io.setown(writer->queryFile()->open(IFOcreate));
  10870. }
  10871. if(!io)
  10872. throw MakeStringException(errno, "Failed to create file %s for writing", filename.str());
  10873. Owned<IFileIOStream> out = createIOStream(io);
  10874. unsigned flags = COL_PREFIX | HTREE_FULLSORT_KEY;
  10875. if (helper.getFlags() & TIWrowcompress)
  10876. flags |= HTREE_COMPRESSED_KEY|HTREE_QUICK_COMPRESSED_KEY;
  10877. else if (!(helper.getFlags() & TIWnolzwcompress))
  10878. flags |= HTREE_COMPRESSED_KEY;
  10879. if (isVariable)
  10880. flags |= HTREE_VARSIZE;
  10881. Owned<IPropertyTree> metadata;
  10882. buildUserMetadata(metadata);
  10883. buildLayoutMetadata(metadata);
  10884. unsigned nodeSize = metadata ? metadata->getPropInt("_nodeSize", NODESIZE) : NODESIZE;
  10885. Owned<IKeyBuilder> builder = createKeyBuilder(out, flags, maxDiskRecordSize, nodeSize, helper.getKeyedSize(), 0, &helper, true, false);
  10886. class BcWrapper : implements IBlobCreator
  10887. {
  10888. IKeyBuilder *builder;
  10889. public:
  10890. BcWrapper(IKeyBuilder *_builder) : builder(_builder) {}
  10891. virtual unsigned __int64 createBlob(size32_t size, const void * ptr)
  10892. {
  10893. return builder->createBlob(size, (const char *) ptr);
  10894. }
  10895. } bc(builder);
  10896. // Loop thru the results
  10897. for (;;)
  10898. {
  10899. OwnedConstRoxieRow nextrec(inputStream->ungroupedNextRow());
  10900. if (!nextrec)
  10901. break;
  10902. try
  10903. {
  10904. unsigned __int64 fpos=0;
  10905. RtlStaticRowBuilder rowBuilder(rowBuffer, maxDiskRecordSize);
  10906. size32_t thisSize = helper.transform(rowBuilder, nextrec, &bc, fpos);
  10907. builder->processKeyData(rowBuffer, fpos, thisSize);
  10908. }
  10909. catch(IException * e)
  10910. {
  10911. throw makeWrappedException(e);
  10912. }
  10913. reccount++;
  10914. }
  10915. duplicateKeyCount = builder->getDuplicateCount();
  10916. cummulativeDuplicateKeyCount += duplicateKeyCount;
  10917. builder->finish(metadata, &fileCrc);
  10918. }
  10919. }
  10920. virtual void stop()
  10921. {
  10922. if (writer)
  10923. {
  10924. if (!aborted)
  10925. updateWorkUnitResult();
  10926. writer->finish(!aborted, this);
  10927. writer.clear();
  10928. }
  10929. CRoxieServerActivity::stop();
  10930. }
  10931. virtual void reset()
  10932. {
  10933. noteStatistic(StNumDuplicateKeys, cummulativeDuplicateKeyCount);
  10934. CRoxieServerActivity::reset();
  10935. writer.clear();
  10936. }
  10937. //interface IRoxiePublishCallback
  10938. virtual void setFileProperties(IFileDescriptor *desc) const
  10939. {
  10940. IPropertyTree &partProps = desc->queryPart(0)->queryProperties(); //properties of the first file part.
  10941. IPropertyTree &fileProps = desc->queryProperties(); // properties of the logical file
  10942. // Now publish to name services
  10943. StringBuffer dir,base;
  10944. offset_t indexFileSize = writer->queryFile()->size();
  10945. if(clusterHandler)
  10946. clusterHandler->splitPhysicalFilename(dir, base);
  10947. else
  10948. {
  10949. // Check filename is URL and get localpath, only actually necessary if force remote reads are are on
  10950. RemoteFilename rfn;
  10951. rfn.setRemotePath(filename);
  10952. StringBuffer localPath;
  10953. rfn.getLocalPath(localPath);
  10954. splitFilename(localPath, &dir, &dir, &base, &base);
  10955. }
  10956. desc->setDefaultDir(dir.str());
  10957. //properties of the first file part.
  10958. Owned<IPropertyTree> attrs;
  10959. if(clusterHandler)
  10960. attrs.setown(createPTree("Part", ipt_fast)); // clusterHandler is going to set attributes
  10961. else
  10962. {
  10963. // add cluster
  10964. StringBuffer mygroupname;
  10965. desc->setNumParts(1);
  10966. desc->setPartMask(base.str());
  10967. attrs.set(&desc->queryPart(0)->queryProperties());
  10968. }
  10969. attrs->setPropInt64("@size", indexFileSize);
  10970. CDateTime createTime, modifiedTime, accessedTime;
  10971. writer->queryFile()->getTime(&createTime, &modifiedTime, &accessedTime);
  10972. // round file time down to nearest sec. Nanosec accurancy is not preserved elsewhere and can lead to mismatch later.
  10973. unsigned hour, min, sec, nanosec;
  10974. modifiedTime.getTime(hour, min, sec, nanosec);
  10975. modifiedTime.setTime(hour, min, sec, 0);
  10976. StringBuffer timestr;
  10977. modifiedTime.getString(timestr);
  10978. if(timestr.length())
  10979. attrs->setProp("@modified", timestr.str());
  10980. if(clusterHandler)
  10981. clusterHandler->setDescriptorParts(desc, base.str(), attrs);
  10982. // properties of the logical file
  10983. IPropertyTree & properties = desc->queryProperties();
  10984. properties.setProp("@kind", "key");
  10985. properties.setPropInt64("@size", indexFileSize);
  10986. properties.setPropInt64("@recordCount", reccount);
  10987. properties.setPropInt64("@duplicateKeyCount", duplicateKeyCount);
  10988. WorkunitUpdate workUnit = ctx->updateWorkUnit();
  10989. if (workUnit)
  10990. {
  10991. properties.setProp("@owner", workUnit->queryUser());
  10992. properties.setProp("@workunit", workUnit->queryWuid());
  10993. properties.setProp("@job", workUnit->queryJobName());
  10994. }
  10995. char const * rececl = helper.queryRecordECL();
  10996. if(rececl && *rececl)
  10997. properties.setProp("ECL", rececl);
  10998. if (helper.getFlags() & TIWexpires)
  10999. setExpiryTime(properties, helper.getExpiryDays());
  11000. if (helper.getFlags() & TIWupdate)
  11001. {
  11002. unsigned eclCRC;
  11003. unsigned __int64 totalCRC;
  11004. helper.getUpdateCRCs(eclCRC, totalCRC);
  11005. properties.setPropInt("@eclCRC", eclCRC);
  11006. properties.setPropInt64("@totalCRC", totalCRC);
  11007. }
  11008. properties.setPropInt("@fileCrc", fileCrc);
  11009. properties.setPropInt("@formatCrc", helper.getFormatCrc());
  11010. // Legacy record layout info
  11011. void * layoutMetaBuff;
  11012. size32_t layoutMetaSize;
  11013. if(helper.getIndexLayout(layoutMetaSize, layoutMetaBuff))
  11014. {
  11015. properties.setPropBin("_record_layout", layoutMetaSize, layoutMetaBuff);
  11016. rtlFree(layoutMetaBuff);
  11017. }
  11018. // New record layout info
  11019. setRtlFormat(properties, helper.queryDiskRecordSize());
  11020. }
  11021. IUserDescriptor *queryUserDescriptor() const
  11022. {
  11023. IConstWorkUnit *workUnit = ctx->queryWorkUnit();
  11024. if (workUnit)
  11025. return workUnit->queryUserDescriptor();//ad-hoc mode
  11026. else
  11027. {
  11028. Owned<IRoxieDaliHelper> daliHelper = connectToDali(false);
  11029. if (daliHelper)
  11030. return daliHelper->queryUserDescriptor();//predeployed query mode
  11031. }
  11032. return NULL;
  11033. }
  11034. };
  11035. //=================================================================================
  11036. class CRoxieServerIndexWriteActivityFactory : public CRoxieServerMultiOutputFactory
  11037. {
  11038. public:
  11039. CRoxieServerIndexWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  11040. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  11041. {
  11042. setNumOutputs(0);
  11043. }
  11044. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  11045. {
  11046. return new CRoxieServerIndexWriteActivity(_ctx, this, _probeManager);
  11047. }
  11048. virtual bool isSink() const
  11049. {
  11050. return true;
  11051. }
  11052. virtual const StatisticsMapping &queryStatsMapping() const
  11053. {
  11054. return indexWriteStatistics; // Overridden by anyone that needs more
  11055. }
  11056. };
  11057. IRoxieServerActivityFactory *createRoxieServerIndexWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  11058. {
  11059. return new CRoxieServerIndexWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  11060. }
  11061. //=================================================================================
  11062. static inline void getLimitType(unsigned flags, bool & limitFail, bool & limitOnFail)
  11063. {
  11064. if((flags & JFmatchAbortLimitSkips) != 0)
  11065. {
  11066. limitFail = false;
  11067. limitOnFail = false;
  11068. }
  11069. else
  11070. {
  11071. limitOnFail = ((flags & JFonfail) != 0);
  11072. limitFail = !limitOnFail;
  11073. }
  11074. }
  11075. class CRoxieServerJoinActivity : public CRoxieServerTwoInputActivity
  11076. {
  11077. enum { JSfill, JSfillleft, JSfillright, JScollate, JScompare, JSleftonly, JSrightonly } state;
  11078. IHThorJoinArg &helper;
  11079. ICompare * collate;
  11080. ICompare * collateupper;
  11081. ThorActivityKind activityKind;
  11082. bool leftOuterJoin;
  11083. bool rightOuterJoin;
  11084. bool exclude;
  11085. bool limitFail;
  11086. bool limitOnFail;
  11087. bool forceSpill;
  11088. unsigned keepLimit;
  11089. unsigned joinLimit;
  11090. unsigned atmostLimit;
  11091. unsigned abortLimit;
  11092. unsigned atmostsTriggered;
  11093. bool betweenjoin;
  11094. OwnedRowArray right;
  11095. const void * left;
  11096. const void * pendingRight;
  11097. unsigned rightIndex;
  11098. unsigned joinCounter;
  11099. BoolArray matchedRight;
  11100. bool matchedLeft;
  11101. Owned<IException> failingLimit;
  11102. ConstPointerArray filteredRight;
  11103. Owned<IRHLimitedCompareHelper> limitedhelper;
  11104. OwnedConstRoxieRow defaultLeft;
  11105. OwnedConstRoxieRow defaultRight;
  11106. Owned<IEngineRowAllocator> defaultLeftAllocator;
  11107. Owned<IEngineRowAllocator> defaultRightAllocator;
  11108. Owned<IGroupedInput> sortedLeft;
  11109. Owned<IGroupedInput> groupedSortedRight;
  11110. bool cloneLeft;
  11111. void createDefaultLeft()
  11112. {
  11113. if (!defaultLeft)
  11114. {
  11115. if (!defaultLeftAllocator)
  11116. defaultLeftAllocator.setown(createRowAllocator(input->queryOutputMeta()));
  11117. RtlDynamicRowBuilder rowBuilder(defaultLeftAllocator);
  11118. size32_t thisSize = helper.createDefaultLeft(rowBuilder);
  11119. defaultLeft.setown(rowBuilder.finalizeRowClear(thisSize));
  11120. }
  11121. }
  11122. void createDefaultRight()
  11123. {
  11124. if (!defaultRight)
  11125. {
  11126. if (!defaultRightAllocator)
  11127. defaultRightAllocator.setown(createRowAllocator(input1->queryOutputMeta()));
  11128. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  11129. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  11130. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  11131. }
  11132. }
  11133. public:
  11134. CRoxieServerJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _forceSpill)
  11135. : CRoxieServerTwoInputActivity(_ctx, _factory, _probeManager), helper((IHThorJoinArg &)basehelper), forceSpill(_forceSpill)
  11136. {
  11137. // MORE - some of this should be done in factory
  11138. unsigned joinFlags = helper.getJoinFlags();
  11139. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  11140. rightOuterJoin = (joinFlags & JFrightouter) != 0;
  11141. exclude = (joinFlags & JFexclude) != 0;
  11142. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  11143. getLimitType(joinFlags, limitFail, limitOnFail);
  11144. if (joinFlags & JFslidingmatch)
  11145. {
  11146. betweenjoin = true;
  11147. collate = helper.queryCompareLeftRightLower();
  11148. collateupper = helper.queryCompareLeftRightUpper();
  11149. }
  11150. else
  11151. {
  11152. betweenjoin = false;
  11153. collate = collateupper = helper.queryCompareLeftRight();
  11154. }
  11155. rightIndex = 0;
  11156. joinCounter = 0;
  11157. state = JSfill;
  11158. matchedLeft = false;
  11159. joinLimit = 0;
  11160. keepLimit = 0; // wait until ctx available
  11161. atmostLimit = 0; // wait until ctx available
  11162. abortLimit = 0; // wait until ctx available
  11163. atmostsTriggered = 0;
  11164. assertex((joinFlags & (JFfirst | JFfirstleft | JFfirstright)) == 0);
  11165. left = NULL;
  11166. pendingRight = NULL;
  11167. activityKind = _factory->getKind();
  11168. }
  11169. virtual bool needsAllocator() const { return true; }
  11170. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11171. {
  11172. left = NULL;
  11173. rightIndex = 0;
  11174. joinCounter = 0;
  11175. state = JSfill;
  11176. matchedLeft = false;
  11177. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  11178. keepLimit = helper.getKeepLimit();
  11179. if (keepLimit == 0)
  11180. keepLimit = (unsigned)-1;
  11181. atmostsTriggered = 0;
  11182. atmostLimit = helper.getJoinLimit();
  11183. if(atmostLimit == 0)
  11184. atmostLimit = (unsigned)-1;
  11185. else
  11186. assertex(!rightOuterJoin && !betweenjoin);
  11187. abortLimit = helper.getMatchAbortLimit();
  11188. if (abortLimit == 0)
  11189. abortLimit = (unsigned)-1;
  11190. if (rightOuterJoin)
  11191. createDefaultLeft();
  11192. if ((leftOuterJoin && (activityKind==TAKjoin || activityKind==TAKjoinlight || activityKind==TAKdenormalizegroup)) || limitOnFail)
  11193. createDefaultRight();
  11194. bool isStable = (helper.getJoinFlags() & JFunstable) == 0;
  11195. RoxieSortAlgorithm sortAlgorithm;
  11196. if (forceSpill)
  11197. sortAlgorithm = isStable ? stableSpillingQuickSortAlgorithm : spillingQuickSortAlgorithm;
  11198. else
  11199. sortAlgorithm = isStable ? stableQuickSortAlgorithm : quickSortAlgorithm;
  11200. if (helper.isLeftAlreadySorted())
  11201. sortedLeft.setown(createDegroupedInputReader(inputStream));
  11202. else
  11203. sortedLeft.setown(createSortedInputReader(inputStream, createSortAlgorithm(sortAlgorithm, helper.queryCompareLeft(), ctx->queryRowManager(), input->queryOutputMeta(), ctx->queryCodeContext(), tempDirectory, activityId)));
  11204. ICompare *compareRight = helper.queryCompareRight();
  11205. if (helper.isRightAlreadySorted())
  11206. groupedSortedRight.setown(createGroupedInputReader(inputStream1, compareRight));
  11207. else
  11208. groupedSortedRight.setown(createSortedGroupedInputReader(inputStream1, compareRight, createSortAlgorithm(sortAlgorithm, compareRight, ctx->queryRowManager(), input1->queryOutputMeta(), ctx->queryCodeContext(), tempDirectory, activityId)));
  11209. if ((helper.getJoinFlags() & JFlimitedprefixjoin) && helper.getJoinLimit())
  11210. { //limited match join (s[1..n])
  11211. limitedhelper.setown(createRHLimitedCompareHelper());
  11212. limitedhelper->init( helper.getJoinLimit(), groupedSortedRight, collate, helper.queryPrefixCompare() );
  11213. }
  11214. }
  11215. virtual void reset()
  11216. {
  11217. if (atmostsTriggered)
  11218. noteStatistic(StNumAtmostTriggered, atmostsTriggered);
  11219. right.clear();
  11220. ReleaseClearRoxieRow(left);
  11221. ReleaseClearRoxieRow(pendingRight);
  11222. defaultRight.clear();
  11223. defaultLeft.clear();
  11224. sortedLeft.clear();
  11225. groupedSortedRight.clear();
  11226. CRoxieServerTwoInputActivity::reset();
  11227. }
  11228. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  11229. {
  11230. if (!idx && (helper.getJoinFlags() & JFparallel) != 0)
  11231. {
  11232. puller.setown(new CRoxieServerReadAheadInput(ctx, ctx->queryOptions().parallelJoinPreload));
  11233. puller->setInput(0, _sourceIdx, _in);
  11234. _in = puller;
  11235. _sourceIdx = 0;
  11236. }
  11237. CRoxieServerTwoInputActivity::setInput(idx, _sourceIdx, _in);
  11238. }
  11239. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  11240. {
  11241. if (idx==(unsigned)-1)
  11242. idx = 0;
  11243. return idx ? NULL : this;
  11244. }
  11245. void fillLeft()
  11246. {
  11247. matchedLeft = false;
  11248. left = sortedLeft->nextRow(); // NOTE: already degrouped by the IGroupedInput we attached
  11249. if (betweenjoin && left && pendingRight && (collate->docompare(left, pendingRight) >= 0))
  11250. fillRight();
  11251. if (limitedhelper && 0==rightIndex)
  11252. {
  11253. rightIndex = 0;
  11254. joinCounter = 0;
  11255. right.clear();
  11256. matchedRight.kill();
  11257. if (left)
  11258. {
  11259. limitedhelper->getGroup(right,left);
  11260. ForEachItemIn(idx, right)
  11261. matchedRight.append(false);
  11262. }
  11263. }
  11264. }
  11265. void fillRight()
  11266. {
  11267. if (limitedhelper)
  11268. return;
  11269. failingLimit.clear();
  11270. if(betweenjoin && left)
  11271. {
  11272. aindex_t start = 0;
  11273. while(right.isItem(start) && (collateupper->docompare(left, right.item(start)) > 0))
  11274. start++;
  11275. if(start>0)
  11276. right.clearPart(0, start);
  11277. }
  11278. else
  11279. right.clear();
  11280. rightIndex = 0;
  11281. joinCounter = 0;
  11282. unsigned groupCount = 0;
  11283. const void * next;
  11284. while(true)
  11285. {
  11286. if(pendingRight)
  11287. {
  11288. next = pendingRight;
  11289. pendingRight = NULL;
  11290. }
  11291. else
  11292. {
  11293. next = groupedSortedRight->nextRow();
  11294. }
  11295. if(!rightOuterJoin && next && (!left || (collateupper->docompare(left, next) > 0))) // if right is less than left, and not right outer, can skip group
  11296. {
  11297. while(next)
  11298. {
  11299. ReleaseClearRoxieRow(next);
  11300. next = groupedSortedRight->nextRow();
  11301. }
  11302. continue;
  11303. }
  11304. while(next)
  11305. {
  11306. if(groupCount==abortLimit)
  11307. {
  11308. if(limitFail)
  11309. failLimit();
  11310. if (ctx->queryDebugContext())
  11311. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  11312. if(limitOnFail)
  11313. {
  11314. assertex(!failingLimit);
  11315. try
  11316. {
  11317. failLimit();
  11318. }
  11319. catch(IException * except)
  11320. {
  11321. failingLimit.setown(except);
  11322. }
  11323. assertex(failingLimit != NULL);
  11324. }
  11325. right.append(next);
  11326. do
  11327. {
  11328. next = groupedSortedRight->nextRow();
  11329. ReleaseRoxieRow(next);
  11330. } while(next);
  11331. break;
  11332. }
  11333. else if(groupCount==atmostLimit)
  11334. {
  11335. atmostsTriggered++;
  11336. right.clear();
  11337. groupCount = 0;
  11338. while(next)
  11339. {
  11340. ReleaseRoxieRow(next);
  11341. next = groupedSortedRight->nextRow();
  11342. }
  11343. }
  11344. else
  11345. {
  11346. right.append(next);
  11347. groupCount++;
  11348. }
  11349. next = groupedSortedRight->nextRow();
  11350. }
  11351. // 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
  11352. if(betweenjoin && left)
  11353. {
  11354. pendingRight = groupedSortedRight->nextRow();
  11355. if(!pendingRight || (collate->docompare(left, pendingRight) < 0))
  11356. break;
  11357. }
  11358. else
  11359. break;
  11360. }
  11361. matchedRight.kill();
  11362. ForEachItemIn(idx, right)
  11363. matchedRight.append(false);
  11364. }
  11365. const void * joinRecords(const void * curLeft, const void * curRight, unsigned counter, unsigned flags)
  11366. {
  11367. if (cloneLeft)
  11368. {
  11369. LinkRoxieRow(curLeft);
  11370. return curLeft;
  11371. }
  11372. try
  11373. {
  11374. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11375. size32_t thisSize = helper.transform(rowBuilder, curLeft, curRight, counter, flags);
  11376. if (thisSize)
  11377. return rowBuilder.finalizeRowClear(thisSize);
  11378. else
  11379. return NULL;
  11380. }
  11381. catch (IException *E)
  11382. {
  11383. throw makeWrappedException(E);
  11384. }
  11385. }
  11386. const void * denormalizeRecords(const void * curLeft, ConstPointerArray & rows, unsigned flags)
  11387. {
  11388. try
  11389. {
  11390. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11391. unsigned numRows = rows.ordinality();
  11392. const void * right = numRows ? rows.item(0) : defaultRight.get();
  11393. if (numRows>0)
  11394. flags |= JTFmatchedright;
  11395. size32_t thisSize = helper.transform(rowBuilder, curLeft, right, numRows, (const void * *)rows.getArray(), flags);
  11396. if (thisSize)
  11397. return rowBuilder.finalizeRowClear(thisSize);
  11398. else
  11399. return NULL;
  11400. }
  11401. catch (IException *E)
  11402. {
  11403. throw makeWrappedException(E);
  11404. }
  11405. }
  11406. const void * joinException(const void * curLeft, IException * except)
  11407. {
  11408. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11409. size32_t thisSize = helper.onFailTransform(rowBuilder, curLeft, defaultRight, except, JTFmatchedleft);
  11410. return rowBuilder.finalizeRowClear(thisSize);
  11411. }
  11412. void failLimit()
  11413. {
  11414. helper.onMatchAbortLimitExceeded();
  11415. CommonXmlWriter xmlwrite(0);
  11416. if (input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  11417. {
  11418. input->queryOutputMeta()->toXML((byte *) left, xmlwrite);
  11419. }
  11420. throw MakeStringException(ROXIE_TOO_MANY_RESULTS, "More than %d match candidates in join %d for row %s", abortLimit, queryId(), xmlwrite.str());
  11421. }
  11422. virtual const void * nextRow()
  11423. {
  11424. ActivityTimer t(totalCycles, timeActivities);
  11425. for (;;)
  11426. {
  11427. switch (state)
  11428. {
  11429. case JSfill:
  11430. fillLeft();
  11431. state = JSfillright;
  11432. break;
  11433. case JSfillright:
  11434. fillRight();
  11435. state = JScollate;
  11436. break;
  11437. case JSfillleft:
  11438. fillLeft();
  11439. state = JScollate;
  11440. break;
  11441. case JScollate:
  11442. if (right.ordinality() == 0)
  11443. {
  11444. if (left == NULL)
  11445. return NULL;
  11446. state = JSleftonly;
  11447. }
  11448. else
  11449. {
  11450. if (!left)
  11451. state = JSrightonly;
  11452. else
  11453. {
  11454. int diff;
  11455. if(betweenjoin)
  11456. diff = ((collate->docompare(left, right.item(0)) < 0) ? -1 : ((collateupper->docompare(left, right.item(right.ordinality()-1)) > 0) ? +1 : 0));
  11457. else
  11458. diff = collate->docompare(left, right.item(0));
  11459. bool limitExceeded = right.ordinality()>abortLimit;
  11460. if (diff == 0)
  11461. {
  11462. if (limitExceeded)
  11463. {
  11464. const void * ret = NULL;
  11465. if(failingLimit)
  11466. ret = joinException(left, failingLimit);
  11467. ReleaseRoxieRow(left);
  11468. left = NULL;
  11469. state = JSfillleft;
  11470. ForEachItemIn(idx, right)
  11471. matchedRight.replace(true, idx);
  11472. if(ret)
  11473. {
  11474. processed++;
  11475. return ret;
  11476. }
  11477. }
  11478. else
  11479. {
  11480. state = JScompare;
  11481. joinLimit = keepLimit;
  11482. }
  11483. }
  11484. else if (diff < 0)
  11485. state = JSleftonly;
  11486. else if (limitExceeded)
  11487. {
  11488. // MORE - Roxie code seems to think there should be a destroyRowset(right) here....
  11489. state = JSfillright;
  11490. }
  11491. else
  11492. state = JSrightonly;
  11493. }
  11494. }
  11495. break;
  11496. case JSrightonly:
  11497. if (rightOuterJoin)
  11498. {
  11499. switch (activityKind)
  11500. {
  11501. case TAKjoin:
  11502. {
  11503. while (right.isItem(rightIndex))
  11504. {
  11505. if (!matchedRight.item(rightIndex))
  11506. {
  11507. const void * rhs = right.item(rightIndex++);
  11508. const void *ret = joinRecords(defaultLeft, rhs, 0, JTFmatchedright);
  11509. if (ret)
  11510. {
  11511. processed++;
  11512. return ret;
  11513. }
  11514. }
  11515. else
  11516. rightIndex++;
  11517. }
  11518. break;
  11519. }
  11520. //Probably excessive to implement the following, but possibly useful
  11521. case TAKdenormalize:
  11522. {
  11523. OwnedConstRoxieRow newLeft;
  11524. newLeft.set(defaultLeft);
  11525. unsigned rowSize = 0;
  11526. unsigned leftCount = 0;
  11527. while (right.isItem(rightIndex))
  11528. {
  11529. if (!matchedRight.item(rightIndex))
  11530. {
  11531. const void * rhs = right.item(rightIndex);
  11532. try
  11533. {
  11534. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11535. unsigned thisSize = helper.transform(rowBuilder, newLeft, rhs, ++leftCount, JTFmatchedright);
  11536. if (thisSize)
  11537. {
  11538. rowSize = thisSize;
  11539. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  11540. }
  11541. }
  11542. catch (IException *E)
  11543. {
  11544. throw makeWrappedException(E);
  11545. }
  11546. }
  11547. rightIndex++;
  11548. }
  11549. state = JSfillright;
  11550. if (rowSize)
  11551. {
  11552. processed++;
  11553. return newLeft.getClear();
  11554. }
  11555. break;
  11556. }
  11557. case TAKdenormalizegroup:
  11558. {
  11559. filteredRight.kill();
  11560. while (right.isItem(rightIndex))
  11561. {
  11562. if (!matchedRight.item(rightIndex))
  11563. filteredRight.append(right.item(rightIndex));
  11564. rightIndex++;
  11565. }
  11566. state = JSfillright;
  11567. if (filteredRight.ordinality())
  11568. {
  11569. const void * ret = denormalizeRecords(defaultLeft, filteredRight, 0);
  11570. filteredRight.kill();
  11571. if (ret)
  11572. {
  11573. processed++;
  11574. return ret;
  11575. }
  11576. }
  11577. break;
  11578. }
  11579. }
  11580. }
  11581. state = JSfillright;
  11582. break;
  11583. case JSleftonly:
  11584. {
  11585. const void * ret = NULL;
  11586. if (!matchedLeft && leftOuterJoin)
  11587. {
  11588. switch (activityKind)
  11589. {
  11590. case TAKjoin:
  11591. ret = joinRecords(left, defaultRight, 0, JTFmatchedleft);
  11592. break;
  11593. case TAKdenormalize:
  11594. ret = left;
  11595. left = NULL;
  11596. break;
  11597. case TAKdenormalizegroup:
  11598. filteredRight.kill();
  11599. ret = denormalizeRecords(left, filteredRight, JTFmatchedleft);
  11600. break;
  11601. }
  11602. }
  11603. ReleaseRoxieRow(left);
  11604. left = NULL;
  11605. state = JSfillleft;
  11606. if (ret)
  11607. {
  11608. processed++;
  11609. return ret;
  11610. }
  11611. break;
  11612. }
  11613. case JScompare:
  11614. if (joinLimit != 0)
  11615. {
  11616. switch (activityKind)
  11617. {
  11618. case TAKjoin:
  11619. {
  11620. while (right.isItem(rightIndex))
  11621. {
  11622. const void * rhs = right.item(rightIndex++);
  11623. if (helper.match(left, rhs))
  11624. {
  11625. matchedRight.replace(true, rightIndex-1);
  11626. matchedLeft = true;
  11627. if (!exclude)
  11628. {
  11629. const void *ret = joinRecords(left, rhs, ++joinCounter, JTFmatchedleft|JTFmatchedright);
  11630. if (ret)
  11631. {
  11632. processed++;
  11633. joinLimit--;
  11634. return ret;
  11635. }
  11636. }
  11637. }
  11638. }
  11639. break;
  11640. }
  11641. case TAKdenormalize:
  11642. {
  11643. OwnedConstRoxieRow newLeft;
  11644. newLeft.set(left);
  11645. unsigned rowSize = 0;
  11646. unsigned leftCount = 0;
  11647. while (right.isItem(rightIndex) && joinLimit)
  11648. {
  11649. try
  11650. {
  11651. const void * rhs = right.item(rightIndex++);
  11652. if (helper.match(left, rhs))
  11653. {
  11654. matchedRight.replace(true, rightIndex-1);
  11655. matchedLeft = true;
  11656. if (!exclude)
  11657. {
  11658. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11659. unsigned thisSize = helper.transform(rowBuilder, newLeft, rhs, ++leftCount, JTFmatchedleft|JTFmatchedright);
  11660. if (thisSize)
  11661. {
  11662. rowSize = thisSize;
  11663. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  11664. joinLimit--;
  11665. }
  11666. }
  11667. }
  11668. }
  11669. catch (IException *E)
  11670. {
  11671. throw makeWrappedException(E);
  11672. }
  11673. }
  11674. state = JSleftonly;
  11675. rightIndex = 0;
  11676. if (rowSize)
  11677. {
  11678. processed++;
  11679. return newLeft.getClear();
  11680. }
  11681. break;
  11682. }
  11683. case TAKdenormalizegroup:
  11684. {
  11685. filteredRight.kill();
  11686. while (right.isItem(rightIndex))
  11687. {
  11688. const void * rhs = right.item(rightIndex++);
  11689. if (helper.match(left, rhs))
  11690. {
  11691. matchedRight.replace(true, rightIndex-1);
  11692. filteredRight.append(rhs);
  11693. matchedLeft = true;
  11694. if (filteredRight.ordinality()==joinLimit)
  11695. break;
  11696. }
  11697. }
  11698. state = JSleftonly;
  11699. rightIndex = 0;
  11700. if (!exclude && filteredRight.ordinality())
  11701. {
  11702. const void * ret = denormalizeRecords(left, filteredRight, JTFmatchedleft);
  11703. filteredRight.kill();
  11704. if (ret)
  11705. {
  11706. processed++;
  11707. return ret;
  11708. }
  11709. }
  11710. break;
  11711. }
  11712. }
  11713. }
  11714. state = JSleftonly;
  11715. rightIndex = 0;
  11716. joinCounter = 0;
  11717. break;
  11718. }
  11719. }
  11720. }
  11721. };
  11722. class CRoxieServerJoinActivityFactory : public CRoxieServerActivityFactory
  11723. {
  11724. unsigned input2;
  11725. unsigned input2idx;
  11726. bool forceSpill;
  11727. public:
  11728. CRoxieServerJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  11729. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  11730. {
  11731. forceSpill = _graphNode.getPropBool("hint[@name='spill']/@value", _queryFactory.queryOptions().allSortsMaySpill);
  11732. input2 = 0;
  11733. input2idx = 0;
  11734. }
  11735. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  11736. {
  11737. return new CRoxieServerJoinActivity(_ctx, this, _probeManager, forceSpill);
  11738. }
  11739. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  11740. {
  11741. if (idx==1)
  11742. {
  11743. input2 = source;
  11744. input2idx = sourceidx;
  11745. }
  11746. else
  11747. CRoxieServerActivityFactory::setInput(idx, source, sourceidx);
  11748. }
  11749. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  11750. {
  11751. switch (idx)
  11752. {
  11753. case 1:
  11754. sourceidx = input2idx;
  11755. return input2;
  11756. case 0:
  11757. return CRoxieServerActivityFactory::getInput(idx, sourceidx);
  11758. default:
  11759. return (unsigned) -1;
  11760. }
  11761. }
  11762. virtual unsigned numInputs() const { return 2; }
  11763. virtual const StatisticsMapping &queryStatsMapping() const
  11764. {
  11765. return joinStatistics;
  11766. }
  11767. };
  11768. IRoxieServerActivityFactory *createRoxieServerJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  11769. {
  11770. return new CRoxieServerJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  11771. }
  11772. //=================================================================================
  11773. #define CONCAT_READAHEAD 1000
  11774. class CRoxieThreadedConcatReader : implements IRecordPullerCallback, public CInterface
  11775. {
  11776. public:
  11777. IMPLEMENT_IINTERFACE;
  11778. CRoxieThreadedConcatReader(InterruptableSemaphore &_ready, bool _grouped)
  11779. : puller(false), grouped(_grouped), atEog(true), ready(_ready), eof(false)
  11780. {
  11781. }
  11782. void start(unsigned parentExtractSize, const byte *parentExtract, bool paused, IRoxieSlaveContext *ctx)
  11783. {
  11784. space.reinit(CONCAT_READAHEAD);
  11785. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().concatPreload, false, ctx);
  11786. }
  11787. void stop()
  11788. {
  11789. space.interrupt();
  11790. puller.stop();
  11791. }
  11792. IFinalRoxieInput *queryInput() const
  11793. {
  11794. return puller.queryInput();
  11795. }
  11796. void reset()
  11797. {
  11798. puller.reset();
  11799. ForEachItemIn(idx, buffer)
  11800. ReleaseRoxieRow(buffer.item(idx));
  11801. buffer.clear();
  11802. eof = false;
  11803. atEog = true;
  11804. }
  11805. void setInput(unsigned _sourceIdx, IFinalRoxieInput *_in)
  11806. {
  11807. puller.setInput(this, _sourceIdx, _in);
  11808. }
  11809. void connectInputStreams(IRoxieSlaveContext *ctx, bool consumerOrdered)
  11810. {
  11811. puller.connectInputStreams(ctx, consumerOrdered);
  11812. }
  11813. virtual void processRow(const void *row)
  11814. {
  11815. buffer.enqueue(row);
  11816. ready.signal();
  11817. space.wait();
  11818. }
  11819. virtual void processGroup(const ConstPointerArray &rows)
  11820. {
  11821. // We use record-by-record input mode of the puller thread even in grouped mode.
  11822. throwUnexpected();
  11823. }
  11824. virtual void processEOG()
  11825. {
  11826. if (grouped)
  11827. processRow(NULL);
  11828. }
  11829. virtual void processDone()
  11830. {
  11831. processRow(NULL);
  11832. }
  11833. virtual bool fireException(IException *e)
  11834. {
  11835. // called from puller thread on failure
  11836. ready.interrupt(LINK(e));
  11837. space.interrupt(e);
  11838. return true;
  11839. }
  11840. bool peek(const void * &row, bool &anyActive)
  11841. {
  11842. if (!eof)
  11843. {
  11844. if (buffer.ordinality())
  11845. {
  11846. space.signal();
  11847. row = buffer.dequeue();
  11848. if (row==NULL)
  11849. {
  11850. if (atEog)
  11851. {
  11852. eof = true;
  11853. return false;
  11854. }
  11855. else
  11856. atEog = true;
  11857. }
  11858. else if (grouped)
  11859. atEog = false;
  11860. return true;
  11861. }
  11862. anyActive = true;
  11863. }
  11864. return false;
  11865. }
  11866. protected:
  11867. RecordPullerThread puller;
  11868. InterruptableSemaphore space;
  11869. InterruptableSemaphore &ready;
  11870. SafeQueueOf<const void, true> buffer;
  11871. bool atEog;
  11872. bool eof;
  11873. bool grouped;
  11874. };
  11875. typedef CopyReferenceArrayOf<CRoxieThreadedConcatReader> ReaderArray;
  11876. class CRoxieServerThreadedConcatActivity : public CRoxieServerActivity
  11877. {
  11878. InterruptableSemaphore ready;
  11879. ReaderArray pullers;
  11880. unsigned numInputs;
  11881. unsigned nextPuller; // for round robin
  11882. unsigned readyPending;
  11883. bool eof;
  11884. bool inGroup;
  11885. bool grouped;
  11886. public:
  11887. CRoxieServerThreadedConcatActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _grouped, unsigned _numInputs)
  11888. : CRoxieServerActivity(_ctx, _factory, _probeManager), grouped(_grouped)
  11889. {
  11890. numInputs = _numInputs;
  11891. eof = (numInputs==0);
  11892. inGroup = false;
  11893. nextPuller = 0;
  11894. readyPending = 0;
  11895. for (unsigned i = 0; i < numInputs; i++)
  11896. pullers.append(*new CRoxieThreadedConcatReader(ready, _grouped));
  11897. }
  11898. ~CRoxieServerThreadedConcatActivity()
  11899. {
  11900. ForEachItemIn(idx, pullers)
  11901. delete &pullers.item(idx);
  11902. }
  11903. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11904. {
  11905. eof = (numInputs==0);
  11906. inGroup = false;
  11907. nextPuller = 0;
  11908. readyPending = 0;
  11909. ready.reinit();
  11910. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  11911. ForEachItemIn(idx, pullers)
  11912. {
  11913. pullers.item(idx).start(parentExtractSize, parentExtract, paused, ctx);
  11914. // NOTE - it is ok to start the thread running while parts of the subgraph are still being started, since everything
  11915. // in the part of the subgraph that the thread uses has been started.
  11916. // Note that splitters are supposed to cope with being used when only some outputs have been started.
  11917. }
  11918. }
  11919. virtual void stop()
  11920. {
  11921. ready.interrupt();
  11922. ForEachItemIn(idx, pullers)
  11923. pullers.item(idx).stop();
  11924. CRoxieServerActivity::stop();
  11925. }
  11926. virtual unsigned __int64 queryLocalCycles() const
  11927. {
  11928. return 0;
  11929. }
  11930. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  11931. {
  11932. if (pullers.isItem(idx))
  11933. return pullers.item(idx).queryInput();
  11934. else
  11935. return NULL;
  11936. }
  11937. virtual void reset()
  11938. {
  11939. CRoxieServerActivity::reset();
  11940. ForEachItemIn(idx, pullers)
  11941. pullers.item(idx).reset();
  11942. eof = false;
  11943. inGroup = false;
  11944. nextPuller = 0;
  11945. readyPending = 0;
  11946. }
  11947. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  11948. {
  11949. if (pullers.isItem(idx))
  11950. pullers.item(idx).setInput(_sourceIdx, _in);
  11951. else
  11952. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
  11953. }
  11954. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  11955. {
  11956. ForEachItemIn(i, pullers)
  11957. pullers.item(i).connectInputStreams(ctx, consumerOrdered);
  11958. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, nullptr, consumerOrdered, nullptr); // No input actually connected
  11959. }
  11960. virtual const void * nextRow()
  11961. {
  11962. ActivityTimer t(totalCycles, timeActivities);
  11963. if (eof)
  11964. return NULL;
  11965. for (;;)
  11966. {
  11967. if (readyPending && !inGroup)
  11968. {
  11969. if (readyPending > 1)
  11970. ready.signal(readyPending-1);
  11971. readyPending = 0;
  11972. }
  11973. else
  11974. ready.wait();
  11975. bool anyActive = false;
  11976. ForEachItemIn(unused_index, pullers)
  11977. {
  11978. // NOTE - we round robin not just because it's more efficient, but because it ensures the preservation of grouping information
  11979. const void *ret;
  11980. bool fetched = pullers.item(nextPuller).peek(ret, anyActive);
  11981. if (fetched)
  11982. {
  11983. inGroup = (ret != NULL);
  11984. return ret;
  11985. }
  11986. if (inGroup && grouped)
  11987. {
  11988. // Some other puller has data, but we can't consume it until the group we are reading is complete.
  11989. readyPending++;
  11990. anyActive = true;
  11991. break;
  11992. }
  11993. nextPuller++;
  11994. if (nextPuller==pullers.ordinality())
  11995. nextPuller = 0;
  11996. }
  11997. if (!anyActive)
  11998. break;
  11999. // A ready signal without anything being ready means someone reached end-of-file.
  12000. }
  12001. eof = true;
  12002. return NULL;
  12003. }
  12004. };
  12005. class CRoxieServerOrderedConcatActivity : public CRoxieServerMultiInputActivity
  12006. {
  12007. IEngineRowStream *curStream;
  12008. bool eogSeen;
  12009. bool anyThisGroup;
  12010. bool grouped;
  12011. unsigned streamIdx;
  12012. public:
  12013. CRoxieServerOrderedConcatActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _grouped, unsigned _numInputs)
  12014. : CRoxieServerMultiInputActivity(_ctx, _factory, _probeManager, _numInputs)
  12015. {
  12016. eogSeen = false;
  12017. anyThisGroup = false;
  12018. grouped = _grouped;
  12019. streamIdx = 0;
  12020. curStream = NULL;
  12021. }
  12022. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12023. {
  12024. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  12025. streamIdx = 0;
  12026. curStream = streamArray[streamIdx];
  12027. eogSeen = false;
  12028. anyThisGroup = false;
  12029. }
  12030. virtual const void * nextRow()
  12031. {
  12032. ActivityTimer t(totalCycles, timeActivities);
  12033. if (!curStream)
  12034. return NULL; // eof
  12035. const void * next = curStream->nextRow();
  12036. if (next)
  12037. {
  12038. anyThisGroup = true;
  12039. eogSeen = false;
  12040. processed++;
  12041. return next;
  12042. }
  12043. else if (!eogSeen)
  12044. {
  12045. eogSeen = true;
  12046. if (grouped)
  12047. {
  12048. if (anyThisGroup)
  12049. {
  12050. anyThisGroup = false;
  12051. return NULL;
  12052. }
  12053. else
  12054. return nextRow();
  12055. }
  12056. else
  12057. return nextRow();
  12058. }
  12059. else if (streamIdx < numStreams-1)
  12060. {
  12061. streamIdx++;
  12062. curStream = streamArray[streamIdx];
  12063. eogSeen = false;
  12064. return nextRow();
  12065. }
  12066. else
  12067. {
  12068. curStream = NULL;
  12069. return NULL;
  12070. }
  12071. }
  12072. };
  12073. class CRoxieServerConcatActivityFactory : public CRoxieServerMultiInputFactory
  12074. {
  12075. bool ordered;
  12076. bool grouped;
  12077. public:
  12078. CRoxieServerConcatActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12079. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12080. {
  12081. Owned <IHThorFunnelArg> helper = (IHThorFunnelArg *) helperFactory();
  12082. ordered = helper->isOrdered();
  12083. grouped = helper->queryOutputMeta()->isGrouped();
  12084. }
  12085. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12086. {
  12087. if (ordered || (_probeManager && _probeManager->queryDebugManager()))
  12088. return new CRoxieServerOrderedConcatActivity(_ctx, this, _probeManager, grouped, numInputs());
  12089. else
  12090. return new CRoxieServerThreadedConcatActivity(_ctx, this, _probeManager, grouped, numInputs());
  12091. }
  12092. };
  12093. IRoxieServerActivityFactory *createRoxieServerConcatActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12094. {
  12095. return new CRoxieServerConcatActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12096. }
  12097. //=================================================================================
  12098. class CRoxieServerNonEmptyActivity : public CRoxieServerMultiInputBaseActivity
  12099. {
  12100. IEngineRowStream* selectedStream;
  12101. unsigned savedParentExtractSize;
  12102. const byte * savedParentExtract;
  12103. bool foundInput;
  12104. bool unusedStopped;
  12105. public:
  12106. CRoxieServerNonEmptyActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  12107. : CRoxieServerMultiInputBaseActivity(_ctx, _factory, _probeManager, _numInputs)
  12108. {
  12109. foundInput = false;
  12110. unusedStopped = false;
  12111. selectedStream = NULL;
  12112. savedParentExtractSize = 0;;
  12113. savedParentExtract = NULL;
  12114. }
  12115. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12116. {
  12117. //Don't start the inputs yet so we can short-circuit...
  12118. CRoxieServerMultiInputBaseActivity::start(parentExtractSize, parentExtract, paused);
  12119. savedParentExtractSize = parentExtractSize;
  12120. savedParentExtract = parentExtract;
  12121. }
  12122. virtual void stop()
  12123. {
  12124. if (unusedStopped)
  12125. {
  12126. if (selectedStream)
  12127. selectedStream->stop();
  12128. }
  12129. else
  12130. {
  12131. //May possibly call stop too many times if input->start() throws an exception (e.g. due to a dependency)
  12132. for (unsigned i = 0; i < numStreams; i++)
  12133. streamArray[i]->stop();
  12134. }
  12135. CRoxieServerMultiInputBaseActivity::stop();
  12136. }
  12137. virtual void reset()
  12138. {
  12139. CRoxieServerMultiInputBaseActivity::reset();
  12140. foundInput = false;
  12141. unusedStopped = false;
  12142. selectedStream = NULL;
  12143. }
  12144. virtual unsigned __int64 queryLocalCycles() const
  12145. {
  12146. return 0; // Can't easily calculate anything reliable but local processing is negligible
  12147. }
  12148. virtual const void * nextRow()
  12149. {
  12150. ActivityTimer t(totalCycles, timeActivities);
  12151. if (!foundInput)
  12152. {
  12153. foundInput = true;
  12154. assertex(numInputs == numStreams); // If this ceases to be true we will need to rethink some of this
  12155. //If we get an exception in this loop then stop() will stop any started inputs
  12156. for (unsigned i=0; i < numStreams; i++)
  12157. {
  12158. selectedStream = streamArray[i];
  12159. inputArray[i]->start(savedParentExtractSize, savedParentExtract, false); // Assumes 1:1 mapping streams to inputs
  12160. startJunction(junctionArray[i]);
  12161. const void * next = selectedStream->nextRow();
  12162. if (next)
  12163. {
  12164. //Found a row so stop remaining
  12165. for (unsigned j=i+1; j < numInputs; j++)
  12166. streamArray[j]->stop();
  12167. unusedStopped = true;
  12168. processed++;
  12169. return next;
  12170. }
  12171. selectedStream->stop();
  12172. }
  12173. unusedStopped = true;
  12174. selectedStream = NULL;
  12175. return NULL;
  12176. }
  12177. if (!selectedStream)
  12178. return NULL;
  12179. const void * next = selectedStream->nextRow();
  12180. if (next)
  12181. processed++;
  12182. return next;
  12183. }
  12184. };
  12185. class CRoxieServerNonEmptyActivityFactory : public CRoxieServerMultiInputFactory
  12186. {
  12187. public:
  12188. CRoxieServerNonEmptyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12189. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12190. {
  12191. }
  12192. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12193. {
  12194. return new CRoxieServerNonEmptyActivity(_ctx, this, _probeManager, numInputs());
  12195. }
  12196. };
  12197. IRoxieServerActivityFactory *createRoxieServerNonEmptyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12198. {
  12199. return new CRoxieServerNonEmptyActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12200. }
  12201. //=================================================================================
  12202. class SingleNodeActivityContext : public IThorActivityContext
  12203. {
  12204. public:
  12205. SingleNodeActivityContext(unsigned _numStrands, unsigned _curStrand) : strands(_numStrands), curStrand(_curStrand) { assertex(curStrand < strands); }
  12206. virtual bool isLocal() const override { return false; }
  12207. virtual unsigned numSlaves() const override { return 1; }
  12208. virtual unsigned numStrands() const override { return strands; }
  12209. virtual unsigned querySlave() const override { return 0; }
  12210. virtual unsigned queryStrand() const override { return curStrand; }
  12211. protected:
  12212. unsigned strands;
  12213. unsigned curStrand;
  12214. };
  12215. class CRoxieServerExternalActivity : public CRoxieServerMultiInputActivity
  12216. {
  12217. Owned<IRowStream> rows;
  12218. SingleNodeActivityContext activityContext;
  12219. public:
  12220. CRoxieServerExternalActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  12221. : CRoxieServerMultiInputActivity(_ctx, _factory, _probeManager, _numInputs), activityContext(1, 0)
  12222. {
  12223. }
  12224. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  12225. {
  12226. Owned<IStrandJunction> junction = CRoxieServerMultiInputActivity::getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
  12227. associateInputsWithHelper();
  12228. return junction.getClear();
  12229. }
  12230. virtual void connectInputStreams(bool consumerOrdered)
  12231. {
  12232. CRoxieServerMultiInputActivity::connectInputStreams(consumerOrdered);
  12233. associateInputsWithHelper();
  12234. }
  12235. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12236. {
  12237. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  12238. if (factory->getKind() != TAKexternalsink)
  12239. {
  12240. IHThorExternalArg & helper = static_cast<IHThorExternalArg &>(basehelper);
  12241. rows.setown(helper.createOutput(&activityContext));
  12242. }
  12243. }
  12244. virtual void stop()
  12245. {
  12246. if (rows)
  12247. {
  12248. rows->stop();
  12249. rows.clear();
  12250. }
  12251. CRoxieServerMultiInputBaseActivity::stop();
  12252. }
  12253. virtual void reset()
  12254. {
  12255. rows.clear();
  12256. }
  12257. virtual const void * nextRow()
  12258. {
  12259. ActivityTimer t(totalCycles, timeActivities);
  12260. assertex(rows);
  12261. const void * next = rows->nextRow();
  12262. if (next)
  12263. processed++;
  12264. return next;
  12265. }
  12266. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  12267. {
  12268. try
  12269. {
  12270. start(parentExtractSize, parentExtract, false);
  12271. assertex(!rows);
  12272. IHThorExternalArg & helper = static_cast<IHThorExternalArg &>(basehelper);
  12273. helper.execute(&activityContext);
  12274. stop();
  12275. }
  12276. catch (IException * E)
  12277. {
  12278. ctx->notifyAbort(E);
  12279. abort();
  12280. throw;
  12281. }
  12282. }
  12283. protected:
  12284. void associateInputsWithHelper()
  12285. {
  12286. IHThorExternalArg & helper = static_cast<IHThorExternalArg &>(basehelper);
  12287. for (unsigned i = 0; i < numInputs; i++)
  12288. helper.setInput(i, streamArray[i]);
  12289. }
  12290. };
  12291. class CRoxieServerExternalActivityFactory : public CRoxieServerMultiInputFactory
  12292. {
  12293. bool isRoot;
  12294. public:
  12295. CRoxieServerExternalActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  12296. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  12297. {
  12298. }
  12299. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12300. {
  12301. return new CRoxieServerExternalActivity(_ctx, this, _probeManager, numInputs());
  12302. }
  12303. virtual bool isSink() const
  12304. {
  12305. return (kind == TAKexternalsink) && isRoot;
  12306. }
  12307. };
  12308. IRoxieServerActivityFactory *createRoxieServerExternalActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  12309. {
  12310. return new CRoxieServerExternalActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  12311. }
  12312. //=================================================================================
  12313. class CRoxieServerMergeActivity : public CRoxieServerMultiInputActivity
  12314. {
  12315. IHThorMergeArg &helper;
  12316. unsigned *mergeheap;
  12317. unsigned activeInputs;
  12318. const void **pending;
  12319. bool first;
  12320. ICompare *compare;
  12321. bool dedup;
  12322. void permute()
  12323. {
  12324. assertex(activeInputs == 0);
  12325. for(unsigned i = 0; i < numStreams; i++)
  12326. if(pullInput(i))
  12327. mergeheap[activeInputs++] = i;
  12328. // the tree structure: element p has children p*2+1 and p*2+2, or element c has parent (unsigned)(c-1)/2
  12329. // the heap property: no element should be smaller than its parent
  12330. // the dedup variant: if(dedup), the top of the heap should also not be equal to either child
  12331. // 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
  12332. if (activeInputs >= 2)
  12333. for(unsigned p = (activeInputs-2)/2; p > 0; --p)
  12334. siftDown(p);
  12335. if(dedup)
  12336. siftDownDedupTop();
  12337. else
  12338. siftDown(0);
  12339. }
  12340. void readNext()
  12341. {
  12342. if(!pullInput(mergeheap[0]))
  12343. if(!promote(0))
  12344. return;
  12345. // we have changed the element at the top of the heap, so need to sift it down to maintain the heap property
  12346. if(dedup)
  12347. siftDownDedupTop();
  12348. else
  12349. siftDown(0);
  12350. }
  12351. bool pullInput(unsigned i)
  12352. {
  12353. const void *next = streamArray[i]->ungroupedNextRow();
  12354. pending[i] = next;
  12355. return (next != NULL);
  12356. }
  12357. bool promote(unsigned p)
  12358. {
  12359. activeInputs--;
  12360. if(activeInputs == p)
  12361. return false;
  12362. mergeheap[p] = mergeheap[activeInputs];
  12363. return true;
  12364. }
  12365. bool siftDown(unsigned p)
  12366. {
  12367. // assuming that all descendants of p form a heap, sift p down to its correct position, and so include it in the heap
  12368. bool nochange = true;
  12369. while(1)
  12370. {
  12371. unsigned c = p*2 + 1;
  12372. if(c >= activeInputs)
  12373. return nochange;
  12374. if(c+1 < activeInputs)
  12375. {
  12376. int childcmp = BuffCompare(c+1, c);
  12377. if((childcmp < 0) || ((childcmp == 0) && (mergeheap[c+1] < mergeheap[c])))
  12378. ++c;
  12379. }
  12380. int cmp = BuffCompare(c, p);
  12381. if((cmp > 0) || ((cmp == 0) && (mergeheap[c] > mergeheap[p])))
  12382. return nochange;
  12383. nochange = false;
  12384. unsigned r = mergeheap[c];
  12385. mergeheap[c] = mergeheap[p];
  12386. mergeheap[p] = r;
  12387. p = c;
  12388. }
  12389. }
  12390. void siftDownDedupTop()
  12391. {
  12392. // same as siftDown(0), except that it also ensures that the top of the heap is not equal to either of its children
  12393. if(activeInputs < 2)
  12394. return;
  12395. unsigned c = 1;
  12396. int childcmp = 1;
  12397. if(activeInputs >= 3)
  12398. {
  12399. childcmp = BuffCompare(2, 1);
  12400. if(childcmp < 0)
  12401. c = 2;
  12402. }
  12403. int cmp = BuffCompare(c, 0);
  12404. if(cmp > 0)
  12405. return;
  12406. // the following loop ensures the correct property holds on the smaller branch, and that childcmp==0 iff the top matches the other branch
  12407. while(cmp <= 0)
  12408. {
  12409. if(cmp == 0)
  12410. {
  12411. if(mergeheap[c] < mergeheap[0])
  12412. {
  12413. unsigned r = mergeheap[c];
  12414. mergeheap[c] = mergeheap[0];
  12415. mergeheap[0] = r;
  12416. }
  12417. ReleaseClearRoxieRow(pending[mergeheap[c]]);
  12418. if(!pullInput(mergeheap[c]))
  12419. if(!promote(c))
  12420. break;
  12421. siftDown(c);
  12422. }
  12423. else
  12424. {
  12425. unsigned r = mergeheap[c];
  12426. mergeheap[c] = mergeheap[0];
  12427. mergeheap[0] = r;
  12428. if(siftDown(c))
  12429. break;
  12430. }
  12431. cmp = BuffCompare(c, 0);
  12432. }
  12433. // the following loop ensures the uniqueness property holds on the other branch too
  12434. c = 3-c;
  12435. if(activeInputs <= c)
  12436. return;
  12437. while(childcmp == 0)
  12438. {
  12439. if(mergeheap[c] < mergeheap[0])
  12440. {
  12441. unsigned r = mergeheap[c];
  12442. mergeheap[c] = mergeheap[0];
  12443. mergeheap[0] = r;
  12444. }
  12445. ReleaseClearRoxieRow(pending[mergeheap[c]]);
  12446. if(!pullInput(mergeheap[c]))
  12447. if(!promote(c))
  12448. break;
  12449. siftDown(c);
  12450. childcmp = BuffCompare(c, 0);
  12451. }
  12452. }
  12453. inline int BuffCompare(unsigned a, unsigned b)
  12454. {
  12455. return compare->docompare(pending[mergeheap[a]], pending[mergeheap[b]]);
  12456. }
  12457. public:
  12458. CRoxieServerMergeActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  12459. : CRoxieServerMultiInputActivity(_ctx, _factory, _probeManager, _numInputs), helper((IHThorMergeArg &)basehelper)
  12460. {
  12461. activeInputs = 0;
  12462. first = true;
  12463. mergeheap = new unsigned[numInputs];
  12464. pending = new const void *[numStreams];
  12465. compare = helper.queryCompare();
  12466. dedup = helper.dedup();
  12467. for (unsigned i = 0; i < numStreams; i++)
  12468. pending[i] = NULL;
  12469. }
  12470. ~CRoxieServerMergeActivity()
  12471. {
  12472. delete [] mergeheap;
  12473. delete [] pending;
  12474. }
  12475. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12476. {
  12477. activeInputs = 0;
  12478. first = true;
  12479. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  12480. }
  12481. virtual void reset()
  12482. {
  12483. for (unsigned i = 0; i < numStreams; i++)
  12484. ReleaseClearRoxieRow(pending[i]);
  12485. CRoxieServerMultiInputActivity::reset();
  12486. }
  12487. virtual const void * nextRow()
  12488. {
  12489. ActivityTimer t(totalCycles, timeActivities);
  12490. if (first)
  12491. {
  12492. permute();
  12493. first = false;
  12494. }
  12495. if (activeInputs)
  12496. {
  12497. const void *next = pending[mergeheap[0]];
  12498. readNext();
  12499. if (next)
  12500. processed++;
  12501. return next;
  12502. }
  12503. else
  12504. return NULL;
  12505. }
  12506. };
  12507. class CRoxieServerMergeActivityFactory : public CRoxieServerMultiInputFactory
  12508. {
  12509. public:
  12510. CRoxieServerMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12511. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12512. {
  12513. }
  12514. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12515. {
  12516. return new CRoxieServerMergeActivity(_ctx, this, _probeManager, numInputs());
  12517. }
  12518. };
  12519. IRoxieServerActivityFactory *createRoxieServerMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12520. {
  12521. return new CRoxieServerMergeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12522. }
  12523. //=================================================================================
  12524. class CRoxieServerRegroupActivity : public CRoxieServerMultiInputActivity
  12525. {
  12526. IHThorRegroupArg &helper;
  12527. unsigned streamIndex;
  12528. bool eof;
  12529. unsigned __int64 numProcessedLastGroup;
  12530. public:
  12531. CRoxieServerRegroupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  12532. : CRoxieServerMultiInputActivity(_ctx, _factory, _probeManager, _numInputs), helper((IHThorRegroupArg &)basehelper)
  12533. {
  12534. streamIndex = 0;
  12535. eof = false;
  12536. numProcessedLastGroup = 0;
  12537. }
  12538. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12539. {
  12540. streamIndex = 0;
  12541. eof = false;
  12542. numProcessedLastGroup = processed;
  12543. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  12544. }
  12545. const void * nextFromInputs()
  12546. {
  12547. unsigned initialStream = streamIndex;
  12548. while (streamIndex < numStreams)
  12549. {
  12550. const void * next = streamArray[streamIndex]->nextRow();
  12551. if (next)
  12552. {
  12553. if ((streamIndex != initialStream) && (streamIndex != initialStream+1))
  12554. {
  12555. ReleaseRoxieRow(next);
  12556. throw MakeStringException(ROXIE_MISMATCH_GROUP_ERROR, "Mismatched groups supplied to Regroup (%d)", factory->queryId());
  12557. }
  12558. return next;
  12559. }
  12560. streamIndex++;
  12561. }
  12562. if ((initialStream != 0) && (initialStream+1 != numStreams))
  12563. throw MakeStringException(ROXIE_MISMATCH_GROUP_ERROR, "Mismatched groups supplied to Regroup (%d)", factory->queryId());
  12564. streamIndex = 0;
  12565. return NULL;
  12566. }
  12567. virtual const void * nextRow()
  12568. {
  12569. ActivityTimer t(totalCycles, timeActivities);
  12570. if (eof)
  12571. return NULL;
  12572. const void * ret = nextFromInputs();
  12573. if (ret)
  12574. {
  12575. processed++;
  12576. return ret;
  12577. }
  12578. if (numProcessedLastGroup != processed)
  12579. {
  12580. numProcessedLastGroup = processed;
  12581. return NULL;
  12582. }
  12583. eof = true;
  12584. return NULL;
  12585. }
  12586. };
  12587. class CRoxieServerRegroupActivityFactory : public CRoxieServerMultiInputFactory
  12588. {
  12589. public:
  12590. CRoxieServerRegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12591. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12592. {
  12593. }
  12594. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12595. {
  12596. return new CRoxieServerRegroupActivity(_ctx, this, _probeManager, numInputs());
  12597. }
  12598. };
  12599. IRoxieServerActivityFactory *createRoxieServerRegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12600. {
  12601. return new CRoxieServerRegroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12602. }
  12603. //=================================================================================
  12604. class CRoxieServerCombineActivity : public CRoxieServerMultiInputActivity
  12605. {
  12606. IHThorCombineArg &helper;
  12607. unsigned __int64 numProcessedLastGroup;
  12608. public:
  12609. CRoxieServerCombineActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  12610. : CRoxieServerMultiInputActivity(_ctx, _factory, _probeManager, _numInputs), helper((IHThorCombineArg &)basehelper)
  12611. {
  12612. numProcessedLastGroup = 0;
  12613. }
  12614. ~CRoxieServerCombineActivity()
  12615. {
  12616. }
  12617. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12618. {
  12619. numProcessedLastGroup = processed;
  12620. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  12621. }
  12622. void nextInputs(ConstPointerArray & out)
  12623. {
  12624. for (unsigned i=0; i < numStreams; i++)
  12625. {
  12626. const void * next = streamArray[i]->nextRow();
  12627. if (next)
  12628. out.append(next);
  12629. }
  12630. }
  12631. virtual bool needsAllocator() const { return true; }
  12632. virtual const void * nextRow()
  12633. {
  12634. ActivityTimer t(totalCycles, timeActivities);
  12635. for (;;)
  12636. {
  12637. ConstPointerArray group;
  12638. nextInputs(group);
  12639. if ((group.ordinality() == 0) && (numProcessedLastGroup == processed))
  12640. nextInputs(group);
  12641. if (group.ordinality() == 0)
  12642. {
  12643. numProcessedLastGroup = processed;
  12644. return NULL;
  12645. }
  12646. else if (group.ordinality() != numInputs)
  12647. {
  12648. ReleaseRoxieRows(group);
  12649. throw MakeStringException(ROXIE_MISMATCH_GROUP_ERROR, "Mismatched group input for Combine Activity(%d)", factory->queryId());
  12650. }
  12651. try
  12652. {
  12653. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12654. size32_t outSize = helper.transform(rowBuilder, group.ordinality(), group.getArray());
  12655. ReleaseRoxieRows(group);
  12656. if (outSize)
  12657. {
  12658. processed++;
  12659. return rowBuilder.finalizeRowClear(outSize);
  12660. }
  12661. }
  12662. catch (IException *E)
  12663. {
  12664. ReleaseRoxieRows(group);
  12665. throw makeWrappedException(E);
  12666. }
  12667. }
  12668. }
  12669. };
  12670. class CRoxieServerCombineActivityFactory : public CRoxieServerMultiInputFactory
  12671. {
  12672. public:
  12673. CRoxieServerCombineActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12674. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12675. {
  12676. }
  12677. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12678. {
  12679. return new CRoxieServerCombineActivity(_ctx, this, _probeManager, numInputs());
  12680. }
  12681. };
  12682. IRoxieServerActivityFactory *createRoxieServerCombineActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12683. {
  12684. return new CRoxieServerCombineActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12685. }
  12686. //=================================================================================
  12687. class CRoxieServerCombineGroupActivity : public CRoxieServerTwoInputActivity
  12688. {
  12689. IHThorCombineGroupArg &helper;
  12690. unsigned __int64 numProcessedLastGroup;
  12691. public:
  12692. CRoxieServerCombineGroupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  12693. : CRoxieServerTwoInputActivity(_ctx, _factory, _probeManager), helper((IHThorCombineGroupArg &)basehelper)
  12694. {
  12695. numProcessedLastGroup = 0;
  12696. }
  12697. ~CRoxieServerCombineGroupActivity()
  12698. {
  12699. }
  12700. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12701. {
  12702. numProcessedLastGroup = processed;
  12703. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  12704. }
  12705. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  12706. {
  12707. if (idx==(unsigned)-1)
  12708. idx = 0;
  12709. return idx ? NULL : this;
  12710. }
  12711. virtual bool needsAllocator() const { return true; }
  12712. virtual const void * nextRow()
  12713. {
  12714. ActivityTimer t(totalCycles, timeActivities);
  12715. for (;;)
  12716. {
  12717. const void * left = inputStream->nextRow();
  12718. if (!left && (numProcessedLastGroup == processed))
  12719. left = inputStream->nextRow();
  12720. if (!left)
  12721. {
  12722. if (numProcessedLastGroup == processed)
  12723. {
  12724. const void * nextRight = inputStream1->nextRow();
  12725. if (nextRight)
  12726. {
  12727. ReleaseRoxieRow(nextRight);
  12728. throw MakeStringException(ROXIE_MISSING_GROUP_ERROR, "Missing LEFT record for Combine Group (%d)", factory->queryId());
  12729. }
  12730. }
  12731. else
  12732. numProcessedLastGroup = processed;
  12733. return NULL;
  12734. }
  12735. ConstPointerArray group;
  12736. for (;;)
  12737. {
  12738. const void * in = inputStream1->nextRow();
  12739. if (!in)
  12740. break;
  12741. group.append(in);
  12742. }
  12743. if (group.ordinality() == 0)
  12744. {
  12745. ReleaseRoxieRow(left);
  12746. ReleaseRoxieRows(group);
  12747. throw MakeStringException(ROXIE_MISSING_GROUP_ERROR, "Missing RIGHT group for Combine Group (%d)", factory->queryId());
  12748. }
  12749. try
  12750. {
  12751. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12752. size32_t outSize = helper.transform(rowBuilder, left, group.ordinality(), (const void * *)group.getArray());
  12753. ReleaseRoxieRow(left);
  12754. ReleaseRoxieRows(group);
  12755. if (outSize)
  12756. {
  12757. processed++;
  12758. return rowBuilder.finalizeRowClear(outSize);
  12759. }
  12760. }
  12761. catch (IException *E)
  12762. {
  12763. ReleaseRoxieRow(left);
  12764. ReleaseRoxieRows(group);
  12765. throw makeWrappedException(E);
  12766. }
  12767. }
  12768. }
  12769. };
  12770. class CRoxieServerCombineGroupActivityFactory : public CRoxieServerActivityFactory
  12771. {
  12772. unsigned input2;
  12773. unsigned input2idx;
  12774. public:
  12775. CRoxieServerCombineGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12776. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12777. {
  12778. input2 = 0;
  12779. input2idx = 0;
  12780. }
  12781. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12782. {
  12783. return new CRoxieServerCombineGroupActivity(_ctx, this, _probeManager);
  12784. }
  12785. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  12786. {
  12787. if (idx==1)
  12788. {
  12789. input2 = source;
  12790. input2idx = sourceidx;
  12791. }
  12792. else
  12793. CRoxieServerActivityFactory::setInput(idx, source, sourceidx);
  12794. }
  12795. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  12796. {
  12797. switch (idx)
  12798. {
  12799. case 1:
  12800. sourceidx = input2idx;
  12801. return input2;
  12802. case 0:
  12803. return CRoxieServerActivityFactory::getInput(idx, sourceidx);
  12804. default:
  12805. return (unsigned) -1;
  12806. }
  12807. }
  12808. virtual unsigned numInputs() const { return 2; }
  12809. };
  12810. IRoxieServerActivityFactory *createRoxieServerCombineGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12811. {
  12812. return new CRoxieServerCombineGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12813. }
  12814. //=================================================================================
  12815. class CRoxieServerRollupGroupActivity : public CRoxieServerActivity
  12816. {
  12817. IHThorRollupGroupArg &helper;
  12818. bool eof;
  12819. public:
  12820. CRoxieServerRollupGroupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  12821. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  12822. helper((IHThorRollupGroupArg &)basehelper)
  12823. {
  12824. eof = false;
  12825. }
  12826. ~CRoxieServerRollupGroupActivity()
  12827. {
  12828. }
  12829. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12830. {
  12831. eof = false;
  12832. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  12833. }
  12834. virtual bool needsAllocator() const { return true; }
  12835. virtual const void * nextRow()
  12836. {
  12837. ActivityTimer t(totalCycles, timeActivities);
  12838. if (eof)
  12839. return NULL;
  12840. for (;;)
  12841. {
  12842. ConstPointerArray group;
  12843. for (;;)
  12844. {
  12845. const void * in = inputStream->nextRow();
  12846. if (!in)
  12847. break;
  12848. group.append(in);
  12849. }
  12850. if (group.ordinality() == 0)
  12851. {
  12852. eof = true;
  12853. return NULL;
  12854. }
  12855. try
  12856. {
  12857. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12858. size32_t outSize = helper.transform(rowBuilder, group.ordinality(), (const void * *)group.getArray());
  12859. ReleaseRoxieRows(group);
  12860. if (outSize)
  12861. {
  12862. processed++;
  12863. return rowBuilder.finalizeRowClear(outSize);
  12864. }
  12865. }
  12866. catch (IException * E)
  12867. {
  12868. ReleaseRoxieRows(group);
  12869. throw makeWrappedException(E);
  12870. }
  12871. }
  12872. }
  12873. };
  12874. class CRoxieServerRollupGroupActivityFactory : public CRoxieServerActivityFactory
  12875. {
  12876. public:
  12877. CRoxieServerRollupGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12878. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12879. {
  12880. }
  12881. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12882. {
  12883. return new CRoxieServerRollupGroupActivity(_ctx, this, _probeManager);
  12884. }
  12885. };
  12886. IRoxieServerActivityFactory *createRoxieServerRollupGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12887. {
  12888. return new CRoxieServerRollupGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12889. }
  12890. //=================================================================================
  12891. class CRoxieServerFilterProjectActivity : public CRoxieServerLateStartActivity
  12892. {
  12893. IHThorFilterProjectArg &helper;
  12894. unsigned numProcessedLastGroup;
  12895. unsigned __int64 recordCount;
  12896. public:
  12897. CRoxieServerFilterProjectActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  12898. : CRoxieServerLateStartActivity(_ctx, _factory, _probeManager), helper((IHThorFilterProjectArg &)basehelper)
  12899. {
  12900. numProcessedLastGroup = 0;
  12901. recordCount = 0;
  12902. }
  12903. ~CRoxieServerFilterProjectActivity()
  12904. {
  12905. }
  12906. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12907. {
  12908. numProcessedLastGroup = 0;
  12909. recordCount = 0;
  12910. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  12911. lateStart(parentExtractSize, parentExtract, helper.canMatchAny()); //sets eof
  12912. }
  12913. virtual bool needsAllocator() const { return true; }
  12914. virtual const void * nextRow()
  12915. {
  12916. ActivityTimer t(totalCycles, timeActivities);
  12917. if (eof)
  12918. return NULL;
  12919. for (;;)
  12920. {
  12921. const void * in = inputStream->nextRow();
  12922. if (!in)
  12923. {
  12924. recordCount = 0;
  12925. if (numProcessedLastGroup == processed)
  12926. in = inputStream->nextRow();
  12927. if (!in)
  12928. {
  12929. numProcessedLastGroup = processed;
  12930. return NULL;
  12931. }
  12932. }
  12933. try
  12934. {
  12935. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12936. size32_t outSize = helper.transform(rowBuilder, in, ++recordCount);
  12937. ReleaseRoxieRow(in);
  12938. if (outSize)
  12939. {
  12940. processed++;
  12941. return rowBuilder.finalizeRowClear(outSize);
  12942. }
  12943. }
  12944. catch (IException *E)
  12945. {
  12946. throw makeWrappedException(E);
  12947. }
  12948. }
  12949. }
  12950. };
  12951. class CRoxieServerFilterProjectActivityFactory : public CRoxieServerActivityFactory
  12952. {
  12953. public:
  12954. CRoxieServerFilterProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12955. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12956. {
  12957. //MORE: Code generator needs to indicate if the count is used.
  12958. //optStableInput = false;
  12959. }
  12960. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12961. {
  12962. return new CRoxieServerFilterProjectActivity(_ctx, this, _probeManager);
  12963. }
  12964. };
  12965. IRoxieServerActivityFactory *createRoxieServerFilterProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12966. {
  12967. return new CRoxieServerFilterProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12968. }
  12969. //=====================================================
  12970. class CRoxieServerStrandedProjectActivity : public CRoxieServerStrandedActivity
  12971. {
  12972. class ProjectProcessor : public StrandProcessor
  12973. {
  12974. protected:
  12975. IHThorProjectArg &helper;
  12976. public:
  12977. ProjectProcessor(CRoxieServerActivity &_parent, IEngineRowStream *_inputStream, IHThorProjectArg &_helper)
  12978. : StrandProcessor(_parent, _inputStream, true), helper(_helper)
  12979. {
  12980. }
  12981. virtual const void * nextRow()
  12982. {
  12983. ActivityTimer t(totalCycles, timeActivities);
  12984. for (;;)
  12985. {
  12986. OwnedConstRoxieRow in = inputStream->nextRow();
  12987. if (!in)
  12988. {
  12989. if (numProcessedLastGroup == processed)
  12990. in.setown(inputStream->nextRow());
  12991. if (!in)
  12992. {
  12993. numProcessedLastGroup = processed;
  12994. return NULL;
  12995. }
  12996. }
  12997. try
  12998. {
  12999. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  13000. size32_t outSize;
  13001. outSize = helper.transform(rowBuilder, in);
  13002. if (outSize)
  13003. {
  13004. processed++;
  13005. return rowBuilder.finalizeRowClear(outSize);
  13006. }
  13007. }
  13008. catch (IException *E)
  13009. {
  13010. throw parent.makeWrappedException(E);
  13011. }
  13012. }
  13013. }
  13014. };
  13015. public:
  13016. CRoxieServerStrandedProjectActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const StrandOptions &_strandOptions)
  13017. : CRoxieServerStrandedActivity(_ctx, _factory, _probeManager, _strandOptions)
  13018. {
  13019. }
  13020. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13021. {
  13022. CRoxieServerStrandedActivity::start(parentExtractSize, parentExtract, paused);
  13023. onStartStrands();
  13024. }
  13025. virtual StrandProcessor *createStrandProcessor(IEngineRowStream *instream)
  13026. {
  13027. return new ProjectProcessor(*this, instream, (IHThorProjectArg &) basehelper);
  13028. }
  13029. virtual StrandProcessor *createStrandSourceProcessor(bool inputOrdered) { throwUnexpected(); }
  13030. };
  13031. class CRoxieServerProjectActivity : public CRoxieServerActivity
  13032. {
  13033. unsigned numProcessedLastGroup;
  13034. unsigned __int64 recordCount;
  13035. bool count;
  13036. public:
  13037. CRoxieServerProjectActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _count)
  13038. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  13039. count(_count)
  13040. {
  13041. numProcessedLastGroup = 0;
  13042. recordCount = 0;
  13043. }
  13044. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13045. {
  13046. numProcessedLastGroup = 0;
  13047. recordCount = 0;
  13048. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  13049. }
  13050. virtual bool needsAllocator() const { return true; }
  13051. virtual const void * nextRow()
  13052. {
  13053. ActivityTimer t(totalCycles, timeActivities);
  13054. for (;;)
  13055. {
  13056. OwnedConstRoxieRow in = inputStream->nextRow();
  13057. if (!in)
  13058. {
  13059. recordCount = 0;
  13060. if (numProcessedLastGroup == processed)
  13061. in.setown(inputStream->nextRow());
  13062. if (!in)
  13063. {
  13064. numProcessedLastGroup = processed;
  13065. return NULL;
  13066. }
  13067. }
  13068. try
  13069. {
  13070. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  13071. size32_t outSize;
  13072. if (count)
  13073. outSize = ((IHThorCountProjectArg &) basehelper).transform(rowBuilder, in, ++recordCount);
  13074. else
  13075. outSize = ((IHThorProjectArg &) basehelper).transform(rowBuilder, in);
  13076. if (outSize)
  13077. {
  13078. processed++;
  13079. return rowBuilder.finalizeRowClear(outSize);
  13080. }
  13081. }
  13082. catch (IException *E)
  13083. {
  13084. throw makeWrappedException(E);
  13085. }
  13086. }
  13087. }
  13088. };
  13089. class CRoxieServerProjectActivityFactory : public CRoxieServerActivityFactory
  13090. {
  13091. protected:
  13092. StrandOptions strandOptions;
  13093. bool count;
  13094. public:
  13095. CRoxieServerProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  13096. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), strandOptions(_graphNode)
  13097. {
  13098. count = (kind==TAKcountproject || kind==TAKprefetchcountproject);
  13099. optStableInput = count;
  13100. }
  13101. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  13102. {
  13103. // 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.
  13104. if (kind == TAKproject) // Not supported on prefetch or count projects
  13105. return new CRoxieServerStrandedProjectActivity(_ctx, this, _probeManager, strandOptions);
  13106. else
  13107. return new CRoxieServerProjectActivity(_ctx, this, _probeManager, count);
  13108. }
  13109. };
  13110. IRoxieServerActivityFactory *createRoxieServerProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  13111. {
  13112. return new CRoxieServerProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  13113. }
  13114. //=================================================================================
  13115. class CRoxieServerPrefetchProjectActivity : public CRoxieServerActivity, implements IRecordPullerCallback
  13116. {
  13117. unsigned numProcessedLastGroup;
  13118. bool count;
  13119. bool eof;
  13120. bool allPulled;
  13121. bool isThreaded;
  13122. unsigned preload;
  13123. unsigned __int64 recordCount;
  13124. IHThorPrefetchProjectArg &helper;
  13125. RecordPullerThread puller;
  13126. InterruptableSemaphore ready;
  13127. InterruptableSemaphore space;
  13128. class PrefetchInfo : public CInterface
  13129. {
  13130. public:
  13131. inline PrefetchInfo(IHThorPrefetchProjectArg &helper, const void *_in, unsigned __int64 _recordCount)
  13132. {
  13133. if (helper.preTransform(extract, _in, _recordCount))
  13134. {
  13135. in.setown(_in);
  13136. recordCount = _recordCount;
  13137. }
  13138. else
  13139. {
  13140. ReleaseRoxieRow(_in);
  13141. recordCount = 0;
  13142. }
  13143. }
  13144. OwnedConstRoxieRow in;
  13145. unsigned __int64 recordCount;
  13146. rtlRowBuilder extract;
  13147. };
  13148. QueueOf<PrefetchInfo, true> pulled;
  13149. CriticalSection pulledCrit;
  13150. public:
  13151. CRoxieServerPrefetchProjectActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _count)
  13152. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  13153. helper((IHThorPrefetchProjectArg &) basehelper),
  13154. puller(false),
  13155. count(_count)
  13156. {
  13157. numProcessedLastGroup = 0;
  13158. recordCount = 0;
  13159. eof = false;
  13160. allPulled = false;
  13161. isThreaded = (helper.getFlags() & PPFparallel) != 0;
  13162. preload = 0;
  13163. }
  13164. ~CRoxieServerPrefetchProjectActivity()
  13165. {
  13166. while (pulled.ordinality())
  13167. ::Release(pulled.dequeue());
  13168. }
  13169. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  13170. {
  13171. if (idx)
  13172. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
  13173. puller.setInput(this, _sourceIdx, _in);
  13174. }
  13175. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  13176. {
  13177. puller.connectInputStreams(ctx, consumerOrdered);
  13178. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
  13179. }
  13180. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  13181. {
  13182. if (idx==0)
  13183. return puller.queryInput();
  13184. else
  13185. return NULL;
  13186. }
  13187. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13188. {
  13189. numProcessedLastGroup = 0;
  13190. recordCount = 0;
  13191. eof = false;
  13192. allPulled = false;
  13193. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  13194. preload = helper.getLookahead();
  13195. if (!preload)
  13196. preload = ctx->queryOptions().prefetchProjectPreload;
  13197. space.reinit(preload);
  13198. ready.reinit();
  13199. puller.start(parentExtractSize, parentExtract, paused, preload, !isThreaded, ctx);
  13200. }
  13201. virtual void stop()
  13202. {
  13203. space.interrupt();
  13204. ready.interrupt();
  13205. CRoxieServerActivity::stop();
  13206. puller.stop();
  13207. }
  13208. virtual void reset()
  13209. {
  13210. CRoxieServerActivity::reset();
  13211. puller.reset();
  13212. allPulled = false;
  13213. while (pulled.ordinality())
  13214. ::Release(pulled.dequeue());
  13215. }
  13216. virtual PrefetchInfo *readNextRecord()
  13217. {
  13218. if (!isThreaded)
  13219. {
  13220. if (!allPulled) // This looks like it's thread unsafe but we are inside the if(!isThreaded) so should be ok
  13221. puller.pullRecords(1);
  13222. }
  13223. else
  13224. ready.wait();
  13225. CriticalBlock b(pulledCrit);
  13226. PrefetchInfo *ret = pulled.ordinality() ? pulled.dequeue() : NULL;
  13227. space.signal();
  13228. return ret;
  13229. }
  13230. virtual bool needsAllocator() const { return true; }
  13231. virtual const void * nextRow()
  13232. {
  13233. ActivityTimer t(totalCycles, timeActivities);
  13234. if (eof)
  13235. return NULL;
  13236. for (;;)
  13237. {
  13238. Owned<PrefetchInfo> in = readNextRecord();
  13239. if (!in)
  13240. {
  13241. recordCount = 0;
  13242. if (numProcessedLastGroup == processed)
  13243. in.setown(readNextRecord());
  13244. if (!in)
  13245. {
  13246. numProcessedLastGroup = processed;
  13247. eof = true;
  13248. return NULL;
  13249. }
  13250. }
  13251. try
  13252. {
  13253. if (in->in)
  13254. {
  13255. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  13256. size32_t outSize;
  13257. IThorChildGraph *child = helper.queryChild();
  13258. Owned<IEclGraphResults> results;
  13259. if (child)
  13260. results.setown(child->evaluate(in->extract.size(), in->extract.getbytes()));
  13261. outSize = helper.transform(rowBuilder, in->in, results, in->recordCount);
  13262. if (outSize)
  13263. {
  13264. processed++;
  13265. return rowBuilder.finalizeRowClear(outSize);
  13266. }
  13267. }
  13268. }
  13269. catch (IException *E)
  13270. {
  13271. throw makeWrappedException(E);
  13272. }
  13273. }
  13274. }
  13275. // interface IExceptionHandler
  13276. virtual bool fireException(IException *e)
  13277. {
  13278. // called from puller thread on failure
  13279. ready.interrupt(LINK(e));
  13280. space.interrupt(e);
  13281. return true;
  13282. }
  13283. // interface IRecordPullerCallback
  13284. virtual void processRow(const void *row)
  13285. {
  13286. {
  13287. CriticalBlock b(pulledCrit);
  13288. pulled.enqueue(new PrefetchInfo(helper, row, ++recordCount));
  13289. }
  13290. if (isThreaded)
  13291. {
  13292. ready.signal();
  13293. space.wait();
  13294. }
  13295. }
  13296. virtual void processEOG()
  13297. {
  13298. {
  13299. CriticalBlock b(pulledCrit);
  13300. pulled.enqueue(NULL);
  13301. }
  13302. if (isThreaded)
  13303. {
  13304. ready.signal();
  13305. space.wait();
  13306. }
  13307. }
  13308. virtual void processGroup(const ConstPointerArray &rows)
  13309. {
  13310. throwUnexpected();
  13311. }
  13312. virtual void processDone()
  13313. {
  13314. CriticalBlock b(pulledCrit);
  13315. allPulled = true;
  13316. if (isThreaded)
  13317. ready.signal();
  13318. }
  13319. };
  13320. class CRoxieServerPrefetchProjectActivityFactory : public CRoxieServerProjectActivityFactory
  13321. {
  13322. public:
  13323. CRoxieServerPrefetchProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  13324. : CRoxieServerProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  13325. {
  13326. }
  13327. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  13328. {
  13329. return new CRoxieServerPrefetchProjectActivity(_ctx, this, _probeManager, count);
  13330. }
  13331. };
  13332. extern IRoxieServerActivityFactory *createRoxieServerPrefetchProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  13333. {
  13334. return new CRoxieServerPrefetchProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  13335. }
  13336. //=================================================================================
  13337. class CPointerArrayRoxieInput : public CPseudoRoxieInput
  13338. {
  13339. public:
  13340. CPointerArrayRoxieInput()
  13341. {
  13342. rowset = NULL;
  13343. rowcount = 0;
  13344. curRow = 0;
  13345. }
  13346. void init(size32_t _rowcount, const byte **_rowset)
  13347. {
  13348. rowset = _rowset;
  13349. rowcount = _rowcount;
  13350. curRow = 0;
  13351. }
  13352. virtual const void * nextRow()
  13353. {
  13354. if (curRow < rowcount)
  13355. {
  13356. const void * ret = rowset[curRow];
  13357. if (ret)
  13358. LinkRoxieRow(ret);
  13359. curRow++;
  13360. return ret;
  13361. }
  13362. return NULL;
  13363. }
  13364. protected:
  13365. const byte **rowset;
  13366. size32_t rowcount;
  13367. size32_t curRow;
  13368. };
  13369. class CRoxieServerLoopActivity : public CRoxieServerActivity
  13370. {
  13371. protected:
  13372. IHThorLoopArg &helper;
  13373. ThorActivityKind activityKind;
  13374. unsigned maxIterations;
  13375. bool finishedLooping;
  13376. unsigned flags;
  13377. bool eof;
  13378. rtlRowBuilder loopExtractBuilder;
  13379. unsigned loopGraphId;
  13380. Linked<IOutputMetaData> counterMeta;
  13381. public:
  13382. CRoxieServerLoopActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _loopGraphId, IOutputMetaData * _counterMeta)
  13383. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  13384. helper((IHThorLoopArg &)basehelper), loopGraphId(_loopGraphId), counterMeta(_counterMeta)
  13385. {
  13386. eof = false;
  13387. finishedLooping = false;
  13388. activityKind = factory->getKind();
  13389. flags = helper.getFlags();
  13390. maxIterations = 0;
  13391. }
  13392. virtual bool needsAllocator() const { return true; }
  13393. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13394. {
  13395. eof = false;
  13396. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  13397. int iterations = (int) helper.numIterations();
  13398. maxIterations = (iterations >= 0) ? iterations : 0;
  13399. finishedLooping = ((activityKind == TAKloopcount) && (maxIterations == 0));
  13400. if ((flags & IHThorLoopArg::LFnewloopagain) && !helper.loopFirstTime())
  13401. finishedLooping = true;
  13402. loopExtractBuilder.clear();
  13403. helper.createParentExtract(loopExtractBuilder); // could possibly delay this until execution actually happens
  13404. }
  13405. virtual void stop()
  13406. {
  13407. CRoxieServerActivity::stop();
  13408. loopExtractBuilder.clear();
  13409. }
  13410. void createCounterResult(IRoxieServerChildGraph * graph, unsigned counter)
  13411. {
  13412. if (flags & IHThorLoopArg::LFcounter)
  13413. {
  13414. void * counterRow = ctx->queryRowManager().allocate(sizeof(thor_loop_counter_t), activityId);
  13415. *((thor_loop_counter_t *)counterRow) = counter;
  13416. RtlLinkedDatasetBuilder builder(rowAllocator);
  13417. builder.appendOwn(counterRow);
  13418. Owned<CGraphResult> counterResult = new CGraphResult(builder.getcount(), builder.linkrows());
  13419. graph->setInputResult(2, counterResult);
  13420. }
  13421. }
  13422. };
  13423. //=================================================================================
  13424. class CRoxieServerSequentialLoopActivity : public CRoxieServerLoopActivity
  13425. {
  13426. Owned<IActivityGraph> loopQuery;
  13427. Owned<IRoxieServerChildGraph> loopGraph;
  13428. IEngineRowStream * curStream;
  13429. RtlLinkedDatasetBuilder *loopInputBuilder;
  13430. CPointerArrayRoxieInput arrayInput;
  13431. Linked<IEngineRowStream> resultStream;
  13432. unsigned loopCounter;
  13433. public:
  13434. CRoxieServerSequentialLoopActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _loopGraphId, IOutputMetaData * _counterMeta)
  13435. : CRoxieServerLoopActivity(_ctx, _factory, _probeManager, _loopGraphId, _counterMeta)
  13436. {
  13437. curStream = NULL;
  13438. loopCounter = 0;
  13439. loopInputBuilder = NULL;
  13440. }
  13441. virtual bool needsAllocator() const { return true; }
  13442. virtual void onCreate(IHThorArg *_colocalParent)
  13443. {
  13444. CRoxieServerLoopActivity::onCreate(_colocalParent);
  13445. loopQuery.set(ctx->queryChildGraph(loopGraphId));
  13446. }
  13447. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13448. {
  13449. curStream = inputStream;
  13450. loopCounter = 1;
  13451. CRoxieServerLoopActivity::start(parentExtractSize, parentExtract, paused);
  13452. //MORE: Not sure about this, should IRoxieServerChildGraph be combined with IActivityGraph?
  13453. loopGraph.set(loopQuery->queryLoopGraph());
  13454. loopInputBuilder = new RtlLinkedDatasetBuilder(rowAllocator);
  13455. }
  13456. virtual void stop()
  13457. {
  13458. delete loopInputBuilder;
  13459. loopInputBuilder = NULL;
  13460. CRoxieServerLoopActivity::stop();
  13461. }
  13462. virtual const void * nextRow()
  13463. {
  13464. ActivityTimer t(totalCycles, timeActivities);
  13465. if (eof)
  13466. return NULL;
  13467. unsigned emptyIterations = 0;
  13468. for (;;)
  13469. {
  13470. for (;;)
  13471. {
  13472. const void * ret = curStream->nextRow();
  13473. if (!ret)
  13474. {
  13475. ret = curStream->nextRow(); // more cope with groups somehow....
  13476. if (!ret)
  13477. {
  13478. if (finishedLooping)
  13479. {
  13480. eof = true;
  13481. return NULL;
  13482. }
  13483. break;
  13484. }
  13485. }
  13486. if (finishedLooping ||
  13487. ((flags & IHThorLoopArg::LFfiltered) && !helper.sendToLoop(loopCounter, ret)))
  13488. {
  13489. processed++;
  13490. return ret;
  13491. }
  13492. loopInputBuilder->appendOwn(ret);
  13493. }
  13494. switch (activityKind)
  13495. {
  13496. case TAKloopdataset:
  13497. {
  13498. if (!(flags & IHThorLoopArg::LFnewloopagain))
  13499. {
  13500. if (!helper.loopAgain(loopCounter, loopInputBuilder->getcount(), (const void**) loopInputBuilder->queryrows()))
  13501. {
  13502. if (loopInputBuilder->getcount() == 0)
  13503. {
  13504. eof = true;
  13505. return NULL;
  13506. }
  13507. arrayInput.init(loopInputBuilder->getcount(), loopInputBuilder->linkrows());
  13508. // MORE - should builder be cleared here?
  13509. curStream = &arrayInput;
  13510. finishedLooping = true;
  13511. continue; // back to the input loop again
  13512. }
  13513. }
  13514. break;
  13515. }
  13516. case TAKlooprow:
  13517. if (!loopInputBuilder->getcount())
  13518. {
  13519. finishedLooping = true;
  13520. eof = true;
  13521. return NULL;
  13522. }
  13523. break;
  13524. }
  13525. if (loopInputBuilder->getcount())
  13526. emptyIterations = 0;
  13527. else
  13528. {
  13529. //note: any outputs which didn't go around the loop again, would return the record, reinitializing emptyIterations
  13530. emptyIterations++;
  13531. if (emptyIterations > maxEmptyLoopIterations)
  13532. throw MakeStringException(ROXIE_TOO_MANY_EMPTY_LOOP, "Executed LOOP with empty input and output %u times", emptyIterations);
  13533. if (emptyIterations % 32 == 0)
  13534. CTXLOG("Executing LOOP with empty input and output %u times", emptyIterations);
  13535. }
  13536. checkAbort();
  13537. try
  13538. {
  13539. Owned<IRoxieGraphResults> results = executeIteration(loopExtractBuilder.size(), loopExtractBuilder.getbytes(), loopCounter);
  13540. resultStream.setown(results->createIterator(0));
  13541. if (flags & IHThorLoopArg::LFnewloopagain)
  13542. {
  13543. Owned<IEngineRowStream> againResult = results->createIterator(helper.loopAgainResult());
  13544. OwnedConstRoxieRow row = againResult->nextRow();
  13545. assertex(row);
  13546. //Result is a row which contains a single boolean field.
  13547. if (!((const bool *)row.get())[0])
  13548. finishedLooping = true;
  13549. }
  13550. }
  13551. catch (IException *E)
  13552. {
  13553. throw makeWrappedException(E);
  13554. }
  13555. curStream = resultStream.get();
  13556. loopCounter++;
  13557. if ((activityKind == TAKloopcount) && (loopCounter > maxIterations))
  13558. finishedLooping = true;
  13559. }
  13560. }
  13561. IRoxieGraphResults * executeIteration(unsigned parentExtractSize, const byte *parentExtract, unsigned counter)
  13562. {
  13563. try
  13564. {
  13565. loopGraph->beforeExecute();
  13566. Owned<IGraphResult> inputRowsResult = new CGraphResult(loopInputBuilder->getcount(), loopInputBuilder->linkrows());
  13567. loopInputBuilder->clear();
  13568. loopGraph->setInputResult(1, inputRowsResult);
  13569. createCounterResult(loopGraph, counter);
  13570. Owned<IRoxieGraphResults> ret = loopGraph->execute(parentExtractSize, parentExtract);
  13571. loopGraph->afterExecute();
  13572. return ret.getClear();
  13573. }
  13574. catch (...)
  13575. {
  13576. CTXLOG("Exception thrown in loop body - cleaning up");
  13577. loopGraph->afterExecute();
  13578. throw;
  13579. }
  13580. }
  13581. };
  13582. //=================================================================================
  13583. typedef SafeQueueOf<const void, true> SafeRowQueue;
  13584. class CRowQueuePseudoInput : public CPseudoRoxieInput
  13585. {
  13586. public:
  13587. CRowQueuePseudoInput(SafeRowQueue & _input, IOutputMetaData * _meta)
  13588. : meta(_meta), input(_input)
  13589. {
  13590. eof = false;
  13591. }
  13592. virtual const void * nextRow()
  13593. {
  13594. if (eof)
  13595. return NULL;
  13596. const void * ret = input.dequeue();
  13597. if (!ret)
  13598. eof = true;
  13599. return ret;
  13600. }
  13601. virtual IOutputMetaData * queryOutputMeta() const { return meta; }
  13602. protected:
  13603. SafeRowQueue & input;
  13604. IOutputMetaData * meta;
  13605. bool eof;
  13606. };
  13607. class CRoxieServerParallelLoopActivity;
  13608. class LoopFilterPseudoInput : public CIndirectRoxieInput
  13609. {
  13610. public:
  13611. LoopFilterPseudoInput(CRoxieServerParallelLoopActivity * _activity, unsigned _counter) :
  13612. activity(_activity), counter(_counter)
  13613. {
  13614. }
  13615. virtual const void * nextRow();
  13616. protected:
  13617. CRoxieServerParallelLoopActivity * activity;
  13618. unsigned counter;
  13619. };
  13620. class LoopExecutorThread : public RestartableThread
  13621. {
  13622. protected:
  13623. Owned<CSafeRoxieInput> safeInput;
  13624. CRoxieServerParallelLoopActivity * activity;
  13625. bool eof;
  13626. CriticalSection crit;
  13627. unsigned flags;
  13628. SafeRowQueue tempResults[2];
  13629. unsigned savedParentExtractSize;
  13630. const byte * savedParentExtract;
  13631. IArrayOf<IActivityGraph> cachedGraphs;
  13632. IRoxieSlaveContext *ctx;
  13633. public:
  13634. LoopExecutorThread()
  13635. : RestartableThread("LoopExecutorThread")
  13636. {
  13637. activity = NULL;
  13638. eof = false;
  13639. flags = 0;
  13640. ctx = NULL;
  13641. savedParentExtract = NULL;
  13642. savedParentExtractSize = 0;
  13643. }
  13644. void setInput(CRoxieServerParallelLoopActivity * _activity, unsigned _sourceIdx, IFinalRoxieInput *_input, unsigned _flags)
  13645. {
  13646. activity = _activity;
  13647. flags = _flags;
  13648. // 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.
  13649. safeInput.setown(new CSafeRoxieInput(_sourceIdx, _input));
  13650. }
  13651. void connectInputStreams(bool consumerOrdered)
  13652. {
  13653. safeInput->connectInputStreams(ctx, consumerOrdered);
  13654. }
  13655. IFinalRoxieInput *queryInput() const
  13656. {
  13657. return safeInput;
  13658. }
  13659. void onCreate(IRoxieSlaveContext * _ctx);
  13660. void start(unsigned parentExtractSize, const byte *parentExtract, bool paused);
  13661. void stop();
  13662. void reset();
  13663. virtual int run();
  13664. protected:
  13665. void executeLoop();
  13666. void executeLoopInstance(unsigned counter, unsigned numIterations, unsigned inputIdx, IFinalRoxieInput * input, SafeRowQueue * spillOutput);
  13667. IFinalRoxieInput * createLoopIterationGraph(unsigned i, unsigned inputIdx, IFinalRoxieInput * input, unsigned counter);
  13668. };
  13669. class CRoxieServerParallelLoopActivity : public CRoxieServerLoopActivity
  13670. {
  13671. friend class LoopFilterPseudoInput;
  13672. friend class LoopExecutorThread;
  13673. QueueOf<const void, true> ready;
  13674. CriticalSection helperCS;
  13675. CriticalSection cs;
  13676. unsigned defaultNumParallel;
  13677. LoopExecutorThread executor;
  13678. IProbeManager* probeManager;
  13679. CriticalSection canAccess;
  13680. CriticalSection scrit;
  13681. InterruptableSemaphore readySpace;
  13682. InterruptableSemaphore recordsReady;
  13683. protected:
  13684. bool includeInLoop(unsigned counter, const void * row)
  13685. {
  13686. CriticalBlock b(helperCS);
  13687. return helper.sendToLoop(counter, row);
  13688. }
  13689. public:
  13690. CRoxieServerParallelLoopActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _loopGraphId, IOutputMetaData * _counterMeta)
  13691. : CRoxieServerLoopActivity(_ctx, _factory, _probeManager, _loopGraphId, _counterMeta),
  13692. readySpace(parallelLoopFlowLimit)
  13693. {
  13694. probeManager = _probeManager;
  13695. defaultNumParallel = 0;
  13696. }
  13697. virtual void onCreate(IHThorArg *_colocalParent)
  13698. {
  13699. CRoxieServerActivity::onCreate(_colocalParent);
  13700. executor.onCreate(ctx);
  13701. }
  13702. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13703. {
  13704. CriticalBlock b(scrit); // can stop while still starting, if unlucky...
  13705. readySpace.reinit(parallelLoopFlowLimit);
  13706. recordsReady.reinit();
  13707. CRoxieServerLoopActivity::start(parentExtractSize, parentExtract, paused);
  13708. defaultNumParallel = helper.defaultParallelIterations();
  13709. if (!defaultNumParallel)
  13710. defaultNumParallel = DEFAULT_PARALLEL_LOOP_THREADS;
  13711. //MORE: If numIterations <= number of parallel iterations[1],
  13712. //then we don't need to create a separate thread to do the processing, and the results will also avoid
  13713. //being transferred via a queue
  13714. executor.start(parentExtractSize, parentExtract, paused);
  13715. }
  13716. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  13717. {
  13718. if (idx)
  13719. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
  13720. executor.setInput(this, _sourceIdx, _in, flags);
  13721. }
  13722. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  13723. {
  13724. executor.connectInputStreams(consumerOrdered);
  13725. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, nullptr, consumerOrdered, nullptr);
  13726. }
  13727. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  13728. {
  13729. if (idx==0)
  13730. return executor.queryInput();
  13731. else
  13732. return NULL;
  13733. }
  13734. virtual void stop()
  13735. {
  13736. CriticalBlock b(scrit); // can stop while still starting, if unlucky...
  13737. readySpace.interrupt();
  13738. recordsReady.interrupt();
  13739. executor.join(); // MORE - may not be needed given stop/reset split
  13740. CRoxieServerLoopActivity::stop();
  13741. }
  13742. virtual void reset()
  13743. {
  13744. while (ready.ordinality())
  13745. ReleaseRoxieRow(ready.dequeue());
  13746. executor.reset();
  13747. CRoxieServerActivity::reset();
  13748. }
  13749. virtual const void * nextRow()
  13750. {
  13751. ActivityTimer t(totalCycles, timeActivities);
  13752. for (;;)
  13753. {
  13754. if (eof)
  13755. return NULL;
  13756. recordsReady.wait();
  13757. CriticalBlock procedure(canAccess);
  13758. if (ready.ordinality())
  13759. {
  13760. const void *result = ready.dequeue();
  13761. readySpace.signal();
  13762. if (result)
  13763. processed++;
  13764. return result;
  13765. }
  13766. else
  13767. eof = true;
  13768. }
  13769. }
  13770. unsigned getNumParallel(unsigned iter)
  13771. {
  13772. return defaultNumParallel;
  13773. }
  13774. inline void enqueueResult(const void * row)
  13775. {
  13776. try
  13777. {
  13778. while(!readySpace.wait(1000))
  13779. {
  13780. CTXLOG("Blocked waiting for space in loop %p activity id: %d output queue: %d records in queue", this, queryId(), ready.ordinality());
  13781. }
  13782. }
  13783. catch (...)
  13784. {
  13785. ReleaseRoxieRow(row);
  13786. throw;
  13787. }
  13788. CriticalBlock b2(canAccess);
  13789. ready.enqueue(row);
  13790. recordsReady.signal();
  13791. }
  13792. inline void finishResults()
  13793. {
  13794. recordsReady.signal();
  13795. }
  13796. virtual bool fireException(IException *e)
  13797. {
  13798. readySpace.interrupt(LINK(e));
  13799. recordsReady.interrupt(e);
  13800. return true;
  13801. }
  13802. IActivityGraph * createChildGraphInstance()
  13803. {
  13804. return factory->createChildGraph(ctx, &helper, loopGraphId, this, probeManager, *this);
  13805. }
  13806. IActivityGraph * queryChildGraph()
  13807. {
  13808. return ctx->queryChildGraph(loopGraphId);
  13809. }
  13810. };
  13811. //=================================================================================
  13812. const void * LoopFilterPseudoInput::nextRow()
  13813. {
  13814. for (;;)
  13815. {
  13816. const void * next = stream->nextRow();
  13817. if (!next || activity->includeInLoop(counter, next))
  13818. return next;
  13819. activity->enqueueResult(next);
  13820. }
  13821. }
  13822. void LoopExecutorThread::onCreate(IRoxieSlaveContext * _ctx)
  13823. {
  13824. //Initialise the cached graph list with the child instance that will always be created. Other iterations will be created on demand.
  13825. ctx = _ctx;
  13826. cachedGraphs.append(*LINK(activity->queryChildGraph()));
  13827. }
  13828. void LoopExecutorThread::start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13829. {
  13830. savedParentExtractSize = parentExtractSize;
  13831. savedParentExtract = parentExtract;
  13832. eof = false;
  13833. StringBuffer logPrefix("[");
  13834. ctx->getLogPrefix(logPrefix).append("] ");
  13835. RestartableThread::start(logPrefix);
  13836. }
  13837. int LoopExecutorThread::run()
  13838. {
  13839. try
  13840. {
  13841. executeLoop();
  13842. }
  13843. catch (IException *e)
  13844. {
  13845. activity->fireException(e);
  13846. }
  13847. catch (...)
  13848. {
  13849. activity->fireException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unexpected exception caught in LoopExecutorThread::run"));
  13850. }
  13851. return 0;
  13852. }
  13853. void LoopExecutorThread::stop()
  13854. {
  13855. safeInput->stop();
  13856. RestartableThread::join();
  13857. }
  13858. void LoopExecutorThread::reset()
  13859. {
  13860. safeInput->reset();
  13861. }
  13862. void LoopExecutorThread::executeLoop()
  13863. {
  13864. unsigned iterations = 0;
  13865. unsigned counter = 0;
  13866. unsigned outputIndex = 0;
  13867. //Note, activities don't link inputs, so need to be careful that special inputs remain linked while the activity is executing.
  13868. for (;;)
  13869. {
  13870. if (activity->activityKind == TAKloopcount)
  13871. {
  13872. if (counter == activity->maxIterations)
  13873. break;
  13874. }
  13875. else
  13876. {
  13877. //This condition isn't quite right because it needs to be whether the filtered
  13878. //input is empty. May be ok if we include that in the semantics,
  13879. if (tempResults[1-outputIndex].ordinality() == 0)
  13880. break;
  13881. }
  13882. unsigned numParallel = activity->getNumParallel(iterations);
  13883. Linked<IFinalRoxieInput> curInput;
  13884. if (iterations == 0)
  13885. curInput.set(safeInput);
  13886. else
  13887. {
  13888. SafeRowQueue & inputQueue = tempResults[1-outputIndex];
  13889. inputQueue.enqueue(NULL);
  13890. curInput.setown(new CRowQueuePseudoInput(inputQueue, activity->queryOutputMeta()));
  13891. }
  13892. SafeRowQueue * curOutput = NULL;
  13893. if (counter+numParallel > activity->maxIterations)
  13894. numParallel = activity->maxIterations - counter;
  13895. else if (counter+numParallel < activity->maxIterations)
  13896. curOutput = &tempResults[outputIndex];
  13897. executeLoopInstance(counter, numParallel, 0, curInput, curOutput); // CurInput is always SOME sort of proxy so idx always 0
  13898. outputIndex = 1-outputIndex;
  13899. counter += numParallel;
  13900. iterations++;
  13901. }
  13902. //Check for TAKlooprow, where end of loop couldn't be determined ahead of time
  13903. SafeRowQueue & inputQueue = tempResults[1-outputIndex];
  13904. while (inputQueue.ordinality())
  13905. {
  13906. const void * next = inputQueue.dequeue();
  13907. activity->enqueueResult(next);
  13908. }
  13909. activity->finishResults();
  13910. }
  13911. void LoopExecutorThread::executeLoopInstance(unsigned counter, unsigned numIterations, unsigned inputIdx, IFinalRoxieInput * input, SafeRowQueue * spillOutput)
  13912. {
  13913. IArrayOf<IFinalRoxieInput> savedInputs; // activities don't link their inputs, so this list keeps filters alive.
  13914. Linked<IFinalRoxieInput> curInput = input;
  13915. unsigned i;
  13916. for (i= 0; i != numIterations; i++)
  13917. {
  13918. unsigned thisCounter = counter+i+1;
  13919. IFinalRoxieInput * filtered = curInput;
  13920. if (flags & IHThorLoopArg::LFfiltered)
  13921. {
  13922. LoopFilterPseudoInput *newFiltered = new LoopFilterPseudoInput(activity, thisCounter);
  13923. newFiltered->setInput(inputIdx, curInput);
  13924. filtered = newFiltered;
  13925. savedInputs.append(*filtered);
  13926. inputIdx = 0;
  13927. }
  13928. //graph is kept, so new curInput will be guaranteed to exist
  13929. curInput.setown(createLoopIterationGraph(i, inputIdx, filtered, thisCounter));
  13930. inputIdx = 0;
  13931. }
  13932. Owned<IStrandJunction> curJunction;
  13933. IEngineRowStream *curStream = connectSingleStream(ctx, curInput, inputIdx, curJunction, true);
  13934. Owned<IException> failure;
  13935. try
  13936. {
  13937. curInput->start(savedParentExtractSize, savedParentExtract, false);
  13938. if (spillOutput)
  13939. {
  13940. for (;;)
  13941. {
  13942. const void * next = curStream->nextRow();
  13943. if (!next)
  13944. break;
  13945. spillOutput->enqueue(next);
  13946. }
  13947. }
  13948. else
  13949. {
  13950. for (;;)
  13951. {
  13952. const void * next = curStream->nextRow();
  13953. if (!next)
  13954. break;
  13955. activity->enqueueResult(next);
  13956. }
  13957. }
  13958. }
  13959. catch (IException *E)
  13960. {
  13961. ctx->notifyAbort(E);
  13962. failure.setown(E);
  13963. }
  13964. for (i= 0; i != numIterations; i++)
  13965. {
  13966. IRoxieServerChildGraph * loopGraph = cachedGraphs.item(i).queryLoopGraph();
  13967. loopGraph->afterExecute();
  13968. //NOTE: inputIdx is always 0 - the code above could be cleaned up.
  13969. loopGraph->querySetInputResult(1, 0, nullptr);
  13970. }
  13971. curStream->stop();
  13972. curInput->reset();
  13973. if (failure)
  13974. throw failure.getClear();
  13975. }
  13976. IFinalRoxieInput * LoopExecutorThread::createLoopIterationGraph(unsigned i, unsigned inputIdx, IFinalRoxieInput * input, unsigned counter)
  13977. {
  13978. if (!cachedGraphs.isItem(i))
  13979. cachedGraphs.append(*activity->createChildGraphInstance());
  13980. Linked<IRoxieServerChildGraph> loopGraph = cachedGraphs.item(i).queryLoopGraph();
  13981. loopGraph->beforeExecute();
  13982. if (!loopGraph->querySetInputResult(1, inputIdx, input))
  13983. throwUnexpected(); // a loop which doesn't use the value from the previous iteration. Should probably handle even if daft.
  13984. activity->createCounterResult(loopGraph, counter);
  13985. return loopGraph->selectOutput(0);
  13986. }
  13987. //=================================================================================
  13988. class CCounterRowMetaData : implements IOutputMetaData, public CInterface
  13989. {
  13990. public:
  13991. IMPLEMENT_IINTERFACE
  13992. virtual size32_t getRecordSize(const void *) { return sizeof(thor_loop_counter_t); }
  13993. virtual size32_t getMinRecordSize() const { return sizeof(thor_loop_counter_t); }
  13994. virtual size32_t getFixedSize() const { return sizeof(thor_loop_counter_t); }
  13995. virtual void toXML(const byte * self, IXmlWriter & out) { }
  13996. virtual unsigned getVersion() const { return OUTPUTMETADATA_VERSION; }
  13997. virtual unsigned getMetaFlags() { return 0; }
  13998. virtual void destruct(byte * self) {}
  13999. virtual IOutputRowSerializer * createDiskSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  14000. virtual IOutputRowDeserializer * createDiskDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  14001. virtual ISourceRowPrefetcher * createDiskPrefetcher() { return NULL; }
  14002. virtual IOutputMetaData * querySerializedDiskMeta() { return this; }
  14003. virtual IOutputRowSerializer * createInternalSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  14004. virtual IOutputRowDeserializer * createInternalDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  14005. virtual void walkIndirectMembers(const byte * self, IIndirectMemberVisitor & visitor) {}
  14006. virtual IOutputMetaData * queryChildMeta(unsigned i) { return NULL; }
  14007. virtual const RtlRecord &queryRecordAccessor(bool expand) const { throwUnexpected(); } // could provide a static implementation if needed
  14008. };
  14009. class CRoxieServerLoopActivityFactory : public CRoxieServerActivityFactory
  14010. {
  14011. unsigned loopGraphId;
  14012. unsigned flags;
  14013. Linked<IOutputMetaData> counterMeta;
  14014. public:
  14015. CRoxieServerLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _loopGraphId)
  14016. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), loopGraphId(_loopGraphId)
  14017. {
  14018. Owned<IHThorLoopArg> helper = (IHThorLoopArg *) helperFactory();
  14019. flags = helper->getFlags();
  14020. counterMeta.setown(new CCounterRowMetaData);
  14021. }
  14022. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  14023. {
  14024. if (flags & IHThorLoopArg::LFparallel)
  14025. return new CRoxieServerParallelLoopActivity(_ctx, this, _probeManager, loopGraphId, counterMeta);
  14026. else
  14027. return new CRoxieServerSequentialLoopActivity(_ctx, this, _probeManager, loopGraphId, counterMeta);
  14028. }
  14029. };
  14030. IRoxieServerActivityFactory *createRoxieServerLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _loopGraphId)
  14031. {
  14032. return new CRoxieServerLoopActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _loopGraphId);
  14033. }
  14034. //=================================================================================
  14035. class CRoxieServerGraphLoopActivity : public CRoxieServerActivity
  14036. {
  14037. protected:
  14038. IHThorGraphLoopArg &helper;
  14039. unsigned maxIterations;
  14040. unsigned flags;
  14041. rtlRowBuilder GraphExtractBuilder;
  14042. unsigned loopGraphId;
  14043. Linked<IOutputMetaData> counterMeta;
  14044. public:
  14045. CRoxieServerGraphLoopActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _GraphGraphId, IOutputMetaData * _counterMeta)
  14046. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  14047. helper((IHThorGraphLoopArg &)basehelper), loopGraphId(_GraphGraphId), counterMeta(_counterMeta)
  14048. {
  14049. flags = helper.getFlags();
  14050. maxIterations = 0;
  14051. }
  14052. virtual bool needsAllocator() const { return true; }
  14053. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14054. {
  14055. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14056. int iterations = (int) helper.numIterations();
  14057. maxIterations = (iterations >= 0) ? iterations : 0;
  14058. if (maxIterations > maxGraphLoopIterations)
  14059. throw MakeStringException(ROXIE_TOO_MANY_GRAPH_LOOP, "Attempt to execute graph %u times", maxIterations);
  14060. if (maxIterations != 0)
  14061. {
  14062. GraphExtractBuilder.clear();
  14063. helper.createParentExtract(GraphExtractBuilder);
  14064. }
  14065. }
  14066. virtual void stop()
  14067. {
  14068. CRoxieServerActivity::stop();
  14069. GraphExtractBuilder.clear();
  14070. }
  14071. void createCounterResult(IRoxieServerChildGraph * graph, unsigned counter)
  14072. {
  14073. if (flags & IHThorGraphLoopArg::GLFcounter)
  14074. {
  14075. void * counterRow = ctx->queryRowManager().allocate(sizeof(thor_loop_counter_t), activityId);
  14076. *((thor_loop_counter_t *)counterRow) = counter;
  14077. RtlLinkedDatasetBuilder builder(rowAllocator);
  14078. builder.appendOwn(counterRow);
  14079. Owned<CGraphResult> counterResult = new CGraphResult(builder.getcount(), builder.linkrows());
  14080. graph->setInputResult(0, counterResult);
  14081. }
  14082. }
  14083. };
  14084. //=================================================================================
  14085. class CRoxieServerSequentialGraphLoopActivity : public CRoxieServerGraphLoopActivity
  14086. {
  14087. Owned<IActivityGraph> GraphQuery;
  14088. Owned<IRoxieServerChildGraph> loopGraph;
  14089. Linked<IEngineRowStream> resultStream;
  14090. bool evaluated;
  14091. public:
  14092. CRoxieServerSequentialGraphLoopActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _GraphGraphId, IOutputMetaData * _counterMeta)
  14093. : CRoxieServerGraphLoopActivity(_ctx, _factory, _probeManager, _GraphGraphId, _counterMeta)
  14094. {
  14095. evaluated = false;
  14096. }
  14097. virtual void onCreate(IHThorArg *_colocalParent)
  14098. {
  14099. CRoxieServerGraphLoopActivity::onCreate(_colocalParent);
  14100. GraphQuery.set(ctx->queryChildGraph(loopGraphId));
  14101. }
  14102. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14103. {
  14104. CRoxieServerGraphLoopActivity::start(parentExtractSize, parentExtract, paused);
  14105. //MORE: Not sure about this, should IRoxieServerChildGraph be combined with IActivityGraph?
  14106. loopGraph.set(GraphQuery->queryLoopGraph());
  14107. evaluated = false;
  14108. }
  14109. virtual void stop()
  14110. {
  14111. if (loopGraph)
  14112. loopGraph->clearGraphLoopResults();
  14113. CRoxieServerGraphLoopActivity::stop();
  14114. }
  14115. virtual const void * nextRow()
  14116. {
  14117. ActivityTimer t(totalCycles, timeActivities);
  14118. if (!evaluated)
  14119. {
  14120. executeEntireGraph();
  14121. evaluated = true;
  14122. }
  14123. const void * ret = resultStream->nextRow();
  14124. if (ret)
  14125. processed++;
  14126. return ret;
  14127. }
  14128. void executeIteration(unsigned parentExtractSize, const byte *parentExtract, unsigned counter)
  14129. {
  14130. try
  14131. {
  14132. loopGraph->beforeExecute();
  14133. createCounterResult(loopGraph, counter);
  14134. loopGraph->executeGraphLoop(parentExtractSize, parentExtract);
  14135. loopGraph->afterExecute();
  14136. }
  14137. catch (...)
  14138. {
  14139. CTXLOG("Exception thrown in graph body - cleaning up");
  14140. loopGraph->afterExecute();
  14141. throw;
  14142. }
  14143. }
  14144. void createInitialGraphInput()
  14145. {
  14146. loopGraph->clearGraphLoopResults();
  14147. RtlLinkedDatasetBuilder builder(rowAllocator);
  14148. inputStream->readAll(builder);
  14149. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  14150. loopGraph->setGraphLoopResult(0, result);
  14151. }
  14152. void executeEntireGraph()
  14153. {
  14154. createInitialGraphInput();
  14155. for (unsigned loopCounter=1; loopCounter <= maxIterations; loopCounter++)
  14156. {
  14157. executeIteration(GraphExtractBuilder.size(), GraphExtractBuilder.getbytes(), loopCounter);
  14158. }
  14159. resultStream.setown(loopGraph->getGraphLoopResult(maxIterations));
  14160. }
  14161. };
  14162. //=================================================================================
  14163. struct GraphOutputSplitterArg : public CThorSplitArg
  14164. {
  14165. public:
  14166. virtual unsigned numBranches()
  14167. {
  14168. return 0;
  14169. }
  14170. virtual IOutputMetaData * queryOutputMeta()
  14171. {
  14172. return NULL;// get it from the parent..
  14173. }
  14174. };
  14175. extern "C" IHThorArg * createGraphOutputSplitter() { return new GraphOutputSplitterArg; }
  14176. class CGraphIterationInfo : public CInterface
  14177. {
  14178. private:
  14179. Owned<IRoxieServerActivityFactory> factory; // Note - before sourceAct, so destroyed last
  14180. unsigned sourceIdx;
  14181. Linked<IRoxieServerActivity> sourceAct;
  14182. Linked<IFinalRoxieInput> sourceInput;
  14183. unsigned numUses;
  14184. unsigned iteration;
  14185. public:
  14186. CGraphIterationInfo(IRoxieServerActivity * _sourceAct, IFinalRoxieInput *_input, unsigned _sourceIdx, unsigned _iteration)
  14187. : sourceAct(_sourceAct), sourceInput(_input), sourceIdx(_sourceIdx), iteration(_iteration)
  14188. {
  14189. numUses = 0;
  14190. }
  14191. inline void noteUsed()
  14192. {
  14193. numUses++;
  14194. }
  14195. void createSplitter(IRoxieSlaveContext *ctx, IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes)
  14196. {
  14197. if (numUses > 1)
  14198. {
  14199. Owned<IPropertyTree> splitterNode = createPTree(ipt_fast);
  14200. factory.setown(createRoxieServerThroughSpillActivityFactory(sourceAct->queryFactory()->queryQueryFactory(), createGraphOutputSplitter, numUses, *splitterNode));
  14201. IRoxieServerActivity *splitter = factory->createActivity(ctx, NULL);
  14202. splitter->onCreate(NULL);
  14203. IFinalRoxieInput *input = sourceAct->queryOutput(sourceIdx);
  14204. if (probeManager)
  14205. {
  14206. IRoxieProbe * inputProbe = probeManager->createProbe(static_cast<IInputBase*>(input), sourceAct, splitter, sourceIdx, 0, iteration);
  14207. probes.append(*LINK(inputProbe));
  14208. input = &dynamic_cast<IFinalRoxieInput &>(inputProbe->queryInput());
  14209. sourceIdx = 0;
  14210. }
  14211. sourceAct.setown(splitter);
  14212. sourceAct->setInput(0, sourceIdx, input);
  14213. sourceIdx = 0;
  14214. sourceInput.clear();
  14215. }
  14216. }
  14217. IFinalRoxieInput *connectOutput(IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes, IRoxieServerActivity *targetAct, unsigned targetIdx)
  14218. {
  14219. // MORE - not really necessary to create splitters in separate pass, is it?
  14220. if (factory) // we created a splitter....
  14221. sourceInput.set(sourceAct->queryOutput(sourceIdx));
  14222. IFinalRoxieInput *ret = sourceInput;
  14223. if (probeManager)
  14224. {
  14225. IRoxieProbe * inputProbe = probeManager->createProbe(sourceInput, sourceAct, targetAct, sourceIdx, targetIdx, iteration);
  14226. probes.append(*LINK(inputProbe));
  14227. ret = &dynamic_cast<IFinalRoxieInput &>(inputProbe->queryInput());
  14228. // MORE - do we need to connect the stream in the probe?
  14229. }
  14230. if (factory) // we created a splitter....
  14231. sourceIdx++;
  14232. return ret;
  14233. }
  14234. };
  14235. class CRoxieServerParallelGraphLoopActivity : public CRoxieServerGraphLoopActivity, implements IRoxieServerLoopResultProcessor
  14236. {
  14237. Owned<IActivityGraph> childGraph;
  14238. IFinalRoxieInput * resultInput;
  14239. IEngineRowStream * resultStream;
  14240. Owned<IStrandJunction> resultJunction;
  14241. CIArrayOf<CGraphIterationInfo> outputs;
  14242. IArrayOf<IRoxieServerChildGraph> iterationGraphs;
  14243. Owned<CExtractMapperInput> inputExtractMapper;
  14244. IProbeManager *probeManager;
  14245. unsigned createLoopCounter;
  14246. IArrayOf<IRoxieProbe> probes;
  14247. public:
  14248. CRoxieServerParallelGraphLoopActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _GraphGraphId, IOutputMetaData * _counterMeta)
  14249. : CRoxieServerGraphLoopActivity(_ctx, _factory, _probeManager, _GraphGraphId, _counterMeta), probeManager(_probeManager)
  14250. {
  14251. inputExtractMapper.setown(new CExtractMapperInput);
  14252. resultInput = NULL;
  14253. resultStream = NULL;
  14254. createLoopCounter = 0;
  14255. }
  14256. virtual void onCreate(IHThorArg *_colocalParent)
  14257. {
  14258. CRoxieServerGraphLoopActivity::onCreate(_colocalParent);
  14259. childGraph.set(ctx->queryChildGraph(loopGraphId));
  14260. }
  14261. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  14262. {
  14263. //Input needs to be handled very carefully.....
  14264. //We don't want to call onStart on the input unless it is actually used, so don't use the base CRoxieServerActivity implementation.
  14265. //This activity's input needs to be started with (parentExtractSize, parentExtract), but the elements in the graph need to be started with the
  14266. //GraphExtractBuilder parent extract. So we need to wrap the input in a pseudo-input (inputExtractMapper) that passes through a different
  14267. //parentExtract. Something very similar will be needed for query library calls with streaming inputs when they are implemented.
  14268. assertex(idx == 0);
  14269. inputExtractMapper->setInput(_sourceIdx, _in);
  14270. }
  14271. virtual void connectInputStreams(bool consumerOrdered)
  14272. {
  14273. //NB: inputExtractMapper is not connected at this point - only if/when it is used from within the graph
  14274. CRoxieServerActivity::connectInputStreams(consumerOrdered);
  14275. }
  14276. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  14277. {
  14278. if (idx==0)
  14279. return inputExtractMapper->queryInput();
  14280. else
  14281. return NULL;
  14282. }
  14283. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14284. {
  14285. CRoxieServerGraphLoopActivity::start(parentExtractSize, parentExtract, paused); // initialises GraphExtractBuilder
  14286. inputExtractMapper->setParentExtract(parentExtractSize, parentExtract);
  14287. createExpandedGraph(GraphExtractBuilder.size(), GraphExtractBuilder.getbytes(), probeManager);
  14288. resultInput->start(GraphExtractBuilder.size(), GraphExtractBuilder.getbytes(), paused);
  14289. startJunction(resultJunction);
  14290. }
  14291. virtual void stop()
  14292. {
  14293. if (resultStream)
  14294. resultStream->stop();
  14295. CRoxieServerGraphLoopActivity::stop();
  14296. }
  14297. virtual void reset()
  14298. {
  14299. if (resultInput)
  14300. resultInput->reset();
  14301. resetJunction(resultJunction);
  14302. resultInput = NULL;
  14303. resultStream = NULL;
  14304. resultJunction.clear();
  14305. ForEachItemIn(i, iterationGraphs)
  14306. iterationGraphs.item(i).updateFactoryStatistics();
  14307. outputs.kill();
  14308. iterationGraphs.kill(); // must be done after all activities killed
  14309. if (probeManager)
  14310. {
  14311. probeManager->deleteGraph(NULL, (IArrayOf<IInputBase>*)&probes);
  14312. probes.kill();
  14313. }
  14314. CRoxieServerGraphLoopActivity::reset();
  14315. }
  14316. virtual const void * nextRow()
  14317. {
  14318. ActivityTimer t(totalCycles, timeActivities);
  14319. const void * ret = resultStream->nextRow();
  14320. if (ret)
  14321. processed++;
  14322. return ret;
  14323. }
  14324. void createExpandedGraph(unsigned parentExtractSize, const byte *parentExtract, IProbeManager *probeManager)
  14325. {
  14326. //result(0) is the input to the graph.
  14327. resultInput = inputExtractMapper;
  14328. outputs.append(* new CGraphIterationInfo(resultInput->queryActivity(), resultInput, 0, 1));
  14329. for (createLoopCounter=1; createLoopCounter <= maxIterations; createLoopCounter++)
  14330. {
  14331. IRoxieServerChildGraph * graph = childGraph->createGraphLoopInstance(ctx, createLoopCounter, parentExtractSize, parentExtract, *this);
  14332. graph->beforeExecute();
  14333. iterationGraphs.append(*graph);
  14334. graph->gatherIterationUsage(*this);
  14335. CGraphIterationInfo *iteration = graph->selectGraphLoopOutput();
  14336. outputs.append(*iteration);
  14337. }
  14338. createLoopCounter = 0;
  14339. createSplitters(probeManager, probes);
  14340. ForEachItemIn(i2, iterationGraphs)
  14341. iterationGraphs.item(i2).associateIterationOutputs(*this);
  14342. resultInput = outputs.tos().connectOutput(probeManager, probes, this, 0);
  14343. resultStream = connectSingleStream(ctx, resultInput, 0, resultJunction, true);
  14344. }
  14345. void createSplitters(IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes)
  14346. {
  14347. ForEachItemIn(i, outputs)
  14348. {
  14349. CGraphIterationInfo & next = outputs.item(i);
  14350. next.createSplitter(ctx, probeManager, probes);
  14351. }
  14352. }
  14353. //IRoxieServerLoopResultProcessor
  14354. virtual void noteUseIteration(unsigned _whichIteration)
  14355. {
  14356. int whichIteration = (int) _whichIteration; // May go negative - API is unsigned for historical reasons
  14357. if (whichIteration >= 0)
  14358. {
  14359. if (!outputs.isItem(whichIteration))
  14360. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Error reading graph result %d from iteration %d", whichIteration, createLoopCounter);
  14361. outputs.item(whichIteration).noteUsed();
  14362. }
  14363. }
  14364. virtual IFinalRoxieInput* connectIterationOutput(unsigned whichIteration, IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes, IRoxieServerActivity *targetAct, unsigned targetIdx)
  14365. {
  14366. if (outputs.isItem(whichIteration))
  14367. {
  14368. CGraphIterationInfo & next = outputs.item(whichIteration);
  14369. return next.connectOutput(probeManager, probes, targetAct, targetIdx);
  14370. }
  14371. return NULL;
  14372. }
  14373. };
  14374. //=================================================================================
  14375. class CRoxieServerGraphLoopActivityFactory : public CRoxieServerActivityFactory
  14376. {
  14377. unsigned loopGraphId;
  14378. unsigned flags;
  14379. Linked<IOutputMetaData> counterMeta;
  14380. public:
  14381. CRoxieServerGraphLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _loopGraphId)
  14382. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), loopGraphId(_loopGraphId)
  14383. {
  14384. Owned<IHThorGraphLoopArg> helper = (IHThorGraphLoopArg *) helperFactory();
  14385. flags = helper->getFlags();
  14386. counterMeta.setown(new CCounterRowMetaData);
  14387. }
  14388. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  14389. {
  14390. if (kind == TAKparallelgraphloop)
  14391. return new CRoxieServerParallelGraphLoopActivity(_ctx, this, _probeManager, loopGraphId, counterMeta);
  14392. else
  14393. return new CRoxieServerSequentialGraphLoopActivity(_ctx, this, _probeManager, loopGraphId, counterMeta);
  14394. }
  14395. };
  14396. IRoxieServerActivityFactory *createRoxieServerGraphLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _loopGraphId)
  14397. {
  14398. return new CRoxieServerGraphLoopActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _loopGraphId);
  14399. }
  14400. //=====================================================================================================
  14401. class CRoxieServerLibraryCallActivity : public CRoxieServerActivity
  14402. {
  14403. class OutputAdaptor : public CExtractMapperInput
  14404. {
  14405. bool stopped;
  14406. public:
  14407. CRoxieServerLibraryCallActivity *parent;
  14408. IOutputMetaData * meta = nullptr;
  14409. unsigned oid;
  14410. unsigned processed;
  14411. public:
  14412. OutputAdaptor()
  14413. {
  14414. parent = NULL;
  14415. oid = 0;
  14416. init();
  14417. }
  14418. ~OutputAdaptor()
  14419. {
  14420. if (traceStartStop)
  14421. DBGLOG("%p ~OutputAdaptor %d", this, oid);
  14422. if (processed && parent && parent->factory)
  14423. {
  14424. parent->factory->noteProcessed(oid, processed);
  14425. if (parent->ctx)
  14426. parent->ctx->noteProcessed(parent->querySubgraphId(), parent->activityId, oid, processed, 0);
  14427. }
  14428. }
  14429. void setParent(CRoxieServerLibraryCallActivity * _parent, IOutputMetaData * _meta, unsigned _oid)
  14430. {
  14431. parent = _parent;
  14432. meta = _meta;
  14433. oid = _oid;
  14434. }
  14435. void init()
  14436. {
  14437. processed = 0;
  14438. stopped = false;
  14439. }
  14440. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14441. {
  14442. parent->start(oid, parentExtractSize, parentExtract, paused);
  14443. CExtractMapperInput::start(parentExtractSize, parentExtract, paused);
  14444. }
  14445. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  14446. {
  14447. //MORE value of consumerOrdered depends on whether this activity is marked as ordered.
  14448. if (!oid) // Only need to set up once
  14449. {
  14450. parent->connectInputStreams(true); // To handle dependencies etc
  14451. }
  14452. return CExtractMapperInput::getOutputStreams(ctx, 0, streams, nullptr, true, nullptr);
  14453. }
  14454. //This override should not really be needed, but input is set up too late for the call to connect strands
  14455. virtual IOutputMetaData * queryOutputMeta() const
  14456. {
  14457. return meta;
  14458. }
  14459. virtual void stop()
  14460. {
  14461. if (!stopped)
  14462. {
  14463. stopped = true;
  14464. parent->stop(oid); // parent code relies on stop being called exactly once per adaptor, so make sure it is!
  14465. CExtractMapperInput::stop();
  14466. }
  14467. };
  14468. virtual void reset()
  14469. {
  14470. parent->reset(oid);
  14471. CExtractMapperInput::reset();
  14472. init();
  14473. };
  14474. virtual void checkAbort()
  14475. {
  14476. parent->checkAbort();
  14477. }
  14478. };
  14479. IHThorLibraryCallArg &helper;
  14480. unsigned numInputs;
  14481. unsigned numOutputs;
  14482. unsigned numActiveOutputs;
  14483. bool started;
  14484. OutputAdaptor* outputAdaptors;
  14485. CExtractMapperInput * * inputAdaptors;
  14486. bool * inputUsed;
  14487. bool * outputUsed;
  14488. Owned<IException> error;
  14489. CriticalSection crit;
  14490. rtlRowBuilder libraryExtractBuilder;
  14491. Owned<IActivityGraph> libraryGraph;
  14492. const LibraryCallFactoryExtra & extra;
  14493. public:
  14494. CRoxieServerLibraryCallActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs, unsigned _numOutputs, const LibraryCallFactoryExtra & _extra)
  14495. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  14496. helper((IHThorLibraryCallArg &)basehelper), extra(_extra)
  14497. {
  14498. numInputs = _numInputs;
  14499. numOutputs = _numOutputs;
  14500. numActiveOutputs = numOutputs;
  14501. inputAdaptors = new CExtractMapperInput*[numInputs];
  14502. inputUsed = new bool[numInputs];
  14503. for (unsigned i1 = 0; i1 < numInputs; i1++)
  14504. {
  14505. inputAdaptors[i1] = new CExtractMapperInput;
  14506. inputUsed[i1] = false;
  14507. }
  14508. outputAdaptors = new OutputAdaptor[numOutputs];
  14509. outputUsed = new bool[numOutputs];
  14510. for (unsigned i2 = 0; i2 < numOutputs; i2++)
  14511. {
  14512. outputAdaptors[i2].setParent(this, helper.queryOutputMeta(i2), i2);
  14513. outputUsed[i2] = false;
  14514. }
  14515. started = false;
  14516. }
  14517. ~CRoxieServerLibraryCallActivity()
  14518. {
  14519. for (unsigned i1 = 0; i1 < numInputs; i1++)
  14520. ::Release(inputAdaptors[i1]);
  14521. delete [] inputAdaptors;
  14522. delete [] inputUsed;
  14523. delete [] outputAdaptors;
  14524. delete [] outputUsed;
  14525. }
  14526. virtual void onCreate(IHThorArg *_colocalParent)
  14527. {
  14528. CRoxieServerActivity::onCreate(_colocalParent);
  14529. libraryGraph.setown(ctx->getLibraryGraph(extra, this));
  14530. libraryGraph->onCreate(_colocalParent);
  14531. //Now map the inputs and outputs to the adapters
  14532. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  14533. for (unsigned i1=0; i1<numInputs; i1++)
  14534. inputUsed[i1] = graph->querySetInputResult(i1, 0, inputAdaptors[i1]);
  14535. for (unsigned i2=0; i2<numOutputs; i2++)
  14536. {
  14537. unsigned outputIndex = extra.outputs.item(i2);
  14538. Owned<IFinalRoxieInput> output = graph->selectOutput(numInputs+outputIndex);
  14539. outputAdaptors[i2].setInput(0, output); // MORE - no idea if this 0 is right??
  14540. outputAdaptors[i2].connectInputStreams(ctx, true);
  14541. }
  14542. }
  14543. virtual void start(unsigned oid, unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14544. {
  14545. CriticalBlock b(crit);
  14546. if (error)
  14547. throw error.getLink();
  14548. if (factory)
  14549. factory->noteStarted(oid);
  14550. if (!started)
  14551. {
  14552. // even though it is not complete, we don't want to run this again if it fails.
  14553. started = true;
  14554. //see notes on splitter above
  14555. try
  14556. {
  14557. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14558. }
  14559. catch (IException *E)
  14560. {
  14561. #ifdef TRACE_SPLIT
  14562. CTXLOG("spill %d caught exception in start", activityId);
  14563. #endif
  14564. error.set(E);
  14565. throw;
  14566. }
  14567. catch (...)
  14568. {
  14569. IException *E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught in CRoxieServerLibraryCallActivity::start");
  14570. error.set(E);
  14571. throw E;
  14572. }
  14573. //recreate the parent extract, and use it to reinitialize the graphs...
  14574. libraryExtractBuilder.clear();
  14575. helper.createParentExtract(libraryExtractBuilder);
  14576. // 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
  14577. // some inputs before we see start on others.
  14578. for (unsigned i1 = 0; i1 < numInputs; i1++)
  14579. {
  14580. if (inputUsed[i1])
  14581. inputAdaptors[i1]->setParentExtract(parentExtractSize, parentExtract);
  14582. else
  14583. inputAdaptors[i1]->queryInput()->stopall();
  14584. }
  14585. for (unsigned i2 = 0; i2 < numOutputs; i2++)
  14586. outputAdaptors[i2].setParentExtract(libraryExtractBuilder.size(), libraryExtractBuilder.getbytes());
  14587. //call stop on all the unused inputs.
  14588. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  14589. graph->beforeExecute();
  14590. ForEachItemIn(i3, extra.unusedOutputs)
  14591. {
  14592. Owned<IFinalRoxieInput> output = graph->selectOutput(numInputs+extra.unusedOutputs.item(i3));
  14593. output->stopall();
  14594. }
  14595. }
  14596. }
  14597. virtual void stop(unsigned oid)
  14598. {
  14599. CriticalBlock b(crit);
  14600. if (--numActiveOutputs == 0)
  14601. {
  14602. //call stop on all the unused inputs.
  14603. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  14604. graph->beforeExecute();
  14605. ForEachItemIn(i3, extra.unusedOutputs)
  14606. {
  14607. Owned<IFinalRoxieInput> output = graph->selectOutput(numInputs+extra.unusedOutputs.item(i3));
  14608. output->stopall();
  14609. }
  14610. CRoxieServerActivity::stop();
  14611. }
  14612. }
  14613. void reset(unsigned oid)
  14614. {
  14615. started = false;
  14616. error.clear();
  14617. numActiveOutputs = numOutputs;
  14618. if (state != STATEreset) // make sure input is only reset once
  14619. {
  14620. CRoxieServerActivity::reset();
  14621. libraryGraph->reset();
  14622. //Call reset on all unused inputs/outputs from the graph - no one else will.
  14623. for (unsigned i1 = 0; i1 < numInputs; i1++)
  14624. {
  14625. if (!inputUsed[i1])
  14626. inputAdaptors[i1]->reset();
  14627. }
  14628. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  14629. ForEachItemIn(i3, extra.unusedOutputs)
  14630. {
  14631. Owned<IFinalRoxieInput> output = graph->selectOutput(numInputs+extra.unusedOutputs.item(i3));
  14632. output->reset();
  14633. }
  14634. }
  14635. };
  14636. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  14637. {
  14638. inputAdaptors[idx]->setInput(_sourceIdx, _in);
  14639. }
  14640. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  14641. {
  14642. if (idx < numInputs && inputAdaptors[idx])
  14643. return inputAdaptors[idx]->queryInput();
  14644. else
  14645. return NULL;
  14646. }
  14647. public:
  14648. virtual const void *nextRow()
  14649. {
  14650. throwUnexpected(); // Internal logic error - we are not anybody's input
  14651. }
  14652. virtual IOutputMetaData * queryOutputMeta() const
  14653. {
  14654. throwUnexpected(); // should be called on outputs instead
  14655. }
  14656. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  14657. {
  14658. assertex(idx!=(unsigned)-1);
  14659. assertex(!outputUsed[idx]);
  14660. outputUsed[idx] = true;
  14661. return &outputAdaptors[idx];
  14662. }
  14663. virtual void updateFactoryStatistics() const override
  14664. {
  14665. if (libraryGraph)
  14666. libraryGraph->updateFactoryStatistics();
  14667. CRoxieServerActivity::updateFactoryStatistics();
  14668. }
  14669. };
  14670. void LibraryCallFactoryExtra::set(const LibraryCallFactoryExtra & _other)
  14671. {
  14672. ForEachItemIn(i1, _other.outputs)
  14673. outputs.append(_other.outputs.item(i1));
  14674. ForEachItemIn(i2, _other.unusedOutputs)
  14675. unusedOutputs.append(_other.unusedOutputs.item(i2));
  14676. maxOutputs = _other.maxOutputs;
  14677. graphid = _other.graphid;
  14678. libraryName.set(_other.libraryName);
  14679. embeddedGraphName.set(_other.embeddedGraphName);
  14680. interfaceHash = _other.interfaceHash;
  14681. embedded = _other.embedded;
  14682. }
  14683. void LibraryCallFactoryExtra::calcUnused()
  14684. {
  14685. for (unsigned i=0; i < maxOutputs; i++)
  14686. if (!outputs.contains(i))
  14687. unusedOutputs.append(i);
  14688. }
  14689. class CRoxieServerLibraryCallActivityFactory : public CRoxieServerMultiOutputFactory
  14690. {
  14691. private:
  14692. CRoxieServerMultiInputInfo inputs;
  14693. LibraryCallFactoryExtra extra;
  14694. public:
  14695. CRoxieServerLibraryCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, LibraryCallFactoryExtra & _extra)
  14696. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  14697. {
  14698. extra.set(_extra);
  14699. extra.calcUnused();
  14700. setNumOutputs(extra.outputs.ordinality());
  14701. }
  14702. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  14703. {
  14704. return new CRoxieServerLibraryCallActivity(_ctx, this, _probeManager, numInputs(), numOutputs, extra);
  14705. }
  14706. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  14707. {
  14708. inputs.set(idx, source, sourceidx);
  14709. }
  14710. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  14711. {
  14712. return inputs.get(idx, sourceidx);
  14713. }
  14714. virtual unsigned numInputs() const { return inputs.ordinality(); }
  14715. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  14716. {
  14717. addXrefLibraryInfo(reply, extra.libraryName);
  14718. }
  14719. };
  14720. IRoxieServerActivityFactory *createRoxieServerLibraryCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, LibraryCallFactoryExtra & _extra)
  14721. {
  14722. return new CRoxieServerLibraryCallActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _extra);
  14723. }
  14724. //=====================================================================================================
  14725. // CRoxieServerNWayInputActivity is a multi-input, multi-output activity, where the outputs are a subset of the inputs
  14726. // Used to implement RANGE(<rowset-expression>, [set-of-indices])
  14727. class CRoxieServerNWayInputBaseActivity : public CRoxieServerMultiInputBaseActivity
  14728. {
  14729. protected:
  14730. PointerArrayOf<IFinalRoxieInput> selectedInputs;
  14731. PointerArrayOf<IEngineRowStream> selectedStreams;
  14732. PointerArrayOf<IStrandJunction> selectedJunctions;
  14733. public:
  14734. CRoxieServerNWayInputBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14735. : CRoxieServerMultiInputBaseActivity(_ctx, _factory, _probeManager, _numInputs)
  14736. {
  14737. }
  14738. virtual unsigned __int64 queryLocalCycles() const
  14739. {
  14740. __int64 localCycles = totalCycles.totalCycles;
  14741. ForEachItemIn(i, selectedInputs)
  14742. {
  14743. localCycles -= selectedInputs.item(i)->queryTotalCycles();
  14744. }
  14745. if (localCycles < 0)
  14746. localCycles = 0;
  14747. return localCycles;
  14748. }
  14749. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  14750. {
  14751. if (selectedInputs.isItem(idx))
  14752. return selectedInputs.item(idx);
  14753. else
  14754. return NULL;
  14755. }
  14756. virtual void reset()
  14757. {
  14758. ForEachItemIn(i, selectedInputs)
  14759. selectedInputs.item(i)->reset();
  14760. selectedInputs.kill();
  14761. selectedStreams.kill();
  14762. selectedJunctions.kill();
  14763. CRoxieServerMultiInputBaseActivity::reset();
  14764. }
  14765. virtual const void * nextRow()
  14766. {
  14767. throwUnexpected();
  14768. }
  14769. virtual unsigned numConcreteOutputs() const
  14770. {
  14771. return selectedInputs.ordinality();
  14772. }
  14773. virtual IFinalRoxieInput * queryConcreteInput(unsigned idx)
  14774. {
  14775. return queryInput(idx);
  14776. }
  14777. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput)
  14778. {
  14779. if (selectedStreams.isItem(whichInput))
  14780. return selectedStreams.item(whichInput);
  14781. return NULL;
  14782. }
  14783. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const
  14784. {
  14785. if (selectedJunctions.isItem(idx))
  14786. return selectedJunctions.item(idx);
  14787. return NULL;
  14788. }
  14789. };
  14790. class CRoxieServerNWayInputActivity : public CRoxieServerNWayInputBaseActivity
  14791. {
  14792. IHThorNWayInputArg & helper;
  14793. public:
  14794. CRoxieServerNWayInputActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14795. : CRoxieServerNWayInputBaseActivity(_ctx, _factory, _probeManager, _numInputs), helper((IHThorNWayInputArg &)basehelper)
  14796. {
  14797. }
  14798. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14799. {
  14800. CRoxieServerNWayInputBaseActivity::start(parentExtractSize, parentExtract, paused);
  14801. bool selectionIsAll;
  14802. size32_t selectionLen;
  14803. rtlDataAttr selection;
  14804. helper.getInputSelection(selectionIsAll, selectionLen, selection.refdata());
  14805. selectedInputs.kill();
  14806. selectedStreams.kill();
  14807. selectedJunctions.kill();
  14808. assertex(numInputs==numStreams); // Will need refactoring when that ceases to be true
  14809. if (selectionIsAll)
  14810. {
  14811. for (unsigned i=0; i < numInputs; i++)
  14812. {
  14813. selectedInputs.append(inputArray[i]);
  14814. selectedStreams.append(streamArray[i]); // Assumes 1:1 relationship - is that good?
  14815. selectedJunctions.append(junctionArray[i]);
  14816. }
  14817. }
  14818. else
  14819. {
  14820. const size32_t * selections = (const size32_t *)selection.getdata();
  14821. unsigned max = selectionLen/sizeof(size32_t);
  14822. for (unsigned i = 0; i < max; i++)
  14823. {
  14824. unsigned nextIndex = selections[i];
  14825. //Check there are no duplicates..... Assumes there are a fairly small number of inputs, so n^2 search is ok.
  14826. for (unsigned j=i+1; j < max; j++)
  14827. {
  14828. if (nextIndex == selections[j])
  14829. throw MakeStringException(ROXIE_NWAY_INPUT_ERROR, "Selection list for nway input can not contain duplicates");
  14830. }
  14831. if (nextIndex > numInputs || nextIndex > numStreams)
  14832. throw MakeStringException(ROXIE_NWAY_INPUT_ERROR, "Index %d in RANGE selection list is out of range", nextIndex);
  14833. selectedInputs.append(inputArray[nextIndex-1]);
  14834. selectedStreams.append(streamArray[nextIndex-1]); // Assumes 1:1 relationship - is that good?
  14835. selectedJunctions.append(junctionArray[nextIndex-1]);
  14836. }
  14837. }
  14838. // NB: Whatever pulls this nwayinput activity, starts and stops the selectedInputs and selectedJunctions
  14839. // But the N-Way input itself is now done with processing, and can stop itself/dependencies.
  14840. stop();
  14841. }
  14842. };
  14843. class CRoxieServerNWayInputActivityFactory : public CRoxieServerMultiInputFactory
  14844. {
  14845. public:
  14846. CRoxieServerNWayInputActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  14847. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  14848. {
  14849. }
  14850. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  14851. {
  14852. return new CRoxieServerNWayInputActivity(_ctx, this, _probeManager, numInputs());
  14853. }
  14854. };
  14855. IRoxieServerActivityFactory *createRoxieServerNWayInputActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  14856. {
  14857. return new CRoxieServerNWayInputActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  14858. }
  14859. //=====================================================================================================
  14860. class CRoxieServerNWayGraphLoopResultReadActivity : public CRoxieServerNWayInputBaseActivity
  14861. {
  14862. IHThorNWayGraphLoopResultReadArg & helper;
  14863. IArrayOf<IRoxieServerActivity> resultReaders;
  14864. Owned<IStrandJunction> *resultJunctions;
  14865. unsigned graphId;
  14866. bool grouped;
  14867. bool selectionIsAll;
  14868. size32_t selectionLen;
  14869. rtlDataAttr selection;
  14870. public:
  14871. CRoxieServerNWayGraphLoopResultReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId)
  14872. : CRoxieServerNWayInputBaseActivity(_ctx, _factory, _probeManager, 0), helper((IHThorNWayGraphLoopResultReadArg &)basehelper)
  14873. {
  14874. grouped = helper.isGrouped();
  14875. graphId = _graphId;
  14876. selectionIsAll = false;
  14877. selectionLen = 0;
  14878. resultJunctions = NULL;
  14879. }
  14880. ~CRoxieServerNWayGraphLoopResultReadActivity()
  14881. {
  14882. delete [] resultJunctions;
  14883. }
  14884. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14885. {
  14886. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14887. if (selectedInputs.ordinality() == 0)
  14888. {
  14889. initInputSelection();
  14890. unsigned max = selectionLen / sizeof(size32_t);
  14891. const size32_t * selections = (const size32_t *)selection.getdata();
  14892. IProbeManager * probeManager = NULL; // MORE!!
  14893. for (unsigned i = 0; i < max; i++)
  14894. {
  14895. CRoxieServerActivity * resultInput = new CRoxieServerInternalGraphLoopResultReadActivity(ctx, factory, probeManager, graphId, selections[i]);
  14896. resultReaders.append(*resultInput);
  14897. selectedInputs.append(resultInput);
  14898. resultInput->onCreate(colocalParent);
  14899. resultInput->start(parentExtractSize, parentExtract, paused);
  14900. selectedStreams.append(connectSingleStream(ctx, resultInput, 0, resultJunctions[i], true));
  14901. selectedJunctions.append(resultJunctions[i]);
  14902. }
  14903. }
  14904. // I have done with my processing - note that this won't stop my inputs
  14905. stop();
  14906. }
  14907. virtual void reset()
  14908. {
  14909. resultReaders.kill();
  14910. CRoxieServerNWayInputBaseActivity::reset();
  14911. ForEachItemIn(i, selectedStreams)
  14912. resetJunction(resultJunctions[i]);
  14913. }
  14914. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract)
  14915. {
  14916. ensureCreated();
  14917. basehelper.onStart(parentExtract, NULL);
  14918. initInputSelection();
  14919. unsigned max = selectionLen / sizeof(size32_t);
  14920. const size32_t * selections = (const size32_t *)selection.getdata();
  14921. for (unsigned i = 0; i < max; i++)
  14922. processor.noteUseIteration(selections[i]);
  14923. }
  14924. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract, IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes)
  14925. {
  14926. //selection etc. already initialised from the gatherIterationUsage() call.
  14927. unsigned max = selectionLen / sizeof(size32_t);
  14928. const size32_t * selections = (const size32_t *)selection.getdata();
  14929. resultJunctions = new Owned<IStrandJunction> [max];
  14930. for (unsigned i = 0; i < max; i++)
  14931. {
  14932. IFinalRoxieInput *in = processor.connectIterationOutput(selections[i], probeManager, probes, this, i);
  14933. selectedInputs.append(in);
  14934. selectedStreams.append(connectSingleStream(ctx, in, 0, resultJunctions[i], true));
  14935. selectedJunctions.append(resultJunctions[i]);
  14936. }
  14937. }
  14938. protected:
  14939. void initInputSelection()
  14940. {
  14941. helper.getInputSelection(selectionIsAll, selectionLen, selection.refdata());
  14942. if (selectionIsAll)
  14943. throw MakeStringException(ROXIE_NWAY_INPUT_ERROR, "ALL not yet supported for NWay graph inputs");
  14944. }
  14945. };
  14946. class CRoxieServerNWayGraphLoopResultReadActivityFactory : public CRoxieServerActivityFactory
  14947. {
  14948. unsigned graphId;
  14949. public:
  14950. CRoxieServerNWayGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _graphId)
  14951. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), graphId(_graphId)
  14952. {
  14953. }
  14954. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  14955. {
  14956. return new CRoxieServerNWayGraphLoopResultReadActivity(_ctx, this, _probeManager, graphId);
  14957. }
  14958. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  14959. {
  14960. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for NWay GraphLoopResultRead activity");
  14961. }
  14962. };
  14963. IRoxieServerActivityFactory *createRoxieServerNWayGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned graphId)
  14964. {
  14965. return new CRoxieServerNWayGraphLoopResultReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, graphId);
  14966. }
  14967. //=================================================================================
  14968. class RoxieSteppedInput : implements ISteppedInput, public CInterface
  14969. {
  14970. public:
  14971. RoxieSteppedInput(IFinalRoxieInput * _input, IEngineRowStream *_stream) { input = _input; inputStream = _stream; }
  14972. IMPLEMENT_IINTERFACE
  14973. protected:
  14974. virtual const void * nextInputRow()
  14975. {
  14976. #ifdef TRACE_SEEK_REQUESTS
  14977. IRoxieContextLogger * logger = input->queryActivity();
  14978. const void * ret = doNextInputRow();
  14979. {
  14980. CommonXmlWriter xmlwrite(XWFtrim|XWFopt|XWFnoindent);
  14981. if (!ret)
  14982. xmlwrite.outputBool(true,"eof");
  14983. else if (input->queryOutputMeta()->hasXML())
  14984. input->queryOutputMeta()->toXML((byte *) ret, xmlwrite);
  14985. logger->CTXLOG("next() returns (%s)", xmlwrite.str());
  14986. }
  14987. return ret;
  14988. #else
  14989. return inputStream->ungroupedNextRow();
  14990. #endif
  14991. }
  14992. virtual const void * nextInputRowGE(const void * seek, unsigned numFields, bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  14993. {
  14994. #ifdef TRACE_SEEK_REQUESTS
  14995. IRoxieContextLogger * logger = input->queryActivity();
  14996. {
  14997. CommonXmlWriter xmlwrite(XWFtrim|XWFopt|XWFnoindent);
  14998. if (input->queryOutputMeta()->hasXML())
  14999. input->queryOutputMeta()->toXML((byte *) seek, xmlwrite);
  15000. logger->CTXLOG("nextInputRowGE(%d, %s%s%s, %s) seek(%s)",
  15001. numFields,
  15002. stepExtra.readAheadManyResults() ? "readahead " : "",
  15003. stepExtra.returnMismatches() ? "mismatch" : "exact",
  15004. stepExtra.onlyReturnFirstSeekMatch() ? " single-match" : "",
  15005. stepExtra.queryExtraSeeks() ? "multi-seek":"",
  15006. xmlwrite.str());
  15007. }
  15008. const void * ret = doNextInputRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  15009. {
  15010. CommonXmlWriter xmlwrite(XWFtrim|XWFopt|XWFnoindent);
  15011. if (!ret)
  15012. xmlwrite.outputBool(true,"eof");
  15013. else if (input->queryOutputMeta()->hasXML())
  15014. input->queryOutputMeta()->toXML((byte *) ret, xmlwrite);
  15015. logger->CTXLOG("nextInputRowGE(%d, %s%s%s, %s) result(%s)",
  15016. numFields,
  15017. stepExtra.readAheadManyResults() ? "readahead " : "",
  15018. stepExtra.returnMismatches() ? "mismatch" : "exact",
  15019. stepExtra.onlyReturnFirstSeekMatch() ? " single-match" : "",
  15020. stepExtra.queryExtraSeeks() ? "multi-seek":"",
  15021. xmlwrite.str());
  15022. }
  15023. return ret;
  15024. #else
  15025. return doNextInputRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  15026. #endif
  15027. }
  15028. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  15029. {
  15030. return input->gatherConjunctions(collector);
  15031. }
  15032. virtual void resetEOF()
  15033. {
  15034. inputStream->resetEOF();
  15035. }
  15036. virtual IInputSteppingMeta * queryInputSteppingMeta()
  15037. {
  15038. return input->querySteppingMeta();
  15039. }
  15040. inline const void * doNextInputRowGE(const void * seek, unsigned numFields, bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  15041. {
  15042. assertex(wasCompleteMatch);
  15043. return inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  15044. }
  15045. protected:
  15046. IFinalRoxieInput * input;
  15047. IEngineRowStream * inputStream;
  15048. };
  15049. //=================================================================================
  15050. class CRoxieServerNWayBaseActivity : public CRoxieServerMultiInputBaseActivity
  15051. {
  15052. public:
  15053. CRoxieServerNWayBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  15054. : CRoxieServerMultiInputBaseActivity(_ctx, _factory, _probeManager, _numInputs)
  15055. {
  15056. }
  15057. void startExpandedInputs(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15058. {
  15059. ForEachItemIn(ei, expandedInputs)
  15060. expandedInputs.item(ei)->start(parentExtractSize, parentExtract, paused);
  15061. ForEachItemIn(idx, expandedInputs)
  15062. startJunction(expandedJunctions.item(idx));
  15063. }
  15064. virtual void stop()
  15065. {
  15066. ForEachItemIn(i, expandedStreams)
  15067. expandedStreams.item(i)->stop();
  15068. CRoxieServerMultiInputBaseActivity::stop();
  15069. }
  15070. virtual void reset()
  15071. {
  15072. ForEachItemIn(idx, expandedInputs)
  15073. resetJunction(expandedJunctions.item(idx));
  15074. expandedInputs.kill();
  15075. expandedStreams.kill();
  15076. expandedJunctions.kill();
  15077. CRoxieServerMultiInputBaseActivity::reset();
  15078. }
  15079. protected:
  15080. PointerArrayOf<IFinalRoxieInput> expandedInputs;
  15081. PointerArrayOf<IEngineRowStream> expandedStreams;
  15082. PointerArrayOf<IStrandJunction> expandedJunctions;
  15083. };
  15084. //=================================================================================
  15085. class CRoxieServerNaryActivity : public CRoxieServerNWayBaseActivity
  15086. {
  15087. public:
  15088. CRoxieServerNaryActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  15089. : CRoxieServerNWayBaseActivity(_ctx, _factory, _probeManager, _numInputs)
  15090. {
  15091. }
  15092. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15093. {
  15094. CRoxieServerNWayBaseActivity::start(parentExtractSize, parentExtract, paused);
  15095. for (unsigned i=0; i < numInputs; i++)
  15096. {
  15097. IFinalRoxieInput * cur = inputArray[i];
  15098. CRoxieServerNWayInputBaseActivity *nWayInput = dynamic_cast<CRoxieServerNWayInputBaseActivity *>(cur);
  15099. if (nWayInput)
  15100. {
  15101. nWayInput->start(parentExtractSize, parentExtract, paused);
  15102. unsigned numRealInputs = cur->numConcreteOutputs();
  15103. for (unsigned j = 0; j < numRealInputs; j++)
  15104. {
  15105. expandedInputs.append(cur->queryConcreteInput(j));
  15106. expandedStreams.append(cur->queryConcreteOutputStream(j));
  15107. expandedJunctions.append(cur->queryConcreteOutputJunction(j));
  15108. }
  15109. }
  15110. else
  15111. {
  15112. expandedInputs.append(cur);
  15113. // NB: this activities input streams + junction have been setup and held in CRoxieServerMultiInputActivity base
  15114. expandedStreams.append(queryConcreteOutputStream(i));
  15115. expandedJunctions.append(queryConcreteOutputJunction(i));
  15116. }
  15117. }
  15118. startExpandedInputs(parentExtractSize, parentExtract, paused);
  15119. }
  15120. };
  15121. //=================================================================================
  15122. class CRoxieStreamMerger : public CStreamMerger
  15123. {
  15124. public:
  15125. CRoxieStreamMerger() : CStreamMerger(true)
  15126. {
  15127. streamArray = NULL;
  15128. }
  15129. void initInputs(unsigned _numInputs, IEngineRowStream ** _streamArray)
  15130. {
  15131. CStreamMerger::initInputs(_numInputs);
  15132. streamArray = _streamArray;
  15133. }
  15134. virtual bool pullInput(unsigned i, const void * seek, unsigned numFields, const SmartStepExtra * stepExtra)
  15135. {
  15136. const void * next;
  15137. bool matches = true;
  15138. if (seek)
  15139. next = streamArray[i]->nextRowGE(seek, numFields, matches, *stepExtra);
  15140. else
  15141. next = streamArray[i]->ungroupedNextRow();
  15142. pending[i] = next;
  15143. pendingMatches[i] = matches;
  15144. return (next != NULL);
  15145. }
  15146. virtual void releaseRow(const void * row)
  15147. {
  15148. ReleaseRoxieRow(row);
  15149. }
  15150. protected:
  15151. IEngineRowStream **streamArray;
  15152. };
  15153. class CRoxieServerNWayMergeActivity : public CRoxieServerNaryActivity
  15154. {
  15155. public:
  15156. CRoxieServerNWayMergeActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  15157. : CRoxieServerNaryActivity(_ctx, _factory, _probeManager, _numInputs),
  15158. helper((IHThorNWayMergeArg &)basehelper)
  15159. {
  15160. initializedMeta = false;
  15161. }
  15162. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15163. {
  15164. CRoxieServerNaryActivity::start(parentExtractSize, parentExtract, paused);
  15165. merger.init(helper.queryCompare(), helper.dedup(), helper.querySteppingMeta()->queryCompare());
  15166. merger.initInputs(expandedStreams.length(), expandedStreams.getArray());
  15167. }
  15168. virtual void stop()
  15169. {
  15170. merger.done();
  15171. CRoxieServerNaryActivity::stop();
  15172. }
  15173. virtual void reset()
  15174. {
  15175. merger.cleanup();
  15176. CRoxieServerNaryActivity::reset();
  15177. initializedMeta = false;
  15178. }
  15179. virtual const void * nextRow()
  15180. {
  15181. ActivityTimer t(totalCycles, timeActivities);
  15182. const void * next = merger.nextRow();
  15183. if (next)
  15184. processed++;
  15185. return next;
  15186. }
  15187. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  15188. {
  15189. ActivityTimer t(totalCycles, timeActivities);
  15190. const void * next = merger.nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  15191. if (next)
  15192. processed++;
  15193. return next;
  15194. }
  15195. virtual IInputSteppingMeta * querySteppingMeta()
  15196. {
  15197. if (expandedStreams.ordinality() == 0)
  15198. return NULL;
  15199. if (!initializedMeta)
  15200. {
  15201. meta.init(helper.querySteppingMeta(), false);
  15202. ForEachItemIn(i, expandedStreams)
  15203. {
  15204. if (meta.getNumFields() == 0)
  15205. break;
  15206. IInputSteppingMeta * inputMeta = expandedInputs.item(i)->querySteppingMeta();
  15207. meta.intersect(inputMeta);
  15208. }
  15209. initializedMeta = true;
  15210. }
  15211. if (meta.getNumFields() == 0)
  15212. return NULL;
  15213. return &meta;
  15214. }
  15215. protected:
  15216. IHThorNWayMergeArg &helper;
  15217. CRoxieStreamMerger merger;
  15218. CSteppingMeta meta;
  15219. bool initializedMeta;
  15220. };
  15221. class CRoxieServerNWayMergeActivityFactory : public CRoxieServerMultiInputFactory
  15222. {
  15223. public:
  15224. CRoxieServerNWayMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15225. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15226. {
  15227. }
  15228. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15229. {
  15230. return new CRoxieServerNWayMergeActivity(_ctx, this, _probeManager, numInputs());
  15231. }
  15232. };
  15233. IRoxieServerActivityFactory *createRoxieServerNWayMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15234. {
  15235. return new CRoxieServerNWayMergeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15236. }
  15237. //=================================================================================
  15238. class CRoxieServerNWayMergeJoinActivity : public CRoxieServerNaryActivity
  15239. {
  15240. public:
  15241. CRoxieServerNWayMergeJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs, CMergeJoinProcessor & _processor)
  15242. : CRoxieServerNaryActivity(_ctx, _factory, _probeManager, _numInputs),processor(_processor),
  15243. helper((IHThorNWayMergeJoinArg &)basehelper)
  15244. {
  15245. }
  15246. virtual void onCreate(IHThorArg *_colocalParent)
  15247. {
  15248. CRoxieServerNaryActivity::onCreate(_colocalParent);
  15249. ICodeContext * codectx = ctx->queryCodeContext();
  15250. inputAllocator.setown(createRowAllocator(helper.queryInputMeta()));
  15251. outputAllocator.setown(createRowAllocator(helper.queryOutputMeta()));
  15252. }
  15253. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15254. {
  15255. CRoxieServerNaryActivity::start(parentExtractSize, parentExtract, paused);
  15256. ForEachItemIn(i1, expandedInputs)
  15257. {
  15258. Owned<RoxieSteppedInput> stepInput = new RoxieSteppedInput(expandedInputs.item(i1), expandedStreams.item(i1));
  15259. processor.addInput(stepInput);
  15260. }
  15261. processor.beforeProcessing(inputAllocator, outputAllocator);
  15262. }
  15263. virtual void stop()
  15264. {
  15265. processor.afterProcessing();
  15266. CRoxieServerNaryActivity::stop();
  15267. }
  15268. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  15269. {
  15270. return processor.gatherConjunctions(collector);
  15271. }
  15272. virtual void resetEOF()
  15273. {
  15274. processor.queryResetEOF();
  15275. }
  15276. virtual const void * nextRow()
  15277. {
  15278. ActivityTimer t(totalCycles, timeActivities);
  15279. const void * next = processor.nextRow();
  15280. if (next)
  15281. processed++;
  15282. return next;
  15283. }
  15284. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  15285. {
  15286. ActivityTimer t(totalCycles, timeActivities);
  15287. const void * next = processor.nextGE(seek, numFields, wasCompleteMatch, stepExtra);
  15288. if (next)
  15289. processed++;
  15290. return next;
  15291. }
  15292. virtual IInputSteppingMeta * querySteppingMeta()
  15293. {
  15294. return processor.queryInputSteppingMeta();
  15295. }
  15296. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  15297. {
  15298. CRoxieServerNaryActivity::gatherStats(merged);
  15299. if (inputAllocator)
  15300. inputAllocator->gatherStats(merged);
  15301. if (outputAllocator)
  15302. outputAllocator->gatherStats(merged);
  15303. }
  15304. protected:
  15305. IHThorNWayMergeJoinArg & helper;
  15306. CMergeJoinProcessor & processor;
  15307. Owned<IEngineRowAllocator> inputAllocator;
  15308. Owned<IEngineRowAllocator> outputAllocator;
  15309. };
  15310. class CRoxieServerAndMergeJoinActivity : public CRoxieServerNWayMergeJoinActivity
  15311. {
  15312. public:
  15313. CRoxieServerAndMergeJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  15314. : CRoxieServerNWayMergeJoinActivity(_ctx, _factory, _probeManager, _numInputs, andProcessor), andProcessor(helper)
  15315. {
  15316. }
  15317. protected:
  15318. CAndMergeJoinProcessor andProcessor;
  15319. };
  15320. class CRoxieServerAndLeftMergeJoinActivity : public CRoxieServerNWayMergeJoinActivity
  15321. {
  15322. public:
  15323. CRoxieServerAndLeftMergeJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  15324. : CRoxieServerNWayMergeJoinActivity(_ctx, _factory, _probeManager, _numInputs, andLeftProcessor), andLeftProcessor(helper)
  15325. {
  15326. }
  15327. protected:
  15328. CAndLeftMergeJoinProcessor andLeftProcessor;
  15329. };
  15330. class CRoxieServerMofNMergeJoinActivity : public CRoxieServerNWayMergeJoinActivity
  15331. {
  15332. public:
  15333. CRoxieServerMofNMergeJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  15334. : CRoxieServerNWayMergeJoinActivity(_ctx, _factory, _probeManager, _numInputs, mofnProcessor), mofnProcessor(helper)
  15335. {
  15336. }
  15337. protected:
  15338. CMofNMergeJoinProcessor mofnProcessor;
  15339. };
  15340. class CRoxieServerProximityJoinActivity : public CRoxieServerNWayMergeJoinActivity
  15341. {
  15342. public:
  15343. CRoxieServerProximityJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  15344. : CRoxieServerNWayMergeJoinActivity(_ctx, _factory, _probeManager, _numInputs, proximityProcessor), proximityProcessor(helper)
  15345. {
  15346. }
  15347. protected:
  15348. CProximityJoinProcessor proximityProcessor;
  15349. };
  15350. class CRoxieServerNWayMergeJoinActivityFactory : public CRoxieServerMultiInputFactory
  15351. {
  15352. unsigned flags;
  15353. public:
  15354. CRoxieServerNWayMergeJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15355. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15356. {
  15357. Owned<IHThorNWayMergeJoinArg> helper = (IHThorNWayMergeJoinArg *) helperFactory();
  15358. flags = helper->getJoinFlags();
  15359. }
  15360. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15361. {
  15362. if (flags & IHThorNWayMergeJoinArg::MJFhasrange)
  15363. return new CRoxieServerProximityJoinActivity(_ctx, this, _probeManager, numInputs());
  15364. switch (flags & IHThorNWayMergeJoinArg::MJFkindmask)
  15365. {
  15366. case IHThorNWayMergeJoinArg::MJFinner:
  15367. return new CRoxieServerAndMergeJoinActivity(_ctx, this, _probeManager, numInputs());
  15368. case IHThorNWayMergeJoinArg::MJFleftonly:
  15369. case IHThorNWayMergeJoinArg::MJFleftouter:
  15370. return new CRoxieServerAndLeftMergeJoinActivity(_ctx, this, _probeManager, numInputs());
  15371. case IHThorNWayMergeJoinArg::MJFmofn:
  15372. return new CRoxieServerMofNMergeJoinActivity(_ctx, this, _probeManager, numInputs());
  15373. default:
  15374. throwUnexpected();
  15375. }
  15376. }
  15377. };
  15378. IRoxieServerActivityFactory *createRoxieServerNWayMergeJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15379. {
  15380. return new CRoxieServerNWayMergeJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15381. }
  15382. //=================================================================================
  15383. class CRoxieServerNWaySelectActivity : public CRoxieServerNWayBaseActivity
  15384. {
  15385. IHThorNWaySelectArg &helper;
  15386. public:
  15387. CRoxieServerNWaySelectActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  15388. : CRoxieServerNWayBaseActivity(_ctx, _factory, _probeManager, _numInputs),
  15389. helper((IHThorNWaySelectArg &)basehelper)
  15390. {
  15391. }
  15392. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15393. {
  15394. CRoxieServerNWayBaseActivity::start(parentExtractSize, parentExtract, paused);
  15395. unsigned whichInput = helper.getInputIndex();
  15396. selectedInput = nullptr;
  15397. selectedStream = nullptr;
  15398. if (whichInput--)
  15399. {
  15400. for (unsigned i=0; i < numInputs; i++)
  15401. {
  15402. IFinalRoxieInput * cur = inputArray[i];
  15403. CRoxieServerNWayInputBaseActivity *nWayInput = dynamic_cast<CRoxieServerNWayInputBaseActivity *>(cur);
  15404. if (nWayInput)
  15405. {
  15406. nWayInput->start(parentExtractSize, parentExtract, paused);
  15407. unsigned numRealInputs = cur->numConcreteOutputs();
  15408. if (whichInput < numRealInputs)
  15409. {
  15410. expandedInputs.append(cur->queryConcreteInput(whichInput));
  15411. expandedStreams.append(cur->queryConcreteOutputStream(whichInput));
  15412. expandedJunctions.append(cur->queryConcreteOutputJunction(whichInput));
  15413. break;
  15414. }
  15415. whichInput -= numRealInputs;
  15416. }
  15417. else
  15418. {
  15419. if (whichInput == 0)
  15420. {
  15421. expandedInputs.append(cur);
  15422. // NB: this activities input streams + junction have been setup and held in CRoxieServerMultiInputActivity base
  15423. expandedStreams.append(queryConcreteOutputStream(i));
  15424. expandedJunctions.append(queryConcreteOutputJunction(i));
  15425. break;
  15426. }
  15427. whichInput -= 1;
  15428. }
  15429. }
  15430. }
  15431. if (expandedInputs.ordinality())
  15432. {
  15433. startExpandedInputs(parentExtractSize, parentExtract, paused);
  15434. selectedInput = expandedInputs.item(0);
  15435. selectedStream = expandedStreams.item(0);
  15436. }
  15437. }
  15438. const void * nextRow()
  15439. {
  15440. ActivityTimer t(totalCycles, timeActivities);
  15441. if (!selectedStream)
  15442. return NULL;
  15443. return selectedStream->nextRow();
  15444. }
  15445. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  15446. {
  15447. if (!selectedInput)
  15448. return false;
  15449. return selectedInput->gatherConjunctions(collector);
  15450. }
  15451. virtual void resetEOF()
  15452. {
  15453. if (selectedStream)
  15454. selectedStream->resetEOF();
  15455. }
  15456. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  15457. {
  15458. ActivityTimer t(totalCycles, timeActivities);
  15459. if (!selectedStream)
  15460. return NULL;
  15461. return selectedStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  15462. }
  15463. IInputSteppingMeta * querySteppingMeta()
  15464. {
  15465. if (selectedInput)
  15466. return selectedInput->querySteppingMeta();
  15467. return NULL;
  15468. }
  15469. protected:
  15470. IFinalRoxieInput * selectedInput = nullptr;
  15471. IEngineRowStream * selectedStream = nullptr;
  15472. Owned<IStrandJunction> selectedJunction;
  15473. };
  15474. class CRoxieServerNWaySelectActivityFactory : public CRoxieServerMultiInputFactory
  15475. {
  15476. public:
  15477. CRoxieServerNWaySelectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15478. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15479. {
  15480. }
  15481. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15482. {
  15483. return new CRoxieServerNWaySelectActivity(_ctx, this, _probeManager, numInputs());
  15484. }
  15485. };
  15486. IRoxieServerActivityFactory *createRoxieServerNWaySelectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15487. {
  15488. return new CRoxieServerNWaySelectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15489. }
  15490. //=================================================================================
  15491. class CRoxieServerRemoteActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler
  15492. {
  15493. protected:
  15494. IHThorRemoteArg &helper;
  15495. CRemoteResultAdaptor remote;
  15496. public:
  15497. CRoxieServerRemoteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteID)
  15498. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  15499. helper((IHThorRemoteArg &)basehelper),
  15500. remote(_ctx, this, _remoteID, meta.queryOriginal(), helper, *this, false, false) // MORE - if they need it stable we'll have to think!
  15501. {
  15502. }
  15503. virtual const IResolvedFile *queryVarFileInfo() const
  15504. {
  15505. return NULL;
  15506. }
  15507. virtual void onCreate(IHThorArg *_colocalParent)
  15508. {
  15509. CRoxieServerActivity::onCreate(_colocalParent);
  15510. remote.onCreate(_colocalParent);
  15511. }
  15512. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15513. {
  15514. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  15515. remote.onStart(parentExtractSize, parentExtract);
  15516. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  15517. unsigned fileNo = 0; // MORE - superfiles require us to do this per file part... maybe (needs thought)
  15518. remote.getMem(0, fileNo, 0); // the cached context is all we need to send
  15519. remote.flush();
  15520. remote.senddone();
  15521. }
  15522. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  15523. {
  15524. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  15525. }
  15526. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  15527. {
  15528. if (idx==(unsigned)-1)
  15529. idx = 0;
  15530. return idx ? NULL: &remote;
  15531. }
  15532. virtual void reset()
  15533. {
  15534. processed = remote.processed;
  15535. remote.processed = 0;
  15536. CRoxieServerActivity::reset();
  15537. }
  15538. virtual void onLimitExceeded(bool isKeyed)
  15539. {
  15540. if (traceLevel > 4)
  15541. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  15542. helper.onLimitExceeded();
  15543. }
  15544. virtual const void *createLimitFailRow(bool isKeyed)
  15545. {
  15546. UNIMPLEMENTED; // MORE - is there an ONFAIL for a limit folded into a remote?
  15547. }
  15548. virtual const void *nextRow()
  15549. {
  15550. throwUnexpected(); // I am nobody's input
  15551. }
  15552. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  15553. {
  15554. CRoxieServerActivity::gatherStats(merged);
  15555. remote.gatherStats(merged);
  15556. }
  15557. };
  15558. class CRoxieServerRemoteActivityFactory : public CRoxieServerActivityFactory
  15559. {
  15560. public:
  15561. RemoteActivityId remoteId;
  15562. bool isRoot;
  15563. CRoxieServerRemoteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId, bool _isRoot)
  15564. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), remoteId(_remoteId), isRoot(_isRoot)
  15565. {
  15566. }
  15567. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15568. {
  15569. return new CRoxieServerRemoteActivity(_ctx, this, _probeManager, remoteId);
  15570. }
  15571. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  15572. {
  15573. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  15574. }
  15575. virtual bool isSink() const
  15576. {
  15577. //I don't think the action version of this is implemented - but this would be the code
  15578. return isRoot && !meta.queryOriginal();
  15579. }
  15580. virtual const StatisticsMapping &queryStatsMapping() const
  15581. {
  15582. return allStatistics; // Child queries...
  15583. }
  15584. };
  15585. IRoxieServerActivityFactory *createRoxieServerRemoteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId, bool _isRoot)
  15586. {
  15587. return new CRoxieServerRemoteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId, _isRoot);
  15588. }
  15589. //=================================================================================
  15590. class CRoxieServerIterateActivity : public CRoxieServerActivity
  15591. {
  15592. IHThorIterateArg &helper;
  15593. OwnedConstRoxieRow defaultRecord;
  15594. OwnedConstRoxieRow left;
  15595. OwnedConstRoxieRow right;
  15596. unsigned counter;
  15597. public:
  15598. CRoxieServerIterateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  15599. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  15600. helper((IHThorIterateArg &)basehelper)
  15601. {
  15602. counter = 0;
  15603. }
  15604. virtual bool needsAllocator() const { return true; }
  15605. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15606. {
  15607. counter = 0;
  15608. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  15609. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15610. size32_t thisSize = helper.createDefault(rowBuilder);
  15611. defaultRecord.setown(rowBuilder.finalizeRowClear(thisSize));
  15612. }
  15613. virtual void reset()
  15614. {
  15615. defaultRecord.clear();
  15616. right.clear();
  15617. left.clear();
  15618. CRoxieServerActivity::reset();
  15619. }
  15620. virtual const void * nextRow()
  15621. {
  15622. ActivityTimer t(totalCycles, timeActivities);
  15623. for (;;)
  15624. {
  15625. right.setown(inputStream->nextRow());
  15626. if (!right)
  15627. {
  15628. bool skippedGroup = (left == NULL) && (counter > 0); //we have just skipped entire group, but shouldn't output a double null
  15629. left.clear();
  15630. counter = 0;
  15631. if (skippedGroup) continue;
  15632. return NULL;
  15633. }
  15634. try
  15635. {
  15636. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15637. unsigned outSize = helper.transform(rowBuilder, left ? left : defaultRecord, right, ++counter);
  15638. if (outSize)
  15639. {
  15640. left.setown(rowBuilder.finalizeRowClear(outSize));
  15641. processed++;
  15642. return left.getLink();
  15643. }
  15644. }
  15645. catch (IException *E)
  15646. {
  15647. throw makeWrappedException(E);
  15648. }
  15649. }
  15650. }
  15651. };
  15652. class CRoxieServerIterateActivityFactory : public CRoxieServerActivityFactory
  15653. {
  15654. public:
  15655. CRoxieServerIterateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15656. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15657. {
  15658. }
  15659. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15660. {
  15661. return new CRoxieServerIterateActivity(_ctx, this, _probeManager);
  15662. }
  15663. };
  15664. IRoxieServerActivityFactory *createRoxieServerIterateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15665. {
  15666. return new CRoxieServerIterateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15667. }
  15668. //=================================================================================
  15669. class CRoxieServerProcessActivity : public CRoxieServerActivity
  15670. {
  15671. IHThorProcessArg &helper;
  15672. OwnedConstRoxieRow curRight;
  15673. OwnedConstRoxieRow initialRight;
  15674. unsigned counter;
  15675. Owned<IEngineRowAllocator> rightRowAllocator;
  15676. public:
  15677. CRoxieServerProcessActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  15678. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorProcessArg &)basehelper)
  15679. {
  15680. counter = 0;
  15681. }
  15682. virtual bool needsAllocator() const { return true; }
  15683. virtual void onCreate(IHThorArg *_colocalParent)
  15684. {
  15685. CRoxieServerActivity::onCreate(_colocalParent);
  15686. rightRowAllocator.setown(createRowAllocator(helper.queryRightRecordSize()));
  15687. }
  15688. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15689. {
  15690. counter = 0;
  15691. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  15692. RtlDynamicRowBuilder rowBuilder(rightRowAllocator);
  15693. size32_t thisSize = helper.createInitialRight(rowBuilder);
  15694. initialRight.setown(rowBuilder.finalizeRowClear(thisSize));
  15695. curRight.set(initialRight);
  15696. }
  15697. virtual const void * nextRow()
  15698. {
  15699. ActivityTimer t(totalCycles, timeActivities);
  15700. try
  15701. {
  15702. for (;;)
  15703. {
  15704. const void * in = inputStream->nextRow();
  15705. if (!in)
  15706. {
  15707. bool eog = (curRight != initialRight); // processed any records?
  15708. counter = 0;
  15709. curRight.set(initialRight);
  15710. if (eog)
  15711. return NULL;
  15712. in = inputStream->nextRow();
  15713. if (!in)
  15714. return NULL;
  15715. }
  15716. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15717. RtlDynamicRowBuilder rightRowBuilder(rightRowAllocator);
  15718. size32_t outSize = helper.transform(rowBuilder, rightRowBuilder, in, curRight, ++counter);
  15719. ReleaseRoxieRow(in);
  15720. if (outSize)
  15721. {
  15722. //MORE: This should be returned...
  15723. size32_t rightSize = rightRowAllocator->queryOutputMeta()->getRecordSize(rightRowBuilder.getSelf());
  15724. curRight.setown(rightRowBuilder.finalizeRowClear(rightSize));
  15725. processed++;
  15726. return rowBuilder.finalizeRowClear(outSize);
  15727. }
  15728. }
  15729. }
  15730. catch (IException *E)
  15731. {
  15732. throw makeWrappedException(E);
  15733. }
  15734. }
  15735. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  15736. {
  15737. CRoxieServerActivity::gatherStats(merged);
  15738. if (rightRowAllocator)
  15739. rightRowAllocator->gatherStats(merged);
  15740. }
  15741. };
  15742. class CRoxieServerProcessActivityFactory : public CRoxieServerActivityFactory
  15743. {
  15744. public:
  15745. CRoxieServerProcessActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15746. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15747. {
  15748. }
  15749. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15750. {
  15751. return new CRoxieServerProcessActivity(_ctx, this, _probeManager);
  15752. }
  15753. };
  15754. IRoxieServerActivityFactory *createRoxieServerProcessActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15755. {
  15756. return new CRoxieServerProcessActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15757. }
  15758. //=================================================================================
  15759. class CRoxieServerGroupActivity : public CRoxieServerActivity
  15760. {
  15761. IHThorGroupArg &helper;
  15762. bool endPending;
  15763. bool eof;
  15764. bool first;
  15765. unsigned numGroups;
  15766. unsigned numGroupMax;
  15767. unsigned numProcessedLastGroup;
  15768. const void *next;
  15769. public:
  15770. CRoxieServerGroupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  15771. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorGroupArg &)basehelper)
  15772. {
  15773. next = NULL;
  15774. endPending = false;
  15775. eof = false;
  15776. first = true;
  15777. numGroups = 0;
  15778. numGroupMax = 0;
  15779. numProcessedLastGroup = 0;
  15780. }
  15781. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15782. {
  15783. endPending = false;
  15784. eof = false;
  15785. first = true;
  15786. numGroups = 0;
  15787. numGroupMax = 0;
  15788. numProcessedLastGroup = processed;
  15789. assertex(next == NULL);
  15790. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  15791. }
  15792. virtual void reset()
  15793. {
  15794. noteStatistic(StNumGroups, numGroups);
  15795. noteStatistic(StNumGroupMax, numGroupMax);
  15796. ReleaseClearRoxieRow(next);
  15797. CRoxieServerActivity::reset();
  15798. }
  15799. virtual const void * nextRow()
  15800. {
  15801. ActivityTimer t(totalCycles, timeActivities);
  15802. if (first)
  15803. {
  15804. next = inputStream->nextRow();
  15805. first = false;
  15806. }
  15807. if (eof || endPending)
  15808. {
  15809. endPending = false;
  15810. return NULL;
  15811. }
  15812. const void * prev = next;
  15813. next = inputStream->ungroupedNextRow();
  15814. if (next)
  15815. {
  15816. assertex(prev);
  15817. if (!helper.isSameGroup(prev, next))
  15818. {
  15819. noteEndOfGroup();
  15820. endPending = true;
  15821. }
  15822. }
  15823. else
  15824. {
  15825. noteEndOfGroup();
  15826. eof = true;
  15827. }
  15828. if (prev)
  15829. processed++;
  15830. return prev;
  15831. }
  15832. inline void noteEndOfGroup()
  15833. {
  15834. unsigned numThisGroup = processed - numProcessedLastGroup;
  15835. if (numThisGroup == 0)
  15836. return;
  15837. numProcessedLastGroup = processed;
  15838. if (numThisGroup > numGroupMax)
  15839. numGroupMax = numThisGroup;
  15840. numGroups++;
  15841. }
  15842. };
  15843. class CRoxieServerGroupActivityFactory : public CRoxieServerActivityFactory
  15844. {
  15845. public:
  15846. CRoxieServerGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15847. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15848. {
  15849. }
  15850. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15851. {
  15852. return new CRoxieServerGroupActivity(_ctx, this, _probeManager);
  15853. }
  15854. virtual const StatisticsMapping &queryStatsMapping() const
  15855. {
  15856. return groupStatistics;
  15857. }
  15858. };
  15859. IRoxieServerActivityFactory *createRoxieServerGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15860. {
  15861. return new CRoxieServerGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15862. }
  15863. //=================================================================================
  15864. class CRoxieServerFirstNActivity : public CRoxieServerLateStartActivity
  15865. {
  15866. unsigned __int64 limit;
  15867. unsigned __int64 skip;
  15868. unsigned doneThisGroup;
  15869. IHThorFirstNArg &helper;
  15870. public:
  15871. CRoxieServerFirstNActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  15872. : CRoxieServerLateStartActivity(_ctx, _factory, _probeManager), helper((IHThorFirstNArg &)basehelper)
  15873. {
  15874. doneThisGroup = 0;
  15875. limit = 0;
  15876. skip = 0;
  15877. }
  15878. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15879. {
  15880. doneThisGroup = 0;
  15881. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  15882. limit = helper.getLimit();
  15883. skip = helper.numToSkip();
  15884. lateStart(parentExtractSize, parentExtract, limit > 0);
  15885. if (limit + skip >= limit)
  15886. limit += skip;
  15887. }
  15888. const void * nextRow()
  15889. {
  15890. ActivityTimer t(totalCycles, timeActivities);
  15891. if (eof)
  15892. return NULL;
  15893. const void *ret;
  15894. for (;;)
  15895. {
  15896. ret = inputStream->nextRow();
  15897. if (!ret)
  15898. {
  15899. if (meta.isGrouped())
  15900. {
  15901. if (doneThisGroup > skip)
  15902. {
  15903. doneThisGroup = 0;
  15904. return NULL;
  15905. }
  15906. doneThisGroup = 0;
  15907. }
  15908. ret = inputStream->nextRow();
  15909. if (!ret)
  15910. {
  15911. eof = true;
  15912. return NULL;
  15913. }
  15914. }
  15915. doneThisGroup++;
  15916. if (doneThisGroup > skip)
  15917. break;
  15918. ReleaseRoxieRow(ret);
  15919. }
  15920. if (doneThisGroup <= limit)
  15921. {
  15922. processed++;
  15923. return ret;
  15924. }
  15925. ReleaseRoxieRow(ret);
  15926. if (meta.isGrouped())
  15927. {
  15928. while ((ret = inputStream->nextRow()) != NULL)
  15929. ReleaseRoxieRow(ret);
  15930. doneThisGroup = 0;
  15931. }
  15932. else
  15933. eof = true;
  15934. return NULL;
  15935. }
  15936. };
  15937. class CRoxieServerFirstNActivityFactory : public CRoxieServerActivityFactory
  15938. {
  15939. public:
  15940. CRoxieServerFirstNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15941. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15942. {
  15943. }
  15944. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15945. {
  15946. return new CRoxieServerFirstNActivity(_ctx, this, _probeManager);
  15947. }
  15948. };
  15949. IRoxieServerActivityFactory *createRoxieServerFirstNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15950. {
  15951. return new CRoxieServerFirstNActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15952. }
  15953. //=================================================================================
  15954. class CRoxieServerSelectNActivity : public CRoxieServerActivity
  15955. {
  15956. bool done;
  15957. IHThorSelectNArg &helper;
  15958. public:
  15959. CRoxieServerSelectNActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  15960. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorSelectNArg &)basehelper)
  15961. {
  15962. done = false;
  15963. }
  15964. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15965. {
  15966. done = false;
  15967. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  15968. }
  15969. const void *defaultRow()
  15970. {
  15971. if (!rowAllocator)
  15972. ensureRowAllocator(); // We delay as often not needed...
  15973. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15974. size32_t thisSize = helper.createDefault(rowBuilder);
  15975. return rowBuilder.finalizeRowClear(thisSize);
  15976. }
  15977. virtual const void * nextRow()
  15978. {
  15979. ActivityTimer t(totalCycles, timeActivities);
  15980. if (done)
  15981. return NULL;
  15982. done = true;
  15983. processed++; // always going to return a row!
  15984. unsigned __int64 index = helper.getRowToSelect();
  15985. while (--index)
  15986. {
  15987. const void * next = inputStream->ungroupedNextRow();
  15988. if (!next)
  15989. return defaultRow();
  15990. ReleaseRoxieRow(next);
  15991. }
  15992. const void * next = inputStream->ungroupedNextRow();
  15993. if (!next)
  15994. next = defaultRow();
  15995. return next;
  15996. }
  15997. };
  15998. class CRoxieServerSelectNActivityFactory : public CRoxieServerActivityFactory
  15999. {
  16000. public:
  16001. CRoxieServerSelectNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  16002. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  16003. {
  16004. }
  16005. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  16006. {
  16007. return new CRoxieServerSelectNActivity(_ctx, this, _probeManager);
  16008. }
  16009. };
  16010. IRoxieServerActivityFactory *createRoxieServerSelectNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  16011. {
  16012. return new CRoxieServerSelectNActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  16013. }
  16014. //=================================================================================
  16015. class CRoxieServerSelfJoinActivity : public CRoxieServerActivity
  16016. {
  16017. IHThorJoinArg &helper;
  16018. ICompare *collate;
  16019. OwnedRowArray group;
  16020. bool matchedLeft;
  16021. BoolArray matchedRight;
  16022. bool eof;
  16023. bool first;
  16024. unsigned leftIndex;
  16025. unsigned rightIndex;
  16026. unsigned rightOuterIndex;
  16027. unsigned joinLimit;
  16028. unsigned atmostLimit;
  16029. unsigned atmostsTriggered;
  16030. unsigned abortLimit;
  16031. unsigned keepLimit;
  16032. unsigned joinCounter;
  16033. bool leftOuterJoin;
  16034. bool rightOuterJoin;
  16035. bool exclude;
  16036. bool limitFail;
  16037. bool limitOnFail;
  16038. bool cloneLeft;
  16039. bool forceSpill;
  16040. OwnedConstRoxieRow defaultLeft;
  16041. OwnedConstRoxieRow defaultRight;
  16042. OwnedConstRoxieRow lhs;
  16043. Owned<IException> failingLimit;
  16044. bool failingOuterAtmost;
  16045. Owned<IEngineRowAllocator> defaultAllocator;
  16046. Owned<IRHLimitedCompareHelper> limitedhelper;
  16047. Owned<CRHDualCache> dualcache;
  16048. Owned<IGroupedInput> groupedInput;
  16049. IRowStream *dualCacheInput;
  16050. bool fillGroup()
  16051. {
  16052. group.clear();
  16053. matchedLeft = false;
  16054. matchedRight.kill();
  16055. failingOuterAtmost = false;
  16056. const void * next;
  16057. unsigned groupCount = 0;
  16058. while((next = groupedInput->nextRow()) != NULL)
  16059. {
  16060. if(groupCount==abortLimit)
  16061. {
  16062. if(limitFail)
  16063. failLimit(next);
  16064. if (ctx->queryDebugContext())
  16065. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  16066. if(limitOnFail)
  16067. {
  16068. assertex(!failingLimit);
  16069. try
  16070. {
  16071. failLimit(next);
  16072. }
  16073. catch(IException * except)
  16074. {
  16075. failingLimit.setown(except);
  16076. }
  16077. assertex(failingLimit != NULL);
  16078. group.append(next);
  16079. groupCount++;
  16080. break;
  16081. }
  16082. group.clear();
  16083. groupCount = 0;
  16084. while(next)
  16085. {
  16086. ReleaseRoxieRow(next);
  16087. next = groupedInput->nextRow();
  16088. }
  16089. }
  16090. else if(groupCount==atmostLimit)
  16091. {
  16092. atmostsTriggered++;
  16093. if(leftOuterJoin)
  16094. {
  16095. group.append(next);
  16096. groupCount++;
  16097. failingOuterAtmost = true;
  16098. break;
  16099. }
  16100. else
  16101. {
  16102. group.clear();
  16103. groupCount = 0;
  16104. while (next)
  16105. {
  16106. ReleaseRoxieRow(next);
  16107. next = groupedInput->nextRow();
  16108. }
  16109. }
  16110. }
  16111. else
  16112. {
  16113. group.append(next);
  16114. groupCount++;
  16115. }
  16116. }
  16117. if(group.ordinality()==0)
  16118. {
  16119. eof = true;
  16120. return false;
  16121. }
  16122. leftIndex = 0;
  16123. rightIndex = 0;
  16124. rightOuterIndex = 0;
  16125. joinCounter = 0;
  16126. joinLimit = keepLimit;
  16127. ForEachItemIn(idx, group)
  16128. matchedRight.append(false);
  16129. return true;
  16130. }
  16131. void failLimit(const void * next)
  16132. {
  16133. helper.onMatchAbortLimitExceeded();
  16134. CommonXmlWriter xmlwrite(XWFtrim|XWFopt );
  16135. if (!ctx->isBlind() && input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  16136. {
  16137. input->queryOutputMeta()->toXML((byte *) next, xmlwrite);
  16138. }
  16139. throw MakeStringException(ROXIE_TOO_MANY_RESULTS, "More than %d match candidates in self-join %d for row %s", abortLimit, queryId(), xmlwrite.str());
  16140. }
  16141. virtual bool needsAllocator() const { return true; }
  16142. const void *joinRecords(const void * curLeft, const void * curRight, unsigned counter, IException * except, unsigned flags)
  16143. {
  16144. try
  16145. {
  16146. if (cloneLeft && !except)
  16147. {
  16148. LinkRoxieRow(curLeft);
  16149. return curLeft;
  16150. }
  16151. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16152. size32_t outsize = except ? helper.onFailTransform(rowBuilder, curLeft, curRight, except, flags) : helper.transform(rowBuilder, curLeft, curRight, counter, flags);
  16153. if (outsize)
  16154. return rowBuilder.finalizeRowClear(outsize);
  16155. else
  16156. return NULL;
  16157. }
  16158. catch (IException *E)
  16159. {
  16160. throw makeWrappedException(E);
  16161. }
  16162. }
  16163. void createDefaultLeft()
  16164. {
  16165. if (!defaultLeft)
  16166. {
  16167. if (!defaultAllocator)
  16168. defaultAllocator.setown(createRowAllocator(input->queryOutputMeta()));
  16169. RtlDynamicRowBuilder rowBuilder(defaultAllocator);
  16170. size32_t thisSize = helper.createDefaultLeft(rowBuilder);
  16171. defaultLeft.setown(rowBuilder.finalizeRowClear(thisSize));
  16172. }
  16173. }
  16174. void createDefaultRight()
  16175. {
  16176. if (!defaultRight)
  16177. {
  16178. if (!defaultAllocator)
  16179. defaultAllocator.setown(createRowAllocator(input->queryOutputMeta()));
  16180. RtlDynamicRowBuilder rowBuilder(defaultAllocator);
  16181. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  16182. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  16183. }
  16184. }
  16185. public:
  16186. CRoxieServerSelfJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _forceSpill)
  16187. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorJoinArg &)basehelper), forceSpill(_forceSpill)
  16188. {
  16189. collate = helper.queryCompareLeftRight();
  16190. eof = false;
  16191. first = true;
  16192. keepLimit = 0;
  16193. atmostLimit = 0;
  16194. atmostsTriggered = 0;
  16195. unsigned joinFlags = helper.getJoinFlags();
  16196. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  16197. rightOuterJoin = (joinFlags & JFrightouter) != 0;
  16198. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  16199. exclude = (joinFlags & JFexclude) != 0;
  16200. abortLimit = 0;
  16201. joinLimit = 0;
  16202. assertex((joinFlags & (JFfirst | JFfirstleft | JFfirstright)) == 0); // no longer supported
  16203. getLimitType(joinFlags, limitFail, limitOnFail);
  16204. if((joinFlags & JFslidingmatch) != 0)
  16205. throw MakeStringException(ROXIE_UNIMPLEMENTED_ERROR, "Internal Error: Sliding self join not supported");
  16206. failingOuterAtmost = false;
  16207. matchedLeft = false;
  16208. leftIndex = 0;
  16209. rightIndex = 0;
  16210. rightOuterIndex = 0;
  16211. joinCounter = 0;
  16212. dualCacheInput = NULL;
  16213. }
  16214. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16215. {
  16216. eof = false;
  16217. first = true;
  16218. failingLimit.clear();
  16219. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  16220. keepLimit = helper.getKeepLimit();
  16221. if(keepLimit == 0)
  16222. keepLimit = (unsigned)-1;
  16223. atmostsTriggered = 0;
  16224. atmostLimit = helper.getJoinLimit();
  16225. if(atmostLimit == 0)
  16226. atmostLimit = (unsigned)-1;
  16227. else
  16228. assertex(!rightOuterJoin);
  16229. abortLimit = helper.getMatchAbortLimit();
  16230. if (abortLimit == 0)
  16231. abortLimit = (unsigned)-1;
  16232. if (rightOuterJoin)
  16233. createDefaultLeft();
  16234. if (leftOuterJoin || limitOnFail)
  16235. createDefaultRight();
  16236. ICompare *compareLeft = helper.queryCompareLeft();
  16237. if (helper.isLeftAlreadySorted())
  16238. groupedInput.setown(createGroupedInputReader(inputStream, compareLeft));
  16239. else
  16240. {
  16241. bool isStable = (helper.getJoinFlags() & JFunstable) == 0;
  16242. RoxieSortAlgorithm sortAlgorithm;
  16243. if (forceSpill)
  16244. sortAlgorithm = isStable ? stableSpillingQuickSortAlgorithm : spillingQuickSortAlgorithm;
  16245. else
  16246. sortAlgorithm = isStable ? stableQuickSortAlgorithm : quickSortAlgorithm;
  16247. groupedInput.setown(createSortedGroupedInputReader(inputStream, compareLeft, createSortAlgorithm(sortAlgorithm, compareLeft, ctx->queryRowManager(), input->queryOutputMeta(), ctx->queryCodeContext(), tempDirectory, activityId)));
  16248. }
  16249. if ((helper.getJoinFlags() & JFlimitedprefixjoin) && helper.getJoinLimit())
  16250. { //limited match join (s[1..n])
  16251. dualcache.setown(new CRHDualCache());
  16252. dualcache->init(groupedInput);
  16253. dualCacheInput = dualcache->queryOut1();
  16254. failingOuterAtmost = false;
  16255. matchedLeft = false;
  16256. leftIndex = 0;
  16257. rightOuterIndex = 0;
  16258. joinCounter = 0;
  16259. limitedhelper.setown(createRHLimitedCompareHelper());
  16260. limitedhelper->init( helper.getJoinLimit(), dualcache->queryOut2(), collate, helper.queryPrefixCompare() );
  16261. }
  16262. }
  16263. virtual void reset()
  16264. {
  16265. if (atmostsTriggered)
  16266. noteStatistic(StNumAtmostTriggered, atmostsTriggered);
  16267. group.clear();
  16268. groupedInput.clear();
  16269. CRoxieServerActivity::reset();
  16270. defaultLeft.clear();
  16271. defaultRight.clear();
  16272. }
  16273. virtual const void * nextRow()
  16274. {
  16275. ActivityTimer t(totalCycles, timeActivities);
  16276. if (limitedhelper)
  16277. {
  16278. while(!eof) //limited match join
  16279. {
  16280. if (!group.isItem(rightIndex))
  16281. {
  16282. lhs.setown(dualCacheInput->nextRow());
  16283. if (lhs)
  16284. {
  16285. rightIndex = 0;
  16286. joinCounter = 0;
  16287. group.clear();
  16288. limitedhelper->getGroup(group,lhs);
  16289. }
  16290. else
  16291. {
  16292. eof = true;
  16293. }
  16294. }
  16295. if (group.isItem(rightIndex))
  16296. {
  16297. const void * rhs = group.item(rightIndex++);
  16298. if(helper.match(lhs, rhs))
  16299. {
  16300. const void * ret = joinRecords(lhs, rhs, ++joinCounter, NULL, JTFmatchedleft|JTFmatchedright);
  16301. if(ret)
  16302. {
  16303. processed++;
  16304. return ret;
  16305. }
  16306. }
  16307. }
  16308. }
  16309. return NULL;
  16310. }
  16311. else
  16312. {
  16313. if (first)
  16314. {
  16315. first = false;
  16316. fillGroup();
  16317. }
  16318. while(!eof)
  16319. {
  16320. if(failingOuterAtmost)
  16321. while(group.isItem(leftIndex))
  16322. {
  16323. const void * ret = joinRecords(group.item(leftIndex++), defaultRight, 0, NULL, JTFmatchedleft);
  16324. if(ret)
  16325. {
  16326. processed++;
  16327. return ret;
  16328. }
  16329. }
  16330. if((joinLimit == 0) || !group.isItem(rightIndex))
  16331. {
  16332. if(leftOuterJoin && !matchedLeft && !failingLimit)
  16333. {
  16334. const void * ret = joinRecords(group.item(leftIndex), defaultRight, 0, NULL, JTFmatchedleft);
  16335. if(ret)
  16336. {
  16337. matchedLeft = true;
  16338. processed++;
  16339. return ret;
  16340. }
  16341. }
  16342. leftIndex++;
  16343. matchedLeft = false;
  16344. rightIndex = 0;
  16345. joinCounter = 0;
  16346. joinLimit = keepLimit;
  16347. }
  16348. if(!group.isItem(leftIndex))
  16349. {
  16350. if(failingLimit || failingOuterAtmost)
  16351. {
  16352. const void * lhs;
  16353. while((lhs = groupedInput->nextRow()) != NULL) // dualCache never active here
  16354. {
  16355. const void * ret = joinRecords(lhs, defaultRight, 0, failingLimit, JTFmatchedleft);
  16356. ReleaseRoxieRow(lhs);
  16357. if(ret)
  16358. {
  16359. processed++;
  16360. return ret;
  16361. }
  16362. }
  16363. failingLimit.clear();
  16364. }
  16365. if(rightOuterJoin && !failingLimit)
  16366. while(group.isItem(rightOuterIndex))
  16367. if(!matchedRight.item(rightOuterIndex++))
  16368. {
  16369. const void * ret = joinRecords(defaultLeft, group.item(rightOuterIndex-1), 0, NULL, JTFmatchedright);
  16370. if(ret)
  16371. {
  16372. processed++;
  16373. return ret;
  16374. }
  16375. }
  16376. if(!fillGroup())
  16377. return NULL;
  16378. continue;
  16379. }
  16380. const void * lhs = group.item(leftIndex);
  16381. if(failingLimit)
  16382. {
  16383. leftIndex++;
  16384. const void * ret = joinRecords(lhs, defaultRight, 0, failingLimit, JTFmatchedleft);
  16385. if(ret)
  16386. {
  16387. processed++;
  16388. return ret;
  16389. }
  16390. }
  16391. else
  16392. {
  16393. const void * rhs = group.item(rightIndex++);
  16394. if(helper.match(lhs, rhs))
  16395. {
  16396. matchedLeft = true;
  16397. matchedRight.replace(true, rightIndex-1);
  16398. if(!exclude)
  16399. {
  16400. const void * ret = joinRecords(lhs, rhs, ++joinCounter, NULL, JTFmatchedleft|JTFmatchedright);
  16401. if(ret)
  16402. {
  16403. processed++;
  16404. joinLimit--;
  16405. return ret;
  16406. }
  16407. }
  16408. }
  16409. }
  16410. }
  16411. return NULL;
  16412. }
  16413. }
  16414. };
  16415. class CRoxieServerSelfJoinActivityFactory : public CRoxieServerActivityFactory
  16416. {
  16417. bool forceSpill;
  16418. public:
  16419. CRoxieServerSelfJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  16420. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  16421. {
  16422. forceSpill = queryFactory.queryOptions().allSortsMaySpill || _graphNode.getPropBool("hint[@name='spill']/@value", false);;
  16423. }
  16424. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  16425. {
  16426. return new CRoxieServerSelfJoinActivity(_ctx, this, _probeManager, forceSpill);
  16427. }
  16428. virtual const StatisticsMapping &queryStatsMapping() const
  16429. {
  16430. return joinStatistics;
  16431. }
  16432. };
  16433. IRoxieServerActivityFactory *createRoxieServerSelfJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  16434. {
  16435. return new CRoxieServerSelfJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  16436. }
  16437. //=====================================================================================================
  16438. class CRoxieServerLookupJoinActivity : public CRoxieServerTwoInputActivity
  16439. {
  16440. private:
  16441. class LookupTable : public CInterface
  16442. {
  16443. public:
  16444. LookupTable(IHThorHashJoinArg &helper)
  16445. : leftRightCompare(helper.queryCompareLeftRight()), rightCompare(helper.queryCompareRight()),
  16446. leftHash(helper.queryHashLeft()), rightHash(helper.queryHashRight())
  16447. {
  16448. size = 0;
  16449. }
  16450. virtual const void *find(const void * left) const = 0;
  16451. virtual const void *findNext(const void * left) const = 0;
  16452. protected:
  16453. ICompare * leftRightCompare;
  16454. ICompare * rightCompare;
  16455. IHash * leftHash;
  16456. IHash * rightHash;
  16457. unsigned size;
  16458. };
  16459. class DedupLookupTable : public LookupTable
  16460. {
  16461. public:
  16462. DedupLookupTable(ConstPointerArray &rightRows, IHThorHashJoinArg &helper)
  16463. : LookupTable(helper)
  16464. {
  16465. size = (4*rightRows.length())/3 + 1;
  16466. table = (const void * *)calloc(size, sizeof(void *)); // This should probably be allocated from roxiemem (and size rounded up to actual available size)
  16467. ForEachItemIn(idx, rightRows)
  16468. add(rightRows.item(idx));
  16469. }
  16470. ~DedupLookupTable()
  16471. {
  16472. roxiemem::ReleaseRoxieRowArray(size, table);
  16473. free(table);
  16474. }
  16475. virtual const void *find(const void * left) const
  16476. {
  16477. unsigned index = leftHash->hash(left) % size;
  16478. unsigned start = index;
  16479. while (table[index])
  16480. {
  16481. if(leftRightCompare->docompare(left, table[index]) == 0)
  16482. return table[index];
  16483. index++;
  16484. if (index==size)
  16485. index = 0;
  16486. if (index==start)
  16487. throw MakeStringException(ROXIE_JOIN_ERROR, "Internal error in lookup join activity (hash table full on lookup)");
  16488. }
  16489. return NULL;
  16490. }
  16491. virtual const void *findNext(const void * left) const
  16492. {
  16493. return NULL;
  16494. }
  16495. protected:
  16496. void add(const void * right)
  16497. {
  16498. unsigned index = rightHash->hash(right) % size;
  16499. unsigned start = index;
  16500. while (table[index])
  16501. {
  16502. if (rightCompare->docompare(table[index], right) == 0)
  16503. {
  16504. ReleaseRoxieRow(right);
  16505. return;
  16506. }
  16507. index++;
  16508. if (index==size)
  16509. index = 0;
  16510. if (index==start)
  16511. throw MakeStringException(ROXIE_JOIN_ERROR, "Internal error in lookup join activity (hash table full on add)");
  16512. }
  16513. table[index] = right;
  16514. }
  16515. const void * * table;
  16516. };
  16517. class FewLookupTable : public LookupTable
  16518. {
  16519. public:
  16520. FewLookupTable(ConstPointerArray &rightRows, IHThorHashJoinArg &helper)
  16521. : LookupTable(helper)
  16522. {
  16523. size = (4*rightRows.length())/3 + 1;
  16524. table = (const void * *)calloc(size, sizeof(void *)); // This should probably be allocated from roxiemem
  16525. findex = fstart = BadIndex;
  16526. ForEachItemIn(idx, rightRows)
  16527. add(rightRows.item(idx));
  16528. }
  16529. ~FewLookupTable()
  16530. {
  16531. roxiemem::ReleaseRoxieRowArray(size, table);
  16532. free(table);
  16533. }
  16534. virtual const void *find(const void * left) const
  16535. {
  16536. fstart = leftHash->hash(left) % size;
  16537. findex = fstart;
  16538. return doFind(left);
  16539. }
  16540. virtual const void *findNext(const void * left) const
  16541. {
  16542. if (findex == BadIndex)
  16543. return NULL;
  16544. advance();
  16545. return doFind(left);
  16546. }
  16547. protected:
  16548. void add(const void * right)
  16549. {
  16550. unsigned start = rightHash->hash(right) % size;
  16551. unsigned index = start;
  16552. while (table[index])
  16553. {
  16554. index++;
  16555. if (index==size)
  16556. index = 0;
  16557. if (index==start)
  16558. throwUnexpected(); //table is full, should never happen
  16559. }
  16560. table[index] = right;
  16561. }
  16562. void advance() const
  16563. {
  16564. findex++;
  16565. if(findex==size)
  16566. findex = 0;
  16567. if(findex==fstart)
  16568. throw MakeStringException(ROXIE_JOIN_ERROR, "Internal error in lookup join activity (hash table full on lookup)");
  16569. }
  16570. const void *doFind(const void * left) const
  16571. {
  16572. while(table[findex])
  16573. {
  16574. if (leftRightCompare->docompare(left, table[findex]) == 0)
  16575. return table[findex];
  16576. advance();
  16577. }
  16578. findex = BadIndex;
  16579. return NULL;
  16580. }
  16581. const void * * table;
  16582. unsigned mutable fstart;
  16583. unsigned mutable findex;
  16584. static unsigned const BadIndex;
  16585. };
  16586. class ManyLookupTable : public LookupTable
  16587. {
  16588. public:
  16589. ManyLookupTable(ConstPointerArray &rightRows, IHThorHashJoinArg &helper)
  16590. : LookupTable(helper)
  16591. {
  16592. rightRows.swapWith(rowtable);
  16593. UInt64Array groups;
  16594. unsigned numRows = rowtable.length();
  16595. if (numRows)
  16596. {
  16597. unsigned groupStart = 0;
  16598. const void *groupStartRow = rowtable.item(0);
  16599. for (unsigned i=1; i < numRows; i++)
  16600. {
  16601. const void *thisRow = rowtable.item(i);
  16602. if (rightCompare->docompare(groupStartRow, thisRow))
  16603. {
  16604. groups.append(makeint64(groupStart, i-groupStart));
  16605. groupStart = i;
  16606. groupStartRow = thisRow;
  16607. }
  16608. }
  16609. groups.append(makeint64(groupStart, numRows-groupStart));
  16610. }
  16611. size = (4*groups.length())/3 + 1;
  16612. table = (__uint64 *) calloc(size, sizeof(__uint64)); // This should probably be allocated from roxiemem
  16613. ForEachItemIn(idx, groups)
  16614. {
  16615. unsigned __int64 group = groups.item(idx);
  16616. unsigned groupstart = high(group);
  16617. const void *row = rowtable.item(groupstart);
  16618. add(row, group);
  16619. }
  16620. }
  16621. ~ManyLookupTable()
  16622. {
  16623. roxiemem::ReleaseRoxieRows(rowtable);
  16624. free(table);
  16625. }
  16626. void add(const void *row, unsigned __int64 group)
  16627. {
  16628. unsigned start = rightHash->hash(row) % size;
  16629. unsigned index = start;
  16630. while (table[index])
  16631. {
  16632. index++;
  16633. if (index==size)
  16634. index = 0;
  16635. if (index==start)
  16636. throwUnexpected(); //table is full, should never happen
  16637. }
  16638. table[index] = group;
  16639. }
  16640. virtual const void *find(const void * left) const
  16641. {
  16642. unsigned index = leftHash->hash(left) % size;
  16643. unsigned start = index;
  16644. while (table[index])
  16645. {
  16646. __uint64 group = table[index];
  16647. currentMatch = high(group);
  16648. const void *right = rowtable.item(currentMatch);
  16649. if (leftRightCompare->docompare(left, right) == 0)
  16650. {
  16651. currentMatch++;
  16652. matchCount = low(group) - 1;
  16653. return right;
  16654. }
  16655. index++;
  16656. if (index==size)
  16657. index = 0;
  16658. if (index==start)
  16659. throw MakeStringException(ROXIE_JOIN_ERROR, "Internal error in lookup join activity (hash table full on lookup)");
  16660. }
  16661. matchCount = 0;
  16662. return NULL;
  16663. }
  16664. virtual const void *findNext(const void * left) const
  16665. {
  16666. if (!matchCount)
  16667. return NULL;
  16668. matchCount--;
  16669. return rowtable.item(currentMatch++);
  16670. }
  16671. protected:
  16672. __uint64 *table;
  16673. ConstPointerArray rowtable;
  16674. mutable unsigned currentMatch = 0;
  16675. mutable unsigned matchCount = 0;
  16676. };
  16677. IHThorHashJoinArg &helper;
  16678. bool leftOuterJoin;
  16679. bool exclude;
  16680. bool eog;
  16681. bool many;
  16682. bool dedupRHS;
  16683. bool useFewTable;
  16684. bool matchedGroup;
  16685. const void *left;
  16686. OwnedConstRoxieRow defaultRight;
  16687. Owned<LookupTable> table;
  16688. unsigned keepLimit;
  16689. unsigned atmostLimit;
  16690. unsigned atmostsTriggered;
  16691. unsigned limitLimit;
  16692. unsigned joinCounter;
  16693. bool limitFail;
  16694. bool limitOnFail;
  16695. bool hasGroupLimit;
  16696. bool isSmartJoin;
  16697. unsigned keepCount;
  16698. bool gotMatch;
  16699. bool cloneLeft;
  16700. ConstPointerArray rightGroup;
  16701. aindex_t rightGroupIndex;
  16702. Owned<IException> failingLimit;
  16703. ConstPointerArray filteredRight;
  16704. ThorActivityKind activityKind;
  16705. Owned<IEngineRowAllocator> defaultRightAllocator;
  16706. void createDefaultRight()
  16707. {
  16708. if (!defaultRight)
  16709. {
  16710. if (!defaultRightAllocator)
  16711. defaultRightAllocator.setown(createRowAllocator(input1->queryOutputMeta()));
  16712. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  16713. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  16714. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  16715. }
  16716. }
  16717. public:
  16718. CRoxieServerLookupJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _useFewTable)
  16719. : CRoxieServerTwoInputActivity(_ctx, _factory, _probeManager), helper((IHThorHashJoinArg &)basehelper), useFewTable(_useFewTable)
  16720. {
  16721. unsigned joinFlags = helper.getJoinFlags();
  16722. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  16723. assertex((joinFlags & JFrightouter) == 0);
  16724. exclude = (joinFlags & JFexclude) != 0;
  16725. many = (joinFlags & JFmanylookup) != 0;
  16726. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  16727. dedupRHS = (joinFlags & (JFmanylookup | JFmatchrequired | JFtransformMaySkip)) == 0; // optimisation: can implicitly dedup RHS unless is many lookup, or match required, or transform may skip
  16728. left = NULL;
  16729. activityKind = factory->getKind();
  16730. eog = false;
  16731. matchedGroup = false;
  16732. gotMatch = false;
  16733. keepLimit = 0;
  16734. keepCount = 0;
  16735. joinCounter = 0;
  16736. atmostLimit = 0;
  16737. atmostsTriggered = 0;
  16738. limitLimit = 0;
  16739. rightGroupIndex = 0;
  16740. hasGroupLimit = false;
  16741. isSmartJoin = (joinFlags & JFsmart) != 0;
  16742. getLimitType(joinFlags, limitFail, limitOnFail);
  16743. }
  16744. void loadRight()
  16745. {
  16746. ConstPointerArray rightset;
  16747. try
  16748. {
  16749. const void * next;
  16750. while(true)
  16751. {
  16752. next = inputStream1->ungroupedNextRow();
  16753. if(!next)
  16754. break;
  16755. rightset.append(next);
  16756. }
  16757. if (!dedupRHS)
  16758. {
  16759. if (useFewTable)
  16760. {
  16761. table.setown(new FewLookupTable(rightset, helper)); // NOTE - takes ownership of rightset
  16762. }
  16763. else
  16764. {
  16765. if (!helper.isRightAlreadySorted())
  16766. {
  16767. if (helper.getJoinFlags() & JFunstable)
  16768. {
  16769. qsortvec(const_cast<void * *>(rightset.getArray()), rightset.ordinality(), *helper.queryCompareRight());
  16770. }
  16771. else
  16772. {
  16773. unsigned rightord = rightset.ordinality();
  16774. MemoryAttr tempAttr(rightord*sizeof(void **)); // Temp storage for stable sort. This should probably be allocated from roxiemem
  16775. void **temp = (void **) tempAttr.bufferBase();
  16776. void **_rows = const_cast<void * *>(rightset.getArray());
  16777. msortvecstableinplace(_rows, rightord, *helper.queryCompareRight(), temp);
  16778. }
  16779. }
  16780. table.setown(new ManyLookupTable(rightset, helper)); // NOTE - takes ownership of rightset
  16781. }
  16782. }
  16783. else
  16784. {
  16785. table.setown(new DedupLookupTable(rightset, helper)); // NOTE - takes ownership of rightset
  16786. }
  16787. }
  16788. catch (...)
  16789. {
  16790. roxiemem::ReleaseRoxieRows(rightset);
  16791. throw;
  16792. }
  16793. };
  16794. virtual void reset()
  16795. {
  16796. if (atmostsTriggered)
  16797. noteStatistic(StNumAtmostTriggered, atmostsTriggered);
  16798. CRoxieServerTwoInputActivity::reset();
  16799. ReleaseClearRoxieRow(left);
  16800. defaultRight.clear();
  16801. table.clear();
  16802. }
  16803. virtual bool needsAllocator() const { return true; }
  16804. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16805. {
  16806. eog = false;
  16807. matchedGroup = false;
  16808. left = NULL;
  16809. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  16810. keepLimit = helper.getKeepLimit();
  16811. if(keepLimit==0) keepLimit = static_cast<unsigned>(-1);
  16812. atmostsTriggered = 0;
  16813. atmostLimit = helper.getJoinLimit();
  16814. limitLimit = helper.getMatchAbortLimit();
  16815. hasGroupLimit = ((atmostLimit > 0) || (limitLimit > 0));
  16816. if(atmostLimit==0) atmostLimit = static_cast<unsigned>(-1);
  16817. if(limitLimit==0) limitLimit = static_cast<unsigned>(-1);
  16818. getLimitType(helper.getJoinFlags(), limitFail, limitOnFail);
  16819. switch (activityKind)
  16820. {
  16821. case TAKlookupjoin:
  16822. case TAKlookupdenormalizegroup:
  16823. case TAKsmartjoin:
  16824. case TAKsmartdenormalizegroup:
  16825. if (leftOuterJoin)
  16826. createDefaultRight();
  16827. break;
  16828. }
  16829. if (limitOnFail)
  16830. createDefaultRight();
  16831. }
  16832. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  16833. {
  16834. if (!idx && (helper.getJoinFlags() & JFparallel) != 0)
  16835. {
  16836. puller.setown(new CRoxieServerReadAheadInput(ctx, ctx->queryOptions().parallelJoinPreload));
  16837. puller->setInput(0, _sourceIdx, _in);
  16838. _in = puller;
  16839. _sourceIdx = 0;
  16840. }
  16841. CRoxieServerTwoInputActivity::setInput(idx, _sourceIdx, _in);
  16842. }
  16843. virtual const void * nextRow()
  16844. {
  16845. ActivityTimer t(totalCycles, timeActivities);
  16846. if(!table)
  16847. loadRight();
  16848. switch (activityKind)
  16849. {
  16850. case TAKlookupjoin:
  16851. case TAKsmartjoin:
  16852. return nextRowJoin();
  16853. case TAKlookupdenormalize:
  16854. case TAKlookupdenormalizegroup:
  16855. case TAKsmartdenormalize:
  16856. case TAKsmartdenormalizegroup:
  16857. return nextRowDenormalize();
  16858. }
  16859. throwUnexpected();
  16860. }
  16861. private:
  16862. const void * nextRowJoin()
  16863. {
  16864. if(!table)
  16865. loadRight();
  16866. while(true)
  16867. {
  16868. const void * right = NULL;
  16869. if(!left)
  16870. {
  16871. left = inputStream->nextRow();
  16872. keepCount = keepLimit;
  16873. joinCounter = 0;
  16874. if(!left)
  16875. {
  16876. if (isSmartJoin)
  16877. left = inputStream->nextRow();
  16878. if (!left)
  16879. {
  16880. if(matchedGroup || eog)
  16881. {
  16882. matchedGroup = false;
  16883. eog = true;
  16884. return NULL;
  16885. }
  16886. eog = true;
  16887. continue;
  16888. }
  16889. }
  16890. eog = false;
  16891. gotMatch = false;
  16892. right = getRightFirst();
  16893. }
  16894. else
  16895. right = getRightNext();
  16896. const void * ret = NULL;
  16897. if(failingLimit)
  16898. {
  16899. ret = joinException(left, failingLimit);
  16900. }
  16901. else
  16902. {
  16903. while(right)
  16904. {
  16905. if(helper.match(left, right))
  16906. {
  16907. gotMatch = true;
  16908. if(exclude)
  16909. break;
  16910. ret = joinRecords(left, right, ++joinCounter, JTFmatchedleft|JTFmatchedright);
  16911. if(ret)
  16912. {
  16913. processed++;
  16914. break;
  16915. }
  16916. }
  16917. right = getRightNext();
  16918. ret = NULL;
  16919. }
  16920. if(leftOuterJoin && !gotMatch)
  16921. {
  16922. ret = joinRecords(left, defaultRight, 0, JTFmatchedleft);
  16923. gotMatch = true;
  16924. }
  16925. }
  16926. if(ret)
  16927. {
  16928. matchedGroup = true;
  16929. processed++;
  16930. if(!many || (--keepCount == 0) || failingLimit)
  16931. {
  16932. ReleaseClearRoxieRow(left);
  16933. failingLimit.clear();
  16934. }
  16935. return ret;
  16936. }
  16937. ReleaseClearRoxieRow(left);
  16938. }
  16939. }
  16940. const void * nextRowDenormalize()
  16941. {
  16942. while(true)
  16943. {
  16944. left = inputStream->nextRow();
  16945. if(!left)
  16946. {
  16947. if (!matchedGroup || isSmartJoin)
  16948. left = inputStream->nextRow();
  16949. if (!left)
  16950. {
  16951. matchedGroup = false;
  16952. return NULL;
  16953. }
  16954. }
  16955. gotMatch = false;
  16956. const void * right = getRightFirst();
  16957. const void * ret = NULL;
  16958. if (failingLimit)
  16959. ret = joinException(left, failingLimit);
  16960. else if (activityKind == TAKlookupdenormalize || activityKind == TAKsmartdenormalize)
  16961. {
  16962. OwnedConstRoxieRow newLeft;
  16963. newLeft.set(left);
  16964. unsigned rowSize = 0;
  16965. unsigned leftCount = 0;
  16966. keepCount = keepLimit;
  16967. while (right)
  16968. {
  16969. try
  16970. {
  16971. if (helper.match(left, right))
  16972. {
  16973. gotMatch = true;
  16974. if (exclude)
  16975. break;
  16976. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16977. unsigned thisSize = helper.transform(rowBuilder, newLeft, right, ++leftCount, JTFmatchedleft|JTFmatchedright);
  16978. if (thisSize)
  16979. {
  16980. rowSize = thisSize;
  16981. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  16982. }
  16983. if(!many || (--keepCount == 0))
  16984. break;
  16985. }
  16986. right = getRightNext();
  16987. }
  16988. catch (IException *E)
  16989. {
  16990. throw makeWrappedException(E);
  16991. }
  16992. }
  16993. if (rowSize)
  16994. ret = newLeft.getClear();
  16995. else if (leftOuterJoin && !gotMatch)
  16996. {
  16997. ret = left;
  16998. left = NULL;
  16999. }
  17000. }
  17001. else
  17002. {
  17003. filteredRight.kill();
  17004. keepCount = keepLimit;
  17005. while (right)
  17006. {
  17007. if (helper.match(left, right))
  17008. {
  17009. gotMatch = true;
  17010. if(exclude)
  17011. break;
  17012. filteredRight.append(right);
  17013. if(!many || (--keepCount == 0))
  17014. break;
  17015. }
  17016. right = getRightNext();
  17017. }
  17018. if((filteredRight.ordinality() > 0) || (leftOuterJoin && !gotMatch))
  17019. ret = denormalizeRecords(left, filteredRight, JTFmatchedleft);
  17020. filteredRight.kill();
  17021. }
  17022. ReleaseRoxieRow(left);
  17023. left = NULL;
  17024. failingLimit.clear();
  17025. if(ret)
  17026. {
  17027. matchedGroup = true;
  17028. processed++;
  17029. return ret;
  17030. }
  17031. }
  17032. }
  17033. const void * joinRecords(const void * left, const void * right, unsigned counter, unsigned flags)
  17034. {
  17035. if (cloneLeft)
  17036. {
  17037. LinkRoxieRow(left);
  17038. return left;
  17039. }
  17040. try
  17041. {
  17042. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17043. unsigned outSize = helper.transform(rowBuilder, left, right, counter, flags);
  17044. if (outSize)
  17045. return rowBuilder.finalizeRowClear(outSize);
  17046. else
  17047. return NULL;
  17048. }
  17049. catch (IException *E)
  17050. {
  17051. throw makeWrappedException(E);
  17052. }
  17053. }
  17054. const void * joinException(const void * left, IException * except)
  17055. {
  17056. try
  17057. {
  17058. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17059. unsigned outSize = helper.onFailTransform(rowBuilder, left, defaultRight, except, JTFmatchedleft);
  17060. if (outSize)
  17061. return rowBuilder.finalizeRowClear(outSize);
  17062. else
  17063. return NULL;
  17064. }
  17065. catch (IException *E)
  17066. {
  17067. throw makeWrappedException(E);
  17068. }
  17069. }
  17070. const void * denormalizeRecords(const void * left, ConstPointerArray & rows, unsigned flags)
  17071. {
  17072. try
  17073. {
  17074. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17075. unsigned numRows = rows.ordinality();
  17076. const void * right = numRows ? rows.item(0) : defaultRight.get();
  17077. if (numRows>0)
  17078. flags |= JTFmatchedright;
  17079. unsigned outSize = helper.transform(rowBuilder, left, right, numRows, (const void * *)rows.getArray(), flags);
  17080. if (outSize)
  17081. return rowBuilder.finalizeRowClear(outSize);
  17082. else
  17083. return NULL;
  17084. }
  17085. catch (IException *E)
  17086. {
  17087. throw makeWrappedException(E);
  17088. }
  17089. }
  17090. const void * getRightFirst() { if(hasGroupLimit) return fillRightGroup(); else return table->find(left); }
  17091. const void * getRightNext() { if(hasGroupLimit) return readRightGroup(); else return table->findNext(left); }
  17092. const void * readRightGroup() { if(rightGroup.isItem(rightGroupIndex)) return rightGroup.item(rightGroupIndex++); else return NULL; }
  17093. const void *fillRightGroup()
  17094. {
  17095. rightGroup.kill();
  17096. for(const void * right = table->find(left); right; right = table->findNext(left))
  17097. {
  17098. rightGroup.append(right);
  17099. if(rightGroup.ordinality() > limitLimit)
  17100. {
  17101. if(limitFail)
  17102. failLimit();
  17103. gotMatch = true;
  17104. if (ctx->queryDebugContext())
  17105. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  17106. if(limitOnFail)
  17107. {
  17108. assertex(!failingLimit);
  17109. try
  17110. {
  17111. failLimit();
  17112. }
  17113. catch(IException * e)
  17114. {
  17115. failingLimit.setown(e);
  17116. }
  17117. assertex(failingLimit != NULL);
  17118. }
  17119. else
  17120. {
  17121. rightGroup.kill();
  17122. }
  17123. break;
  17124. }
  17125. if(rightGroup.ordinality() > atmostLimit)
  17126. {
  17127. atmostsTriggered++;
  17128. rightGroup.kill();
  17129. break;
  17130. }
  17131. }
  17132. rightGroupIndex = 0;
  17133. return readRightGroup();
  17134. }
  17135. void failLimit()
  17136. {
  17137. helper.onMatchAbortLimitExceeded();
  17138. CommonXmlWriter xmlwrite(XWFtrim|XWFopt );
  17139. if(!ctx->isBlind() && input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  17140. {
  17141. input->queryOutputMeta()->toXML(static_cast<const unsigned char *>(left), xmlwrite);
  17142. }
  17143. throw MakeStringException(ROXIE_TOO_MANY_RESULTS, "More than %u match candidates in join %d for row %s", limitLimit, queryId(), xmlwrite.str());
  17144. }
  17145. };
  17146. unsigned const CRoxieServerLookupJoinActivity::FewLookupTable::BadIndex(static_cast<unsigned>(-1));
  17147. class CRoxieServerLookupJoinActivityFactory : public CRoxieServerJoinActivityFactory
  17148. {
  17149. public:
  17150. CRoxieServerLookupJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17151. : CRoxieServerJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  17152. {
  17153. Owned<IHThorHashJoinArg> helper = (IHThorHashJoinArg *) helperFactory();
  17154. useFewTable = _graphNode.getPropBool("hint[@name='usefewtable']/@value", false);
  17155. if((helper->getJoinFlags() & (JFfirst | JFfirstleft | JFfirstright | JFslidingmatch)) != 0)
  17156. throw MakeStringException(ROXIE_INVALID_FLAGS, "Invalid flags for lookup join activity"); // code generator should never create such an activity
  17157. }
  17158. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  17159. {
  17160. return new CRoxieServerLookupJoinActivity(_ctx, this, _probeManager, useFewTable);
  17161. }
  17162. virtual const StatisticsMapping &queryStatsMapping() const
  17163. {
  17164. return joinStatistics;
  17165. }
  17166. protected:
  17167. bool useFewTable;
  17168. };
  17169. IRoxieServerActivityFactory *createRoxieServerLookupJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17170. {
  17171. return new CRoxieServerLookupJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  17172. }
  17173. //=====================================================================================================
  17174. class CRoxieServerAllJoinActivity : public CRoxieServerTwoInputActivity
  17175. {
  17176. private:
  17177. IHThorAllJoinArg &helper;
  17178. bool leftOuterJoin;
  17179. bool rightOuterJoin;
  17180. bool exclude;
  17181. OwnedConstRoxieRow defaultRight;
  17182. OwnedConstRoxieRow defaultLeft;
  17183. Owned<IEngineRowAllocator> defaultRightAllocator;
  17184. Owned<IEngineRowAllocator> defaultLeftAllocator;
  17185. const void *left;
  17186. unsigned countForLeft;
  17187. ConstPointerArray rightset;
  17188. BoolArray matchedRight; // MORE - could use a bitset...
  17189. unsigned keepLimit;
  17190. bool started;
  17191. bool eog;
  17192. bool eos;
  17193. bool matchedLeft;
  17194. bool matchedGroup;
  17195. bool leftIsGrouped;
  17196. bool cloneLeft;
  17197. unsigned rightIndex;
  17198. unsigned joinCounter;
  17199. unsigned rightOrdinality;
  17200. ThorActivityKind activityKind;
  17201. ConstPointerArray filteredRight;
  17202. void createDefaultLeft()
  17203. {
  17204. if (!defaultLeft)
  17205. {
  17206. if (!defaultLeftAllocator)
  17207. defaultLeftAllocator.setown(createRowAllocator(input->queryOutputMeta()));
  17208. RtlDynamicRowBuilder rowBuilder(defaultLeftAllocator);
  17209. size32_t thisSize = helper.createDefaultLeft(rowBuilder);
  17210. defaultLeft.setown(rowBuilder.finalizeRowClear(thisSize));
  17211. }
  17212. }
  17213. void createDefaultRight()
  17214. {
  17215. if (!defaultRight)
  17216. {
  17217. if (!defaultRightAllocator)
  17218. defaultRightAllocator.setown(createRowAllocator(input1->queryOutputMeta()));
  17219. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  17220. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  17221. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  17222. }
  17223. }
  17224. public:
  17225. CRoxieServerAllJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17226. : CRoxieServerTwoInputActivity(_ctx, _factory, _probeManager), helper((IHThorAllJoinArg &)basehelper)
  17227. {
  17228. unsigned joinFlags = helper.getJoinFlags();
  17229. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  17230. rightOuterJoin = (joinFlags & JFrightouter) != 0;
  17231. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  17232. keepLimit = (unsigned) -1;
  17233. exclude = (joinFlags & JFexclude) != 0;
  17234. left = NULL;
  17235. started = true;
  17236. eog = false;
  17237. eos = false;
  17238. matchedLeft = false;
  17239. matchedGroup = false;
  17240. activityKind = factory->getKind();
  17241. rightIndex = 0;
  17242. rightOrdinality = 0;
  17243. leftIsGrouped = false;
  17244. countForLeft = 0;
  17245. joinCounter = 0;
  17246. }
  17247. virtual void reset()
  17248. {
  17249. defaultRight.clear();
  17250. defaultLeft.clear();
  17251. ReleaseRoxieRows(rightset);
  17252. matchedRight.kill();
  17253. CRoxieServerTwoInputActivity::reset();
  17254. }
  17255. virtual bool needsAllocator() const { return true; }
  17256. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17257. {
  17258. eog = false;
  17259. eos = false;
  17260. matchedLeft = false;
  17261. matchedGroup = false;
  17262. started = false;
  17263. left = NULL;
  17264. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  17265. keepLimit = helper.getKeepLimit();
  17266. if(keepLimit==0)
  17267. keepLimit = (unsigned) -1;
  17268. countForLeft = keepLimit;
  17269. joinCounter = 0;
  17270. leftIsGrouped = input->queryOutputMeta()->isGrouped();
  17271. if((activityKind==TAKalljoin || activityKind==TAKalldenormalizegroup) && leftOuterJoin)
  17272. createDefaultRight();
  17273. if(rightOuterJoin)
  17274. createDefaultLeft();
  17275. }
  17276. void loadRight()
  17277. {
  17278. const void * next;
  17279. while(true)
  17280. {
  17281. next = inputStream1->ungroupedNextRow();
  17282. if(!next)
  17283. break;
  17284. rightset.append(next);
  17285. matchedRight.append(false);
  17286. }
  17287. rightIndex = 0;
  17288. joinCounter = 0;
  17289. rightOrdinality = rightset.ordinality();
  17290. }
  17291. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  17292. {
  17293. if (!idx && (helper.getJoinFlags() & JFparallel) != 0)
  17294. {
  17295. puller.setown(new CRoxieServerReadAheadInput(ctx, ctx->queryOptions().parallelJoinPreload));
  17296. puller->setInput(0, _sourceIdx, _in);
  17297. _in = puller;
  17298. _sourceIdx = 0;
  17299. }
  17300. CRoxieServerTwoInputActivity::setInput(idx, _sourceIdx, _in);
  17301. }
  17302. const void * joinRecords(const void * left, const void * right, unsigned counter, unsigned flags)
  17303. {
  17304. // MORE - could share some code with lookup join
  17305. if (cloneLeft)
  17306. {
  17307. LinkRoxieRow(left);
  17308. return left;
  17309. }
  17310. try
  17311. {
  17312. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17313. unsigned outSize = helper.transform(rowBuilder, left, right, counter, flags);
  17314. if (outSize)
  17315. return rowBuilder.finalizeRowClear(outSize);
  17316. else
  17317. return NULL;
  17318. }
  17319. catch (IException *E)
  17320. {
  17321. throw makeWrappedException(E);
  17322. }
  17323. }
  17324. const void * denormalizeRecords(const void * curLeft, ConstPointerArray & rows, unsigned flags)
  17325. {
  17326. try
  17327. {
  17328. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17329. unsigned numRows = rows.ordinality();
  17330. const void * right = numRows ? rows.item(0) : defaultRight.get();
  17331. if (numRows>0)
  17332. flags |= JTFmatchedright;
  17333. unsigned outSize = helper.transform(rowBuilder, curLeft, right, numRows, rows.getArray(), flags);
  17334. if (outSize)
  17335. return rowBuilder.finalizeRowClear(outSize);
  17336. else
  17337. return NULL;
  17338. }
  17339. catch (IException *E)
  17340. {
  17341. throw makeWrappedException(E);
  17342. }
  17343. }
  17344. virtual const void *nextRow()
  17345. {
  17346. ActivityTimer t(totalCycles, timeActivities);
  17347. if(!started)
  17348. {
  17349. started = true;
  17350. left = inputStream->nextRow();
  17351. matchedLeft = false;
  17352. countForLeft = keepLimit;
  17353. joinCounter = 0;
  17354. if(left == NULL)
  17355. {
  17356. eos = true;
  17357. return NULL;
  17358. }
  17359. loadRight();
  17360. }
  17361. const void * ret;
  17362. const void * right;
  17363. if(eos)
  17364. return NULL;
  17365. while(true)
  17366. {
  17367. ret = NULL;
  17368. if((rightIndex == rightOrdinality) || (countForLeft==0))
  17369. {
  17370. if(leftOuterJoin && left && !matchedLeft)
  17371. {
  17372. switch(activityKind)
  17373. {
  17374. case TAKalljoin:
  17375. ret = joinRecords(left, defaultRight, 0, JTFmatchedleft);
  17376. break;
  17377. case TAKalldenormalize:
  17378. ret = left;
  17379. left = NULL;
  17380. break;
  17381. case TAKalldenormalizegroup:
  17382. filteredRight.kill();
  17383. ret = denormalizeRecords(left, filteredRight, JTFmatchedleft);
  17384. break;
  17385. default:
  17386. throwUnexpected();
  17387. }
  17388. }
  17389. rightIndex = 0;
  17390. joinCounter = 0;
  17391. ReleaseRoxieRow(left);
  17392. left = NULL;
  17393. if(ret)
  17394. {
  17395. matchedGroup = true;
  17396. processed++;
  17397. return ret;
  17398. }
  17399. }
  17400. if(!left)
  17401. {
  17402. left = inputStream->nextRow();
  17403. matchedLeft = false;
  17404. countForLeft = keepLimit;
  17405. joinCounter = 0;
  17406. }
  17407. if(!left)
  17408. {
  17409. if(eog)
  17410. {
  17411. eos = true;
  17412. matchedGroup = false;
  17413. return NULL;
  17414. }
  17415. eog = true;
  17416. if (matchedGroup && leftIsGrouped)
  17417. {
  17418. matchedGroup = false;
  17419. return NULL;
  17420. }
  17421. matchedGroup = false;
  17422. continue;
  17423. }
  17424. eog = false;
  17425. switch(activityKind)
  17426. {
  17427. case TAKalljoin:
  17428. while(rightIndex < rightOrdinality)
  17429. {
  17430. right = rightset.item(rightIndex);
  17431. if(helper.match(left, right))
  17432. {
  17433. matchedLeft = true;
  17434. matchedRight.replace(true, rightIndex);
  17435. if(!exclude)
  17436. ret = joinRecords(left, right, ++joinCounter, JTFmatchedleft|JTFmatchedright);
  17437. }
  17438. rightIndex++;
  17439. if(ret)
  17440. {
  17441. countForLeft--;
  17442. matchedGroup = true;
  17443. processed++;
  17444. return ret;
  17445. }
  17446. }
  17447. break;
  17448. case TAKalldenormalize:
  17449. {
  17450. OwnedConstRoxieRow newLeft;
  17451. newLeft.set(left);
  17452. unsigned rowSize = 0;
  17453. unsigned leftCount = 0;
  17454. while((rightIndex < rightOrdinality) && countForLeft)
  17455. {
  17456. right = rightset.item(rightIndex);
  17457. if(helper.match(left, right))
  17458. {
  17459. matchedLeft = true;
  17460. matchedRight.replace(true, rightIndex);
  17461. if(!exclude)
  17462. {
  17463. try
  17464. {
  17465. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17466. unsigned thisSize = helper.transform(rowBuilder, newLeft, right, ++leftCount, JTFmatchedleft|JTFmatchedright);
  17467. if(thisSize)
  17468. {
  17469. rowSize = thisSize;
  17470. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  17471. --countForLeft;
  17472. }
  17473. }
  17474. catch (IException *e)
  17475. {
  17476. throw makeWrappedException(e);
  17477. }
  17478. }
  17479. }
  17480. rightIndex++;
  17481. }
  17482. if(rowSize)
  17483. {
  17484. processed++;
  17485. return newLeft.getClear();
  17486. }
  17487. }
  17488. break;
  17489. case TAKalldenormalizegroup:
  17490. filteredRight.kill();
  17491. while((rightIndex < rightOrdinality) && countForLeft)
  17492. {
  17493. right = rightset.item(rightIndex);
  17494. if(helper.match(left, right))
  17495. {
  17496. matchedLeft = true;
  17497. matchedRight.replace(true, rightIndex);
  17498. filteredRight.append(right);
  17499. --countForLeft;
  17500. }
  17501. ++rightIndex;
  17502. }
  17503. if(!exclude && filteredRight.ordinality())
  17504. {
  17505. ret = denormalizeRecords(left, filteredRight, JTFmatchedleft);
  17506. filteredRight.kill();
  17507. if(ret)
  17508. {
  17509. processed++;
  17510. return ret;
  17511. }
  17512. }
  17513. break;
  17514. default:
  17515. throwUnexpected();
  17516. }
  17517. }
  17518. }
  17519. };
  17520. class CRoxieServerAllJoinActivityFactory : public CRoxieServerJoinActivityFactory
  17521. {
  17522. public:
  17523. CRoxieServerAllJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17524. : CRoxieServerJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  17525. {
  17526. Owned<IHThorAllJoinArg> helper = (IHThorAllJoinArg *) helperFactory();
  17527. if((helper->getJoinFlags() & (JFfirst | JFfirstleft | JFfirstright)) != 0)
  17528. throw MakeStringException(ROXIE_INVALID_FLAGS, "Invalid flags for join all activity"); // code generator should never create such an activity
  17529. }
  17530. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  17531. {
  17532. return new CRoxieServerAllJoinActivity(_ctx, this, _probeManager);
  17533. }
  17534. virtual const StatisticsMapping &queryStatsMapping() const
  17535. {
  17536. return joinStatistics;
  17537. }
  17538. };
  17539. IRoxieServerActivityFactory *createRoxieServerAllJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17540. {
  17541. return new CRoxieServerAllJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  17542. }
  17543. //=====================================================================================================
  17544. class CRoxieServerTopNActivity : public CRoxieServerLateStartActivity
  17545. {
  17546. unsigned limit;
  17547. bool hasBest;
  17548. bool eoi;
  17549. const void **sorted;
  17550. unsigned sortedCount;
  17551. unsigned curIndex;
  17552. IHThorTopNArg &helper;
  17553. ICompare &compare;
  17554. public:
  17555. CRoxieServerTopNActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17556. : CRoxieServerLateStartActivity(_ctx, _factory, _probeManager), helper((IHThorTopNArg &)basehelper), compare(*helper.queryCompare())
  17557. {
  17558. sorted = NULL;
  17559. sortedCount = 0;
  17560. curIndex = 0;
  17561. limit = 0;
  17562. eoi = false;
  17563. hasBest = false;
  17564. }
  17565. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17566. {
  17567. assertex(sorted == NULL);
  17568. sortedCount = 0;
  17569. curIndex = 0;
  17570. eoi = false;
  17571. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  17572. limit = (unsigned) helper.getLimit();
  17573. hasBest = helper.hasBest();
  17574. lateStart(parentExtractSize, parentExtract, limit > 0);
  17575. // MORE - should we use an expanding array instead?
  17576. if (limit > 0)
  17577. sorted = (const void **) ctx->queryRowManager().allocate((limit+1) * sizeof(const void *), activityId);
  17578. }
  17579. virtual void reset()
  17580. {
  17581. if (sorted)
  17582. {
  17583. roxiemem::ReleaseRoxieRowRange(sorted, curIndex, sortedCount);
  17584. curIndex = 0;
  17585. sortedCount = 0;
  17586. ReleaseRoxieRow(sorted);
  17587. sorted = NULL;
  17588. }
  17589. CRoxieServerLateStartActivity::reset();
  17590. }
  17591. bool abortEarly()
  17592. {
  17593. if (hasBest && (sortedCount == limit))
  17594. {
  17595. int compare = helper.compareBest(sorted[sortedCount-1]);
  17596. if (compare == 0)
  17597. {
  17598. if (meta.isGrouped())
  17599. {
  17600. //MORE: This would be more efficient if we had a away of skipping to the end of the incoming group.
  17601. const void * next;
  17602. while ((next = inputStream->nextRow()) != NULL)
  17603. ReleaseRoxieRow(next);
  17604. }
  17605. else
  17606. eoi = true;
  17607. return true;
  17608. }
  17609. //This only checks the lowest element - we could check all elements inserted, but it would increase the number of compares
  17610. if (compare < 0)
  17611. throw MakeStringException(ROXIE_TOPN_ROW_ERROR, "TOPN: row found that exceeds the best value");
  17612. }
  17613. return false;
  17614. }
  17615. void getSorted()
  17616. {
  17617. curIndex = 0;
  17618. sortedCount = 0;
  17619. if(eoi)
  17620. return;
  17621. const void * next;
  17622. while ((next = inputStream->nextRow()) != NULL)
  17623. {
  17624. if (sortedCount < limit)
  17625. {
  17626. binary_vec_insert_stable(next, sorted, sortedCount, compare);
  17627. sortedCount++;
  17628. if(abortEarly())
  17629. return;
  17630. }
  17631. else
  17632. {
  17633. if(limit && compare.docompare(sorted[sortedCount-1], next) > 0) // MORE - if stability is an issue, need to consider whether this should be > or >=
  17634. {
  17635. binary_vec_insert_stable(next, sorted, sortedCount, compare); // MORE - not sure this is stable!
  17636. ReleaseRoxieRow(sorted[sortedCount]);
  17637. if(abortEarly())
  17638. return;
  17639. }
  17640. else
  17641. {
  17642. ReleaseRoxieRow(next); // do not bother with insertion sort if we know next will fall off the end
  17643. }
  17644. }
  17645. }
  17646. }
  17647. virtual const void * nextRow()
  17648. {
  17649. ActivityTimer t(totalCycles, timeActivities);
  17650. if (eof)
  17651. return NULL;
  17652. if (curIndex >= sortedCount)
  17653. {
  17654. bool eog = sortedCount != 0;
  17655. getSorted();
  17656. if(sortedCount == 0)
  17657. {
  17658. eof = true;
  17659. return NULL;
  17660. }
  17661. if (eog)
  17662. return NULL;
  17663. }
  17664. processed++;
  17665. return sorted[curIndex++];
  17666. }
  17667. };
  17668. class CRoxieServerTopNActivityFactory : public CRoxieServerActivityFactory
  17669. {
  17670. public:
  17671. CRoxieServerTopNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17672. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  17673. {
  17674. }
  17675. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  17676. {
  17677. return new CRoxieServerTopNActivity(_ctx, this, _probeManager);
  17678. }
  17679. };
  17680. IRoxieServerActivityFactory *createRoxieServerTopNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17681. {
  17682. return new CRoxieServerTopNActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  17683. }
  17684. //=================================================================================
  17685. class CRoxieServerLimitActivity : public CRoxieServerActivity
  17686. {
  17687. protected:
  17688. unsigned __int64 rowLimit;
  17689. IHThorLimitArg &helper;
  17690. public:
  17691. CRoxieServerLimitActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17692. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorLimitArg &)basehelper)
  17693. {
  17694. rowLimit = 0;
  17695. }
  17696. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17697. {
  17698. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  17699. rowLimit = helper.getRowLimit(); // could conceivably depend on context so should not compute any earlier than this
  17700. }
  17701. virtual const void *nextRow()
  17702. {
  17703. ActivityTimer t(totalCycles, timeActivities);
  17704. const void * ret = inputStream->nextRow();
  17705. if (ret)
  17706. {
  17707. processed++;
  17708. if (processed > rowLimit)
  17709. {
  17710. ReleaseRoxieRow(ret);
  17711. if (traceLevel > 4)
  17712. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  17713. helper.onLimitExceeded();
  17714. }
  17715. }
  17716. return ret;
  17717. }
  17718. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  17719. {
  17720. ActivityTimer t(totalCycles, timeActivities);
  17721. const void * ret = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  17722. if (ret)
  17723. {
  17724. if (wasCompleteMatch)
  17725. processed++;
  17726. if (processed > rowLimit)
  17727. {
  17728. ReleaseRoxieRow(ret);
  17729. if (traceLevel > 4)
  17730. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  17731. helper.onLimitExceeded();
  17732. }
  17733. }
  17734. return ret;
  17735. }
  17736. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  17737. {
  17738. return input->gatherConjunctions(collector);
  17739. }
  17740. virtual void resetEOF()
  17741. {
  17742. //Do not reset the rowLimit
  17743. inputStream->resetEOF();
  17744. }
  17745. IInputSteppingMeta * querySteppingMeta()
  17746. {
  17747. return input->querySteppingMeta();
  17748. }
  17749. };
  17750. class CRoxieServerLimitActivityFactory : public CRoxieServerActivityFactory
  17751. {
  17752. public:
  17753. CRoxieServerLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17754. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  17755. {
  17756. }
  17757. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  17758. {
  17759. return new CRoxieServerLimitActivity(_ctx, this, _probeManager);
  17760. }
  17761. };
  17762. IRoxieServerActivityFactory *createRoxieServerLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17763. {
  17764. return new CRoxieServerLimitActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  17765. }
  17766. //=====================================================================================================
  17767. class CRoxieServerSkipLimitActivity : public CRoxieServerLimitActivity
  17768. {
  17769. ConstPointerArray buff;
  17770. bool started = false;
  17771. unsigned index = 0;
  17772. bool isFail = false;
  17773. public:
  17774. CRoxieServerSkipLimitActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _onFail)
  17775. : CRoxieServerLimitActivity(_ctx, _factory, _probeManager)
  17776. {
  17777. started = false;
  17778. index = 0;
  17779. isFail = _onFail;
  17780. }
  17781. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17782. {
  17783. started = false;
  17784. index = 0;
  17785. CRoxieServerLimitActivity::start(parentExtractSize, parentExtract, paused);
  17786. }
  17787. virtual void reset()
  17788. {
  17789. roxiemem::ReleaseRoxieRowRange(buff.getArray(), index, buff.ordinality());
  17790. buff.kill();
  17791. index = 0;
  17792. started = false;
  17793. CRoxieServerLimitActivity::reset();
  17794. }
  17795. virtual const void *nextRow()
  17796. {
  17797. ActivityTimer t(totalCycles, timeActivities);
  17798. if (!started)
  17799. pullInput();
  17800. if (buff.isItem(index))
  17801. {
  17802. const void * next = buff.item(index++);
  17803. if(next)
  17804. processed++;
  17805. return next;
  17806. }
  17807. return NULL;
  17808. }
  17809. protected:
  17810. void pullInput()
  17811. {
  17812. unsigned count = 0;
  17813. for (;;)
  17814. {
  17815. const void * next = inputStream->nextRow();
  17816. if (next == NULL)
  17817. {
  17818. next = inputStream->nextRow();
  17819. if(next == NULL)
  17820. break;
  17821. buff.append(NULL);
  17822. }
  17823. count++;
  17824. if (count > rowLimit)
  17825. {
  17826. ReleaseRoxieRow(next);
  17827. ReleaseRoxieRows(buff);
  17828. if (ctx->queryDebugContext())
  17829. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  17830. if (isFail)
  17831. {
  17832. ensureRowAllocator();
  17833. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17834. size32_t outSize = helper.transformOnLimitExceeded(rowBuilder);
  17835. if (outSize)
  17836. buff.append(rowBuilder.finalizeRowClear(outSize));
  17837. }
  17838. break;
  17839. }
  17840. buff.append(next);
  17841. }
  17842. started = true;
  17843. }
  17844. };
  17845. class CRoxieServerSkipLimitActivityFactory : public CRoxieServerActivityFactory
  17846. {
  17847. public:
  17848. CRoxieServerSkipLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17849. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  17850. {
  17851. }
  17852. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  17853. {
  17854. return new CRoxieServerSkipLimitActivity(_ctx, this, _probeManager, kind==TAKcreaterowlimit);
  17855. }
  17856. };
  17857. IRoxieServerActivityFactory *createRoxieServerSkipLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17858. {
  17859. return new CRoxieServerSkipLimitActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  17860. }
  17861. //=================================================================================
  17862. class CRoxieServerCatchActivity : public CRoxieServerActivity
  17863. {
  17864. IHThorCatchArg &helper;
  17865. public:
  17866. CRoxieServerCatchActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17867. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorCatchArg &)basehelper)
  17868. {
  17869. }
  17870. virtual const void *nextRow()
  17871. {
  17872. ActivityTimer t(totalCycles, timeActivities);
  17873. try
  17874. {
  17875. const void *ret = inputStream->nextRow();
  17876. if (ret)
  17877. processed++;
  17878. return ret;
  17879. }
  17880. catch (IException *E)
  17881. {
  17882. E->Release();
  17883. helper.onExceptionCaught();
  17884. }
  17885. catch (...)
  17886. {
  17887. helper.onExceptionCaught();
  17888. }
  17889. throwUnexpected(); // onExceptionCaught should have thrown something
  17890. }
  17891. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  17892. {
  17893. try
  17894. {
  17895. ActivityTimer t(totalCycles, timeActivities);
  17896. const void * ret = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  17897. if (ret && wasCompleteMatch)
  17898. processed++;
  17899. return ret;
  17900. }
  17901. catch (IException *E)
  17902. {
  17903. E->Release();
  17904. helper.onExceptionCaught();
  17905. }
  17906. catch (...)
  17907. {
  17908. helper.onExceptionCaught();
  17909. }
  17910. throwUnexpected(); // onExceptionCaught should have thrown something
  17911. }
  17912. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  17913. {
  17914. return input->gatherConjunctions(collector);
  17915. }
  17916. virtual void resetEOF()
  17917. {
  17918. inputStream->resetEOF(); // MORE - why not in base class?
  17919. }
  17920. IInputSteppingMeta * querySteppingMeta()
  17921. {
  17922. return input->querySteppingMeta();
  17923. }
  17924. };
  17925. class CRoxieServerSkipCatchActivity : public CRoxieServerActivity
  17926. {
  17927. ConstPointerArray buff;
  17928. bool started;
  17929. unsigned index;
  17930. IHThorCatchArg &helper;
  17931. bool createRow;
  17932. public:
  17933. CRoxieServerSkipCatchActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _createRow)
  17934. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorCatchArg &)basehelper), createRow(_createRow)
  17935. {
  17936. started = false;
  17937. index = 0;
  17938. }
  17939. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17940. {
  17941. started = false;
  17942. index = 0;
  17943. try
  17944. {
  17945. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  17946. }
  17947. catch (IException *E)
  17948. {
  17949. onException(E);
  17950. started = true;
  17951. }
  17952. catch (...)
  17953. {
  17954. onException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught"));
  17955. started = true;
  17956. }
  17957. }
  17958. virtual void reset()
  17959. {
  17960. roxiemem::ReleaseRoxieRowRange(buff.getArray(), index, buff.ordinality());
  17961. buff.kill();
  17962. index = 0;
  17963. started = false;
  17964. CRoxieServerActivity::reset();
  17965. }
  17966. virtual const void *nextRow()
  17967. {
  17968. ActivityTimer t(totalCycles, timeActivities);
  17969. if (!started)
  17970. pullInput();
  17971. if (buff.isItem(index))
  17972. {
  17973. const void * next = buff.item(index++);
  17974. if(next)
  17975. processed++;
  17976. return next;
  17977. }
  17978. return NULL;
  17979. }
  17980. protected:
  17981. void onException(IException *E)
  17982. {
  17983. inputStream->stop();
  17984. ReleaseRoxieRows(buff);
  17985. if (createRow)
  17986. {
  17987. ensureRowAllocator();
  17988. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17989. size32_t outSize = helper.transformOnExceptionCaught(rowBuilder, E);
  17990. if (outSize)
  17991. buff.append(rowBuilder.finalizeRowClear(outSize));
  17992. }
  17993. E->Release();
  17994. }
  17995. void pullInput()
  17996. {
  17997. try
  17998. {
  17999. bool EOGseen = false;
  18000. for (;;)
  18001. {
  18002. const void * next = inputStream->nextRow();
  18003. buff.append(next);
  18004. if (next == NULL)
  18005. {
  18006. if (EOGseen)
  18007. break;
  18008. EOGseen = true;
  18009. }
  18010. else
  18011. EOGseen = false;
  18012. }
  18013. }
  18014. catch (IException *E)
  18015. {
  18016. onException(E);
  18017. }
  18018. catch (...)
  18019. {
  18020. onException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught"));
  18021. }
  18022. started = true;
  18023. }
  18024. };
  18025. class CRoxieServerCatchActivityFactory : public CRoxieServerActivityFactory
  18026. {
  18027. public:
  18028. CRoxieServerCatchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  18029. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  18030. {
  18031. }
  18032. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18033. {
  18034. switch (kind)
  18035. {
  18036. case TAKcatch:
  18037. return new CRoxieServerCatchActivity(_ctx, this, _probeManager);
  18038. case TAKskipcatch:
  18039. return new CRoxieServerSkipCatchActivity(_ctx, this, _probeManager, false);
  18040. case TAKcreaterowcatch:
  18041. return new CRoxieServerSkipCatchActivity(_ctx, this, _probeManager, true);
  18042. default:
  18043. throwUnexpected();
  18044. }
  18045. }
  18046. };
  18047. IRoxieServerActivityFactory *createRoxieServerCatchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  18048. {
  18049. return new CRoxieServerCatchActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  18050. }
  18051. //=================================================================================
  18052. class CRoxieServerPullActivity : public CRoxieServerActivity
  18053. {
  18054. ConstPointerArray buff;
  18055. bool started;
  18056. unsigned index;
  18057. public:
  18058. CRoxieServerPullActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18059. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  18060. {
  18061. started = false;
  18062. index = 0;
  18063. }
  18064. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18065. {
  18066. started = false;
  18067. index = 0;
  18068. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  18069. }
  18070. virtual void reset()
  18071. {
  18072. while (buff.isItem(index))
  18073. ReleaseRoxieRow(buff.item(index++));
  18074. buff.kill();
  18075. started = false;
  18076. index = 0;
  18077. CRoxieServerActivity::reset();
  18078. }
  18079. virtual const void *nextRow()
  18080. {
  18081. ActivityTimer t(totalCycles, timeActivities);
  18082. if (!started)
  18083. pullInput();
  18084. if (buff.isItem(index))
  18085. {
  18086. const void * next = buff.item(index++);
  18087. if (next)
  18088. processed++;
  18089. return next;
  18090. }
  18091. return NULL;
  18092. }
  18093. protected:
  18094. void pullInput()
  18095. {
  18096. bool EOGseen = false;
  18097. for (;;)
  18098. {
  18099. const void * next = inputStream->nextRow();
  18100. buff.append(next);
  18101. if (next == NULL)
  18102. {
  18103. if (EOGseen)
  18104. break;
  18105. EOGseen = true;
  18106. }
  18107. else
  18108. EOGseen = false;
  18109. }
  18110. started = true;
  18111. }
  18112. };
  18113. class CRoxieServerPullActivityFactory : public CRoxieServerActivityFactory
  18114. {
  18115. public:
  18116. CRoxieServerPullActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  18117. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  18118. {
  18119. }
  18120. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18121. {
  18122. return new CRoxieServerPullActivity(_ctx, this, _probeManager);
  18123. }
  18124. };
  18125. IRoxieServerActivityFactory *createRoxieServerPullActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  18126. {
  18127. return new CRoxieServerPullActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  18128. }
  18129. //=================================================================================
  18130. class CRoxieServerTraceActivity : public CRoxieServerActivity
  18131. {
  18132. public:
  18133. CRoxieServerTraceActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18134. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorTraceArg &) basehelper),
  18135. keepLimit(0), skip(0), sample(0)
  18136. {
  18137. assertex(meta.hasXML());
  18138. traceEnabled = defaultTraceEnabled && !isBlind();
  18139. }
  18140. virtual void onCreate(IHThorArg *_colocalParent)
  18141. {
  18142. CRoxieServerActivity::onCreate(_colocalParent);
  18143. if (ctx)
  18144. traceEnabled = ctx->queryOptions().traceEnabled && !isBlind();
  18145. }
  18146. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18147. {
  18148. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  18149. if (traceEnabled && helper.canMatchAny())
  18150. {
  18151. keepLimit = helper.getKeepLimit();
  18152. if (keepLimit==(unsigned) -1)
  18153. keepLimit = ctx->queryOptions().traceLimit;
  18154. skip = helper.getSkip();
  18155. sample = helper.getSample();
  18156. if (sample)
  18157. sample--;
  18158. name.setown(helper.getName());
  18159. if (!name)
  18160. name.set("Row");
  18161. }
  18162. else
  18163. keepLimit = 0;
  18164. }
  18165. virtual void stop()
  18166. {
  18167. name.clear();
  18168. CRoxieServerActivity::stop();
  18169. }
  18170. virtual bool isPassThrough()
  18171. {
  18172. return true;
  18173. }
  18174. virtual const void *nextRow()
  18175. {
  18176. ActivityTimer t(totalCycles, timeActivities);
  18177. const void *row = inputStream->nextRow();
  18178. if (row)
  18179. {
  18180. onTrace(row);
  18181. processed++;
  18182. }
  18183. return row;
  18184. }
  18185. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  18186. {
  18187. // MORE - will need rethinking once we rethink the nextRowGE interface for global smart-stepping.
  18188. ActivityTimer t(totalCycles, timeActivities);
  18189. const void * row = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  18190. if (row)
  18191. {
  18192. onTrace(row);
  18193. processed++;
  18194. }
  18195. return row;
  18196. }
  18197. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  18198. {
  18199. return input->gatherConjunctions(collector);
  18200. }
  18201. virtual void resetEOF()
  18202. {
  18203. inputStream->resetEOF();
  18204. }
  18205. IInputSteppingMeta * querySteppingMeta()
  18206. {
  18207. return input->querySteppingMeta();
  18208. }
  18209. protected:
  18210. void onTrace(const void *row)
  18211. {
  18212. if (keepLimit && helper.isValid(row))
  18213. {
  18214. if (skip)
  18215. skip--;
  18216. else if (sample)
  18217. sample--;
  18218. else
  18219. {
  18220. CommonXmlWriter xmlwrite(XWFnoindent);
  18221. meta.toXML((const byte *) row, xmlwrite);
  18222. CTXLOG("TRACE: <%s>%s<%s>", name.get(), xmlwrite.str(), name.get());
  18223. keepLimit--;
  18224. sample = helper.getSample();
  18225. if (sample)
  18226. sample--;
  18227. }
  18228. }
  18229. }
  18230. OwnedRoxieString name;
  18231. IHThorTraceArg &helper;
  18232. unsigned keepLimit;
  18233. unsigned skip;
  18234. unsigned sample;
  18235. bool traceEnabled;
  18236. };
  18237. class CRoxieServerTraceActivityFactory : public CRoxieServerActivityFactory
  18238. {
  18239. public:
  18240. CRoxieServerTraceActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  18241. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  18242. {
  18243. }
  18244. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18245. {
  18246. return new CRoxieServerTraceActivity(_ctx, this, _probeManager);
  18247. }
  18248. };
  18249. IRoxieServerActivityFactory *createRoxieServerTraceActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  18250. {
  18251. return new CRoxieServerTraceActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  18252. }
  18253. //=================================================================================
  18254. class CRoxieServerCaseActivity : public CRoxieServerMultiInputBaseActivity
  18255. {
  18256. IHThorCaseArg &helper;
  18257. unsigned cond;
  18258. bool unusedStopped;
  18259. IEngineRowStream *active;
  18260. public:
  18261. CRoxieServerCaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  18262. : CRoxieServerMultiInputBaseActivity(_ctx, _factory, _probeManager, _numInputs), helper((IHThorCaseArg &)basehelper)
  18263. {
  18264. unusedStopped = false;
  18265. cond = 0;
  18266. active = NULL;
  18267. }
  18268. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18269. {
  18270. CRoxieServerMultiInputBaseActivity::start(parentExtractSize, parentExtract, paused);
  18271. cond = helper.getBranch();
  18272. //CHOOSE defaults to the last argument if out of range.
  18273. if (cond >= numInputs)
  18274. cond = numInputs - 1;
  18275. inputArray[cond]->start(parentExtractSize, parentExtract, paused);
  18276. startJunction(junctionArray[cond]);
  18277. assertex(numInputs==numStreams);
  18278. for (unsigned idx = 0; idx < numStreams; idx++)
  18279. {
  18280. if (idx!=cond)
  18281. streamArray[idx]->stop(); // Note: stopping unused branches early helps us avoid buffering splits too long.
  18282. }
  18283. active = streamArray[cond];
  18284. unusedStopped = true;
  18285. }
  18286. virtual void stop()
  18287. {
  18288. for (unsigned idx = 0; idx < numStreams; idx++)
  18289. {
  18290. if (idx==cond || !unusedStopped)
  18291. streamArray[idx]->stop();
  18292. }
  18293. CRoxieServerMultiInputBaseActivity::stop();
  18294. }
  18295. virtual void reset()
  18296. {
  18297. unusedStopped = false;
  18298. active = NULL;
  18299. CRoxieServerMultiInputBaseActivity::reset();
  18300. }
  18301. virtual const void *nextRow()
  18302. {
  18303. ActivityTimer t(totalCycles, timeActivities);
  18304. if (active)
  18305. {
  18306. const void *ret = active->nextRow();
  18307. if (ret)
  18308. processed++;
  18309. return ret;
  18310. }
  18311. return NULL;
  18312. }
  18313. };
  18314. class CRoxieServerCaseActivityFactory : public CRoxieServerMultiInputFactory
  18315. {
  18316. bool graphInvariant;
  18317. public:
  18318. CRoxieServerCaseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _graphInvariant)
  18319. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  18320. {
  18321. graphInvariant = _graphInvariant;
  18322. }
  18323. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18324. {
  18325. return new CRoxieServerCaseActivity(_ctx, this, _probeManager, numInputs());
  18326. }
  18327. virtual bool isGraphInvariant() const
  18328. {
  18329. return graphInvariant;
  18330. }
  18331. };
  18332. IRoxieServerActivityFactory *createRoxieServerCaseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _graphInvariant)
  18333. {
  18334. return new CRoxieServerCaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _graphInvariant);
  18335. }
  18336. //=================================================================================
  18337. class CRoxieServerIfActivity : public CRoxieServerActivity
  18338. {
  18339. IHThorIfArg &helper;
  18340. IFinalRoxieInput *inputTrue;
  18341. IFinalRoxieInput *inputFalse;
  18342. IEngineRowStream *streamTrue;
  18343. IEngineRowStream *streamFalse;
  18344. unsigned sourceIdxFalse = 0;
  18345. unsigned sourceIdxTrue = 0;
  18346. Owned<IStrandJunction> junctionTrue;
  18347. Owned<IStrandJunction> junctionFalse;
  18348. bool cond;
  18349. bool unusedStopped;
  18350. public:
  18351. CRoxieServerIfActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18352. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorIfArg &)basehelper)
  18353. {
  18354. inputFalse = NULL;
  18355. inputTrue = NULL;
  18356. streamTrue = NULL;
  18357. streamFalse = NULL;
  18358. unusedStopped = false;
  18359. cond = false;
  18360. }
  18361. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18362. {
  18363. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  18364. cond = helper.getCondition();
  18365. if (cond)
  18366. {
  18367. inputTrue->start(parentExtractSize, parentExtract, paused);
  18368. startJunction(junctionTrue);
  18369. if (streamFalse)
  18370. streamFalse->stop(); // Note: stopping unused branches early helps us avoid buffering splits too long.
  18371. }
  18372. else
  18373. {
  18374. if (inputFalse)
  18375. {
  18376. inputFalse->start(parentExtractSize, parentExtract, paused);
  18377. startJunction(junctionFalse);
  18378. }
  18379. streamTrue->stop();
  18380. }
  18381. unusedStopped = true;
  18382. }
  18383. virtual void stop()
  18384. {
  18385. if (!unusedStopped || cond)
  18386. streamTrue->stop();
  18387. if (streamFalse && (!unusedStopped || !cond))
  18388. streamFalse->stop();
  18389. CRoxieServerActivity::stop();
  18390. }
  18391. virtual unsigned __int64 queryLocalCycles() const
  18392. {
  18393. __int64 localCycles = totalCycles.totalCycles;
  18394. localCycles -= inputTrue->queryTotalCycles();
  18395. if (inputFalse)
  18396. localCycles -= inputFalse->queryTotalCycles();
  18397. if (localCycles < 0)
  18398. localCycles = 0;
  18399. return localCycles;
  18400. }
  18401. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  18402. {
  18403. switch (idx)
  18404. {
  18405. case 0:
  18406. return inputTrue;
  18407. case 1:
  18408. return inputFalse;
  18409. default:
  18410. return NULL;
  18411. }
  18412. }
  18413. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { return this; }
  18414. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { return nullptr; }
  18415. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  18416. {
  18417. IFinalRoxieInput *in = cond ? inputTrue : inputFalse;
  18418. if (in)
  18419. return in->queryIndexReadActivity();
  18420. return NULL;
  18421. }
  18422. virtual void reset()
  18423. {
  18424. CRoxieServerActivity::reset();
  18425. inputTrue->reset();
  18426. if (inputFalse)
  18427. inputFalse->reset();
  18428. resetJunction(junctionTrue);
  18429. resetJunction(junctionFalse);
  18430. unusedStopped = false;
  18431. }
  18432. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  18433. {
  18434. if (idx==1)
  18435. {
  18436. inputFalse = _in;
  18437. sourceIdxFalse = _sourceIdx;
  18438. }
  18439. else
  18440. {
  18441. assertex(!idx);
  18442. inputTrue = _in;
  18443. sourceIdxTrue = _sourceIdx;
  18444. }
  18445. }
  18446. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  18447. {
  18448. //It should be possible to stream IF(), but the number of strands would need to match on the two branches.
  18449. streamTrue = connectSingleStream(ctx, inputTrue, sourceIdxTrue, junctionTrue, consumerOrdered);
  18450. streamFalse = connectSingleStream(ctx, inputFalse, sourceIdxFalse, junctionFalse, consumerOrdered);
  18451. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, nullptr, consumerOrdered, nullptr);
  18452. }
  18453. virtual const void *nextRow()
  18454. {
  18455. ActivityTimer t(totalCycles, timeActivities);
  18456. IEngineRowStream *in = cond ? streamTrue : streamFalse;
  18457. if (in)
  18458. {
  18459. const void * ret;
  18460. if ((ret = in->nextRow()) != NULL)
  18461. processed++;
  18462. return ret;
  18463. }
  18464. return NULL;
  18465. }
  18466. };
  18467. class CRoxieServerIfActivityFactory : public CRoxieServerActivityFactory
  18468. {
  18469. unsigned input2;
  18470. unsigned input2idx;
  18471. bool graphInvariant;
  18472. public:
  18473. CRoxieServerIfActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _graphInvariant)
  18474. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  18475. {
  18476. graphInvariant = _graphInvariant;
  18477. input2 = (unsigned)-1;
  18478. input2idx = (unsigned)-1;
  18479. }
  18480. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18481. {
  18482. return new CRoxieServerIfActivity(_ctx, this, _probeManager);
  18483. }
  18484. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  18485. {
  18486. if (idx==1)
  18487. {
  18488. input2 = source;
  18489. input2idx = sourceidx;
  18490. }
  18491. else
  18492. CRoxieServerActivityFactory::setInput(idx, source, sourceidx);
  18493. }
  18494. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  18495. {
  18496. switch (idx)
  18497. {
  18498. case 1:
  18499. sourceidx = input2idx;
  18500. return input2;
  18501. case 0:
  18502. return CRoxieServerActivityFactory::getInput(idx, sourceidx);
  18503. default:
  18504. return (unsigned) -1;
  18505. }
  18506. }
  18507. virtual unsigned numInputs() const { return (input2 == (unsigned)-1) ? 1 : 2; }
  18508. virtual bool isGraphInvariant() const
  18509. {
  18510. return graphInvariant;
  18511. }
  18512. };
  18513. IRoxieServerActivityFactory *createRoxieServerIfActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _graphInvariant)
  18514. {
  18515. return new CRoxieServerIfActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _graphInvariant);
  18516. }
  18517. //=================================================================================
  18518. class CRoxieServerActionBaseActivity : public CRoxieServerActivity
  18519. {
  18520. CriticalSection ecrit;
  18521. Owned<IException> exception;
  18522. bool executed;
  18523. public:
  18524. CRoxieServerActionBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18525. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  18526. {
  18527. executed = false;
  18528. }
  18529. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract) = 0;
  18530. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  18531. {
  18532. CriticalBlock b(ecrit);
  18533. if (exception)
  18534. throw(exception.getLink());
  18535. if (!executed)
  18536. {
  18537. try
  18538. {
  18539. executed = true;
  18540. start(parentExtractSize, parentExtract, false);
  18541. doExecuteAction(parentExtractSize, parentExtract);
  18542. stop();
  18543. }
  18544. catch (IException * E)
  18545. {
  18546. ctx->notifyAbort(E);
  18547. abort();
  18548. exception.set(E);
  18549. throw;
  18550. }
  18551. }
  18552. }
  18553. virtual void reset()
  18554. {
  18555. executed = false;
  18556. exception.clear();
  18557. CRoxieServerActivity::reset();
  18558. }
  18559. virtual const void *nextRow()
  18560. {
  18561. throwUnexpected(); // I am nobody's input
  18562. }
  18563. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  18564. {
  18565. return NULL;
  18566. }
  18567. };
  18568. class CRoxieServerIfActionActivity : public CRoxieServerActionBaseActivity
  18569. {
  18570. IHThorIfArg &helper;
  18571. public:
  18572. CRoxieServerIfActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18573. : CRoxieServerActionBaseActivity(_ctx, _factory, _probeManager), helper((IHThorIfArg &)basehelper)
  18574. {
  18575. }
  18576. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  18577. {
  18578. bool cond;
  18579. {
  18580. ActivityTimer t(totalCycles, timeActivities);
  18581. cond = helper.getCondition();
  18582. }
  18583. stopDependencies(parentExtractSize, parentExtract, cond ? 2 : 1);
  18584. executeDependencies(parentExtractSize, parentExtract, cond ? 1 : 2);
  18585. }
  18586. };
  18587. class CRoxieServerIfActionActivityFactory : public CRoxieServerActivityFactory
  18588. {
  18589. bool isRoot;
  18590. public:
  18591. CRoxieServerIfActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18592. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  18593. {
  18594. }
  18595. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18596. {
  18597. return new CRoxieServerIfActionActivity(_ctx, this, _probeManager);
  18598. }
  18599. virtual bool isSink() const
  18600. {
  18601. return isRoot;
  18602. }
  18603. };
  18604. IRoxieServerActivityFactory *createRoxieServerIfActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18605. {
  18606. return new CRoxieServerIfActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  18607. }
  18608. //=================================================================================
  18609. class CRoxieServerParallelActionActivity : public CRoxieServerActionBaseActivity
  18610. {
  18611. public:
  18612. CRoxieServerParallelActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18613. : CRoxieServerActionBaseActivity(_ctx, _factory, _probeManager)
  18614. {
  18615. }
  18616. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  18617. {
  18618. #ifdef PARALLEL_EXECUTE
  18619. CParallelActivityExecutor afor(dependencies, parentExtractSize, parentExtract);
  18620. afor.For(dependencies.ordinality(), dependencies.ordinality(), true);
  18621. #else
  18622. ForEachItemIn(idx, dependencies)
  18623. {
  18624. dependencies.item(idx).execute(parentExtractSize, parentExtract);
  18625. }
  18626. #endif
  18627. }
  18628. };
  18629. class CRoxieServerParallelActionActivityFactory : public CRoxieServerActivityFactory
  18630. {
  18631. bool isRoot;
  18632. public:
  18633. CRoxieServerParallelActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18634. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  18635. {
  18636. assertex(!isRoot); // non-internal should be expanded out..
  18637. }
  18638. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18639. {
  18640. return new CRoxieServerParallelActionActivity(_ctx, this, _probeManager);
  18641. }
  18642. virtual bool isSink() const
  18643. {
  18644. return isRoot;
  18645. }
  18646. };
  18647. IRoxieServerActivityFactory *createRoxieServerParallelActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18648. {
  18649. return new CRoxieServerParallelActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  18650. }
  18651. //=================================================================================
  18652. class CRoxieServerSequentialActionActivity : public CRoxieServerActionBaseActivity
  18653. {
  18654. IHThorSequentialArg &helper;
  18655. public:
  18656. CRoxieServerSequentialActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18657. : CRoxieServerActionBaseActivity(_ctx, _factory, _probeManager), helper((IHThorSequentialArg &)basehelper)
  18658. {
  18659. }
  18660. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  18661. {
  18662. unsigned numBranches = helper.numBranches();
  18663. for (unsigned branch=1; branch <= numBranches; branch++)
  18664. executeDependencies(parentExtractSize, parentExtract, branch);
  18665. }
  18666. };
  18667. class CRoxieServerSequentialActionActivityFactory : public CRoxieServerActivityFactory
  18668. {
  18669. bool isRoot;
  18670. public:
  18671. CRoxieServerSequentialActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18672. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  18673. {
  18674. }
  18675. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18676. {
  18677. return new CRoxieServerSequentialActionActivity(_ctx, this, _probeManager);
  18678. }
  18679. virtual bool isSink() const
  18680. {
  18681. return isRoot;
  18682. }
  18683. };
  18684. IRoxieServerActivityFactory *createRoxieServerSequentialActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18685. {
  18686. return new CRoxieServerSequentialActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  18687. }
  18688. //=================================================================================
  18689. class CRoxieServerWhenActivity : public CRoxieServerActivity
  18690. {
  18691. public:
  18692. CRoxieServerWhenActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18693. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  18694. {
  18695. savedExtractSize = 0;
  18696. savedExtract = NULL;
  18697. eofseen = false;
  18698. eogseen = false;
  18699. }
  18700. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18701. {
  18702. savedExtractSize = parentExtractSize;
  18703. savedExtract = parentExtract;
  18704. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  18705. executeDependencies(parentExtractSize, parentExtract, WhenBeforeId);
  18706. executeDependencies(parentExtractSize, parentExtract, WhenParallelId); // MORE: This should probably be done in parallel!
  18707. eofseen = false;
  18708. eogseen = false;
  18709. }
  18710. virtual void stop()
  18711. {
  18712. if (state == STATEreset || (!aborted && !eofseen)) // If someone else aborted, then WHEN clauses don't trigger, whatever
  18713. {
  18714. stopDependencies(savedExtractSize, savedExtract, WhenSuccessId);
  18715. stopDependencies(savedExtractSize, savedExtract, WhenFailureId);
  18716. }
  18717. else if (state != STATEstopped)
  18718. {
  18719. stopDependencies(savedExtractSize, savedExtract, aborted ? WhenSuccessId : WhenFailureId); // These ones don't get executed
  18720. executeDependencies(savedExtractSize, savedExtract, aborted ? WhenFailureId : WhenSuccessId); // These ones do
  18721. }
  18722. CRoxieServerActivity::stop();
  18723. }
  18724. virtual const void *nextRow()
  18725. {
  18726. try
  18727. {
  18728. ActivityTimer t(totalCycles, timeActivities); // bit of a waste of time....
  18729. const void *ret = inputStream->nextRow();
  18730. if (!ret)
  18731. {
  18732. if (eogseen)
  18733. eofseen = true;
  18734. else
  18735. eogseen = true;
  18736. }
  18737. else
  18738. eogseen = false;
  18739. return ret;
  18740. }
  18741. catch (...)
  18742. {
  18743. aborted = true;
  18744. throw;
  18745. }
  18746. }
  18747. protected:
  18748. const byte *savedExtract;
  18749. unsigned savedExtractSize;
  18750. bool eofseen;
  18751. bool eogseen;
  18752. };
  18753. class CRoxieServerWhenActivityFactory : public CRoxieServerActivityFactory
  18754. {
  18755. public:
  18756. CRoxieServerWhenActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  18757. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  18758. {
  18759. }
  18760. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18761. {
  18762. return new CRoxieServerWhenActivity(_ctx, this, _probeManager);
  18763. }
  18764. };
  18765. extern IRoxieServerActivityFactory *createRoxieServerWhenActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  18766. {
  18767. return new CRoxieServerWhenActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  18768. }
  18769. //=================================================================================
  18770. class CRoxieServerWhenActionActivity : public CRoxieServerActionBaseActivity
  18771. {
  18772. public:
  18773. CRoxieServerWhenActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18774. : CRoxieServerActionBaseActivity(_ctx, _factory, _probeManager)
  18775. {
  18776. savedExtractSize = 0;
  18777. savedExtract = NULL;
  18778. }
  18779. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18780. {
  18781. savedExtractSize = parentExtractSize;
  18782. savedExtract = parentExtract;
  18783. CRoxieServerActionBaseActivity::start(parentExtractSize, parentExtract, paused);
  18784. executeDependencies(parentExtractSize, parentExtract, WhenBeforeId);
  18785. executeDependencies(parentExtractSize, parentExtract, WhenParallelId); // MORE: This should probably be done in parallel!
  18786. }
  18787. virtual void stop()
  18788. {
  18789. if (state != STATEstopped)
  18790. {
  18791. stopDependencies(savedExtractSize, savedExtract, aborted ? WhenSuccessId : WhenFailureId); // these are NOT going to execute
  18792. executeDependencies(savedExtractSize, savedExtract, aborted ? WhenFailureId : WhenSuccessId);
  18793. }
  18794. CRoxieServerActionBaseActivity::stop();
  18795. }
  18796. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  18797. {
  18798. executeDependencies(parentExtractSize, parentExtract, 1);
  18799. }
  18800. protected:
  18801. unsigned savedExtractSize;
  18802. const byte *savedExtract;
  18803. };
  18804. class CRoxieServerWhenActionActivityFactory : public CRoxieServerActivityFactory
  18805. {
  18806. public:
  18807. CRoxieServerWhenActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18808. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  18809. {
  18810. }
  18811. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18812. {
  18813. return new CRoxieServerWhenActionActivity(_ctx, this, _probeManager);
  18814. }
  18815. virtual bool isSink() const
  18816. {
  18817. return isRoot;
  18818. }
  18819. private:
  18820. bool isRoot;
  18821. };
  18822. extern IRoxieServerActivityFactory *createRoxieServerWhenActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18823. {
  18824. return new CRoxieServerWhenActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  18825. }
  18826. //=================================================================================
  18827. class CRoxieServerStrandedParseActivity : public CRoxieServerStrandedActivity
  18828. {
  18829. INlpParseAlgorithm * algorithm;
  18830. class ParseProcessor : public StrandProcessor, implements IMatchedAction
  18831. {
  18832. protected:
  18833. IHThorParseArg &helper;
  18834. INlpParser * parser;
  18835. INlpResultIterator * rowIter;
  18836. const void * in;
  18837. char * curSearchText;
  18838. size32_t curSearchTextLen;
  18839. bool processRecord(const void * inRec)
  18840. {
  18841. if (helper.searchTextNeedsFree())
  18842. rtlFree(curSearchText);
  18843. curSearchTextLen = 0;
  18844. curSearchText = NULL;
  18845. helper.getSearchText(curSearchTextLen, curSearchText, inRec);
  18846. return parser->performMatch(*this, in, curSearchTextLen, curSearchText);
  18847. }
  18848. public:
  18849. ParseProcessor(CRoxieServerActivity &_parent, IEngineRowStream *_inputStream, IHThorParseArg &_helper, INlpParseAlgorithm * _algorithm)
  18850. : StrandProcessor(_parent, _inputStream, false), helper(_helper)
  18851. {
  18852. parser = _algorithm->createParser(parent.queryCodeContext(), parent.queryId(), helper.queryHelper(), &helper);
  18853. rowIter = parser->queryResultIter();
  18854. in = NULL;
  18855. curSearchText = NULL;
  18856. curSearchTextLen = 0;
  18857. }
  18858. ~ParseProcessor()
  18859. {
  18860. ::Release(parser);
  18861. }
  18862. virtual void start()
  18863. {
  18864. StrandProcessor::start();
  18865. numProcessedLastGroup = 0;
  18866. curSearchTextLen = 0;
  18867. curSearchText = NULL;
  18868. in = NULL;
  18869. parser->reset();
  18870. }
  18871. virtual void reset()
  18872. {
  18873. if (helper.searchTextNeedsFree())
  18874. rtlFree(curSearchText);
  18875. curSearchText = NULL;
  18876. ReleaseClearRoxieRow(in);
  18877. StrandProcessor::reset();
  18878. }
  18879. virtual const void * nextRow()
  18880. {
  18881. ActivityTimer t(totalCycles, timeActivities);
  18882. for (;;)
  18883. {
  18884. if (rowIter->isValid())
  18885. {
  18886. OwnedConstRoxieRow out = rowIter->getRow();
  18887. rowIter->next();
  18888. processed++;
  18889. return out.getClear();
  18890. }
  18891. ReleaseClearRoxieRow(in);
  18892. in = inputStream->nextRow();
  18893. if (!in)
  18894. {
  18895. if (processed == numProcessedLastGroup)
  18896. in = inputStream->nextRow();
  18897. if (!in)
  18898. {
  18899. processed = numProcessedLastGroup;
  18900. return NULL;
  18901. }
  18902. in = inputStream->nextRow();
  18903. if (!in)
  18904. return NULL;
  18905. }
  18906. processRecord(in);
  18907. rowIter->first();
  18908. }
  18909. }
  18910. virtual unsigned onMatch(ARowBuilder & self, const void * curRecord, IMatchedResults * results, IMatchWalker * walker)
  18911. {
  18912. try
  18913. {
  18914. return helper.transform(self, curRecord, results, walker);
  18915. }
  18916. catch (IException *E)
  18917. {
  18918. throw parent.makeWrappedException(E);
  18919. }
  18920. }
  18921. };
  18922. public:
  18923. CRoxieServerStrandedParseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, INlpParseAlgorithm * _algorithm, const StrandOptions &_strandOptions)
  18924. : CRoxieServerStrandedActivity(_ctx, _factory, _probeManager, _strandOptions), algorithm(_algorithm)
  18925. {
  18926. }
  18927. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18928. {
  18929. CRoxieServerStrandedActivity::start(parentExtractSize, parentExtract, paused);
  18930. onStartStrands();
  18931. }
  18932. virtual StrandProcessor *createStrandProcessor(IEngineRowStream *instream)
  18933. {
  18934. return new ParseProcessor(*this, instream, (IHThorParseArg &) basehelper, algorithm);
  18935. }
  18936. virtual StrandProcessor *createStrandSourceProcessor(bool inputOrdered) { throwUnexpected(); }
  18937. };
  18938. class CRoxieServerParseActivityFactory : public CRoxieServerActivityFactory
  18939. {
  18940. Owned<INlpParseAlgorithm> algorithm;
  18941. Owned<IHThorParseArg> helper;
  18942. StrandOptions strandOptions;
  18943. public:
  18944. CRoxieServerParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, IResourceContext *rc)
  18945. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), strandOptions(_graphNode)
  18946. {
  18947. helper.setown((IHThorParseArg *) helperFactory());
  18948. algorithm.setown(createThorParser(rc, *helper));
  18949. optStableInput = false;
  18950. }
  18951. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18952. {
  18953. return new CRoxieServerStrandedParseActivity(_ctx, this, _probeManager, algorithm, strandOptions);
  18954. }
  18955. };
  18956. IRoxieServerActivityFactory *createRoxieServerParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, IResourceContext *rc)
  18957. {
  18958. return new CRoxieServerParseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, rc);
  18959. }
  18960. //=====================================================================================================
  18961. class CRoxieServerWorkUnitWriteActivity : public CRoxieServerInternalSinkActivity
  18962. {
  18963. IHThorWorkUnitWriteArg &helper;
  18964. bool isReread;
  18965. bool grouped;
  18966. IRoxieServerContext *serverContext;
  18967. public:
  18968. CRoxieServerWorkUnitWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _isReread, unsigned _numOutputs)
  18969. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _numOutputs), helper((IHThorWorkUnitWriteArg &)basehelper), isReread(_isReread)
  18970. {
  18971. grouped = (helper.getFlags() & POFgrouped) != 0;
  18972. serverContext = NULL;
  18973. }
  18974. virtual void onCreate(IHThorArg *_colocalParent)
  18975. {
  18976. CRoxieServerInternalSinkActivity::onCreate(_colocalParent);
  18977. serverContext = ctx->queryServerContext();
  18978. if (!serverContext)
  18979. {
  18980. throw MakeStringException(ROXIE_PIPE_ERROR, "Pipe output activity cannot be executed in slave context");
  18981. }
  18982. }
  18983. virtual bool needsAllocator() const { return true; }
  18984. virtual void onExecute()
  18985. {
  18986. int sequence = helper.getSequence();
  18987. const char *storedName = helper.queryName();
  18988. if (!storedName)
  18989. storedName = "Dataset";
  18990. MemoryBuffer result;
  18991. bool saveInContext = (int) sequence < 0 || isReread;
  18992. if (!meta.queryOriginal()) // this is a bit of a hack - don't know why no meta on an output....
  18993. meta.set(input->queryOutputMeta());
  18994. Owned<IOutputRowSerializer> rowSerializer;
  18995. Owned<IXmlWriter> xmlwriter;
  18996. bool appendRaw = false;
  18997. IHpccProtocolResultsWriter *results = NULL;
  18998. IHpccNativeProtocolResultsWriter *nativeResults = NULL;
  18999. IHpccProtocolResponse *protocol = serverContext->queryProtocol();
  19000. unsigned protocolFlags = (protocol) ? protocol->getFlags() : 0;
  19001. if ((int) sequence >= 0)
  19002. {
  19003. results = (protocol) ? protocol->queryHpccResultsSection() : NULL;
  19004. if (results)
  19005. {
  19006. nativeResults = dynamic_cast<IHpccNativeProtocolResultsWriter*>(results);
  19007. xmlwriter.setown(results->addDataset(helper.queryName(), sequence, "Dataset", appendRaw, serverContext->getXmlFlags(), (helper.getFlags() & POFextend) != 0, serverContext->queryXmlns(sequence))); //xmlwriter only returned if needed
  19008. }
  19009. }
  19010. size32_t outputLimitBytes = 0;
  19011. IConstWorkUnit *workunit = serverContext->queryWorkUnit();
  19012. if (workunit)
  19013. {
  19014. size32_t outputLimit;
  19015. if (helper.getFlags() & POFmaxsize)
  19016. outputLimit = helper.getMaxSize();
  19017. else
  19018. {
  19019. // In absense of OPT_OUTPUTLIMIT check pre 5.2 legacy name OPT_OUTPUTLIMIT_LEGACY
  19020. outputLimit = workunit->getDebugValueInt(OPT_OUTPUTLIMIT, workunit->getDebugValueInt(OPT_OUTPUTLIMIT_LEGACY, defaultDaliResultLimit));
  19021. }
  19022. if (outputLimit>defaultDaliResultOutputMax)
  19023. 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);
  19024. assertex(outputLimit<=0x1000); // 32bit limit because MemoryBuffer/CMessageBuffers involved etc.
  19025. outputLimitBytes = outputLimit * 0x100000;
  19026. }
  19027. if (workunit != NULL || (results && (protocol->getFlags() & HPCC_PROTOCOL_NATIVE_RAW)))
  19028. {
  19029. ensureRowAllocator();
  19030. rowSerializer.setown(rowAllocator->createDiskSerializer(ctx->queryCodeContext()));
  19031. }
  19032. __int64 initialProcessed = processed;
  19033. RtlLinkedDatasetBuilder builder(rowAllocator);
  19034. for (;;)
  19035. {
  19036. const void *row = inputStream->nextRow();
  19037. if (saveInContext)
  19038. {
  19039. if (row || grouped)
  19040. builder.append(row);
  19041. }
  19042. if (grouped && (processed != initialProcessed))
  19043. {
  19044. if (workunit)
  19045. result.append(row == NULL);
  19046. if (results)
  19047. {
  19048. if ((protocolFlags & HPCC_PROTOCOL_NATIVE_RAW) && nativeResults)
  19049. {
  19050. char val = (char)(row == NULL);
  19051. nativeResults->appendRaw(sequence, 1, &val);
  19052. }
  19053. else if (xmlwriter)
  19054. {
  19055. xmlwriter->outputBeginNested("Row", false);
  19056. xmlwriter->outputCString("1", "@__GroupBreak__");
  19057. xmlwriter->outputEndNested("Row");
  19058. }
  19059. }
  19060. }
  19061. if (!row)
  19062. {
  19063. row = inputStream->nextRow();
  19064. if (!row)
  19065. break;
  19066. if (saveInContext)
  19067. builder.append(row);
  19068. }
  19069. processed++;
  19070. if (workunit)
  19071. {
  19072. CThorDemoRowSerializer serializerTarget(result);
  19073. rowSerializer->serialize(serializerTarget, (const byte *) row);
  19074. }
  19075. if ((int) sequence >= 0)
  19076. {
  19077. if (appendRaw && nativeResults)
  19078. {
  19079. // MORE - should be able to serialize straight to the response...
  19080. MemoryBuffer rowbuff;
  19081. CThorDemoRowSerializer serializerTarget(rowbuff);
  19082. rowSerializer->serialize(serializerTarget, (const byte *) row);
  19083. nativeResults->appendRawRow(sequence, rowbuff.length(), rowbuff.toByteArray());
  19084. }
  19085. else if (xmlwriter)
  19086. {
  19087. xmlwriter->outputBeginNested(DEFAULTXMLROWTAG, false);
  19088. helper.serializeXml((byte *) row, *xmlwriter);
  19089. xmlwriter->outputEndNested(DEFAULTXMLROWTAG);
  19090. results->finalizeXmlRow(sequence);
  19091. }
  19092. else if (nativeResults)
  19093. {
  19094. SimpleOutputWriter x;
  19095. helper.serializeXml((byte *) row, x);
  19096. x.newline();
  19097. nativeResults->appendSimpleRow(sequence, x.str());
  19098. }
  19099. }
  19100. ReleaseRoxieRow(row);
  19101. if (outputLimitBytes && result.length() > outputLimitBytes)
  19102. {
  19103. StringBuffer errMsg("Dataset too large to output to workunit (limit ");
  19104. errMsg.append(outputLimitBytes/0x100000).append(" megabytes), in result (");
  19105. const char *name = helper.queryName();
  19106. if (name)
  19107. errMsg.append("name=").append(name);
  19108. else
  19109. errMsg.append("sequence=").append(helper.getSequence());
  19110. errMsg.append(")");
  19111. throw MakeStringExceptionDirect(0, errMsg.str());
  19112. }
  19113. }
  19114. if (xmlwriter)
  19115. xmlwriter->outputEndArray(DEFAULTXMLROWTAG);
  19116. if (saveInContext)
  19117. serverContext->appendResultDeserialized(storedName, sequence, builder.getcount(), builder.linkrows(), (helper.getFlags() & POFextend) != 0, LINK(meta.queryOriginal()));
  19118. if (workunit)
  19119. serverContext->appendResultRawContext(storedName, sequence, result.length(), result.toByteArray(), processed, (helper.getFlags() & POFextend) != 0, false); // MORE - shame to do extra copy...
  19120. }
  19121. };
  19122. class CRoxieServerWorkUnitWriteActivityFactory : public CRoxieServerInternalSinkFactory
  19123. {
  19124. bool isReread;
  19125. public:
  19126. CRoxieServerWorkUnitWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  19127. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot)
  19128. {
  19129. isReread = usageCount > 0;
  19130. Owned<IHThorWorkUnitWriteArg> helper = (IHThorWorkUnitWriteArg *) helperFactory();
  19131. isInternal = (helper->getSequence()==ResultSequenceInternal);
  19132. }
  19133. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  19134. {
  19135. return new CRoxieServerWorkUnitWriteActivity(_ctx, this, _probeManager, isReread, usageCount);
  19136. }
  19137. };
  19138. IRoxieServerActivityFactory *createRoxieServerWorkUnitWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  19139. {
  19140. return new CRoxieServerWorkUnitWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot);
  19141. }
  19142. //=====================================================================================================
  19143. class CRoxieServerWorkUnitWriteDictActivity : public CRoxieServerInternalSinkActivity
  19144. {
  19145. IHThorDictionaryWorkUnitWriteArg &helper;
  19146. IRoxieServerContext *serverContext;
  19147. public:
  19148. CRoxieServerWorkUnitWriteDictActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _usageCount)
  19149. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _usageCount), helper((IHThorDictionaryWorkUnitWriteArg &)basehelper)
  19150. {
  19151. serverContext = NULL;
  19152. }
  19153. virtual void onCreate(IHThorArg *_colocalParent)
  19154. {
  19155. CRoxieServerInternalSinkActivity::onCreate(_colocalParent);
  19156. serverContext = ctx->queryServerContext();
  19157. if (!serverContext)
  19158. {
  19159. throw MakeStringException(ROXIE_PIPE_ERROR, "Write Dictionary activity cannot be executed in slave context");
  19160. }
  19161. }
  19162. virtual bool needsAllocator() const { return true; }
  19163. virtual void onExecute()
  19164. {
  19165. int sequence = helper.getSequence();
  19166. const char *storedName = helper.queryName();
  19167. assertex(storedName && *storedName);
  19168. assertex(sequence < 0);
  19169. RtlLinkedDictionaryBuilder builder(rowAllocator, helper.queryHashLookupInfo());
  19170. for (;;)
  19171. {
  19172. const void *row = inputStream->ungroupedNextRow();
  19173. if (!row)
  19174. break;
  19175. builder.appendOwn(row);
  19176. processed++;
  19177. }
  19178. serverContext->appendResultDeserialized(storedName, sequence, builder.getcount(), builder.linkrows(), (helper.getFlags() & POFextend) != 0, LINK(meta.queryOriginal()));
  19179. }
  19180. };
  19181. class CRoxieServerWorkUnitWriteDictActivityFactory : public CRoxieServerInternalSinkFactory
  19182. {
  19183. public:
  19184. CRoxieServerWorkUnitWriteDictActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  19185. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot)
  19186. {
  19187. Owned<IHThorDictionaryWorkUnitWriteArg> helper = (IHThorDictionaryWorkUnitWriteArg *) helperFactory();
  19188. isInternal = (helper->getSequence()==ResultSequenceInternal);
  19189. }
  19190. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  19191. {
  19192. return new CRoxieServerWorkUnitWriteDictActivity(_ctx, this, _probeManager, usageCount);
  19193. }
  19194. };
  19195. IRoxieServerActivityFactory *createRoxieServerWorkUnitWriteDictActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  19196. {
  19197. return new CRoxieServerWorkUnitWriteDictActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot);
  19198. }
  19199. //=================================================================================
  19200. class CRoxieServerRemoteResultActivity : public CRoxieServerInternalSinkActivity
  19201. {
  19202. IHThorRemoteResultArg &helper;
  19203. public:
  19204. CRoxieServerRemoteResultActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  19205. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _numOutputs), helper((IHThorRemoteResultArg &)basehelper)
  19206. {
  19207. }
  19208. virtual void onExecute()
  19209. {
  19210. OwnedConstRoxieRow row = inputStream->nextRow();
  19211. helper.sendResult(row); // should be only one row or something has gone wrong!
  19212. }
  19213. };
  19214. class CRoxieServerRemoteResultActivityFactory : public CRoxieServerInternalSinkFactory
  19215. {
  19216. public:
  19217. CRoxieServerRemoteResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  19218. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot)
  19219. {
  19220. Owned<IHThorRemoteResultArg> helper = (IHThorRemoteResultArg *) helperFactory();
  19221. isInternal = (helper->getSequence()==ResultSequenceInternal);
  19222. }
  19223. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  19224. {
  19225. return new CRoxieServerRemoteResultActivity(_ctx, this, _probeManager, usageCount);
  19226. }
  19227. };
  19228. IRoxieServerActivityFactory *createRoxieServerRemoteResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  19229. {
  19230. return new CRoxieServerRemoteResultActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot);
  19231. }
  19232. //=================================================================================
  19233. class CRoxieServerXmlParseActivity : public CRoxieServerActivity, implements IXMLSelect
  19234. {
  19235. IHThorXmlParseArg &helper;
  19236. Owned<IXMLParse> xmlParser;
  19237. const void * in;
  19238. char * srchStr;
  19239. unsigned numProcessedLastGroup;
  19240. bool srchStrNeedsFree;
  19241. Owned<IColumnProvider> lastMatch;
  19242. public:
  19243. IMPLEMENT_IINTERFACE_USING(CRoxieServerActivity)
  19244. CRoxieServerXmlParseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  19245. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  19246. helper((IHThorXmlParseArg &)basehelper)
  19247. {
  19248. srchStrNeedsFree = helper.searchTextNeedsFree();
  19249. numProcessedLastGroup = 0;
  19250. srchStr = NULL;
  19251. in = NULL;
  19252. }
  19253. ~CRoxieServerXmlParseActivity()
  19254. {
  19255. }
  19256. virtual bool needsAllocator() const { return true; }
  19257. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19258. {
  19259. numProcessedLastGroup = 0;
  19260. srchStr = NULL;
  19261. in = NULL;
  19262. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  19263. }
  19264. virtual void reset()
  19265. {
  19266. if (helper.searchTextNeedsFree())
  19267. rtlFree(srchStr);
  19268. srchStr = NULL;
  19269. ReleaseClearRoxieRow(in);
  19270. xmlParser.clear();
  19271. CRoxieServerActivity::reset();
  19272. }
  19273. virtual void match(IColumnProvider &entry, offset_t startOffset, offset_t endOffset)
  19274. {
  19275. lastMatch.set(&entry);
  19276. }
  19277. virtual const void *nextRow()
  19278. {
  19279. ActivityTimer t(totalCycles, timeActivities);
  19280. for (;;)
  19281. {
  19282. if(xmlParser)
  19283. {
  19284. for (;;)
  19285. {
  19286. if(!xmlParser->next())
  19287. {
  19288. if (srchStrNeedsFree)
  19289. {
  19290. rtlFree(srchStr);
  19291. srchStr = NULL;
  19292. }
  19293. xmlParser.clear();
  19294. break;
  19295. }
  19296. if(lastMatch)
  19297. {
  19298. try
  19299. {
  19300. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  19301. size32_t outSize = helper.transform(rowBuilder, in, lastMatch);
  19302. lastMatch.clear();
  19303. if (outSize)
  19304. {
  19305. processed++;
  19306. return rowBuilder.finalizeRowClear(outSize);
  19307. }
  19308. }
  19309. catch (IException *E)
  19310. {
  19311. throw makeWrappedException(E);
  19312. }
  19313. }
  19314. }
  19315. }
  19316. ReleaseClearRoxieRow(in);
  19317. in = inputStream->nextRow();
  19318. if(!in)
  19319. {
  19320. if(numProcessedLastGroup == processed)
  19321. in = inputStream->nextRow();
  19322. if(!in)
  19323. {
  19324. numProcessedLastGroup = processed;
  19325. return NULL;
  19326. }
  19327. }
  19328. size32_t srchLen;
  19329. helper.getSearchText(srchLen, srchStr, in);
  19330. OwnedRoxieString xmlIteratorPath(helper.getXmlIteratorPath());
  19331. xmlParser.setown(createXMLParse(srchStr, srchLen, xmlIteratorPath, *this));
  19332. }
  19333. }
  19334. };
  19335. class CRoxieServerXmlParseActivityFactory : public CRoxieServerActivityFactory
  19336. {
  19337. public:
  19338. CRoxieServerXmlParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  19339. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  19340. {
  19341. }
  19342. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  19343. {
  19344. return new CRoxieServerXmlParseActivity(_ctx, this, _probeManager);
  19345. }
  19346. };
  19347. IRoxieServerActivityFactory *createRoxieServerXmlParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  19348. {
  19349. return new CRoxieServerXmlParseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  19350. }
  19351. //=====================================================================================================
  19352. class CRoxieServerDiskReadBaseActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler, implements IIndexReadContext
  19353. {
  19354. protected:
  19355. IHThorDiskReadBaseArg &helper;
  19356. IHThorSourceLimitTransformExtra * limitTransformExtra = nullptr;
  19357. IHThorCompoundExtra * compoundHelper;
  19358. RemoteActivityId remoteId; // Note we copy it rather than reference
  19359. Owned<CSkippableRemoteResultAdaptor> remote;
  19360. unsigned numParts;
  19361. unsigned __int64 rowLimit;
  19362. unsigned __int64 stopAfter;
  19363. Linked<IInMemoryIndexManager> manager;
  19364. Linked<ITranslatorSet> translators;
  19365. ScoredRowFilter postFilter;
  19366. Owned<IDirectReader> reader;
  19367. bool eof;
  19368. bool variableFileName;
  19369. bool isOpt;
  19370. bool sorted;
  19371. bool maySkip;
  19372. bool isLocal;
  19373. bool forceRemote;
  19374. bool isGrouped = false;
  19375. CachedOutputMetaData diskSize;
  19376. Owned<const IResolvedFile> varFileInfo;
  19377. inline bool useRemote()
  19378. {
  19379. return remote != NULL && (forceRemote || numParts > 1);
  19380. }
  19381. public:
  19382. IMPLEMENT_IINTERFACE_USING(CRoxieServerActivity)
  19383. CRoxieServerDiskReadBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  19384. unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager, ITranslatorSet *_translators)
  19385. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  19386. helper((IHThorDiskReadBaseArg &)basehelper),
  19387. numParts(_numParts),
  19388. remoteId(_remoteId),
  19389. manager(_manager),
  19390. translators(_translators),
  19391. isLocal(_isLocal),
  19392. sorted(_sorted),
  19393. maySkip(_maySkip)
  19394. {
  19395. forceRemote = factory->queryQueryFactory().queryOptions().disableLocalOptimizations;
  19396. if ((forceRemote || numParts != 1) && !isLocal) // NOTE : when numParts == 0 (variable case) we create, even though we may not use
  19397. remote.setown(new CSkippableRemoteResultAdaptor(_ctx, this, remoteId, meta.queryOriginal(), helper, *this, sorted, false, _maySkip));
  19398. compoundHelper = NULL;
  19399. eof = false;
  19400. rowLimit = (unsigned __int64) -1;
  19401. stopAfter = I64C(0x7FFFFFFFFFFFFFFF);
  19402. diskSize.set(helper.queryDiskRecordSize()->querySerializedDiskMeta());
  19403. isGrouped = diskSize.isGrouped();
  19404. variableFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getFlags() & (TDXvarfilename|TDXdynamicfilename)) != 0);
  19405. isOpt = (helper.getFlags() & TDRoptional) != 0;
  19406. }
  19407. virtual const IResolvedFile *queryVarFileInfo() const
  19408. {
  19409. return varFileInfo;
  19410. }
  19411. virtual void onCreate(IHThorArg *_colocalParent)
  19412. {
  19413. CRoxieServerActivity::onCreate(_colocalParent);
  19414. if (remote)
  19415. remote->onCreate(_colocalParent);
  19416. }
  19417. virtual bool needsAllocator() const { return true; }
  19418. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19419. {
  19420. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  19421. if (compoundHelper)
  19422. {
  19423. rowLimit = compoundHelper->getRowLimit();
  19424. stopAfter = compoundHelper->getChooseNLimit();
  19425. }
  19426. if (!helper.canMatchAny())
  19427. eof = true;
  19428. else
  19429. {
  19430. if (variableFileName)
  19431. {
  19432. OwnedRoxieString fileName(helper.getFileName());
  19433. varFileInfo.setown(resolveLFNFlat(fileName, isOpt));
  19434. numParts = 0;
  19435. if (varFileInfo)
  19436. numParts = varFileInfo->getNumParts();
  19437. }
  19438. if (!numParts)
  19439. {
  19440. eof = true;
  19441. }
  19442. else if (useRemote())
  19443. {
  19444. remote->onStart(parentExtractSize, parentExtract);
  19445. remote->setLimits(rowLimit, (unsigned __int64) -1, stopAfter);
  19446. unsigned fileNo = 0;
  19447. // Translation into a message per channel done elsewhere....
  19448. remote->getMem(0, fileNo, 0);
  19449. remote->flush();
  19450. remote->senddone();
  19451. }
  19452. else
  19453. {
  19454. if (variableFileName)
  19455. {
  19456. unsigned channel = isLocal ? factory->queryQueryFactory().queryChannel() : 0;
  19457. unsigned projectedFormatCrc = helper.getProjectedFormatCrc();
  19458. translators.setown(varFileInfo->getTranslators(projectedFormatCrc, skipFileFormatCrcCheck(), helper.queryProjectedDiskRecordSize(), helper.queryDiskRecordSize(), getEnableFieldTranslation(), false));
  19459. manager.setown(varFileInfo->getIndexManager(isOpt, channel, translators->queryActualLayout(0), false));
  19460. }
  19461. assertex(manager != NULL);
  19462. postFilter.clear();
  19463. helper.createSegmentMonitors(this);
  19464. const IKeyTranslator *keyTranslator = translators->queryKeyTranslator(0); // any part would do - in-memory requires all actuals to have same layout
  19465. if (keyTranslator)
  19466. keyTranslator->translate(postFilter);
  19467. reader.setown(manager->selectKey(postFilter, translators, *this));
  19468. if (!reader)
  19469. reader.setown(manager->createReader(postFilter, isGrouped, 0, 0, 1, translators));
  19470. assertex(reader);
  19471. helper.setCallback(reader);
  19472. }
  19473. }
  19474. }
  19475. virtual void append(IKeySegmentMonitor *segment)
  19476. {
  19477. segment->Release();
  19478. throwUnexpected();
  19479. }
  19480. virtual void append(FFoption option, const IFieldFilter * filter)
  19481. {
  19482. if (filter->isWild())
  19483. filter->Release();
  19484. else
  19485. postFilter.addFilter(*filter);
  19486. }
  19487. virtual void stop()
  19488. {
  19489. if (useRemote())
  19490. remote->onStop();
  19491. CRoxieServerActivity::stop();
  19492. }
  19493. virtual void reset()
  19494. {
  19495. if (useRemote())
  19496. {
  19497. processed = remote->processed;
  19498. remote->processed = 0;
  19499. remote->onReset();
  19500. }
  19501. varFileInfo.clear();
  19502. eof = false;
  19503. reader.clear();
  19504. CRoxieServerActivity::reset();
  19505. }
  19506. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  19507. {
  19508. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  19509. }
  19510. virtual void onLimitExceeded(bool isKeyed)
  19511. {
  19512. if (traceLevel > 4)
  19513. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  19514. assertex(compoundHelper);
  19515. if (isKeyed) // MORE does this exist for diskread? should it?
  19516. {
  19517. if (helper.getFlags() & (TDRkeyedlimitskips|TDRkeyedlimitcreates))
  19518. {
  19519. if (ctx->queryDebugContext())
  19520. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  19521. throw makeLimitSkipException(true);
  19522. }
  19523. else
  19524. {
  19525. UNIMPLEMENTED;
  19526. //compoundHelper->onKeyedLimitExceeded(); Doesn't exist - though the flags do... interesting...
  19527. }
  19528. }
  19529. else
  19530. {
  19531. if (helper.getFlags() & (TDRlimitskips|TDRlimitcreates))
  19532. {
  19533. if (ctx->queryDebugContext())
  19534. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  19535. throw makeLimitSkipException(false);
  19536. }
  19537. else
  19538. compoundHelper->onLimitExceeded();
  19539. }
  19540. }
  19541. virtual const void * createLimitFailRow(bool isKeyed)
  19542. {
  19543. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  19544. assertex(limitTransformExtra);
  19545. size32_t outSize = isKeyed ? limitTransformExtra->transformOnKeyedLimitExceeded(rowBuilder) : limitTransformExtra->transformOnLimitExceeded(rowBuilder);
  19546. if (outSize)
  19547. return rowBuilder.finalizeRowClear(outSize);
  19548. return NULL;
  19549. }
  19550. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  19551. {
  19552. CRoxieServerActivity::gatherStats(merged);
  19553. if (remote)
  19554. remote->gatherStats(merged);
  19555. }
  19556. };
  19557. class CRoxieServerDiskReadActivity : public CRoxieServerDiskReadBaseActivity
  19558. {
  19559. IHThorDiskReadArg * readHelper;
  19560. ConstPointerArray readrows;
  19561. bool readAheadDone;
  19562. unsigned readIndex;
  19563. unsigned lastGroupProcessed;
  19564. bool someInGroup = false;
  19565. public:
  19566. CRoxieServerDiskReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager, ITranslatorSet *_translators)
  19567. : CRoxieServerDiskReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, _maySkip, _manager, _translators)
  19568. {
  19569. compoundHelper = (IHThorDiskReadArg *)&helper;
  19570. readHelper = (IHThorDiskReadArg *)&helper;
  19571. limitTransformExtra = readHelper;
  19572. readAheadDone = false;
  19573. readIndex = 0;
  19574. lastGroupProcessed = processed;
  19575. }
  19576. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19577. {
  19578. rowLimit = compoundHelper->getRowLimit();
  19579. stopAfter = compoundHelper->getChooseNLimit();
  19580. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  19581. readAheadDone = false;
  19582. readIndex = 0;
  19583. lastGroupProcessed = processed;
  19584. someInGroup = false;
  19585. }
  19586. virtual void reset()
  19587. {
  19588. roxiemem::ReleaseRoxieRowRange(readrows.getArray(), readIndex, readrows.ordinality());
  19589. readrows.kill();
  19590. readAheadDone = false;
  19591. readIndex = 0;
  19592. lastGroupProcessed = processed;
  19593. someInGroup = false;
  19594. CRoxieServerDiskReadBaseActivity::reset();
  19595. }
  19596. virtual const void *nextRow()
  19597. {
  19598. ActivityTimer t(totalCycles, timeActivities);
  19599. if (eof)
  19600. return NULL;
  19601. else if (useRemote())
  19602. return remote->nextRow();
  19603. else if (maySkip)
  19604. {
  19605. if (!readAheadDone)
  19606. {
  19607. unsigned preprocessed = 0;
  19608. while (!eof)
  19609. {
  19610. const void *row = _nextRow();
  19611. if (row)
  19612. preprocessed++;
  19613. if (preprocessed > rowLimit)
  19614. {
  19615. ReleaseRoxieRow(row);
  19616. roxiemem::ReleaseRoxieRowRange(readrows.getArray(), readIndex, readrows.ordinality());
  19617. readrows.kill();
  19618. readIndex = 0;
  19619. eof = true;
  19620. if (ctx->queryDebugContext())
  19621. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  19622. if (helper.getFlags() & TDRlimitskips)
  19623. return NULL;
  19624. else if (helper.getFlags() & TDRlimitcreates)
  19625. return createLimitFailRow(false);
  19626. else
  19627. throwUnexpected();
  19628. }
  19629. if (preprocessed > stopAfter) // MORE - bit of a strange place to check
  19630. {
  19631. eof = true;
  19632. ReleaseRoxieRow(row);
  19633. break;
  19634. }
  19635. readrows.append(row);
  19636. }
  19637. readAheadDone = true;
  19638. }
  19639. if (readrows.isItem(readIndex))
  19640. {
  19641. const void *ret = readrows.item(readIndex++);
  19642. if (ret)
  19643. processed++;
  19644. return ret;
  19645. }
  19646. else
  19647. {
  19648. eof = true;
  19649. return NULL;
  19650. }
  19651. }
  19652. else
  19653. {
  19654. const void *ret = _nextRow();
  19655. if (ret)
  19656. {
  19657. processed++;
  19658. if (processed > rowLimit)
  19659. {
  19660. if (traceLevel > 4)
  19661. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  19662. ReleaseRoxieRow(ret);
  19663. compoundHelper->onLimitExceeded();
  19664. throwUnexpected(); // onLimitExceeded is not supposed to return
  19665. }
  19666. if (processed > stopAfter) // MORE - bit of a strange place to check
  19667. {
  19668. eof = true;
  19669. ReleaseRoxieRow(ret);
  19670. return NULL;
  19671. }
  19672. }
  19673. return ret;
  19674. }
  19675. }
  19676. const void *_nextRow()
  19677. {
  19678. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  19679. unsigned transformedSize = 0;
  19680. for (;;)
  19681. {
  19682. const byte *nextRec = reader->nextRow();
  19683. if (nextRec)
  19684. {
  19685. someInGroup = true;
  19686. transformedSize = readHelper->transform(rowBuilder, nextRec);
  19687. reader->finishedRow();
  19688. if (transformedSize)
  19689. break;
  19690. }
  19691. else if (isGrouped)
  19692. {
  19693. if (lastGroupProcessed != processed)
  19694. {
  19695. someInGroup = false;
  19696. lastGroupProcessed = processed;
  19697. return nullptr;
  19698. }
  19699. else if (!someInGroup)
  19700. {
  19701. eof = true;
  19702. return nullptr;
  19703. }
  19704. }
  19705. else
  19706. {
  19707. eof = true;
  19708. return nullptr;
  19709. }
  19710. }
  19711. return rowBuilder.finalizeRowClear(transformedSize);
  19712. }
  19713. };
  19714. class CRoxieServerXmlReadActivity : public CRoxieServerDiskReadBaseActivity, implements IXMLSelect, implements IThorDiskCallback
  19715. {
  19716. IHThorXmlReadArg * readHelper;
  19717. Owned<IXmlToRowTransformer> rowTransformer;
  19718. Owned<IXMLParse> xmlParser;
  19719. Owned<IColumnProvider> lastMatch;
  19720. unsigned __int64 fileoffset;
  19721. IDirectStreamReader *streamReader = nullptr;
  19722. public:
  19723. IMPLEMENT_IINTERFACE_USING(CRoxieServerDiskReadBaseActivity)
  19724. CRoxieServerXmlReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  19725. unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager, ITranslatorSet *_translators)
  19726. : CRoxieServerDiskReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, _maySkip, _manager, _translators)
  19727. {
  19728. compoundHelper = NULL;
  19729. readHelper = (IHThorXmlReadArg *)&helper;
  19730. fileoffset = 0;
  19731. }
  19732. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19733. {
  19734. rowLimit = readHelper->getRowLimit();
  19735. stopAfter = readHelper->getChooseNLimit();
  19736. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  19737. if (!useRemote())
  19738. {
  19739. rowTransformer.set(readHelper->queryTransformer());
  19740. assertex(reader != NULL);
  19741. streamReader = reader->queryDirectStreamReader();
  19742. assertex(streamReader != NULL);
  19743. OwnedRoxieString xmlIterator(readHelper->getXmlIteratorPath());
  19744. if (factory->getKind()==TAKjsonread)
  19745. xmlParser.setown(createJSONParse(*streamReader, xmlIterator, *this, (0 != (TDRxmlnoroot & readHelper->getFlags()))?ptr_noRoot:ptr_none, (readHelper->getFlags() & TDRusexmlcontents) != 0));
  19746. else
  19747. xmlParser.setown(createXMLParse(*streamReader, xmlIterator, *this, (0 != (TDRxmlnoroot & readHelper->getFlags()))?ptr_noRoot:ptr_none, (readHelper->getFlags() & TDRusexmlcontents) != 0));
  19748. }
  19749. }
  19750. virtual void reset()
  19751. {
  19752. CRoxieServerDiskReadBaseActivity::reset();
  19753. rowTransformer.clear();
  19754. xmlParser.clear();
  19755. }
  19756. virtual void match(IColumnProvider &entry, offset_t startOffset, offset_t endOffset)
  19757. {
  19758. fileoffset = startOffset;
  19759. lastMatch.set(&entry);
  19760. }
  19761. //interface IThorDiskCallback
  19762. virtual unsigned __int64 getFilePosition(const void * row)
  19763. {
  19764. return fileoffset;
  19765. }
  19766. virtual unsigned __int64 getLocalFilePosition(const void * row)
  19767. {
  19768. return streamReader->makeFilePositionLocal(fileoffset);
  19769. }
  19770. virtual const char * queryLogicalFilename(const void * row)
  19771. {
  19772. return reader->queryLogicalFilename(row);
  19773. }
  19774. virtual const void *nextRow()
  19775. {
  19776. ActivityTimer t(totalCycles, timeActivities);
  19777. if (eof)
  19778. return NULL;
  19779. else if (useRemote())
  19780. return remote->nextRow();
  19781. assertex(xmlParser != NULL);
  19782. try
  19783. {
  19784. while (!eof)
  19785. {
  19786. //call to next() will callback on the IXmlSelect interface
  19787. bool gotNext = false;
  19788. gotNext = xmlParser->next();
  19789. if(!gotNext)
  19790. eof = true;
  19791. else if (lastMatch)
  19792. {
  19793. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  19794. unsigned sizeGot = rowTransformer->transform(rowBuilder, lastMatch, this);
  19795. lastMatch.clear();
  19796. fileoffset = 0;
  19797. if (sizeGot)
  19798. {
  19799. OwnedConstRoxieRow ret = rowBuilder.finalizeRowClear(sizeGot);
  19800. if (processed > rowLimit)
  19801. {
  19802. if (traceLevel > 4)
  19803. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  19804. readHelper->onLimitExceeded();
  19805. throwUnexpected(); // onLimitExceeded is not supposed to return
  19806. }
  19807. processed++;
  19808. if (processed > stopAfter) // MORE - bit of a strange place to check
  19809. {
  19810. eof = true;
  19811. return NULL;
  19812. }
  19813. return ret.getClear();
  19814. }
  19815. }
  19816. }
  19817. return NULL;
  19818. }
  19819. catch(IException *E)
  19820. {
  19821. throw makeWrappedException(E);
  19822. }
  19823. }
  19824. };
  19825. class CRoxieServerCsvReadActivity : public CRoxieServerDiskReadBaseActivity
  19826. {
  19827. IHThorCsvReadArg *readHelper;
  19828. ICsvParameters * csvInfo;
  19829. unsigned headerLines;
  19830. unsigned maxDiskSize;
  19831. CSVSplitter csvSplitter;
  19832. unsigned __int64 localOffset;
  19833. IDirectStreamReader *streamReader = nullptr;
  19834. const char *quotes;
  19835. const char *separators;
  19836. const char *terminators;
  19837. const char *escapes;
  19838. size32_t maxRowSize;
  19839. public:
  19840. CRoxieServerCsvReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  19841. unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager, ITranslatorSet *_translators,
  19842. const char *_quotes, const char *_separators, const char *_terminators, const char *_escapes, size32_t _maxRowSize)
  19843. : CRoxieServerDiskReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, _maySkip, _manager, _translators),
  19844. quotes(_quotes), separators(_separators), terminators(_terminators), escapes(_escapes), maxRowSize(_maxRowSize)
  19845. {
  19846. compoundHelper = NULL;
  19847. readHelper = (IHThorCsvReadArg *)&helper;
  19848. rowLimit = readHelper->getRowLimit();
  19849. stopAfter = readHelper->getChooseNLimit();
  19850. csvInfo = readHelper->queryCsvParameters();
  19851. maxDiskSize = csvInfo->queryMaxSize();
  19852. localOffset = 0;
  19853. headerLines = 0;
  19854. }
  19855. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19856. {
  19857. rowLimit = readHelper->getRowLimit();
  19858. stopAfter = readHelper->getChooseNLimit();
  19859. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  19860. if (!useRemote())
  19861. {
  19862. if (!eof)
  19863. {
  19864. assertex(reader != nullptr);
  19865. streamReader = reader->queryDirectStreamReader();
  19866. assertex(streamReader != nullptr);
  19867. headerLines = csvInfo->queryHeaderLen();
  19868. if (headerLines && isLocal && streamReader->queryFilePart() != 1)
  19869. 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...
  19870. if (varFileInfo)
  19871. {
  19872. const IPropertyTree *options = varFileInfo->queryProperties();
  19873. if (options)
  19874. {
  19875. quotes = options->queryProp("@csvQuote");
  19876. separators = options->queryProp("@csvSeparate");
  19877. terminators = options->queryProp("@csvTerminate");
  19878. escapes = options->queryProp("@csvEscape");
  19879. }
  19880. }
  19881. csvSplitter.init(readHelper->getMaxColumns(), csvInfo, quotes, separators, terminators, escapes);
  19882. }
  19883. }
  19884. }
  19885. virtual const void *nextRow()
  19886. {
  19887. ActivityTimer t(totalCycles, timeActivities);
  19888. if (eof)
  19889. return NULL;
  19890. else if (useRemote())
  19891. return remote->nextRow();
  19892. try
  19893. {
  19894. while (!eof)
  19895. {
  19896. size32_t thisLineLength = csvSplitter.splitLine(streamReader, maxRowSize);
  19897. if (!thisLineLength)
  19898. break;
  19899. if (headerLines)
  19900. {
  19901. headerLines--;
  19902. streamReader->skip(thisLineLength);
  19903. }
  19904. else
  19905. {
  19906. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  19907. unsigned transformedSize = readHelper->transform(rowBuilder, csvSplitter.queryLengths(), (const char * *)csvSplitter.queryData());
  19908. streamReader->skip(thisLineLength);
  19909. if (transformedSize)
  19910. {
  19911. OwnedConstRoxieRow ret = rowBuilder.finalizeRowClear(transformedSize);
  19912. if (processed > rowLimit)
  19913. {
  19914. readHelper->onLimitExceeded();
  19915. throwUnexpected(); // onLimitExceeded is not supposed to return
  19916. }
  19917. processed++;
  19918. if (processed > stopAfter) // MORE - bit of a strange place to check
  19919. {
  19920. eof = true;
  19921. return NULL;
  19922. }
  19923. return ret.getClear();
  19924. }
  19925. }
  19926. }
  19927. return NULL;
  19928. }
  19929. catch(IException *E)
  19930. {
  19931. throw makeWrappedException(E);
  19932. }
  19933. }
  19934. virtual void reset()
  19935. {
  19936. CRoxieServerDiskReadBaseActivity::reset();
  19937. csvSplitter.reset();
  19938. localOffset = 0;
  19939. }
  19940. virtual unsigned __int64 getFilePosition(const void * row)
  19941. {
  19942. UNIMPLEMENTED; // we know offset in the reader but not sure it helps us much
  19943. }
  19944. virtual unsigned __int64 getLocalFilePosition(const void * row)
  19945. {
  19946. UNIMPLEMENTED;
  19947. }
  19948. };
  19949. class CRoxieServerDiskNormalizeActivity : public CRoxieServerDiskReadBaseActivity
  19950. {
  19951. IHThorDiskNormalizeArg *normalizeHelper;
  19952. bool firstPending;
  19953. public:
  19954. CRoxieServerDiskNormalizeActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, IInMemoryIndexManager *_manager, ITranslatorSet *_translators)
  19955. : CRoxieServerDiskReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, false, _manager, _translators)
  19956. {
  19957. compoundHelper = (IHThorDiskNormalizeArg *)&helper;
  19958. normalizeHelper = (IHThorDiskNormalizeArg *)&helper;
  19959. limitTransformExtra = normalizeHelper;
  19960. firstPending = true;
  19961. }
  19962. virtual void reset()
  19963. {
  19964. firstPending = true;
  19965. CRoxieServerDiskReadBaseActivity::reset();
  19966. }
  19967. virtual const void *nextRow()
  19968. {
  19969. ActivityTimer t(totalCycles, timeActivities);
  19970. if (eof)
  19971. return NULL;
  19972. else if (useRemote())
  19973. return remote->nextRow();
  19974. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  19975. unsigned transformedSize = 0;
  19976. for (;;)
  19977. {
  19978. while (firstPending)
  19979. {
  19980. const byte *nextRec = reader->nextRow();
  19981. if (!nextRec)
  19982. {
  19983. eof = true;
  19984. return NULL;
  19985. }
  19986. if (normalizeHelper->first(nextRec))
  19987. firstPending = false;
  19988. reader->finishedRow();
  19989. }
  19990. transformedSize = normalizeHelper->transform(rowBuilder);
  19991. firstPending = !normalizeHelper->next();
  19992. if (transformedSize)
  19993. break;
  19994. }
  19995. OwnedConstRoxieRow recBuffer = rowBuilder.finalizeRowClear(transformedSize);
  19996. processed++;
  19997. if (processed > rowLimit)
  19998. {
  19999. compoundHelper->onLimitExceeded();
  20000. throwUnexpected(); // onLimitExceeded is not supposed to return
  20001. }
  20002. if (processed > stopAfter) // MORE - bit of a strange place to check
  20003. {
  20004. eof = true;
  20005. return NULL;
  20006. }
  20007. return recBuffer.getClear();
  20008. }
  20009. };
  20010. class CRoxieServerDiskAggregateBaseActivity : public CRoxieServerDiskReadBaseActivity
  20011. {
  20012. protected:
  20013. bool done;
  20014. public:
  20015. CRoxieServerDiskAggregateBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager, ITranslatorSet *_translators)
  20016. : CRoxieServerDiskReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, false, false, _manager, _translators),
  20017. done(false)
  20018. {
  20019. }
  20020. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20021. {
  20022. done = false;
  20023. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  20024. }
  20025. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  20026. {
  20027. if (idx==(unsigned)-1)
  20028. idx = 0;
  20029. return idx ? NULL: this;
  20030. }
  20031. };
  20032. class CRoxieServerDiskCountActivity : public CRoxieServerDiskAggregateBaseActivity
  20033. {
  20034. IHThorDiskCountArg & countHelper;
  20035. unsigned __int64 choosenLimit;
  20036. unsigned __int64 getSkippedCount()
  20037. {
  20038. unsigned flags = countHelper.getFlags();
  20039. if (flags & TDRlimitskips)
  20040. return 0;
  20041. else if (flags & TDRlimitcreates)
  20042. return 1;
  20043. else
  20044. {
  20045. countHelper.onLimitExceeded();
  20046. throwUnexpected(); // onLimitExceeded should always throw exception
  20047. }
  20048. }
  20049. public:
  20050. CRoxieServerDiskCountActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager, ITranslatorSet *_translators)
  20051. : CRoxieServerDiskAggregateBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _manager, _translators),
  20052. countHelper((IHThorDiskCountArg &)basehelper)
  20053. {
  20054. choosenLimit = 0;
  20055. }
  20056. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20057. {
  20058. choosenLimit = countHelper.getChooseNLimit();
  20059. rowLimit = countHelper.getRowLimit();
  20060. // keyedLimit = countHelper->getKeyedLimit(); // more - should there be one?
  20061. CRoxieServerDiskAggregateBaseActivity::start(parentExtractSize, parentExtract, paused);
  20062. }
  20063. virtual const void *nextRow()
  20064. {
  20065. ActivityTimer t(totalCycles, timeActivities);
  20066. if (done) return NULL;
  20067. done = true;
  20068. unsigned __int64 totalCount = 0;
  20069. if (helper.canMatchAny() && !eof)
  20070. {
  20071. if (useRemote())
  20072. {
  20073. for (;;)
  20074. {
  20075. const void * next = remote->nextRow();
  20076. if (!next)
  20077. break;
  20078. if (meta.getFixedSize() == 1)
  20079. totalCount += *(byte *)next;
  20080. else
  20081. totalCount += *(unsigned __int64 *)next;
  20082. ReleaseRoxieRow(next);
  20083. if (totalCount > rowLimit)
  20084. {
  20085. totalCount = getSkippedCount();
  20086. break;
  20087. }
  20088. else if (totalCount >= choosenLimit)
  20089. {
  20090. totalCount = choosenLimit;
  20091. break;
  20092. }
  20093. }
  20094. }
  20095. else
  20096. {
  20097. for (;;)
  20098. {
  20099. const byte *nextRec = reader->nextRow();
  20100. if (!nextRec)
  20101. break;
  20102. totalCount += countHelper.numValid(nextRec);
  20103. reader->finishedRow();
  20104. if (totalCount > rowLimit)
  20105. {
  20106. totalCount = getSkippedCount();
  20107. break;
  20108. }
  20109. else if (totalCount >= choosenLimit)
  20110. {
  20111. totalCount = choosenLimit;
  20112. break;
  20113. }
  20114. }
  20115. }
  20116. }
  20117. size32_t rowSize = meta.getFixedSize();
  20118. void * result = rowAllocator->createRow();
  20119. if (rowSize == 1)
  20120. *(byte *)result = (byte)totalCount;
  20121. else
  20122. {
  20123. assertex(rowSize == sizeof(unsigned __int64));
  20124. *(unsigned __int64 *)result = totalCount;
  20125. }
  20126. return rowAllocator->finalizeRow(rowSize, result, rowSize);
  20127. }
  20128. };
  20129. class CRoxieServerDiskAggregateActivity : public CRoxieServerDiskAggregateBaseActivity
  20130. {
  20131. IHThorCompoundAggregateExtra & aggregateHelper;
  20132. public:
  20133. CRoxieServerDiskAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  20134. unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager, ITranslatorSet *_translators)
  20135. : CRoxieServerDiskAggregateBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _manager, _translators),
  20136. aggregateHelper((IHThorDiskAggregateArg &)basehelper)
  20137. {
  20138. }
  20139. const void * gatherMerged()
  20140. {
  20141. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  20142. size32_t finalSize = 0;
  20143. if (useRemote())
  20144. {
  20145. const void * firstRow = remote->nextRow();
  20146. if (!firstRow)
  20147. {
  20148. rowBuilder.ensureRow();
  20149. finalSize = aggregateHelper.clearAggregate(rowBuilder);
  20150. }
  20151. else
  20152. {
  20153. // NOTE need to clone this because going to modify below, could special case 1 row only
  20154. finalSize = cloneRow(rowBuilder, firstRow, meta);
  20155. ReleaseRoxieRow(firstRow);
  20156. }
  20157. for (;;)
  20158. {
  20159. const void * next = remote->nextRow();
  20160. if (!next)
  20161. break;
  20162. finalSize = aggregateHelper.mergeAggregate(rowBuilder, next);
  20163. ReleaseRoxieRow(next);
  20164. }
  20165. }
  20166. else
  20167. {
  20168. aggregateHelper.clearAggregate(rowBuilder);
  20169. if (helper.canMatchAny() && !eof)
  20170. {
  20171. for (;;)
  20172. {
  20173. const byte *nextRec = reader->nextRow();
  20174. if (!nextRec)
  20175. break;
  20176. aggregateHelper.processRow(rowBuilder, nextRec);
  20177. reader->finishedRow();
  20178. }
  20179. }
  20180. finalSize = meta.getRecordSize(rowBuilder.getSelf());
  20181. }
  20182. return rowBuilder.finalizeRowClear(finalSize);
  20183. }
  20184. virtual const void *nextRow()
  20185. {
  20186. ActivityTimer t(totalCycles, timeActivities);
  20187. if (done) return NULL;
  20188. const void * ret = gatherMerged();
  20189. done = true;
  20190. return ret;
  20191. }
  20192. };
  20193. class CRoxieServerDiskGroupAggregateActivity : public CRoxieServerDiskAggregateBaseActivity
  20194. {
  20195. IHThorDiskGroupAggregateArg & aggregateHelper;
  20196. RowAggregator resultAggregator;
  20197. bool gathered;
  20198. public:
  20199. CRoxieServerDiskGroupAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager, ITranslatorSet *_translators)
  20200. : CRoxieServerDiskAggregateBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _manager, _translators),
  20201. aggregateHelper((IHThorDiskGroupAggregateArg &)basehelper),
  20202. resultAggregator(aggregateHelper, aggregateHelper),
  20203. gathered(false)
  20204. {
  20205. }
  20206. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20207. {
  20208. gathered= false;
  20209. CRoxieServerDiskAggregateBaseActivity::start(parentExtractSize, parentExtract, paused);
  20210. resultAggregator.start(rowAllocator, ctx->queryCodeContext(), activityId);
  20211. }
  20212. virtual void reset()
  20213. {
  20214. resultAggregator.reset();
  20215. CRoxieServerDiskAggregateBaseActivity::reset();
  20216. }
  20217. void gatherMerged()
  20218. {
  20219. if (useRemote())
  20220. {
  20221. for (;;)
  20222. {
  20223. const void * next = remote->nextRow();
  20224. if (!next)
  20225. break;
  20226. resultAggregator.mergeElement(next);
  20227. ReleaseRoxieRow(next);
  20228. }
  20229. }
  20230. else
  20231. {
  20232. if (helper.canMatchAny() && !eof)
  20233. {
  20234. Owned<IInMemoryFileProcessor> processor = createGroupAggregateRecordProcessor(resultAggregator, aggregateHelper, reader);
  20235. processor->doQuery(NULL, 0, 0, 0);
  20236. }
  20237. }
  20238. gathered = true;
  20239. }
  20240. virtual const void *nextRow()
  20241. {
  20242. ActivityTimer t(totalCycles, timeActivities);
  20243. if (done)
  20244. return NULL;
  20245. if (!gathered)
  20246. gatherMerged();
  20247. Owned<AggregateRowBuilder> next = resultAggregator.nextResult();
  20248. if (next)
  20249. {
  20250. processed++;
  20251. return next->finalizeRowClear();
  20252. }
  20253. done = true;
  20254. return NULL;
  20255. }
  20256. };
  20257. class CRoxieServerDiskReadActivityFactory : public CRoxieServerActivityFactory
  20258. {
  20259. public:
  20260. RemoteActivityId remoteId;
  20261. bool isLocal;
  20262. bool sorted;
  20263. bool maySkip;
  20264. bool variableFileName;
  20265. Owned<ITranslatorSet> translators;
  20266. Owned<IInMemoryIndexManager> manager;
  20267. Owned<const IResolvedFile> datafile;
  20268. const char *quotes;
  20269. const char *separators;
  20270. const char *terminators;
  20271. const char *escapes;
  20272. size32_t maxCsvRowSize;
  20273. CRoxieServerDiskReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  20274. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), remoteId(_remoteId)
  20275. {
  20276. isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  20277. Owned<IHThorDiskReadBaseArg> helper = (IHThorDiskReadBaseArg *) helperFactory();
  20278. sorted = (helper->getFlags() & TDRunsorted) == 0;
  20279. variableFileName = allFilesDynamic || _queryFactory.isDynamic() || ((helper->getFlags() & (TDXvarfilename|TDXdynamicfilename)) != 0);
  20280. maySkip = (helper->getFlags() & (TDRkeyedlimitskips|TDRkeyedlimitcreates|TDRlimitskips|TDRlimitcreates)) != 0;
  20281. quotes = separators = terminators = escapes = NULL;
  20282. if (!variableFileName)
  20283. {
  20284. bool isOpt = (helper->getFlags() & TDRoptional) != 0;
  20285. OwnedRoxieString fileName(helper->getFileName());
  20286. datafile.setown(_queryFactory.queryPackage().lookupFileName(fileName, isOpt, true, true, _queryFactory.queryWorkUnit(), true));
  20287. bool isSimple = (datafile && datafile->getNumParts()==1 && !_queryFactory.queryOptions().disableLocalOptimizations);
  20288. if (isLocal || isSimple)
  20289. {
  20290. if (datafile)
  20291. {
  20292. unsigned channel = isLocal ? queryFactory.queryChannel() : 0;
  20293. unsigned projectFormatCrc = helper->getProjectedFormatCrc();
  20294. translators.setown(datafile->getTranslators(projectFormatCrc, skipFileFormatCrcCheck(), helper->queryProjectedDiskRecordSize(), helper->queryDiskRecordSize(), getEnableFieldTranslation(), false));
  20295. manager.setown(datafile->getIndexManager(isOpt, channel, translators->queryActualLayout(0), _graphNode.getPropBool("att[@name=\"preload\"]/@value", false)));
  20296. const IPropertyTree *options = datafile->queryProperties();
  20297. if (options)
  20298. {
  20299. quotes = options->queryProp("@csvQuote");
  20300. separators = options->queryProp("@csvSeparate");
  20301. terminators = options->queryProp("@csvTerminate");
  20302. escapes = options->queryProp("@csvEscape");
  20303. }
  20304. }
  20305. else
  20306. manager.setown(createInMemoryIndexManager(helper->queryProjectedDiskRecordSize()->queryRecordAccessor(true), true, nullptr));
  20307. }
  20308. }
  20309. switch (kind)
  20310. {
  20311. case TAKcsvread:
  20312. {
  20313. maxCsvRowSize = defaultMaxCsvRowSize * 1024 * 1024;
  20314. IConstWorkUnit *workunit = _queryFactory.queryWorkUnit();
  20315. if (workunit)
  20316. maxCsvRowSize = workunit->getDebugValueInt(OPT_MAXCSVROWSIZE, defaultMaxCsvRowSize) * 1024 * 1024;
  20317. break;
  20318. }
  20319. default:
  20320. maxCsvRowSize = 0; // unused
  20321. }
  20322. }
  20323. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  20324. {
  20325. unsigned numParts = datafile ? datafile->getNumParts() : 0;
  20326. switch (kind)
  20327. {
  20328. case TAKcsvread:
  20329. return new CRoxieServerCsvReadActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, sorted, maySkip, manager, translators,
  20330. quotes, separators, terminators, escapes, maxCsvRowSize);
  20331. case TAKxmlread:
  20332. case TAKjsonread:
  20333. return new CRoxieServerXmlReadActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, sorted, maySkip, manager, translators);
  20334. case TAKdiskread:
  20335. case TAKspillread:
  20336. return new CRoxieServerDiskReadActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, sorted, maySkip, manager, translators);
  20337. case TAKdisknormalize:
  20338. return new CRoxieServerDiskNormalizeActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, sorted, manager, translators);
  20339. case TAKdiskcount:
  20340. return new CRoxieServerDiskCountActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, manager, translators);
  20341. case TAKdiskaggregate:
  20342. return new CRoxieServerDiskAggregateActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, manager, translators);
  20343. case TAKdiskgroupaggregate:
  20344. return new CRoxieServerDiskGroupAggregateActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, manager, translators);
  20345. }
  20346. throwUnexpected();
  20347. }
  20348. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  20349. {
  20350. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  20351. }
  20352. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  20353. {
  20354. if (datafile)
  20355. addXrefFileInfo(reply, datafile);
  20356. else
  20357. {
  20358. // Temporarily resolve the file
  20359. Owned<IHThorDiskReadBaseArg> helper = (IHThorDiskReadBaseArg *) helperFactory();
  20360. if ((helper->getFlags() & (TDXvarfilename|TDXdynamicfilename)) == 0)
  20361. {
  20362. OwnedRoxieString fileName(helper->getFileName());
  20363. Owned<const IResolvedFile> temp = queryFactory.queryPackage().lookupFileName(fileName, true, true, false, queryFactory.queryWorkUnit(), true);
  20364. if (temp)
  20365. addXrefFileInfo(reply, temp);
  20366. }
  20367. }
  20368. }
  20369. virtual const StatisticsMapping &queryStatsMapping() const
  20370. {
  20371. return diskStatistics;
  20372. }
  20373. };
  20374. IRoxieServerActivityFactory *createRoxieServerDiskReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  20375. {
  20376. return new CRoxieServerDiskReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  20377. }
  20378. //=================================================================================
  20379. class CRoxieServerBaseIndexActivityFactory : public CRoxieServerActivityFactory
  20380. {
  20381. public:
  20382. Owned<IKeyArray> keySet;
  20383. Owned<ITranslatorSet> translators;
  20384. RemoteActivityId remoteId;
  20385. bool isSimple;
  20386. bool isLocal;
  20387. bool maySkip;
  20388. bool sorted;
  20389. bool variableFileName;
  20390. unsigned maxSeekLookahead;
  20391. Owned<const IResolvedFile> indexfile;
  20392. CRoxieServerSideCache *cache;
  20393. CRoxieServerBaseIndexActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  20394. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), remoteId(_remoteId)
  20395. {
  20396. Owned<IHThorIndexReadBaseArg> indexHelper = (IHThorIndexReadBaseArg *) helperFactory();
  20397. unsigned flags = indexHelper->getFlags();
  20398. sorted = (flags & TIRunordered) == 0;
  20399. isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  20400. variableFileName = allFilesDynamic || _queryFactory.isDynamic() || ((flags & (TIRvarfilename|TIRdynamicfilename)) != 0);
  20401. if (!variableFileName)
  20402. {
  20403. bool isOpt = (flags & TIRoptional) != 0;
  20404. OwnedRoxieString indexName(indexHelper->getFileName());
  20405. indexfile.setown(queryFactory.queryPackage().lookupFileName(indexName, isOpt, true, true, queryFactory.queryWorkUnit(), true));
  20406. if (indexfile)
  20407. {
  20408. unsigned formatCrc = indexHelper->getFormatCrc();
  20409. IOutputMetaData *projectedMeta = indexHelper->queryProjectedDiskRecordSize();
  20410. IOutputMetaData *expectedMeta = indexHelper->queryDiskRecordSize();
  20411. translators.setown(indexfile->getTranslators(formatCrc, skipFileFormatCrcCheck(), projectedMeta, expectedMeta, getEnableFieldTranslation(), true));
  20412. keySet.setown(indexfile->getKeyArray(isOpt, isLocal ? queryFactory.queryChannel() : 0));
  20413. }
  20414. }
  20415. isSimple = isLocal;
  20416. maySkip = (flags & (TIRkeyedlimitskips|TIRlimitskips|TIRlimitcreates|TIRkeyedlimitcreates)) != 0;
  20417. if (keySet && keySet->length()==1 && !isLocal && (flags & (TIRlimitskips|TIRlimitcreates|TIRkeyedlimitskips|TIRkeyedlimitcreates))==0)
  20418. {
  20419. IKeyIndexBase *thisBase = keySet->queryKeyPart(0);
  20420. if (thisBase->numParts()==1 && !thisBase->queryPart(0)->isTopLevelKey() && !_queryFactory.queryOptions().disableLocalOptimizations)
  20421. isSimple = true;
  20422. }
  20423. int cacheSize = _graphNode.getPropInt("hint[@name='cachehits']/@value", serverSideCacheSize);
  20424. cache = cacheSize ? new CRoxieServerSideCache(cacheSize) : NULL;
  20425. maxSeekLookahead = _graphNode.getPropInt("hint[@name='maxseeklookahead']/@value", 0);
  20426. }
  20427. ~CRoxieServerBaseIndexActivityFactory()
  20428. {
  20429. delete cache;
  20430. }
  20431. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  20432. {
  20433. if (indexfile)
  20434. addXrefFileInfo(reply, indexfile);
  20435. else
  20436. {
  20437. Owned<IHThorIndexReadBaseArg> indexHelper = (IHThorIndexReadBaseArg *) helperFactory();
  20438. if ((indexHelper->getFlags() & (TIRvarfilename|TIRdynamicfilename)) == 0)
  20439. {
  20440. OwnedRoxieString indexName(indexHelper->getFileName());
  20441. Owned<const IResolvedFile> temp = queryFactory.queryPackage().lookupFileName(indexName, true, true, false, queryFactory.queryWorkUnit(), true);
  20442. if (temp)
  20443. addXrefFileInfo(reply, temp);
  20444. }
  20445. }
  20446. }
  20447. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  20448. {
  20449. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for indexread activity");
  20450. }
  20451. virtual IRoxieServerSideCache *queryServerSideCache() const
  20452. {
  20453. return cache;
  20454. }
  20455. virtual const StatisticsMapping &queryStatsMapping() const
  20456. {
  20457. return indexStatistics;
  20458. }
  20459. };
  20460. class CRoxieServerIndexActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler
  20461. {
  20462. protected:
  20463. IHThorIndexReadBaseArg &indexHelper;
  20464. IHThorSteppedSourceExtra *steppedExtra;
  20465. Linked<IKeyArray> keySet;
  20466. Linked<ITranslatorSet> translators;
  20467. CSkippableRemoteResultAdaptor remote;
  20468. CIndexTransformCallback callback;
  20469. bool sorted;
  20470. bool variableFileName;
  20471. bool variableInfoPending;
  20472. bool isOpt;
  20473. bool isLocal;
  20474. unsigned __int64 rowLimit;
  20475. unsigned __int64 keyedLimit;
  20476. unsigned __int64 choosenLimit;
  20477. unsigned accepted;
  20478. unsigned rejected;
  20479. unsigned seekGEOffset;
  20480. Owned<IKeyManager> tlk;
  20481. Owned<const IResolvedFile> varFileInfo;
  20482. const RemoteActivityId &remoteId;
  20483. void setVariableFileInfo()
  20484. {
  20485. OwnedRoxieString indexName(indexHelper.getFileName());
  20486. varFileInfo.setown(resolveLFNIndex(indexName, isOpt));
  20487. if (varFileInfo)
  20488. {
  20489. unsigned formatCrc = indexHelper.getFormatCrc();
  20490. IOutputMetaData *projectedMeta = indexHelper.queryProjectedDiskRecordSize();
  20491. IOutputMetaData *expectedMeta = indexHelper.queryDiskRecordSize();
  20492. translators.setown(varFileInfo->getTranslators(formatCrc, skipFileFormatCrcCheck(), projectedMeta, expectedMeta, getEnableFieldTranslation(), true));
  20493. keySet.setown(varFileInfo->getKeyArray(isOpt, isLocal ? factory->queryQueryFactory().queryChannel() : 0));
  20494. }
  20495. variableInfoPending = false;
  20496. }
  20497. public:
  20498. CRoxieServerIndexActivity(IRoxieSlaveContext *_ctx, const CRoxieServerBaseIndexActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  20499. bool _sorted, bool _isLocal, bool _maySkip)
  20500. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  20501. keySet(_factory->keySet),
  20502. translators(_factory->translators),
  20503. indexHelper((IHThorIndexReadBaseArg &)basehelper),
  20504. remote(_ctx, this, _remoteId, meta.queryOriginal(), indexHelper, *this, _sorted, false, _maySkip),
  20505. remoteId(_remoteId),
  20506. sorted(_sorted),
  20507. isLocal(_isLocal)
  20508. {
  20509. indexHelper.setCallback(&callback);
  20510. steppedExtra = indexHelper.querySteppingExtra();
  20511. variableFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((indexHelper.getFlags() & (TIRvarfilename|TIRdynamicfilename)) != 0);
  20512. variableInfoPending = false;
  20513. isOpt = (indexHelper.getFlags() & TIRoptional) != 0;
  20514. seekGEOffset = 0;
  20515. // started = false;
  20516. rejected = accepted = 0;
  20517. rowLimit = choosenLimit = keyedLimit = 0;
  20518. }
  20519. virtual const IResolvedFile *queryVarFileInfo() const
  20520. {
  20521. return varFileInfo;
  20522. }
  20523. virtual void onCreate(IHThorArg *_colocalParent)
  20524. {
  20525. CRoxieServerActivity::onCreate(_colocalParent);
  20526. remote.onCreate(_colocalParent);
  20527. }
  20528. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20529. {
  20530. accepted = 0;
  20531. rejected = 0;
  20532. rowLimit = (unsigned __int64) -1;
  20533. keyedLimit = (unsigned __int64 ) -1;
  20534. choosenLimit = I64C(0x7fffffffffffffff);
  20535. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  20536. remote.onStart(parentExtractSize, parentExtract);
  20537. variableInfoPending = variableFileName;
  20538. }
  20539. void processAllKeys()
  20540. {
  20541. try
  20542. {
  20543. if (indexHelper.canMatchAny())
  20544. {
  20545. if (variableInfoPending)
  20546. setVariableFileInfo();
  20547. remote.setLimits(rowLimit, keyedLimit, choosenLimit);
  20548. if (keySet)
  20549. {
  20550. // MORE - this recreates the segmonitors per part but not per fileno (which is a little backwards).
  20551. // 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
  20552. // However order is probably better to iterate fileno's inside partnos
  20553. // MORE - also not properly supporting STEPPED I fear.
  20554. // A superkey that mixes single and multipart or tlk and roroot keys might be hard
  20555. for (unsigned partNo = 0; partNo < keySet->length(); partNo++)
  20556. {
  20557. IKeyIndexBase *thisBase = keySet->queryKeyPart(partNo);
  20558. if (thisBase)
  20559. {
  20560. unsigned fileNo = 0;
  20561. IKeyIndex *thisKey = thisBase->queryPart(fileNo);
  20562. if (!thisKey->isTopLevelKey())
  20563. {
  20564. if (keyedLimit != (unsigned __int64) -1)
  20565. {
  20566. if ((indexHelper.getFlags() & TIRcountkeyedlimit) != 0)
  20567. {
  20568. Owned<IKeyManager> countKey;
  20569. countKey.setown(createLocalKeyManager(indexHelper.queryDiskRecordSize()->queryRecordAccessor(true), thisKey, this, indexHelper.hasNewSegmentMonitors()));
  20570. countKey->setLayoutTranslator(translators->queryTranslator(fileNo));
  20571. createSegmentMonitors(countKey);
  20572. unsigned __int64 count = countKey->checkCount(keyedLimit);
  20573. if (count > keyedLimit)
  20574. {
  20575. if (traceLevel > 4)
  20576. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  20577. onLimitExceeded(true);
  20578. }
  20579. }
  20580. }
  20581. }
  20582. if (seekGEOffset && !thisKey->isTopLevelKey())
  20583. {
  20584. tlk.setown(createSingleKeyMerger(indexHelper.queryDiskRecordSize()->queryRecordAccessor(true), thisKey, seekGEOffset, this, indexHelper.hasNewSegmentMonitors()));
  20585. }
  20586. else
  20587. {
  20588. tlk.setown(createLocalKeyManager(indexHelper.queryDiskRecordSize()->queryRecordAccessor(true), thisKey, this, indexHelper.hasNewSegmentMonitors()));
  20589. if (!thisKey->isTopLevelKey())
  20590. tlk->setLayoutTranslator(translators->queryTranslator(fileNo));
  20591. else
  20592. tlk->setLayoutTranslator(nullptr);
  20593. }
  20594. createSegmentMonitors(tlk);
  20595. if (queryTraceLevel() > 3 || ctx->queryProbeManager())
  20596. {
  20597. StringBuffer out;
  20598. tlk->describeFilter(out);
  20599. CTXLOG("Using filter %s", out.str());
  20600. if (ctx->queryProbeManager())
  20601. ctx->queryProbeManager()->setNodeProperty(this, "filter", out.str());
  20602. }
  20603. tlk->reset();
  20604. for (;;) // for each file part
  20605. {
  20606. //block for TransformCallbackAssociation
  20607. {
  20608. TransformCallbackAssociation associate(callback, tlk);
  20609. if (thisKey->isTopLevelKey())
  20610. {
  20611. if (thisKey->isFullySorted())
  20612. {
  20613. while (tlk->lookup(false))
  20614. {
  20615. unsigned slavePart = (unsigned)extractFpos(tlk);
  20616. if (slavePart)
  20617. {
  20618. accepted++;
  20619. remote.getMem(slavePart, fileNo, 0); // the cached context is all we need to send
  20620. if (sorted && numChannels>1)
  20621. remote.flush(); // don't combine parts if we need result sorted, except on a 1-way
  20622. }
  20623. }
  20624. }
  20625. else
  20626. {
  20627. unsigned slavePart = tlk->getPartition(); // Returns 0 if no partition info, or filter cannot be partitioned
  20628. remote.getMem(slavePart, fileNo, 0);
  20629. }
  20630. }
  20631. else
  20632. {
  20633. if (processSingleKey(thisKey, translators->queryTranslator(fileNo)))
  20634. break;
  20635. }
  20636. }
  20637. if (++fileNo < thisBase->numParts())
  20638. {
  20639. thisKey = thisBase->queryPart(fileNo);
  20640. tlk->setKey(thisKey);
  20641. if (!thisKey->isTopLevelKey())
  20642. tlk->setLayoutTranslator(translators->queryTranslator(fileNo));
  20643. else
  20644. tlk->setLayoutTranslator(nullptr);
  20645. tlk->reset();
  20646. }
  20647. else
  20648. break;
  20649. }
  20650. tlk->releaseSegmentMonitors();
  20651. tlk->setKey(NULL);
  20652. }
  20653. }
  20654. }
  20655. }
  20656. remote.flush();
  20657. remote.senddone();
  20658. }
  20659. catch (IException *E)
  20660. {
  20661. remote.setException(E);
  20662. }
  20663. }
  20664. virtual void createSegmentMonitors(IKeyManager *key)
  20665. {
  20666. indexHelper.createSegmentMonitors(key);
  20667. key->finishSegmentMonitors();
  20668. }
  20669. virtual bool processSingleKey(IKeyIndex *key, const IDynamicTransform * trans) = 0;
  20670. virtual void reset()
  20671. {
  20672. if (accepted)
  20673. noteStatistic(StNumIndexAccepted, accepted);
  20674. if (rejected)
  20675. noteStatistic(StNumIndexRejected, rejected);
  20676. remote.onReset();
  20677. CRoxieServerActivity::reset();
  20678. if (varFileInfo)
  20679. {
  20680. keySet.clear();
  20681. varFileInfo.clear();
  20682. }
  20683. variableInfoPending = false;
  20684. }
  20685. virtual void stop()
  20686. {
  20687. remote.onStop();
  20688. CRoxieServerActivity::stop();
  20689. }
  20690. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  20691. {
  20692. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  20693. }
  20694. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  20695. {
  20696. CRoxieServerActivity::gatherStats(merged);
  20697. remote.gatherStats(merged);
  20698. }
  20699. };
  20700. class CRoxieServerIndexReadBaseActivity : public CRoxieServerIndexActivity
  20701. {
  20702. protected:
  20703. IHThorSourceLimitTransformExtra * limitTransformExtra = nullptr;
  20704. public:
  20705. CRoxieServerIndexReadBaseActivity(IRoxieSlaveContext *_ctx, const CRoxieServerBaseIndexActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  20706. bool _sorted, bool _isLocal, bool _maySkip)
  20707. : CRoxieServerIndexActivity(_ctx, _factory, _probeManager, _remoteId, _sorted, _isLocal, _maySkip)
  20708. {
  20709. }
  20710. virtual void reset()
  20711. {
  20712. remote.onReset();
  20713. CRoxieServerIndexActivity::reset();
  20714. }
  20715. virtual const void *nextRow()
  20716. {
  20717. ActivityTimer t(totalCycles, timeActivities);
  20718. try
  20719. {
  20720. const void *ret = remote.nextRow();
  20721. if (ret)
  20722. processed++;
  20723. return ret;
  20724. }
  20725. catch (IException *E)
  20726. {
  20727. throw makeWrappedException(E);
  20728. }
  20729. }
  20730. protected:
  20731. virtual const void * createLimitFailRow(bool isKeyed)
  20732. {
  20733. ensureRowAllocator();
  20734. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  20735. assertex(limitTransformExtra);
  20736. size32_t outSize = isKeyed ? limitTransformExtra->transformOnKeyedLimitExceeded(rowBuilder) : limitTransformExtra->transformOnLimitExceeded(rowBuilder);
  20737. if (outSize)
  20738. return rowBuilder.finalizeRowClear(outSize);
  20739. return NULL;
  20740. }
  20741. };
  20742. class CRoxieServerIndexReadActivity : public CRoxieServerIndexReadBaseActivity, implements IIndexReadActivityInfo
  20743. {
  20744. protected:
  20745. IHThorIndexReadArg & readHelper;
  20746. ISteppingMeta *rawMeta = nullptr;
  20747. CSteppingMeta steppingMeta;
  20748. unsigned * seekSizes = nullptr;
  20749. bool optimizeSteppedPostFilter;
  20750. ISteppingMeta * projectedMeta = nullptr;
  20751. unsigned maxSeekLookahead;
  20752. public:
  20753. CRoxieServerIndexReadActivity(IRoxieSlaveContext *_ctx, const CRoxieServerBaseIndexActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  20754. bool _sorted, bool _isLocal, bool _maySkip, unsigned _maxSeekLookahead)
  20755. : CRoxieServerIndexReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _sorted, _isLocal, _maySkip),
  20756. readHelper((IHThorIndexReadArg &)basehelper)
  20757. {
  20758. limitTransformExtra = &readHelper;
  20759. rawMeta = readHelper.queryRawSteppingMeta();
  20760. unsigned flags = indexHelper.getFlags();
  20761. optimizeSteppedPostFilter = (flags & TIRunfilteredtransform) != 0;
  20762. seekSizes = NULL;
  20763. maxSeekLookahead = _maxSeekLookahead;
  20764. if (rawMeta)
  20765. {
  20766. const CFieldOffsetSize * fields = rawMeta->queryFields();
  20767. unsigned maxFields = rawMeta->getNumFields();
  20768. seekGEOffset = fields[0].offset;
  20769. seekSizes = new unsigned[maxFields];
  20770. seekSizes[0] = fields[0].size;
  20771. for (unsigned i=1; i < maxFields; i++)
  20772. seekSizes[i] = seekSizes[i-1] + fields[i].size;
  20773. projectedMeta = readHelper.queryProjectedSteppingMeta();
  20774. ISteppingMeta *useMeta = projectedMeta ? projectedMeta : rawMeta;
  20775. remote.setMergeInfo(useMeta); // also need to consider superfile case where there is a mix of multiway and singleparts.. ?
  20776. bool hasPostFilter = readHelper.transformMayFilter() && optimizeSteppedPostFilter;
  20777. steppingMeta.init(useMeta, hasPostFilter);
  20778. }
  20779. }
  20780. ~CRoxieServerIndexReadActivity()
  20781. {
  20782. delete [] seekSizes;
  20783. }
  20784. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20785. {
  20786. CRoxieServerIndexReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  20787. steppingMeta.setDistributed();
  20788. if (steppedExtra)
  20789. steppingMeta.setExtra(steppedExtra);
  20790. rowLimit = readHelper.getRowLimit();
  20791. keyedLimit = readHelper.getKeyedLimit();
  20792. choosenLimit = readHelper.getChooseNLimit();
  20793. if (!paused)
  20794. processAllKeys();
  20795. }
  20796. class LazyLocalKeyReader : implements IMessageUnpackCursor, implements IMessageResult, public CInterface
  20797. {
  20798. public:
  20799. IMPLEMENT_IINTERFACE;
  20800. virtual IMessageUnpackCursor *getCursor(roxiemem::IRowManager *rowMgr) const
  20801. {
  20802. Link();
  20803. return const_cast<LazyLocalKeyReader*> (this);
  20804. }
  20805. virtual const void *getMessageHeader(unsigned &length) const
  20806. {
  20807. length = 0;
  20808. return NULL;
  20809. }
  20810. virtual const void *getMessageMetadata(unsigned &length) const
  20811. {
  20812. length = 0;
  20813. return NULL;
  20814. }
  20815. virtual void discard() const
  20816. {
  20817. // nothing to do.
  20818. }
  20819. unsigned keyedCount;
  20820. unsigned matched;
  20821. bool EOFseen;
  20822. Owned<IKeyIndexSet> keySet;
  20823. Owned<IKeyManager> tlk;
  20824. CRoxieServerIndexReadActivity &owner;
  20825. LazyLocalKeyReader(CRoxieServerIndexReadActivity &_owner, IKeyIndex *key, const IDynamicTransform * trans)
  20826. : owner(_owner)
  20827. {
  20828. keyedCount = 0;
  20829. matched = 0;
  20830. EOFseen = false;
  20831. keySet.setown(createKeyIndexSet());
  20832. keySet->addIndex(LINK(key));
  20833. if (owner.seekGEOffset)
  20834. tlk.setown(createKeyMerger(owner.indexHelper.queryDiskRecordSize()->queryRecordAccessor(true), keySet, owner.seekGEOffset, &owner, owner.indexHelper.hasNewSegmentMonitors()));
  20835. else
  20836. tlk.setown(createLocalKeyManager(owner.indexHelper.queryDiskRecordSize()->queryRecordAccessor(true), keySet->queryPart(0), &owner, owner.indexHelper.hasNewSegmentMonitors()));
  20837. if (!key->isTopLevelKey())
  20838. tlk->setLayoutTranslator(trans);
  20839. owner.indexHelper.createSegmentMonitors(tlk);
  20840. tlk->finishSegmentMonitors();
  20841. tlk->reset();
  20842. }
  20843. virtual const void *getNext(int length)
  20844. {
  20845. TransformCallbackAssociation associate(owner.callback, tlk);
  20846. while (tlk->lookup(true))
  20847. {
  20848. keyedCount++;
  20849. if (keyedCount > owner.keyedLimit)
  20850. {
  20851. owner.onLimitExceeded(true); // Should throw exception
  20852. throwUnexpected();
  20853. }
  20854. size32_t transformedSize;
  20855. RtlDynamicRowBuilder rowBuilder(owner.rowAllocator);
  20856. byte const * keyRow = tlk->queryKeyBuffer();
  20857. try
  20858. {
  20859. transformedSize = owner.readHelper.transform(rowBuilder, keyRow);
  20860. owner.callback.finishedRow();
  20861. }
  20862. catch (IException *E)
  20863. {
  20864. throw owner.makeWrappedException(E);
  20865. }
  20866. if (transformedSize)
  20867. {
  20868. OwnedConstRoxieRow result = rowBuilder.finalizeRowClear(transformedSize);
  20869. matched++;
  20870. if (matched > owner.rowLimit)
  20871. {
  20872. owner.onLimitExceeded(false); // Should throw exception
  20873. throwUnexpected();
  20874. }
  20875. if (matched > owner.choosenLimit) // MORE - bit of a strange place to check
  20876. {
  20877. break;
  20878. }
  20879. owner.accepted++;
  20880. return result.getClear();
  20881. }
  20882. else
  20883. owner.rejected++;
  20884. }
  20885. EOFseen = true;
  20886. return NULL;
  20887. }
  20888. virtual bool atEOF() const
  20889. {
  20890. return EOFseen;
  20891. }
  20892. virtual bool isSerialized() const
  20893. {
  20894. return false;
  20895. }
  20896. };
  20897. virtual bool processSingleKey(IKeyIndex *key, const IDynamicTransform * trans) override
  20898. {
  20899. ensureRowAllocator();
  20900. remote.injectResult(new LazyLocalKeyReader(*this, key, trans));
  20901. return false;
  20902. }
  20903. virtual void onLimitExceeded(bool isKeyed)
  20904. {
  20905. if (traceLevel > 4)
  20906. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  20907. if (isKeyed)
  20908. {
  20909. if (indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates))
  20910. {
  20911. if (ctx->queryDebugContext())
  20912. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  20913. throw makeLimitSkipException(true);
  20914. }
  20915. else
  20916. readHelper.onKeyedLimitExceeded();
  20917. }
  20918. else
  20919. {
  20920. if (indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates))
  20921. {
  20922. if (ctx->queryDebugContext())
  20923. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  20924. throw makeLimitSkipException(false);
  20925. }
  20926. else
  20927. readHelper.onLimitExceeded();
  20928. }
  20929. }
  20930. virtual void serializeSkipInfo(MemoryBuffer &out, unsigned seekLen, const void *rawSeek, unsigned numFields, const void * seek, const SmartStepExtra &stepExtra) const
  20931. {
  20932. out.append((unsigned short) numFields);
  20933. out.append((unsigned short) seekLen);
  20934. out.append((unsigned short) stepExtra.queryFlags());
  20935. IMultipleStepSeekInfo *seeks = stepExtra.queryExtraSeeks();
  20936. if (seeks)
  20937. {
  20938. unsigned lookahead = 40000/seekLen;
  20939. if (maxSeekLookahead && (lookahead > maxSeekLookahead))
  20940. lookahead = maxSeekLookahead;
  20941. seeks->ensureFilled(seek, numFields, lookahead);
  20942. out.append(lookahead != seeks->ordinality()); // seeksAreEof flag
  20943. unsigned serialized = 1; // rawseek is always serialized...
  20944. unsigned patchLength = out.length();
  20945. out.append(serialized); // NOTE - we come back and patch with the actual value...
  20946. out.append(seekLen, rawSeek);
  20947. if (seeks->ordinality())
  20948. {
  20949. const void *lastSeek = rawSeek;
  20950. byte *nextSeek = NULL;
  20951. if (projectedMeta)
  20952. nextSeek = (byte *) alloca(seekLen);
  20953. for (unsigned i = 0; i < seeks->ordinality(); i++)
  20954. {
  20955. if (projectedMeta)
  20956. {
  20957. RtlStaticRowBuilder rowBuilder(nextSeek-seekGEOffset, seekGEOffset+seekLen);
  20958. readHelper.mapOutputToInput(rowBuilder, seeks->querySeek(i), numFields); // NOTE - weird interface to mapOutputToInput means that it STARTS writing at seekGEOffset...
  20959. }
  20960. else
  20961. nextSeek = (byte *) seeks->querySeek(i)+seekGEOffset;
  20962. int diff = memcmp(nextSeek, lastSeek, seekLen);
  20963. if (diff > 0)
  20964. {
  20965. serialized++;
  20966. out.append(seekLen, nextSeek);
  20967. lastSeek = (const byte *) out.reserve(0) - seekLen;
  20968. }
  20969. }
  20970. unsigned length = out.length();
  20971. out.setWritePos(patchLength);
  20972. out.append(serialized);
  20973. out.setWritePos(length);
  20974. }
  20975. }
  20976. else
  20977. {
  20978. out.append(false);
  20979. out.append(1);
  20980. out.append(seekLen, rawSeek);
  20981. }
  20982. }
  20983. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  20984. {
  20985. ActivityTimer t(totalCycles, timeActivities);
  20986. try
  20987. {
  20988. unsigned seeklen = 0;
  20989. const void *rawSeek = NULL;
  20990. if (seek && numFields)
  20991. {
  20992. seeklen = seekSizes[numFields-1];
  20993. rawSeek = (const byte *)seek + seekGEOffset;
  20994. if (projectedMeta)
  20995. {
  20996. byte * temp = (byte *) alloca(seeklen);
  20997. RtlStaticRowBuilder rawBuilder(temp-seekGEOffset, seekGEOffset+seeklen);
  20998. readHelper.mapOutputToInput(rawBuilder, seek, numFields); // NOTE - weird interface to mapOutputToInput means that it STARTS writing at seekGEOffset...
  20999. rawSeek = (byte *)temp;
  21000. }
  21001. }
  21002. const void *ret = remote.nextRowGE(seek, rawSeek, numFields, seeklen, wasCompleteMatch, stepExtra);
  21003. if (ret && wasCompleteMatch) // GH pleas confirm the wasCompleteMatch I just added here is right
  21004. processed++;
  21005. return ret;
  21006. }
  21007. catch (IException *E)
  21008. {
  21009. throw makeWrappedException(E);
  21010. }
  21011. }
  21012. virtual IInputSteppingMeta * querySteppingMeta()
  21013. {
  21014. if (rawMeta && steppingEnabled && ((indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates|TIRkeyedlimitskips|TIRkeyedlimitcreates)) == 0))
  21015. return &steppingMeta;
  21016. return NULL;
  21017. }
  21018. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  21019. {
  21020. if (variableInfoPending)
  21021. setVariableFileInfo();
  21022. return this;
  21023. }
  21024. virtual IKeyArray *getKeySet() const
  21025. {
  21026. return keySet.getLink();
  21027. }
  21028. virtual const IResolvedFile *getVarFileInfo() const
  21029. {
  21030. return varFileInfo.getLink();
  21031. }
  21032. virtual ITranslatorSet *getTranslators() const override
  21033. {
  21034. return translators.getLink();
  21035. }
  21036. virtual void mergeSegmentMonitors(IIndexReadContext *irc) const
  21037. {
  21038. indexHelper.createSegmentMonitors(irc); // NOTE: they will merge
  21039. }
  21040. virtual IRoxieServerActivity *queryActivity() { return this; }
  21041. virtual const RemoteActivityId& queryRemoteId() const
  21042. {
  21043. return remoteId;
  21044. }
  21045. };
  21046. class CRoxieServerSimpleIndexReadActivity : public CRoxieServerActivity, implements IIndexReadActivityInfo
  21047. {
  21048. IHThorIndexReadArg & indexHelper;
  21049. IHThorSteppedSourceExtra * steppedExtra;
  21050. bool eof;
  21051. Linked<IKeyArray>keySet;
  21052. Owned<IKeyIndexSet>keyIndexSet;
  21053. Owned<IKeyManager> tlk;
  21054. Linked<ITranslatorSet> translators;
  21055. CIndexTransformCallback callback;
  21056. unsigned __int64 keyedLimit;
  21057. unsigned rowLimit;
  21058. unsigned chooseNLimit;
  21059. unsigned accepted;
  21060. unsigned rejected;
  21061. unsigned keyedCount;
  21062. ISteppingMeta * rawMeta;
  21063. ISteppingMeta * projectedMeta;
  21064. size32_t seekGEOffset;
  21065. unsigned * seekSizes;
  21066. CSteppingMeta steppingMeta;
  21067. Owned<const IResolvedFile> varFileInfo;
  21068. const RemoteActivityId &remoteId;
  21069. bool firstRead;
  21070. bool variableFileName;
  21071. bool variableInfoPending;
  21072. bool isOpt;
  21073. bool isLocal;
  21074. bool optimizeSteppedPostFilter;
  21075. // MORE there may be enough in common between this and CRoxieServerIndexActivity to warrant some refactoring
  21076. void initKeySet()
  21077. {
  21078. if ((keySet->length() > 1 || rawMeta != NULL) && translators->isTranslating())
  21079. {
  21080. throw MakeStringException(ROXIE_UNIMPLEMENTED_ERROR, "Layout translation is not available when merging key parts or smart-stepping, as it may change record order");
  21081. }
  21082. keyIndexSet.setown(createKeyIndexSet());
  21083. for (unsigned part = 0; part < keySet->length(); part++)
  21084. {
  21085. IKeyIndexBase *kib = keySet->queryKeyPart(part);
  21086. if (kib)
  21087. {
  21088. for (unsigned subpart = 0; subpart < kib->numParts(); subpart++)
  21089. {
  21090. IKeyIndex *k = kib->queryPart(subpart);
  21091. if (k)
  21092. {
  21093. assertex(!k->isTopLevelKey());
  21094. keyIndexSet->addIndex(LINK(k));
  21095. }
  21096. }
  21097. }
  21098. }
  21099. }
  21100. void setVariableFileInfo()
  21101. {
  21102. OwnedRoxieString indexName(indexHelper.getFileName());
  21103. varFileInfo.setown(resolveLFNIndex(indexName, isOpt));
  21104. unsigned formatCrc = indexHelper.getFormatCrc();
  21105. IOutputMetaData *projectedMeta = indexHelper.queryProjectedDiskRecordSize();
  21106. IOutputMetaData *expectedMeta = indexHelper.queryDiskRecordSize();
  21107. translators.setown(varFileInfo->getTranslators(formatCrc, skipFileFormatCrcCheck(), projectedMeta, expectedMeta, getEnableFieldTranslation(), true));
  21108. keySet.setown(varFileInfo->getKeyArray(isOpt, isLocal ? factory->queryQueryFactory().queryChannel() : 0));
  21109. initKeySet();
  21110. variableInfoPending = false;
  21111. }
  21112. void onEOF()
  21113. {
  21114. callback.setManager(NULL);
  21115. eof = true;
  21116. tlk.clear();
  21117. }
  21118. public:
  21119. CRoxieServerSimpleIndexReadActivity(IRoxieSlaveContext *_ctx, const CRoxieServerBaseIndexActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, bool _isLocal)
  21120. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  21121. indexHelper((IHThorIndexReadArg &)basehelper),
  21122. translators(_factory->translators),
  21123. keySet(_factory->keySet),
  21124. isLocal(_isLocal),
  21125. remoteId(_remoteId)
  21126. {
  21127. rowLimit = 0;
  21128. keyedLimit = 0;
  21129. chooseNLimit = 0;
  21130. indexHelper.setCallback(&callback);
  21131. steppedExtra = indexHelper.querySteppingExtra();
  21132. unsigned flags = indexHelper.getFlags();
  21133. variableFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((flags & (TIRvarfilename|TIRdynamicfilename)) != 0);
  21134. variableInfoPending = false;
  21135. isOpt = (flags & TIRoptional) != 0;
  21136. optimizeSteppedPostFilter = (flags & TIRunfilteredtransform) != 0;
  21137. firstRead = true;
  21138. accepted = 0;
  21139. rejected = 0;
  21140. keyedCount = 0;
  21141. eof = false;
  21142. rawMeta = indexHelper.queryRawSteppingMeta();
  21143. projectedMeta = indexHelper.queryProjectedSteppingMeta();
  21144. seekGEOffset = 0;
  21145. seekSizes = NULL;
  21146. if (rawMeta)
  21147. {
  21148. // MORE - should check all keys in maxFields list can actually be keyed.
  21149. const CFieldOffsetSize * fields = rawMeta->queryFields();
  21150. unsigned maxFields = rawMeta->getNumFields();
  21151. seekGEOffset = fields[0].offset;
  21152. seekSizes = new unsigned[maxFields];
  21153. seekSizes[0] = fields[0].size;
  21154. for (unsigned i=1; i < maxFields; i++)
  21155. seekSizes[i] = seekSizes[i-1] + fields[i].size;
  21156. bool hasPostFilter = indexHelper.transformMayFilter() && optimizeSteppedPostFilter;
  21157. if (projectedMeta)
  21158. steppingMeta.init(projectedMeta, hasPostFilter);
  21159. else
  21160. steppingMeta.init(rawMeta, hasPostFilter);
  21161. }
  21162. }
  21163. virtual const IResolvedFile *queryVarFileInfo() const
  21164. {
  21165. return varFileInfo;
  21166. }
  21167. ~CRoxieServerSimpleIndexReadActivity()
  21168. {
  21169. delete [] seekSizes;
  21170. }
  21171. virtual bool needsAllocator() const { return true; }
  21172. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21173. {
  21174. firstRead = true;
  21175. accepted = 0;
  21176. rejected = 0;
  21177. keyedCount = 0;
  21178. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  21179. if (steppedExtra)
  21180. steppingMeta.setExtra(steppedExtra);
  21181. eof = !indexHelper.canMatchAny();
  21182. if (variableFileName)
  21183. variableInfoPending = true;
  21184. else
  21185. {
  21186. variableInfoPending = false;
  21187. if (!keyIndexSet)
  21188. initKeySet();
  21189. }
  21190. }
  21191. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  21192. {
  21193. if (variableInfoPending)
  21194. setVariableFileInfo();
  21195. return this;
  21196. }
  21197. virtual IKeyArray *getKeySet() const
  21198. {
  21199. return keySet.getLink();
  21200. }
  21201. virtual const IResolvedFile *getVarFileInfo() const
  21202. {
  21203. return varFileInfo.getLink();
  21204. }
  21205. virtual ITranslatorSet *getTranslators() const override
  21206. {
  21207. return translators.getLink();
  21208. }
  21209. virtual void mergeSegmentMonitors(IIndexReadContext *irc) const
  21210. {
  21211. indexHelper.createSegmentMonitors(irc); // NOTE: they will merge
  21212. }
  21213. virtual IRoxieServerActivity *queryActivity() { return this; }
  21214. virtual const RemoteActivityId& queryRemoteId() const
  21215. {
  21216. return remoteId;
  21217. }
  21218. const void *nextRow()
  21219. {
  21220. bool matched = true;
  21221. return nextRowGE(NULL, 0, matched, dummySmartStepExtra);
  21222. }
  21223. unsigned __int64 checkCount(unsigned __int64 limit)
  21224. {
  21225. unsigned numParts = keyIndexSet->numParts();
  21226. unsigned __int64 result = 0;
  21227. for (unsigned i = 0; i < numParts; i++)
  21228. {
  21229. Owned<IKeyManager> countTlk = createLocalKeyManager(indexHelper.queryDiskRecordSize()->queryRecordAccessor(true), keyIndexSet->queryPart(i), this, indexHelper.hasNewSegmentMonitors());
  21230. countTlk->setLayoutTranslator(translators->queryTranslator(i));
  21231. indexHelper.createSegmentMonitors(countTlk);
  21232. countTlk->finishSegmentMonitors();
  21233. result += countTlk->checkCount(limit-result);
  21234. if (result > limit)
  21235. break;
  21236. }
  21237. return result;
  21238. }
  21239. virtual const void *nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  21240. {
  21241. ActivityTimer t(totalCycles, timeActivities);
  21242. if (eof)
  21243. return NULL;
  21244. if (firstRead)
  21245. {
  21246. if (variableInfoPending)
  21247. setVariableFileInfo();
  21248. rowLimit = (unsigned) indexHelper.getRowLimit();
  21249. chooseNLimit = (unsigned) indexHelper.getChooseNLimit();
  21250. unsigned numParts = keyIndexSet->numParts();
  21251. if (!numParts)
  21252. {
  21253. onEOF();
  21254. return NULL;
  21255. }
  21256. if (numParts > 1 || seekGEOffset)
  21257. {
  21258. tlk.setown(createKeyMerger(indexHelper.queryDiskRecordSize()->queryRecordAccessor(true), keyIndexSet, seekGEOffset, this, indexHelper.hasNewSegmentMonitors()));
  21259. // note that we don't set up translator because we don't support it. If that ever changes...
  21260. }
  21261. else
  21262. {
  21263. tlk.setown(createLocalKeyManager(indexHelper.queryDiskRecordSize()->queryRecordAccessor(true), keyIndexSet->queryPart(0), this, indexHelper.hasNewSegmentMonitors()));
  21264. tlk->setLayoutTranslator(translators->queryTranslator(0));
  21265. }
  21266. indexHelper.createSegmentMonitors(tlk);
  21267. tlk->finishSegmentMonitors();
  21268. if (queryTraceLevel() > 3 || ctx->queryProbeManager())
  21269. {
  21270. StringBuffer out;
  21271. tlk->describeFilter(out);
  21272. CTXLOG("Using filter %s", out.str());
  21273. if (ctx->queryProbeManager())
  21274. ctx->queryProbeManager()->setNodeProperty(this, "filter", out.str());
  21275. }
  21276. tlk->reset();
  21277. callback.setManager(tlk);
  21278. keyedLimit = indexHelper.getKeyedLimit();
  21279. if (keyedLimit != (unsigned __int64) -1)
  21280. {
  21281. if ((indexHelper.getFlags() & TIRcountkeyedlimit) != 0)
  21282. {
  21283. unsigned __int64 count = checkCount(keyedLimit);
  21284. if (count > keyedLimit)
  21285. {
  21286. if ((indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates)) == 0)
  21287. indexHelper.onKeyedLimitExceeded();
  21288. const void * ret = NULL;
  21289. if (indexHelper.getFlags() & TIRkeyedlimitcreates)
  21290. ret = createKeyedLimitOnFailRow();
  21291. onEOF();
  21292. return ret;
  21293. }
  21294. keyedLimit = (unsigned __int64) -1;
  21295. }
  21296. }
  21297. firstRead = false;
  21298. }
  21299. if (accepted == chooseNLimit)
  21300. {
  21301. onEOF();
  21302. return NULL;
  21303. }
  21304. const byte * rawSeek = NULL;
  21305. unsigned seekSize = 0;
  21306. if (seek)
  21307. {
  21308. seekSize = seekSizes[numFields-1];
  21309. rawSeek = (const byte *)seek + seekGEOffset;
  21310. if (projectedMeta)
  21311. {
  21312. byte *temp = (byte *) alloca(seekSize);
  21313. RtlStaticRowBuilder rawBuilder(temp-seekGEOffset, seekGEOffset+seekSize);
  21314. indexHelper.mapOutputToInput(rawBuilder, seek, numFields);// NOTE - weird interface to mapOutputToInput means that it STARTS writing at seekGEOffset...
  21315. rawSeek = (byte *)temp;
  21316. }
  21317. #ifdef _DEBUG
  21318. // StringBuffer seekStr;
  21319. // for (unsigned i = 0; i < seekSize; i++)
  21320. // {
  21321. // seekStr.appendf("%02x ", ((unsigned char *) rawSeek)[i]);
  21322. // }
  21323. // DBGLOG("nextRowGE can skip offset %d size %d value %s", seekGEOffset, seekSize, seekStr.str());
  21324. #endif
  21325. }
  21326. const byte * originalRawSeek = rawSeek;
  21327. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  21328. while (rawSeek ? tlk->lookupSkip(rawSeek, seekGEOffset, seekSize) : tlk->lookup(true))
  21329. {
  21330. checkAbort();
  21331. keyedCount++;
  21332. if (keyedCount > keyedLimit)
  21333. {
  21334. indexHelper.onKeyedLimitExceeded();
  21335. break;
  21336. }
  21337. byte const * keyRow = tlk->queryKeyBuffer();
  21338. #ifdef _DEBUG
  21339. // StringBuffer recstr;
  21340. // unsigned size = (tlk->queryRecordSize()<80) ? tlk->queryRecordSize() : 80;
  21341. // for (unsigned i = 0; i < size; i++)
  21342. // {
  21343. // recstr.appendf("%02x ", ((unsigned char *) keyRow)[i]);
  21344. // }
  21345. // DBGLOG("nextRowGE Got %s", recstr.str());
  21346. if (originalRawSeek && memcmp(keyRow + seekGEOffset, originalRawSeek, seekSize) < 0)
  21347. assertex(!"smart seek failure");
  21348. #endif
  21349. size32_t transformedSize;
  21350. rowBuilder.ensureRow();
  21351. try
  21352. {
  21353. transformedSize =indexHelper.transform(rowBuilder, keyRow);
  21354. //if the post filter causes a mismatch, and the stepping condition no longer matches
  21355. //then return a mismatch record - so the join code can start seeking on the other input.
  21356. if (transformedSize == 0 && optimizeSteppedPostFilter && stepExtra.returnMismatches())
  21357. {
  21358. if (memcmp(keyRow + seekGEOffset, originalRawSeek, seekSize) != 0)
  21359. {
  21360. transformedSize = indexHelper.unfilteredTransform(rowBuilder, keyRow);
  21361. if (transformedSize != 0)
  21362. wasCompleteMatch = false;
  21363. }
  21364. }
  21365. callback.finishedRow();
  21366. }
  21367. catch (IException *E)
  21368. {
  21369. throw makeWrappedException(E);
  21370. }
  21371. if (transformedSize)
  21372. {
  21373. accepted++;
  21374. if (accepted > rowLimit)
  21375. {
  21376. if ((indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates)) != 0)
  21377. {
  21378. throwUnexpected(); // should not have used simple variant if maySkip set...
  21379. }
  21380. if (traceLevel > 4)
  21381. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  21382. indexHelper.onLimitExceeded();
  21383. break;
  21384. }
  21385. processed++;
  21386. #ifdef _DEBUG
  21387. // const byte *ret = (const byte *) out.get();
  21388. // CommonXmlWriter xmlwrite(XWFnoindent|XWFtrim|XWFopt);
  21389. // queryOutputMeta()->toXML(ret, xmlwrite);
  21390. // DBGLOG("ROW: {%p} %s", ret, xmlwrite.str());
  21391. #endif
  21392. return rowBuilder.finalizeRowClear(transformedSize);
  21393. }
  21394. else
  21395. rejected++;
  21396. rawSeek = NULL;
  21397. }
  21398. onEOF();
  21399. return NULL;
  21400. }
  21401. virtual void reset()
  21402. {
  21403. onEOF();
  21404. if (accepted)
  21405. noteStatistic(StNumIndexAccepted, accepted);
  21406. if (rejected)
  21407. noteStatistic(StNumIndexRejected, rejected);
  21408. if (variableFileName)
  21409. {
  21410. varFileInfo.clear();
  21411. translators.clear();
  21412. }
  21413. variableInfoPending = false;
  21414. CRoxieServerActivity::reset();
  21415. }
  21416. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  21417. {
  21418. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  21419. }
  21420. virtual IInputSteppingMeta * querySteppingMeta()
  21421. {
  21422. if (rawMeta && steppingEnabled && ((indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates|TIRkeyedlimitskips|TIRkeyedlimitcreates)) == 0))
  21423. return &steppingMeta;
  21424. return NULL;
  21425. }
  21426. protected:
  21427. const void * createKeyedLimitOnFailRow()
  21428. {
  21429. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  21430. size32_t outSize = indexHelper.transformOnKeyedLimitExceeded(rowBuilder);
  21431. if (outSize)
  21432. return rowBuilder.finalizeRowClear(outSize);
  21433. return NULL;
  21434. }
  21435. };
  21436. class CRoxieServerIndexReadActivityFactory : public CRoxieServerBaseIndexActivityFactory
  21437. {
  21438. public:
  21439. CRoxieServerIndexReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21440. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId)
  21441. {
  21442. }
  21443. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  21444. {
  21445. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  21446. return new CRoxieServerNullActivity(_ctx, this, _probeManager);
  21447. else if (isSimple && !maySkip)
  21448. return new CRoxieServerSimpleIndexReadActivity(_ctx, this, _probeManager, remoteId, isLocal);
  21449. else
  21450. return new CRoxieServerIndexReadActivity(_ctx, this, _probeManager, remoteId, sorted, isLocal, maySkip, maxSeekLookahead);
  21451. }
  21452. };
  21453. IRoxieServerActivityFactory *createRoxieServerIndexReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21454. {
  21455. return new CRoxieServerIndexReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  21456. }
  21457. //--------------------------------------------------------------------------------------------------------------------------
  21458. class CRoxieServerNullCountActivity : public CRoxieServerActivity
  21459. {
  21460. bool done;
  21461. public:
  21462. CRoxieServerNullCountActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  21463. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  21464. {
  21465. done = false;
  21466. }
  21467. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21468. {
  21469. done = false;
  21470. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  21471. }
  21472. virtual bool needsAllocator() const { return true; }
  21473. virtual const void *nextRow()
  21474. {
  21475. ActivityTimer t(totalCycles, timeActivities);
  21476. if (done) return NULL;
  21477. done = true;
  21478. size32_t rowSize = meta.getFixedSize();
  21479. void * nullRow = rowAllocator->createRow();
  21480. if (rowSize == 1)
  21481. *(byte *)nullRow = 0;
  21482. else
  21483. {
  21484. assertex(rowSize == sizeof(unsigned __int64));
  21485. *(unsigned __int64 *)nullRow = 0;
  21486. }
  21487. return rowAllocator->finalizeRow(rowSize, nullRow, rowSize);
  21488. }
  21489. };
  21490. class CRoxieServerIndexCountActivity : public CRoxieServerIndexActivity
  21491. {
  21492. IHThorIndexCountArg & countHelper;
  21493. bool done;
  21494. public:
  21495. CRoxieServerIndexCountActivity(IRoxieSlaveContext *_ctx, const CRoxieServerBaseIndexActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, bool _isLocal)
  21496. : CRoxieServerIndexActivity(_ctx, _factory, _probeManager, _remoteId, false, _isLocal, false),
  21497. countHelper((IHThorIndexCountArg &)basehelper),
  21498. done(false)
  21499. {
  21500. }
  21501. virtual bool needsAllocator() const { return true; }
  21502. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21503. {
  21504. done = false;
  21505. CRoxieServerIndexActivity::start(parentExtractSize, parentExtract, paused);
  21506. choosenLimit = countHelper.getChooseNLimit();
  21507. rowLimit = countHelper.getRowLimit();
  21508. keyedLimit = countHelper.getKeyedLimit();
  21509. if (!paused)
  21510. processAllKeys();
  21511. }
  21512. virtual bool processSingleKey(IKeyIndex *key, const IDynamicTransform * trans) override
  21513. {
  21514. unsigned __int64 count = 0;
  21515. if (countHelper.hasFilter())
  21516. {
  21517. while (tlk->lookup(true))
  21518. {
  21519. try
  21520. {
  21521. count += countHelper.numValid(tlk->queryKeyBuffer());
  21522. callback.finishedRow();
  21523. }
  21524. catch (IException *E)
  21525. {
  21526. throw makeWrappedException(E);
  21527. }
  21528. accepted++;
  21529. if (count >= choosenLimit) // MORE - what about limit?
  21530. break;
  21531. }
  21532. }
  21533. else
  21534. count = tlk->getCount(); //MORE: GH->RKC There should be value in providing a max limit to getCount()
  21535. if (count)
  21536. {
  21537. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), false);
  21538. if (count > choosenLimit)
  21539. count = choosenLimit;
  21540. void * recBuffer = rowAllocator->createRow();
  21541. if (meta.getFixedSize() == 1)
  21542. *(byte *)recBuffer = (byte)count;
  21543. else
  21544. {
  21545. assertex(meta.getFixedSize() == sizeof(unsigned __int64));
  21546. *(unsigned __int64 *)recBuffer = count;
  21547. }
  21548. recBuffer = rowAllocator->finalizeRow(meta.getFixedSize(), recBuffer, meta.getFixedSize());
  21549. result->append(recBuffer);
  21550. remote.injectResult(result.getClear());
  21551. //GH->RKC for count(,choosen)/exists passing in the previous count would short-circuit this much earlier
  21552. if (count >= choosenLimit)
  21553. return true;
  21554. }
  21555. return false;
  21556. }
  21557. virtual void onLimitExceeded(bool isKeyed)
  21558. {
  21559. if (traceLevel > 4)
  21560. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  21561. if (isKeyed)
  21562. {
  21563. if (indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates))
  21564. {
  21565. if (ctx->queryDebugContext())
  21566. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  21567. throw makeLimitSkipException(true);
  21568. }
  21569. else
  21570. {
  21571. countHelper.onKeyedLimitExceeded();
  21572. }
  21573. }
  21574. else
  21575. {
  21576. if (indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates))
  21577. {
  21578. if (ctx->queryDebugContext())
  21579. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  21580. throw makeLimitSkipException(false);
  21581. }
  21582. else
  21583. {
  21584. countHelper.onLimitExceeded();
  21585. }
  21586. }
  21587. }
  21588. virtual const void *createLimitFailRow(bool isKeyed)
  21589. {
  21590. throwUnexpected();
  21591. }
  21592. virtual const void *nextRow()
  21593. {
  21594. ActivityTimer t(totalCycles, timeActivities);
  21595. if (done) return NULL;
  21596. done = true;
  21597. unsigned __int64 totalCount = 0;
  21598. bool hasLimit = rowLimit != (unsigned __int64) -1;
  21599. try
  21600. {
  21601. for (;;)
  21602. {
  21603. const void * next = remote.nextRow();
  21604. if (!next)
  21605. break;
  21606. if (meta.getFixedSize() == 1)
  21607. totalCount += *(byte *)next;
  21608. else
  21609. totalCount += *(unsigned __int64 *) next;
  21610. ReleaseRoxieRow(next);
  21611. if (totalCount > rowLimit || (totalCount > choosenLimit && !hasLimit)) // can't break out early if there is a possibility of later slave throwing limit exception
  21612. break;
  21613. }
  21614. if (totalCount > rowLimit)
  21615. {
  21616. unsigned flags = indexHelper.getFlags();
  21617. if (flags & TIRlimitskips)
  21618. totalCount = 0;
  21619. else if (flags & TIRlimitcreates)
  21620. totalCount = 1;
  21621. else
  21622. countHelper.onLimitExceeded();
  21623. }
  21624. else if (totalCount > choosenLimit)
  21625. totalCount = choosenLimit;
  21626. }
  21627. catch (IException *E)
  21628. {
  21629. if (QUERYINTERFACE(E, LimitSkipException))
  21630. {
  21631. totalCount = 0;
  21632. unsigned flags = indexHelper.getFlags();
  21633. if (E->errorCode() == KeyedLimitSkipErrorCode)
  21634. {
  21635. if (flags & TIRkeyedlimitcreates)
  21636. totalCount++;
  21637. }
  21638. else
  21639. {
  21640. if (flags & TIRlimitcreates)
  21641. totalCount++;
  21642. }
  21643. if (totalCount > choosenLimit)
  21644. totalCount = choosenLimit; // would have to be weird code (and escape the optimizer...)
  21645. E->Release();
  21646. }
  21647. else
  21648. throw ;
  21649. }
  21650. void * result = rowAllocator->createRow();
  21651. if (meta.getFixedSize() == 1)
  21652. *(byte *)result = (byte)totalCount;
  21653. else
  21654. {
  21655. assertex(meta.getFixedSize() == sizeof(unsigned __int64));
  21656. *(unsigned __int64 *)result = totalCount;
  21657. }
  21658. return rowAllocator->finalizeRow(meta.getFixedSize(), result, meta.getFixedSize());
  21659. }
  21660. };
  21661. class CRoxieServerIndexCountActivityFactory : public CRoxieServerBaseIndexActivityFactory
  21662. {
  21663. public:
  21664. CRoxieServerIndexCountActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21665. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId)
  21666. {
  21667. }
  21668. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  21669. {
  21670. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  21671. return new CRoxieServerNullCountActivity(_ctx, this, _probeManager);
  21672. // else if (isSimple)
  21673. // return new CRoxieServerSimpleIndexCountActivity(this, keySet->queryKeyPart(0)->queryPart(0));
  21674. else
  21675. return new CRoxieServerIndexCountActivity(_ctx, this, _probeManager, remoteId, isLocal);
  21676. }
  21677. };
  21678. IRoxieServerActivityFactory *createRoxieServerIndexCountActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21679. {
  21680. return new CRoxieServerIndexCountActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  21681. }
  21682. //--------------------------------------------------------------------------------------------------------------------------
  21683. class CRoxieServerNullIndexAggregateActivity : public CRoxieServerActivity
  21684. {
  21685. IHThorIndexAggregateArg &aggregateHelper;
  21686. bool done;
  21687. public:
  21688. CRoxieServerNullIndexAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  21689. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  21690. aggregateHelper((IHThorIndexAggregateArg &)basehelper)
  21691. {
  21692. done = false;
  21693. }
  21694. virtual bool needsAllocator() const { return true; }
  21695. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21696. {
  21697. done = false;
  21698. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  21699. }
  21700. virtual const void *nextRow()
  21701. {
  21702. ActivityTimer t(totalCycles, timeActivities);
  21703. if (done) return NULL;
  21704. done = true;
  21705. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  21706. size32_t thisSize = aggregateHelper.clearAggregate(rowBuilder);
  21707. return rowBuilder.finalizeRowClear(thisSize);
  21708. }
  21709. };
  21710. class CRoxieServerIndexAggregateActivity : public CRoxieServerIndexActivity
  21711. {
  21712. IHThorCompoundAggregateExtra & aggregateHelper;
  21713. bool done;
  21714. public:
  21715. CRoxieServerIndexAggregateActivity(IRoxieSlaveContext *_ctx, const CRoxieServerBaseIndexActivityFactory *_factory, IProbeManager *_probeManager,
  21716. const RemoteActivityId &_remoteId, bool _isLocal)
  21717. : CRoxieServerIndexActivity(_ctx, _factory, _probeManager, _remoteId, false, _isLocal, false),
  21718. aggregateHelper((IHThorIndexAggregateArg &)basehelper),
  21719. done(false)
  21720. {
  21721. }
  21722. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21723. {
  21724. done = false;
  21725. CRoxieServerIndexActivity::start(parentExtractSize, parentExtract, paused);
  21726. if (!paused)
  21727. processAllKeys();
  21728. }
  21729. virtual bool needsAllocator() const { return true; }
  21730. virtual bool processSingleKey(IKeyIndex *key, const IDynamicTransform * trans) override
  21731. {
  21732. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  21733. while (tlk->lookup(true))
  21734. {
  21735. if (!rowBuilder.exists())
  21736. {
  21737. rowBuilder.ensureRow();
  21738. aggregateHelper.clearAggregate(rowBuilder);
  21739. }
  21740. try
  21741. {
  21742. aggregateHelper.processRow(rowBuilder, tlk->queryKeyBuffer());
  21743. callback.finishedRow();
  21744. }
  21745. catch (IException *E)
  21746. {
  21747. throw makeWrappedException(E);
  21748. }
  21749. accepted++;
  21750. }
  21751. if (aggregateHelper.processedAnyRows())
  21752. {
  21753. size32_t size = meta.getRecordSize(rowBuilder.getSelf());
  21754. const void * recBuffer = rowBuilder.finalizeRowClear(size);
  21755. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), meta.isVariableSize());
  21756. result->append(recBuffer);
  21757. remote.injectResult(result.getClear());
  21758. }
  21759. return false;
  21760. }
  21761. virtual void onLimitExceeded(bool isKeyed)
  21762. {
  21763. if (traceLevel > 4)
  21764. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  21765. throwUnexpected();
  21766. }
  21767. virtual const void *createLimitFailRow(bool isKeyed)
  21768. {
  21769. throwUnexpected();
  21770. }
  21771. const void * gatherMerged()
  21772. {
  21773. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  21774. const void * firstRow = remote.nextRow();
  21775. size32_t finalSize = 0;
  21776. if (!firstRow)
  21777. {
  21778. rowBuilder.ensureRow();
  21779. finalSize = aggregateHelper.clearAggregate(rowBuilder);
  21780. }
  21781. else
  21782. {
  21783. // NOTE need to clone this because going to modify below, could special case 1 row only
  21784. finalSize = cloneRow(rowBuilder, firstRow, meta);
  21785. ReleaseRoxieRow(firstRow);
  21786. }
  21787. for (;;)
  21788. {
  21789. const void * next = remote.nextRow();
  21790. if (!next)
  21791. break;
  21792. finalSize = aggregateHelper.mergeAggregate(rowBuilder, next);
  21793. ReleaseRoxieRow(next);
  21794. }
  21795. return rowBuilder.finalizeRowClear(finalSize);
  21796. }
  21797. virtual const void *nextRow()
  21798. {
  21799. ActivityTimer t(totalCycles, timeActivities);
  21800. if (done) return NULL;
  21801. const void * ret = gatherMerged();
  21802. done = true;
  21803. return ret;
  21804. }
  21805. };
  21806. class CRoxieServerIndexAggregateActivityFactory : public CRoxieServerBaseIndexActivityFactory
  21807. {
  21808. public:
  21809. CRoxieServerIndexAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21810. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId)
  21811. {
  21812. }
  21813. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  21814. {
  21815. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  21816. return new CRoxieServerNullIndexAggregateActivity(_ctx, this, _probeManager);
  21817. // else if (isSimple)
  21818. // return new CRoxieServerSimpleIndexAggregateActivity(this, keySet->queryKeyPart(0)->queryPart(0));
  21819. else
  21820. return new CRoxieServerIndexAggregateActivity(_ctx, this, _probeManager, remoteId, isLocal);
  21821. }
  21822. };
  21823. IRoxieServerActivityFactory *createRoxieServerIndexAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21824. {
  21825. return new CRoxieServerIndexAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  21826. }
  21827. //--------------------------------------------------------------------------------------------------------------------------
  21828. class CRoxieServerIndexGroupAggregateActivity : public CRoxieServerIndexActivity, implements IHThorGroupAggregateCallback
  21829. {
  21830. IHThorCompoundGroupAggregateExtra & aggregateHelper;
  21831. RowAggregator singleAggregator;
  21832. RowAggregator resultAggregator;
  21833. unsigned groupSegCount;
  21834. bool gathered;
  21835. bool eof;
  21836. public:
  21837. CRoxieServerIndexGroupAggregateActivity(IRoxieSlaveContext *_ctx, const CRoxieServerBaseIndexActivityFactory *_factory, IProbeManager *_probeManager,
  21838. const RemoteActivityId &_remoteId, bool _isLocal)
  21839. : CRoxieServerIndexActivity(_ctx, _factory, _probeManager, _remoteId, false, _isLocal, false),
  21840. aggregateHelper((IHThorIndexGroupAggregateArg &)basehelper),
  21841. singleAggregator(aggregateHelper, aggregateHelper),
  21842. resultAggregator(aggregateHelper, aggregateHelper),
  21843. gathered(false), eof(true)
  21844. {
  21845. groupSegCount = 0;
  21846. }
  21847. IMPLEMENT_IINTERFACE_USING(CRoxieServerIndexActivity)
  21848. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21849. {
  21850. eof = false;
  21851. gathered= false;
  21852. CRoxieServerIndexActivity::start(parentExtractSize, parentExtract, paused);
  21853. groupSegCount = 0;
  21854. if (!paused)
  21855. processAllKeys();
  21856. resultAggregator.start(rowAllocator, ctx->queryCodeContext(), activityId);
  21857. }
  21858. virtual bool needsAllocator() const { return true; }
  21859. virtual void reset()
  21860. {
  21861. resultAggregator.reset();
  21862. CRoxieServerIndexActivity::reset();
  21863. }
  21864. virtual void processRow(const void * next)
  21865. {
  21866. singleAggregator.addRow(next);
  21867. }
  21868. virtual void createSegmentMonitors(IKeyManager *key)
  21869. {
  21870. ThorActivityKind kind = factory->getKind();
  21871. CRoxieServerIndexActivity::createSegmentMonitors(key);
  21872. if ((kind==TAKindexgroupcount || kind==TAKindexgroupexists))
  21873. groupSegCount = aggregateHelper.getGroupingMaxField();
  21874. else
  21875. groupSegCount = 0;
  21876. }
  21877. virtual bool processSingleKey(IKeyIndex *key, const IDynamicTransform * trans) override
  21878. {
  21879. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), meta.isVariableSize());
  21880. singleAggregator.start(rowAllocator, ctx->queryCodeContext(), activityId);
  21881. ThorActivityKind kind = factory->getKind();
  21882. while (tlk->lookup(true))
  21883. {
  21884. try
  21885. {
  21886. if (groupSegCount && !trans)
  21887. {
  21888. AggregateRowBuilder &rowBuilder = singleAggregator.addRow(tlk->queryKeyBuffer());
  21889. callback.finishedRow();
  21890. if (kind==TAKindexgroupcount)
  21891. {
  21892. unsigned __int64 count = tlk->getCurrentRangeCount(groupSegCount);
  21893. aggregateHelper.processCountGrouping(rowBuilder, count-1);
  21894. }
  21895. if (!tlk->nextRange(groupSegCount))
  21896. break;
  21897. }
  21898. else
  21899. {
  21900. aggregateHelper.processRow(tlk->queryKeyBuffer(), this);
  21901. callback.finishedRow();
  21902. }
  21903. }
  21904. catch (IException *E)
  21905. {
  21906. throw makeWrappedException(E);
  21907. }
  21908. accepted++;
  21909. }
  21910. for (;;)
  21911. {
  21912. Owned<AggregateRowBuilder> next = singleAggregator.nextResult();
  21913. if (!next)
  21914. break;
  21915. size32_t size = next->querySize();
  21916. result->append(next->finalizeRowClear());
  21917. }
  21918. remote.injectResult(result.getClear());
  21919. singleAggregator.reset();
  21920. return false;
  21921. }
  21922. virtual void onLimitExceeded(bool isKeyed)
  21923. {
  21924. if (traceLevel > 4)
  21925. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  21926. throwUnexpected();
  21927. }
  21928. virtual const void *createLimitFailRow(bool isKeyed)
  21929. {
  21930. throwUnexpected();
  21931. }
  21932. void gatherMerged()
  21933. {
  21934. gathered = true;
  21935. for (;;)
  21936. {
  21937. const void * next = remote.nextRow();
  21938. if (!next)
  21939. break;
  21940. resultAggregator.mergeElement(next);
  21941. ReleaseRoxieRow(next);
  21942. }
  21943. }
  21944. virtual const void *nextRow()
  21945. {
  21946. ActivityTimer t(totalCycles, timeActivities);
  21947. if (eof)
  21948. return NULL;
  21949. if (!gathered)
  21950. gatherMerged();
  21951. Owned<AggregateRowBuilder> next = resultAggregator.nextResult();
  21952. if (next)
  21953. {
  21954. processed++;
  21955. return next->finalizeRowClear();
  21956. }
  21957. eof = true;
  21958. return NULL;
  21959. }
  21960. };
  21961. class CRoxieServerIndexGroupAggregateActivityFactory : public CRoxieServerBaseIndexActivityFactory
  21962. {
  21963. public:
  21964. CRoxieServerIndexGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21965. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId)
  21966. {
  21967. }
  21968. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  21969. {
  21970. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  21971. return new CRoxieServerNullActivity(_ctx, this, _probeManager);
  21972. // else if (isSimple)
  21973. // return new CRoxieServerSimpleIndexGroupAggregateActivity(this, keySet->queryKeyPart(0)->queryPart(0));
  21974. else
  21975. return new CRoxieServerIndexGroupAggregateActivity(_ctx, this, _probeManager, remoteId, isLocal);
  21976. }
  21977. };
  21978. IRoxieServerActivityFactory *createRoxieServerIndexGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21979. {
  21980. return new CRoxieServerIndexGroupAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  21981. }
  21982. //--------------------------------------------------------------------------------------------------------------------------
  21983. class CRoxieServerIndexNormalizeActivity : public CRoxieServerIndexReadBaseActivity
  21984. {
  21985. IHThorIndexNormalizeArg & readHelper;
  21986. public:
  21987. CRoxieServerIndexNormalizeActivity(IRoxieSlaveContext *_ctx, const CRoxieServerBaseIndexActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  21988. bool _sorted, bool _isLocal)
  21989. : CRoxieServerIndexReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _sorted, _isLocal, false),
  21990. readHelper((IHThorIndexNormalizeArg &)basehelper)
  21991. {
  21992. limitTransformExtra = &readHelper;
  21993. }
  21994. virtual bool needsAllocator() const { return true; }
  21995. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21996. {
  21997. CRoxieServerIndexReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  21998. rowLimit = readHelper.getRowLimit();
  21999. keyedLimit = readHelper.getKeyedLimit();
  22000. choosenLimit = readHelper.getChooseNLimit();
  22001. if (!paused)
  22002. processAllKeys();
  22003. }
  22004. virtual bool processSingleKey(IKeyIndex *key, const IDynamicTransform * trans) override
  22005. {
  22006. unsigned keyedCount = 0;
  22007. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  22008. while (tlk->lookup(true))
  22009. {
  22010. keyedCount++;
  22011. if (keyedCount > keyedLimit)
  22012. {
  22013. if (traceLevel > 4)
  22014. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  22015. onLimitExceeded(true);
  22016. break;
  22017. }
  22018. size32_t transformedSize;
  22019. if (readHelper.first(tlk->queryKeyBuffer()))
  22020. {
  22021. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), meta.isVariableSize());
  22022. do
  22023. {
  22024. if (accepted>=choosenLimit)
  22025. break;
  22026. rowBuilder.ensureRow();
  22027. try
  22028. {
  22029. transformedSize = readHelper.transform(rowBuilder);
  22030. }
  22031. catch (IException *E)
  22032. {
  22033. throw makeWrappedException(E);
  22034. }
  22035. if (transformedSize)
  22036. {
  22037. // MORE - would be a good idea to stop these asap if rowlimit exceeded
  22038. result->append(rowBuilder.finalizeRowClear(transformedSize));
  22039. accepted++;
  22040. }
  22041. else
  22042. rejected++;
  22043. } while (readHelper.next());
  22044. remote.injectResult(result.getClear());
  22045. callback.finishedRow();
  22046. if (accepted>=choosenLimit)
  22047. return true;
  22048. }
  22049. }
  22050. return false;
  22051. }
  22052. virtual void onLimitExceeded(bool isKeyed)
  22053. {
  22054. if (traceLevel > 4)
  22055. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  22056. if (isKeyed)
  22057. {
  22058. if (indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates))
  22059. {
  22060. if (ctx->queryDebugContext())
  22061. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  22062. throw makeLimitSkipException(true);
  22063. }
  22064. else
  22065. readHelper.onKeyedLimitExceeded();
  22066. }
  22067. else
  22068. {
  22069. if (indexHelper.getFlags() & (TIRlimitskips||TIRlimitcreates))
  22070. {
  22071. if (ctx->queryDebugContext())
  22072. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  22073. throw makeLimitSkipException(false);
  22074. }
  22075. else
  22076. readHelper.onLimitExceeded();
  22077. }
  22078. }
  22079. virtual const void *createLimitFailRow(bool isKeyed)
  22080. {
  22081. UNIMPLEMENTED;
  22082. }
  22083. };
  22084. class CRoxieServerIndexNormalizeActivityFactory : public CRoxieServerBaseIndexActivityFactory
  22085. {
  22086. public:
  22087. CRoxieServerIndexNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  22088. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId)
  22089. {
  22090. }
  22091. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  22092. {
  22093. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  22094. return new CRoxieServerNullActivity(_ctx, this, _probeManager);
  22095. else
  22096. return new CRoxieServerIndexNormalizeActivity(_ctx, this, _probeManager, remoteId, sorted, isLocal);
  22097. }
  22098. };
  22099. IRoxieServerActivityFactory *createRoxieServerIndexNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  22100. {
  22101. return new CRoxieServerIndexNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  22102. }
  22103. //=================================================================================
  22104. class CRoxieServerFetchActivity : public CRoxieServerActivity, implements IRecordPullerCallback, implements IRoxieServerErrorHandler
  22105. {
  22106. IHThorFetchBaseArg &helper;
  22107. Linked<IFilePartMap> map;
  22108. CRemoteResultAdaptor remote;
  22109. RecordPullerThread puller;
  22110. bool needsRHS;
  22111. bool variableFileName;
  22112. bool isOpt;
  22113. Owned<const IResolvedFile> varFileInfo;
  22114. Owned<IEngineRowAllocator> extractAllocator;
  22115. public:
  22116. CRoxieServerFetchActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IFilePartMap *_map)
  22117. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorFetchBaseArg &)basehelper), map(_map), remote(_ctx, this, _remoteId, meta.queryOriginal(), helper, *this, true, true), puller(false)
  22118. {
  22119. needsRHS = helper.transformNeedsRhs();
  22120. if (needsRHS)
  22121. extractAllocator.setown(createRowAllocator(helper.queryExtractedSize()));
  22122. variableFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  22123. isOpt = (helper.getFetchFlags() & FFdatafileoptional) != 0;
  22124. }
  22125. virtual const IResolvedFile *queryVarFileInfo() const
  22126. {
  22127. return varFileInfo;
  22128. }
  22129. virtual void onCreate(IHThorArg *_colocalParent)
  22130. {
  22131. CRoxieServerActivity::onCreate(_colocalParent);
  22132. remote.onCreate(_colocalParent);
  22133. }
  22134. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  22135. {
  22136. if (idx)
  22137. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
  22138. puller.setInput(this, _sourceIdx, _in);
  22139. }
  22140. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  22141. {
  22142. puller.connectInputStreams(ctx, consumerOrdered);
  22143. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
  22144. }
  22145. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  22146. {
  22147. if (idx==0)
  22148. return puller.queryInput();
  22149. else
  22150. return NULL;
  22151. }
  22152. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  22153. {
  22154. CRoxieServerActivity::gatherStats(merged);
  22155. remote.gatherStats(merged);
  22156. }
  22157. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  22158. {
  22159. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  22160. remote.onStart(parentExtractSize, parentExtract);
  22161. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  22162. if (variableFileName)
  22163. {
  22164. OwnedRoxieString fname(helper.getFileName());
  22165. varFileInfo.setown(resolveLFNFlat(fname, isOpt));
  22166. if (varFileInfo)
  22167. map.setown(varFileInfo->getFileMap());
  22168. }
  22169. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().fetchPreload, false, ctx);
  22170. }
  22171. virtual void stop()
  22172. {
  22173. // Called from remote, so no need to call back to it....
  22174. puller.stop();
  22175. CRoxieServerActivity::stop();
  22176. }
  22177. virtual void reset()
  22178. {
  22179. processed = remote.processed;
  22180. remote.processed = 0;
  22181. puller.reset();
  22182. if (variableFileName)
  22183. {
  22184. varFileInfo.clear();
  22185. map.clear();
  22186. }
  22187. CRoxieServerActivity::reset();
  22188. }
  22189. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  22190. {
  22191. if (idx==(unsigned)-1)
  22192. idx = 0;
  22193. return idx ? NULL : &remote;
  22194. }
  22195. virtual void processRow(const void *row)
  22196. {
  22197. // called from puller thread
  22198. offset_t rp = helper.extractPosition(row);
  22199. unsigned partNo;
  22200. if (isLocalFpos(rp))
  22201. partNo = getLocalFposPart(rp) + 1;
  22202. else
  22203. partNo = map->mapOffset(rp);
  22204. if (needsRHS)
  22205. {
  22206. RtlDynamicRowBuilder rb(extractAllocator, true);
  22207. unsigned rhsSize = helper.extractJoinFields(rb, row);
  22208. char * block = (char *) remote.getMem(partNo, 0, sizeof(rp) + sizeof(rhsSize) + rhsSize); // MORE - superfiles
  22209. *(offset_t *) block = rp;
  22210. block += sizeof(rp);
  22211. *(unsigned *) block = rhsSize;
  22212. block += sizeof(rhsSize);
  22213. memcpy(block, rb.row(), rhsSize);
  22214. }
  22215. else
  22216. *(offset_t *) remote.getMem(partNo, 0, sizeof(rp)) = rp; // MORE - superfiles
  22217. ReleaseRoxieRow(row);
  22218. }
  22219. void processEOG()
  22220. {
  22221. #ifdef FETCH_PRESERVES_GROUPING
  22222. UNIMPLEMENTED;
  22223. #endif
  22224. // else discard is correct
  22225. }
  22226. void processGroup(const ConstPointerArray &)
  22227. {
  22228. throwUnexpected();
  22229. }
  22230. void processDone()
  22231. {
  22232. // called from puller thread
  22233. remote.flush();
  22234. remote.senddone();
  22235. }
  22236. virtual bool fireException(IException *e)
  22237. {
  22238. return remote.fireException(e);
  22239. }
  22240. virtual void onLimitExceeded(bool isKeyed)
  22241. {
  22242. if (traceLevel > 4)
  22243. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  22244. if (isKeyed)
  22245. throwUnexpected();
  22246. helper.onLimitExceeded();
  22247. }
  22248. virtual const void *createLimitFailRow(bool isKeyed)
  22249. {
  22250. UNIMPLEMENTED;
  22251. }
  22252. virtual const void *nextRow()
  22253. {
  22254. throwUnexpected(); // I am nobody's input
  22255. }
  22256. };
  22257. class CRoxieServerFetchActivityFactory : public CRoxieServerActivityFactory
  22258. {
  22259. RemoteActivityId remoteId;
  22260. Owned<IFilePartMap> map;
  22261. bool variableFileName;
  22262. Owned<const IResolvedFile> datafile;
  22263. public:
  22264. CRoxieServerFetchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  22265. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), remoteId(_remoteId)
  22266. {
  22267. Owned<IHThorFetchBaseArg> helper = (IHThorFetchBaseArg *) helperFactory();
  22268. variableFileName = allFilesDynamic || _queryFactory.isDynamic() || ((helper->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  22269. if (!variableFileName)
  22270. {
  22271. OwnedRoxieString fname(helper->getFileName());
  22272. datafile.setown(_queryFactory.queryPackage().lookupFileName(fname,
  22273. (helper->getFetchFlags() & FFdatafileoptional) != 0,
  22274. true, true,
  22275. _queryFactory.queryWorkUnit(), true));
  22276. if (datafile)
  22277. map.setown(datafile->getFileMap());
  22278. }
  22279. }
  22280. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  22281. {
  22282. return new CRoxieServerFetchActivity(_ctx, this, _probeManager, remoteId, map);
  22283. }
  22284. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  22285. {
  22286. if (datafile)
  22287. addXrefFileInfo(reply, datafile);
  22288. else
  22289. {
  22290. // Temporarily resolve the file
  22291. Owned<IHThorFetchBaseArg> helper = (IHThorFetchBaseArg *) helperFactory();
  22292. if ((helper->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) == 0)
  22293. {
  22294. OwnedRoxieString fileName(helper->getFileName());
  22295. Owned<const IResolvedFile> temp = queryFactory.queryPackage().lookupFileName(fileName, true, true, false, queryFactory.queryWorkUnit(), true);
  22296. if (temp)
  22297. addXrefFileInfo(reply, temp);
  22298. }
  22299. }
  22300. }
  22301. virtual const StatisticsMapping &queryStatsMapping() const
  22302. {
  22303. return diskStatistics;
  22304. }
  22305. };
  22306. IRoxieServerActivityFactory *createRoxieServerFetchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  22307. {
  22308. return new CRoxieServerFetchActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  22309. }
  22310. // MORE - is there any point keeping this now?
  22311. class CRoxieServerDummyActivityFactory : public CRoxieServerActivityFactory // not a real activity - just used to properly link files
  22312. {
  22313. public:
  22314. Owned<const IResolvedFile> indexfile;
  22315. Owned<const IResolvedFile> datafile;
  22316. StringAttr fileName;
  22317. StringAttr indexName;
  22318. Owned<IKeyArray> keySet;
  22319. Owned<IFileIOArray> files;
  22320. CRoxieServerDummyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool isLoadDataOnly)
  22321. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  22322. {
  22323. try // does not want any missing file errors to be fatal, or throw traps - just log it
  22324. {
  22325. if (_graphNode.getPropBool("att[@name='_isSpill']/@value", false) || _graphNode.getPropBool("att[@name='_isSpillGlobal']/@value", false))
  22326. return; // ignore 'spills'
  22327. bool isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  22328. ThorActivityKind kind = getActivityKind(_graphNode);
  22329. if (kind != TAKdiskwrite && kind != TAKspillwrite && kind != TAKindexwrite && kind != TAKpiperead && kind != TAKpipewrite)
  22330. {
  22331. fileName.set(queryNodeFileName(_graphNode, kind));
  22332. indexName.set(queryNodeIndexName(_graphNode, kind));
  22333. if (indexName && !allFilesDynamic && !queryFactory.isDynamic())
  22334. {
  22335. bool isOpt = pretendAllOpt || _graphNode.getPropBool("att[@name='_isIndexOpt']/@value");
  22336. indexfile.setown(queryFactory.queryPackage().lookupFileName(indexName, isOpt, true, true, queryFactory.queryWorkUnit(), true));
  22337. if (indexfile)
  22338. keySet.setown(indexfile->getKeyArray(isOpt, isLocal ? queryFactory.queryChannel() : 0));
  22339. }
  22340. if (fileName && !allFilesDynamic && !queryFactory.isDynamic())
  22341. {
  22342. bool isOpt = pretendAllOpt || _graphNode.getPropBool("att[@name='_isOpt']/@value");
  22343. datafile.setown(_queryFactory.queryPackage().lookupFileName(fileName, isOpt, true, true, queryFactory.queryWorkUnit(), true));
  22344. if (datafile)
  22345. {
  22346. if (isLocal)
  22347. files.setown(datafile->getIFileIOArray(isOpt, queryFactory.queryChannel()));
  22348. }
  22349. }
  22350. }
  22351. }
  22352. catch(IException *E)
  22353. {
  22354. StringBuffer errors;
  22355. E->errorMessage(errors);
  22356. DBGLOG("%s File error = %s", (isLoadDataOnly) ? "LOADDATAONLY" : "SUSPENDED QUERY", errors.str());
  22357. E->Release();
  22358. }
  22359. }
  22360. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const { throw MakeStringException(ROXIE_INTERNAL_ERROR, "%s query %s is suspended and cannot be executed - error occurred at %s(%d)", (queryFactory.isQueryLibrary()) ? "Library" : " ", queryFactory.queryQueryName(), sanitizeSourceFile(__FILE__), __LINE__); }
  22361. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  22362. {
  22363. if (!allFilesDynamic)
  22364. {
  22365. if (datafile)
  22366. addXrefFileInfo(reply, datafile);
  22367. if (indexfile)
  22368. addXrefFileInfo(reply, indexfile);
  22369. }
  22370. else
  22371. {
  22372. Owned<const IResolvedFile> temp;
  22373. if (fileName.length())
  22374. {
  22375. temp.setown(queryFactory.queryPackage().lookupFileName(fileName, true, true, false, queryFactory.queryWorkUnit(), true));
  22376. if (temp)
  22377. addXrefFileInfo(reply, temp);
  22378. }
  22379. if (indexName.length())
  22380. {
  22381. temp.setown(queryFactory.queryPackage().lookupFileName(indexName, true, true, false, queryFactory.queryWorkUnit(), true));
  22382. if (temp)
  22383. addXrefFileInfo(reply, temp);
  22384. }
  22385. }
  22386. }
  22387. };
  22388. IRoxieServerActivityFactory *createRoxieServerDummyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool isLoadDataOnly)
  22389. {
  22390. return new CRoxieServerDummyActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, isLoadDataOnly);
  22391. }
  22392. //=====================================================================================================
  22393. // Keyed joins...
  22394. //
  22395. // Input records are pulled by a puller thread, which checks each LHS record to determine which (if any) channels it
  22396. // may have RHS matches on, and sends the relevant fields to the relevant slaves.
  22397. // 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
  22398. // the transform and returns rows that are created.
  22399. // 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)
  22400. //
  22401. //=====================================================================================================
  22402. class CJoinGroup;
  22403. interface IJoinProcessor
  22404. {
  22405. virtual void processEOG() = 0;
  22406. virtual CJoinGroup *createJoinGroup(const void *row) = 0;
  22407. virtual void noteEndReceived(CJoinGroup *jg, unsigned candidateCount) = 0;
  22408. virtual bool fireException(IException *E) = 0;
  22409. virtual void processCompletedGroups() = 0;
  22410. };
  22411. //------------------------------------------------------------------------------------------------------
  22412. // Class CJoinGroup has a record per LHS row, plus (if preserving grouping) a 'head of group' record
  22413. // It gathers all the corresponding RHS rows, keeping track of how may slave transactions are pending in endMarkersPending
  22414. // If preserving groups, the 'head of group' record keeps track of how many LHS records in the group are still incomplete.
  22415. // CJoinGroup records are allocated out of the Roxie row memory manager by overloading operator new, so that they are included in the
  22416. // per-query limits etc (Note that the pointer array block is not though).
  22417. // Because of that, the exact size is significant - especially whether fit just under or just over a chunking threshold...
  22418. //
  22419. // There are two phases to the life of a JoinGroup - it is created by the puller thread that is also firing off slave requests
  22420. // notePending will be called once for every slave request. Puller thread calls noteEndReceived(0) once when done - this corresponds to the
  22421. // initial count when created.
  22422. // Slave replies and are noted by the consumer thread calling addRightMatch() and noteEndReceived(n).
  22423. // Once endMarkersPending reaches 0, JoinGroup is complete. Last thread to call noteEndReceived will process the rows and destroy the group.
  22424. // There is no need for a critsec because although multiple threads will access at different times, only the consumer thread will
  22425. // access any modifiable member variables while endMarkersPending != 0 (i.e. complete() is false). Once complete returns true there is a single
  22426. // remaining reference and the JoinGroup will be processed and destroyed.
  22427. //
  22428. //------------------------------------------------------------------------------------------------------
  22429. class CJoinGroup : public CInterface
  22430. {
  22431. protected:
  22432. const void *left; // LHS row
  22433. PointerArrayOf<KeyedJoinHeader> rows; // matching RHS rows
  22434. atomic_t endMarkersPending; // How many slave responses still waiting for
  22435. CJoinGroup *groupStart; // Head of group, or NULL if not grouping
  22436. unsigned lastPartNo;
  22437. unsigned pos;
  22438. unsigned candidates; // Number of RHS keyed candidates - note this may not be the same as rows.ordinality()
  22439. public:
  22440. void *operator new(size_t size, IRowManager *a, unsigned activityId)
  22441. {
  22442. return a->allocate(size, activityId);
  22443. }
  22444. void operator delete(void *ptr, IRowManager *a, unsigned activityId)
  22445. {
  22446. ReleaseRoxieRow(ptr);
  22447. }
  22448. void operator delete(void *ptr)
  22449. {
  22450. ReleaseRoxieRow(ptr);
  22451. }
  22452. public:
  22453. CJoinGroup(const void *_left, CJoinGroup *_groupStart)
  22454. {
  22455. #ifdef TRACE_JOINGROUPS
  22456. DBGLOG("Creating joinGroup %p, groupstart %p", this, _groupStart);
  22457. #endif
  22458. candidates = 0;
  22459. lastPartNo = 0;
  22460. pos = 0;
  22461. left = _left;
  22462. groupStart = _groupStart;
  22463. if (_groupStart)
  22464. {
  22465. atomic_inc(&_groupStart->endMarkersPending);
  22466. }
  22467. atomic_set(&endMarkersPending, 1);
  22468. }
  22469. ~CJoinGroup()
  22470. {
  22471. #ifdef TRACE_JOINGROUPS
  22472. DBGLOG("Destroying joinGroup %p", this);
  22473. #endif
  22474. if (left)
  22475. {
  22476. ReleaseRoxieRow(left);
  22477. roxiemem::ReleaseRoxieRowArray(rows.ordinality(), (const void * *)rows.getArray());
  22478. rows.kill();
  22479. }
  22480. }
  22481. inline bool isHeadRecord() const
  22482. {
  22483. return left==NULL;
  22484. }
  22485. inline bool complete() const
  22486. {
  22487. return atomic_read(&endMarkersPending) == 0;
  22488. }
  22489. #ifdef TRACE_JOINGROUPS
  22490. inline void notePending(unsigned lineNo)
  22491. #else
  22492. inline void notePending()
  22493. #endif
  22494. {
  22495. assert(!complete());
  22496. atomic_inc(&endMarkersPending);
  22497. #ifdef TRACE_JOINGROUPS
  22498. DBGLOG("CJoinGroup::notePending %p from %d, count became %d group count %d", this, lineNo, atomic_read(&endMarkersPending), groupStart ? atomic_read(&groupStart->endMarkersPending) : 0);
  22499. #endif
  22500. }
  22501. inline bool inGroup(CJoinGroup *leader) const
  22502. {
  22503. return groupStart==leader;
  22504. }
  22505. inline const KeyedJoinHeader *queryRow(unsigned idx) const
  22506. {
  22507. // Single threaded by now
  22508. assert(complete());
  22509. return rows.item(idx);
  22510. }
  22511. #ifdef TRACE_JOINGROUPS
  22512. bool noteEndReceived(unsigned candidateCount, unsigned lineNo)
  22513. #else
  22514. bool noteEndReceived(unsigned candidateCount)
  22515. #endif
  22516. {
  22517. assert(!complete());
  22518. if (candidateCount)
  22519. {
  22520. candidates += candidateCount;
  22521. }
  22522. #ifdef TRACE_JOINGROUPS
  22523. 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);
  22524. #endif
  22525. // NOTE - as soon as endMarkersPending and groupStart->endMarkersPending are decremented to zero this object may get released asynchronously by other threads
  22526. // There must therefore be nothing in this method after them that acceses member variables. Think of it as a delete this...
  22527. // In particular, we can't safely reference groupStart after the dec_and_test of endMarkersPending, hence copy local first
  22528. CJoinGroup *localGroupStart = groupStart;
  22529. if (atomic_dec_and_test(&endMarkersPending))
  22530. {
  22531. if (localGroupStart)
  22532. return atomic_dec_and_test(&localGroupStart->endMarkersPending);
  22533. else
  22534. return true;
  22535. }
  22536. else
  22537. return false;
  22538. }
  22539. inline const void *queryLeft() const
  22540. {
  22541. return left;
  22542. }
  22543. void addRightMatch(KeyedJoinHeader *right)
  22544. {
  22545. assert(!complete());
  22546. unsigned short partNo = right->partNo;
  22547. if (partNo != lastPartNo)
  22548. {
  22549. // MORE - should we binchop? If we did we would need to be careful to find LAST match
  22550. if (partNo > lastPartNo)
  22551. pos = rows.length();
  22552. while (pos>0)
  22553. {
  22554. if (rows.item(pos-1)->partNo <= partNo)
  22555. break;
  22556. pos--;
  22557. }
  22558. lastPartNo = partNo;
  22559. }
  22560. rows.add(right, pos);
  22561. pos++;
  22562. }
  22563. inline unsigned rowsSeen() const
  22564. {
  22565. assert(complete());
  22566. return rows.length();
  22567. }
  22568. inline unsigned candidateCount() const
  22569. {
  22570. assert(complete());
  22571. return candidates;
  22572. }
  22573. };
  22574. #ifdef TRACE_JOINGROUPS
  22575. #define notePending() notePending(__LINE__)
  22576. #define noteEndReceived(a) noteEndReceived(a, __LINE__)
  22577. #endif
  22578. class KeyedJoinRemoteAdaptor : public CRemoteResultAdaptor // MORE - not sure it should be derived from this - makes processed all wrong, for example
  22579. {
  22580. private:
  22581. SafeQueueOf<const void, true> ready;
  22582. public:
  22583. IHThorKeyedJoinArg &helper;
  22584. unsigned joinProcessed;
  22585. bool isFullKey;
  22586. bool eof;
  22587. bool isSimple;
  22588. bool allPulled;
  22589. ActivityTimeAccumulator totalCycles;
  22590. unsigned activityId;
  22591. RecordPullerThread &puller;
  22592. SafeQueueOf<const void, true> injected; // Used in isSimple mode
  22593. Owned<IEngineRowAllocator> ccdRecordAllocator;
  22594. IJoinProcessor &processor;
  22595. KeyedJoinRemoteAdaptor(IRoxieSlaveContext *_ctx, IRoxieServerErrorHandler *_errorHandler, const RemoteActivityId &_remoteId, IHThorKeyedJoinArg &_helper,
  22596. IRoxieServerActivity &_activity, bool _isFullKey, bool _isSimple,
  22597. RecordPullerThread &_puller, IJoinProcessor &_processor)
  22598. : helper(_helper),
  22599. CRemoteResultAdaptor(_ctx, _errorHandler, _remoteId, 0, _helper, _activity, true, true),
  22600. isFullKey(_isFullKey),
  22601. isSimple(_isSimple),
  22602. puller(_puller),
  22603. processor(_processor),
  22604. activityId(_activity.queryId())
  22605. {
  22606. joinProcessed = 0;
  22607. allPulled = false;
  22608. eof = false;
  22609. }
  22610. virtual void onCreate(IHThorArg *_colocalArg)
  22611. {
  22612. CRemoteResultAdaptor::onCreate(_colocalArg);
  22613. ccdRecordAllocator.setown(activity.createRowAllocator(helper.queryJoinFieldsRecordSize()));
  22614. }
  22615. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  22616. {
  22617. eof = false;
  22618. joinProcessed = 0;
  22619. totalCycles.totalCycles = 0;
  22620. allPulled = false;
  22621. assertex(ready.ordinality()==0);
  22622. CRemoteResultAdaptor::start(parentExtractSize, parentExtract, paused);
  22623. }
  22624. virtual void reset()
  22625. {
  22626. CRemoteResultAdaptor::reset();
  22627. while (ready.ordinality())
  22628. {
  22629. const void *goer = ready.dequeue();
  22630. if (goer)
  22631. ReleaseRoxieRow(goer);
  22632. }
  22633. while (injected.ordinality())
  22634. {
  22635. const void *goer = injected.dequeue();
  22636. if (goer)
  22637. ReleaseRoxieRow(goer);
  22638. }
  22639. }
  22640. inline void addResult(const void *row)
  22641. {
  22642. ready.enqueue(row);
  22643. }
  22644. virtual unsigned __int64 queryTotalCycles() const
  22645. {
  22646. return totalCycles.totalCycles;
  22647. }
  22648. virtual const void *nextRow()
  22649. {
  22650. ActivityTimer t(totalCycles, timeActivities);
  22651. for (;;)
  22652. {
  22653. if (eof)
  22654. return NULL;
  22655. processSlaveResults();
  22656. if (ready.ordinality())
  22657. {
  22658. const void *result = ready.dequeue();
  22659. if (result)
  22660. joinProcessed++;
  22661. return result;
  22662. }
  22663. else
  22664. eof = true;
  22665. }
  22666. }
  22667. void gatherStats(CRuntimeStatisticCollection & merged) const
  22668. {
  22669. CRemoteResultAdaptor::gatherStats(merged);
  22670. if (ccdRecordAllocator)
  22671. ccdRecordAllocator->gatherStats(merged);
  22672. }
  22673. private:
  22674. void processSlaveResults()
  22675. {
  22676. while (!ready.ordinality())
  22677. {
  22678. KeyedJoinHeader *fetchedData;
  22679. if (isSimple)
  22680. {
  22681. while (!allPulled && !injected.ordinality())
  22682. {
  22683. if (!puller.pullRecords(1))
  22684. {
  22685. puller.done();
  22686. allPulled = true;
  22687. }
  22688. }
  22689. fetchedData = (KeyedJoinHeader *) injected.dequeue();
  22690. }
  22691. else
  22692. fetchedData = (KeyedJoinHeader *) CRemoteResultAdaptor::nextRow();
  22693. if (fetchedData)
  22694. {
  22695. CJoinGroup *thisGroup = fetchedData->thisGroup;
  22696. if (fetchedData->partNo == (unsigned short) -1)
  22697. {
  22698. #ifdef TRACE_JOINGROUPS
  22699. CTXLOG("Got end for group %p", thisGroup);
  22700. #endif
  22701. unsigned candidateCount = (unsigned) fetchedData->fpos;
  22702. ReleaseRoxieRow(fetchedData);
  22703. processor.noteEndReceived(thisGroup, candidateCount); // note - this can throw exception. So release fetchdata before calling
  22704. }
  22705. else
  22706. {
  22707. #ifdef TRACE_JOINGROUPS
  22708. CTXLOG("Reading another %d bytes for group %p data", ccdRecordSize, thisGroup);
  22709. #endif
  22710. thisGroup->addRightMatch(fetchedData);
  22711. if (isFullKey)
  22712. {
  22713. #ifdef TRACE_JOINGROUPS
  22714. CTXLOG("Calling noteEndReceived for record returned from FETCH of full keyed join");
  22715. #endif
  22716. processor.noteEndReceived(thisGroup, 0); // note - this can throw exception. So release fetchdata before calling
  22717. }
  22718. }
  22719. }
  22720. else
  22721. break;
  22722. }
  22723. }
  22724. };
  22725. class CRoxieServerFullKeyedJoinHead: public CRoxieServerActivity, implements IRecordPullerCallback, implements IRoxieServerErrorHandler
  22726. {
  22727. IHThorKeyedJoinArg &helper;
  22728. Owned<IKeyManager> tlk;
  22729. Linked<IKeyArray> keySet;
  22730. Linked<ITranslatorSet> translators;
  22731. CRemoteResultAdaptor remote;
  22732. RecordPullerThread puller;
  22733. IOutputMetaData *indexReadMeta;
  22734. IJoinProcessor *joinHandler;
  22735. bool variableIndexFileName;
  22736. bool indexReadInputRecordVariable;
  22737. bool isLocal;
  22738. Owned<IEngineRowAllocator> indexReadAllocator;
  22739. Owned<const IResolvedFile> varFileInfo;
  22740. IFinalRoxieInput *indexReadInput;
  22741. unsigned indexReadIdx = 0;
  22742. IIndexReadActivityInfo *rootIndex;
  22743. public:
  22744. CRoxieServerFullKeyedJoinHead(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IKeyArray * _keySet, ITranslatorSet *_translators, IOutputMetaData *_indexReadMeta, IJoinProcessor *_joinHandler, bool _isLocal)
  22745. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  22746. helper((IHThorKeyedJoinArg &)basehelper),
  22747. tlk(createLocalKeyManager(helper.queryIndexRecordSize()->queryRecordAccessor(true), NULL, this, helper.hasNewSegmentMonitors())),
  22748. translators(_translators),
  22749. keySet(_keySet),
  22750. remote(_ctx, this, _remoteId, 0, helper, *this, true, true),
  22751. indexReadMeta(_indexReadMeta),
  22752. joinHandler(_joinHandler),
  22753. puller(false),
  22754. isLocal(_isLocal)
  22755. {
  22756. variableIndexFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getJoinFlags() & (JFvarindexfilename|JFdynamicindexfilename|JFindexfromactivity)) != 0);
  22757. indexReadInputRecordVariable = indexReadMeta->isVariableSize();
  22758. indexReadInput = NULL;
  22759. rootIndex = NULL;
  22760. }
  22761. virtual const IResolvedFile *queryVarFileInfo() const
  22762. {
  22763. return varFileInfo;
  22764. }
  22765. virtual void onCreate(IHThorArg *_colocalParent)
  22766. {
  22767. CRoxieServerActivity::onCreate(_colocalParent);
  22768. remote.onCreate(_colocalParent);
  22769. indexReadAllocator.setown(createRowAllocator(indexReadMeta));
  22770. }
  22771. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  22772. {
  22773. if (!idx)
  22774. puller.setInput(this, _sourceIdx, _in);
  22775. else if (idx==1)
  22776. {
  22777. indexReadInput = _in;
  22778. indexReadIdx = _sourceIdx;
  22779. }
  22780. else
  22781. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
  22782. }
  22783. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  22784. {
  22785. puller.connectInputStreams(ctx, consumerOrdered);
  22786. //No rows are read from indexReadInput, so no need to extract the streams
  22787. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
  22788. }
  22789. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  22790. {
  22791. switch (idx)
  22792. {
  22793. case 0:
  22794. return puller.queryInput();
  22795. case 1:
  22796. return indexReadInput;
  22797. default:
  22798. return NULL;
  22799. }
  22800. }
  22801. virtual void serializeExtra(MemoryBuffer &out)
  22802. {
  22803. if (helper.getJoinFlags() & JFindexfromactivity)
  22804. {
  22805. assertex(rootIndex);
  22806. const RemoteActivityId& indexId = rootIndex->queryRemoteId();
  22807. indexId.serialize(out);
  22808. // could mess about reserving space for length then patching it again, to avoid copy, but probably not worth it
  22809. MemoryBuffer tmp;
  22810. rootIndex->queryActivity()->serializeCreateStartContext(tmp);
  22811. if (rootIndex->queryActivity()->queryVarFileInfo())
  22812. {
  22813. rootIndex->queryActivity()->queryVarFileInfo()->queryTimeStamp().serialize(tmp);
  22814. tmp.append(rootIndex->queryActivity()->queryVarFileInfo()->queryCheckSum());
  22815. }
  22816. unsigned ctxlen = tmp.length();
  22817. out.append(ctxlen).append(tmp);
  22818. }
  22819. }
  22820. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  22821. {
  22822. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  22823. if (indexReadInput)
  22824. {
  22825. indexReadInput->start(parentExtractSize, parentExtract, true); // paused=true because we don't want to actually run the index read
  22826. rootIndex = indexReadInput->queryIndexReadActivity();
  22827. if (!rootIndex)
  22828. throw MakeStringException(ROXIE_INTERNAL_ERROR,"Index in keyed join %d could not be resolved", queryId());
  22829. }
  22830. remote.onStart(parentExtractSize, parentExtract);
  22831. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  22832. if (rootIndex)
  22833. {
  22834. varFileInfo.setown(rootIndex->getVarFileInfo());
  22835. translators.setown(rootIndex->getTranslators());
  22836. keySet.setown(rootIndex->getKeySet());
  22837. }
  22838. else if (variableIndexFileName)
  22839. {
  22840. OwnedRoxieString indexFileName(helper.getIndexFileName());
  22841. varFileInfo.setown(resolveLFNIndex(indexFileName, (helper.getJoinFlags() & JFindexoptional) != 0));
  22842. if (varFileInfo)
  22843. {
  22844. unsigned formatCrc = helper.getIndexFormatCrc();
  22845. translators.setown(varFileInfo->getTranslators(formatCrc, skipFileFormatCrcCheck(), helper.queryProjectedIndexRecordSize(), helper.queryIndexRecordSize(), getEnableFieldTranslation(), true));
  22846. keySet.setown(varFileInfo->getKeyArray(false, isLocal ? factory->queryQueryFactory().queryChannel() : 0));
  22847. }
  22848. }
  22849. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().fullKeyedJoinPreload, false, ctx);
  22850. }
  22851. virtual void stop()
  22852. {
  22853. puller.stop();
  22854. CRoxieServerActivity::stop();
  22855. }
  22856. virtual void reset()
  22857. {
  22858. CRoxieServerActivity::reset();
  22859. puller.reset();
  22860. if (varFileInfo)
  22861. {
  22862. keySet.clear();
  22863. varFileInfo.clear();
  22864. }
  22865. }
  22866. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  22867. {
  22868. if (idx==(unsigned)-1)
  22869. idx = 0;
  22870. return idx ? NULL : &remote;
  22871. }
  22872. virtual void processRow(const void *row)
  22873. {
  22874. // MORE - this code seems to be pretty much duplicated below in half-keyed....
  22875. // called from front puller thread
  22876. // buffer up an IndexRead request
  22877. if (keySet && helper.leftCanMatch(row))
  22878. {
  22879. RtlDynamicRowBuilder extractedBuilder(indexReadAllocator);
  22880. unsigned indexReadSize = helper.extractIndexReadFields(extractedBuilder, row);
  22881. OwnedConstRoxieRow extracted;
  22882. if (indexReadSize)
  22883. extracted.setown(extractedBuilder.finalizeRowClear(indexReadSize));
  22884. CJoinGroup *jg = joinHandler->createJoinGroup(row);
  22885. for (unsigned partNo = 0; partNo < keySet->length(); partNo++)
  22886. {
  22887. IKeyIndexBase *thisBase = keySet->queryKeyPart(partNo);
  22888. if (thisBase)
  22889. {
  22890. unsigned fileNo = 0;
  22891. IKeyIndex *thisKey = thisBase->queryPart(fileNo);
  22892. try
  22893. {
  22894. tlk->setKey(thisKey);
  22895. if (!thisKey->isTopLevelKey())
  22896. tlk->setLayoutTranslator(translators->queryTranslator(fileNo));
  22897. else
  22898. tlk->setLayoutTranslator(nullptr);
  22899. helper.createSegmentMonitors(tlk, extracted);
  22900. if (rootIndex)
  22901. rootIndex->mergeSegmentMonitors(tlk);
  22902. tlk->finishSegmentMonitors();
  22903. tlk->reset();
  22904. for (;;)
  22905. {
  22906. typedef const void * cvp;
  22907. if (thisKey->isTopLevelKey())
  22908. {
  22909. bool locallySorted = !thisKey->isFullySorted();
  22910. while (locallySorted || tlk->lookup(false))
  22911. {
  22912. unsigned slavePart = locallySorted ? tlk->getPartition() : (unsigned)extractFpos(tlk);
  22913. if (locallySorted || slavePart)
  22914. {
  22915. cvp *outputBuffer = (cvp *) remote.getMem(slavePart, fileNo, indexReadSize + sizeof(cvp) + (indexReadInputRecordVariable ? sizeof(unsigned) : 0));
  22916. *outputBuffer++ = jg;
  22917. if (indexReadInputRecordVariable)
  22918. {
  22919. *(unsigned *) outputBuffer = indexReadSize;
  22920. outputBuffer = (cvp*) (((unsigned *) outputBuffer) + 1);
  22921. }
  22922. jg->notePending();
  22923. memcpy(outputBuffer, extracted, indexReadSize);
  22924. if (!slavePart)
  22925. {
  22926. for (unsigned i = 1; i < numChannels; i++)
  22927. jg->notePending();
  22928. }
  22929. if (locallySorted)
  22930. break;
  22931. }
  22932. }
  22933. }
  22934. else
  22935. {
  22936. // MORE - this code seems to be duplicated in half keyed
  22937. unsigned accepted = 0;
  22938. unsigned rejected = 0;
  22939. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), true);
  22940. jg->notePending();
  22941. unsigned candidateCount = 0;
  22942. ScopedAtomic<unsigned> indexRecordsRead(::indexRecordsRead);
  22943. ScopedAtomic<unsigned> postFiltered(::postFiltered);
  22944. while (tlk->lookup(true))
  22945. {
  22946. candidateCount++;
  22947. indexRecordsRead++;
  22948. KLBlobProviderAdapter adapter(tlk);
  22949. const byte *indexRow = tlk->queryKeyBuffer();
  22950. size_t fposOffset = tlk->queryRowSize() - sizeof(offset_t);
  22951. offset_t fpos = rtlReadBigUInt8(indexRow + fposOffset);
  22952. if (helper.indexReadMatch(extracted, indexRow, &adapter))
  22953. {
  22954. KeyedJoinHeader *rhs = (KeyedJoinHeader *) ctx->queryRowManager().allocate(KEYEDJOIN_RECORD_SIZE(0), activityId);
  22955. rhs->fpos = fpos;
  22956. rhs->thisGroup = jg;
  22957. rhs->partNo = partNo;
  22958. result->append(rhs);
  22959. }
  22960. else
  22961. {
  22962. rejected++;
  22963. postFiltered++;
  22964. }
  22965. }
  22966. // output an end marker for the matches to this group
  22967. KeyedJoinHeader *endMarker = (KeyedJoinHeader *) ctx->queryRowManager().allocate(KEYEDJOIN_RECORD_SIZE(0), activityId);
  22968. endMarker->fpos = (offset_t) candidateCount;
  22969. endMarker->thisGroup = jg;
  22970. endMarker->partNo = (unsigned short) -1;
  22971. result->append(endMarker);
  22972. remote.injectResult(result.getClear());
  22973. if (accepted)
  22974. noteStatistic(StNumIndexAccepted, accepted);
  22975. if (rejected)
  22976. noteStatistic(StNumIndexRejected, rejected);
  22977. }
  22978. if (++fileNo < thisBase->numParts())
  22979. {
  22980. thisKey = thisBase->queryPart(fileNo);
  22981. tlk->setKey(thisKey);
  22982. if (!thisKey->isTopLevelKey())
  22983. tlk->setLayoutTranslator(translators->queryTranslator(fileNo));
  22984. else
  22985. tlk->setLayoutTranslator(nullptr);
  22986. tlk->reset();
  22987. }
  22988. else
  22989. break;
  22990. }
  22991. tlk->releaseSegmentMonitors();
  22992. tlk->setKey(NULL);
  22993. }
  22994. catch (...)
  22995. {
  22996. tlk->releaseSegmentMonitors();
  22997. tlk->setKey(NULL);
  22998. throw;
  22999. }
  23000. }
  23001. }
  23002. joinHandler->noteEndReceived(jg, 0);
  23003. }
  23004. else
  23005. {
  23006. joinHandler->noteEndReceived(joinHandler->createJoinGroup(row), 0);
  23007. }
  23008. }
  23009. void processGroup(const ConstPointerArray &)
  23010. {
  23011. throwUnexpected();
  23012. }
  23013. virtual void processEOG()
  23014. {
  23015. joinHandler->processEOG();
  23016. }
  23017. virtual void processDone()
  23018. {
  23019. // called from puller thread
  23020. remote.flush();
  23021. remote.senddone();
  23022. }
  23023. virtual void onLimitExceeded(bool isKeyed)
  23024. {
  23025. if (traceLevel > 4)
  23026. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  23027. if (isKeyed)
  23028. throwUnexpected();
  23029. helper.onLimitExceeded();
  23030. }
  23031. virtual const void *createLimitFailRow(bool isKeyed)
  23032. {
  23033. throwUnexpected();
  23034. }
  23035. virtual bool fireException(IException *e)
  23036. {
  23037. // called from puller thread on failure
  23038. remote.fireException(LINK(e));
  23039. return joinHandler->fireException(e);
  23040. }
  23041. virtual const void *nextRow()
  23042. {
  23043. throwUnexpected(); // I am nobody's input
  23044. }
  23045. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  23046. {
  23047. CRoxieServerActivity::gatherStats(merged);
  23048. remote.gatherStats(merged);
  23049. if (indexReadAllocator)
  23050. indexReadAllocator->gatherStats(merged);
  23051. }
  23052. };
  23053. class CRoxieServerKeyedJoinBase : public CRoxieServerActivity, implements IRecordPullerCallback, implements IRoxieServerErrorHandler, implements IJoinProcessor
  23054. {
  23055. protected:
  23056. IHThorKeyedJoinArg &helper;
  23057. KeyedJoinRemoteAdaptor remote;
  23058. RecordPullerThread puller;
  23059. OwnedConstRoxieRow defaultRight;
  23060. Owned<IEngineRowAllocator> defaultRightAllocator;
  23061. unsigned joinFlags;
  23062. unsigned atMost;
  23063. unsigned atmostsTriggered;
  23064. unsigned abortLimit;
  23065. unsigned keepLimit;
  23066. bool limitFail;
  23067. bool limitOnFail;
  23068. bool preserveGroups;
  23069. bool cloneLeft;
  23070. bool isSimple;
  23071. bool isLocal;
  23072. ThorActivityKind activityKind;
  23073. CJoinGroup *groupStart;
  23074. CriticalSection groupsCrit;
  23075. QueueOf<CJoinGroup, false> groups;
  23076. IFinalRoxieInput *indexReadInput;
  23077. unsigned indexReadIdx = 0;
  23078. Owned<IStrandJunction> indexReadJunction;
  23079. IEngineRowStream *indexReadStream = NULL; // Never actually pulled
  23080. IIndexReadActivityInfo *rootIndex;
  23081. void createDefaultRight()
  23082. {
  23083. if (!defaultRight)
  23084. {
  23085. if (!defaultRightAllocator)
  23086. defaultRightAllocator.setown(createRowAllocator(helper.queryJoinFieldsRecordSize()));
  23087. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  23088. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  23089. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  23090. }
  23091. }
  23092. public:
  23093. CRoxieServerKeyedJoinBase(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _joinFlags
  23094. , bool isFull, bool _isSimple, bool _isLocal)
  23095. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  23096. helper((IHThorKeyedJoinArg &)basehelper),
  23097. remote(_ctx, this, _remoteId, helper, *this, isFull, _isSimple, puller, *this),
  23098. joinFlags(_joinFlags),
  23099. preserveGroups(meta.isGrouped()),
  23100. puller(false),
  23101. isSimple(_isSimple),
  23102. isLocal(_isLocal),
  23103. abortLimit(0),
  23104. keepLimit(0),
  23105. atMost(0),
  23106. limitFail(false),
  23107. limitOnFail(false),
  23108. cloneLeft(false)
  23109. {
  23110. groupStart = NULL;
  23111. activityKind = _factory->getKind();
  23112. indexReadInput = NULL;
  23113. rootIndex = NULL;
  23114. atmostsTriggered = 0;
  23115. // MORE - code would be easier to read if I got more values from helper rather than passing from factory
  23116. }
  23117. virtual void onCreate(IHThorArg *_colocalParent)
  23118. {
  23119. CRoxieServerActivity::onCreate(_colocalParent);
  23120. remote.onCreate(_colocalParent);
  23121. }
  23122. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  23123. {
  23124. if (!idx)
  23125. puller.setInput(this, _sourceIdx, _in);
  23126. else if (idx==1)
  23127. {
  23128. indexReadInput = _in;
  23129. indexReadIdx = _sourceIdx;
  23130. }
  23131. else
  23132. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
  23133. }
  23134. virtual void connectInputStreams(bool consumerOrdered)
  23135. {
  23136. CRoxieServerActivity::connectInputStreams(consumerOrdered);
  23137. puller.connectInputStreams(ctx, consumerOrdered);
  23138. if (indexReadInput)
  23139. indexReadStream = connectSingleStream(ctx, indexReadInput, indexReadIdx, indexReadJunction, consumerOrdered); // We never actually pull the stream
  23140. }
  23141. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  23142. {
  23143. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  23144. if (indexReadInput)
  23145. {
  23146. indexReadInput->start(parentExtractSize, parentExtract, true); // paused=true because we don't want to actually run the index read
  23147. rootIndex = indexReadInput->queryIndexReadActivity();
  23148. if (!rootIndex)
  23149. throw MakeStringException(ROXIE_INTERNAL_ERROR,"Index in keyed join %d could not be resolved", queryId());
  23150. }
  23151. remote.onStart(parentExtractSize, parentExtract);
  23152. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  23153. atmostsTriggered = 0;
  23154. atMost = helper.getJoinLimit();
  23155. if (atMost == 0) atMost = (unsigned)-1;
  23156. abortLimit = helper.getMatchAbortLimit();
  23157. if (abortLimit == 0 || atMost != (unsigned) -1) abortLimit = (unsigned)-1;
  23158. keepLimit = helper.getKeepLimit();
  23159. if (keepLimit == 0) keepLimit = (unsigned)-1;
  23160. getLimitType(joinFlags, limitFail, limitOnFail);
  23161. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  23162. if ((joinFlags & JFleftouter) || limitOnFail)
  23163. createDefaultRight();
  23164. }
  23165. virtual void stop()
  23166. {
  23167. puller.stop();
  23168. if (indexReadStream)
  23169. indexReadStream->stop(); // Could probably do this as soon as re have fetched rootIndex?
  23170. CRoxieServerActivity::stop();
  23171. }
  23172. virtual unsigned __int64 queryLocalCycles() const
  23173. {
  23174. __int64 localCycles = remote.totalCycles.totalCycles;
  23175. localCycles -= puller.queryTotalCycles(); // MORE - debatable... but probably fair.
  23176. if (localCycles < 0)
  23177. localCycles = 0;
  23178. return localCycles;
  23179. }
  23180. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  23181. {
  23182. CRoxieServerActivity::gatherStats(merged);
  23183. remote.gatherStats(merged);
  23184. }
  23185. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  23186. {
  23187. if (idx==0)
  23188. return puller.queryInput();
  23189. else if (idx==1)
  23190. return indexReadInput;
  23191. else
  23192. return NULL;
  23193. }
  23194. virtual void reset()
  23195. {
  23196. totalCycles.totalCycles = remote.totalCycles.totalCycles;
  23197. remote.totalCycles.totalCycles = 0;
  23198. processed = remote.joinProcessed;
  23199. remote.joinProcessed = 0;
  23200. defaultRight.clear();
  23201. if (indexReadInput)
  23202. indexReadInput->reset();
  23203. if (atmostsTriggered)
  23204. noteStatistic(StNumAtmostTriggered, atmostsTriggered);
  23205. CRoxieServerActivity::reset();
  23206. puller.reset();
  23207. while (groups.ordinality())
  23208. {
  23209. ::Release(groups.dequeue());
  23210. }
  23211. }
  23212. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  23213. {
  23214. if (idx==(unsigned)-1)
  23215. idx = 0;
  23216. return idx ? NULL : &remote;
  23217. }
  23218. virtual CJoinGroup *createJoinGroup(const void *row)
  23219. {
  23220. // NOTE - we need to protect access to queue, since it's also modified by consumer thread. Groupstart is only modified by puller thread.
  23221. CriticalBlock c(groupsCrit);
  23222. if (preserveGroups && !groupStart)
  23223. {
  23224. groupStart = new (&ctx->queryRowManager(), activityId) CJoinGroup(NULL, NULL);
  23225. groups.enqueue(groupStart);
  23226. }
  23227. CJoinGroup *jg = new (&ctx->queryRowManager(), activityId) CJoinGroup(row, groupStart);
  23228. groups.enqueue(jg);
  23229. return jg;
  23230. }
  23231. void endGroup()
  23232. {
  23233. CriticalBlock c(groupsCrit);
  23234. if (groupStart)
  23235. noteEndReceived(groupStart, 0);
  23236. groupStart = NULL;
  23237. }
  23238. virtual void noteEndReceived(CJoinGroup *jg, unsigned candidateCount)
  23239. {
  23240. if (jg->noteEndReceived(candidateCount))
  23241. processCompletedGroups();
  23242. }
  23243. void processCompletedGroups()
  23244. {
  23245. CriticalBlock c(groupsCrit);
  23246. while (groups.ordinality())
  23247. {
  23248. if (!groups.head()->complete())
  23249. break;
  23250. Owned<CJoinGroup> head = groups.dequeue();
  23251. if (preserveGroups)
  23252. {
  23253. assert(head->isHeadRecord());
  23254. assert(groups.head()->inGroup(head));
  23255. unsigned joinGroupSize = 0;
  23256. while (groups.ordinality() && groups.head()->inGroup(head))
  23257. {
  23258. Owned<CJoinGroup> finger = groups.dequeue();
  23259. joinGroupSize += doJoinGroup(finger);
  23260. }
  23261. if (joinGroupSize)
  23262. remote.addResult(NULL);
  23263. }
  23264. else
  23265. doJoinGroup(head);
  23266. }
  23267. }
  23268. void failLimit(const void * left)
  23269. {
  23270. helper.onMatchAbortLimitExceeded();
  23271. CommonXmlWriter xmlwrite(0);
  23272. if (input && input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  23273. {
  23274. input->queryOutputMeta()->toXML((byte *) left, xmlwrite);
  23275. }
  23276. throw MakeStringException(ROXIE_JOIN_ERROR, "More than %d match candidates in keyed join %d for row %s", abortLimit, queryId(), xmlwrite.str());
  23277. }
  23278. virtual bool needsAllocator() const { return true; }
  23279. unsigned doTransform(const void *left, const void *right, offset_t fpos_or_count, IException *except, const void **group, unsigned counter)
  23280. {
  23281. if (cloneLeft && !except)
  23282. {
  23283. LinkRoxieRow(left);
  23284. remote.addResult((void *) left);
  23285. return 1;
  23286. }
  23287. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  23288. unsigned outSize;
  23289. try
  23290. {
  23291. outSize = except ? helper.onFailTransform(rowBuilder, left, right, fpos_or_count, except) :
  23292. (activityKind == TAKkeyeddenormalizegroup) ? helper.transform(rowBuilder, left, right, (unsigned)fpos_or_count, group) :
  23293. helper.transform(rowBuilder, left, right, fpos_or_count, counter);
  23294. }
  23295. catch (IException *E)
  23296. {
  23297. throw makeWrappedException(E);
  23298. }
  23299. if (outSize)
  23300. {
  23301. const void *shrunk = rowBuilder.finalizeRowClear(outSize);
  23302. remote.addResult(shrunk);
  23303. return 1;
  23304. }
  23305. else
  23306. return 0;
  23307. }
  23308. unsigned doJoinGroup(CJoinGroup *jg)
  23309. {
  23310. unsigned matched = jg->rowsSeen();
  23311. unsigned added = 0;
  23312. const void *left = jg->queryLeft();
  23313. if (jg->candidateCount() > abortLimit)
  23314. {
  23315. if (limitFail)
  23316. failLimit(left);
  23317. if (ctx->queryDebugContext())
  23318. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  23319. if (limitOnFail)
  23320. {
  23321. Owned<IException> except;
  23322. try
  23323. {
  23324. failLimit(left);
  23325. }
  23326. catch(IException * e)
  23327. {
  23328. except.setown(e);
  23329. }
  23330. added = doTransform(left, defaultRight, 0, except, NULL, 0);
  23331. }
  23332. }
  23333. else if (!matched || jg->candidateCount() > atMost)
  23334. {
  23335. if (jg->candidateCount() > atMost)
  23336. atmostsTriggered++;
  23337. switch (joinFlags & JFtypemask)
  23338. {
  23339. case JFleftouter:
  23340. case JFleftonly:
  23341. switch (activityKind)
  23342. {
  23343. case TAKkeyedjoin:
  23344. case TAKkeyeddenormalizegroup:
  23345. added = doTransform(left, defaultRight, 0, NULL, NULL, 0);
  23346. break;
  23347. case TAKkeyeddenormalize:
  23348. LinkRoxieRow(left);
  23349. remote.addResult((void *) left);
  23350. added++;
  23351. break;
  23352. }
  23353. break;
  23354. }
  23355. }
  23356. else if (!(joinFlags & JFexclude))
  23357. {
  23358. unsigned idx = 0;
  23359. switch (activityKind)
  23360. {
  23361. case TAKkeyedjoin:
  23362. while (idx < matched)
  23363. {
  23364. const KeyedJoinHeader *rhs = jg->queryRow(idx);
  23365. added += doTransform(left, &rhs->rhsdata, 0, NULL, NULL, idx+1);
  23366. if (added==keepLimit)
  23367. break;
  23368. idx++;
  23369. }
  23370. break;
  23371. case TAKkeyeddenormalize:
  23372. {
  23373. OwnedConstRoxieRow newLeft;
  23374. newLeft.set(left);
  23375. unsigned rowSize = 0;
  23376. unsigned rightAdded = 0;
  23377. while (idx < matched)
  23378. {
  23379. const KeyedJoinHeader *rhs = jg->queryRow(idx);
  23380. try
  23381. {
  23382. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  23383. size32_t transformedSize = helper.transform(rowBuilder, newLeft, &rhs->rhsdata, rhs->fpos, idx+1);
  23384. if (transformedSize)
  23385. {
  23386. rowSize = transformedSize;
  23387. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  23388. rightAdded++;
  23389. if (rightAdded==keepLimit)
  23390. break;
  23391. }
  23392. idx++;
  23393. }
  23394. catch (IException *E)
  23395. {
  23396. throw makeWrappedException(E);
  23397. }
  23398. }
  23399. if (rowSize)
  23400. {
  23401. remote.addResult(newLeft.getClear());
  23402. added++;
  23403. }
  23404. }
  23405. break;
  23406. case TAKkeyeddenormalizegroup:
  23407. {
  23408. ConstPointerArray extractedRows;
  23409. while (idx < matched && idx < keepLimit)
  23410. {
  23411. const KeyedJoinHeader *rhs = jg->queryRow(idx);
  23412. extractedRows.append((void *) &rhs->rhsdata);
  23413. idx++;
  23414. }
  23415. added += doTransform(left, extractedRows.item(0), extractedRows.ordinality(), NULL, (const void * *)extractedRows.getArray(), 0);
  23416. }
  23417. break;
  23418. }
  23419. }
  23420. return added;
  23421. }
  23422. virtual void processDone()
  23423. {
  23424. // called from puller thread
  23425. remote.flush();
  23426. remote.senddone();
  23427. }
  23428. virtual void onLimitExceeded(bool isKeyed)
  23429. {
  23430. if (traceLevel > 4)
  23431. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  23432. if (isKeyed)
  23433. throwUnexpected();
  23434. helper.onLimitExceeded();
  23435. }
  23436. virtual const void *createLimitFailRow(bool isKeyed)
  23437. {
  23438. throwUnexpected();
  23439. }
  23440. virtual bool fireException(IException *e)
  23441. {
  23442. // called from puller thread on failure
  23443. return remote.fireException(e);
  23444. }
  23445. virtual const void *nextRow()
  23446. {
  23447. throwUnexpected(); // I am nobody's input
  23448. }
  23449. };
  23450. #ifdef _MSC_VER
  23451. #pragma warning ( push )
  23452. #pragma warning ( disable: 4355 )
  23453. #endif
  23454. class CRoxieServerKeyedJoinActivity : public CRoxieServerKeyedJoinBase
  23455. {
  23456. CRoxieServerFullKeyedJoinHead head;
  23457. Owned<IEngineRowAllocator> fetchInputAllocator;
  23458. Linked<IFilePartMap> map;
  23459. bool variableFetchFileName;
  23460. Owned<const IResolvedFile> varFetchFileInfo;
  23461. CachedOutputMetaData fetchInputFields;
  23462. public:
  23463. CRoxieServerKeyedJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_headId, IKeyArray * _key, ITranslatorSet *_keyTranslators, IOutputMetaData *_indexReadMeta,
  23464. const RemoteActivityId &_tailId, IFilePartMap *_map, unsigned _joinFlags, bool _isLocal)
  23465. : CRoxieServerKeyedJoinBase(_ctx, _factory, _probeManager, _tailId, _joinFlags, true, false, _isLocal),
  23466. head(_ctx, _factory, _probeManager, _headId, _key, _keyTranslators, _indexReadMeta, this, _isLocal),
  23467. map(_map)
  23468. {
  23469. CRoxieServerKeyedJoinBase::setInput(0, 0, head.queryOutput(0));
  23470. variableFetchFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  23471. }
  23472. virtual const IResolvedFile *queryVarFileInfo() const
  23473. {
  23474. return varFetchFileInfo;
  23475. }
  23476. virtual void onCreate(IHThorArg *_colocalParent)
  23477. {
  23478. CRoxieServerKeyedJoinBase::onCreate(_colocalParent);
  23479. head.onCreate(_colocalParent);
  23480. fetchInputFields.set(helper.queryFetchInputRecordSize());
  23481. fetchInputAllocator.setown(createRowAllocator(helper.queryFetchInputRecordSize()));
  23482. }
  23483. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  23484. {
  23485. CRoxieServerKeyedJoinBase::start(parentExtractSize, parentExtract, paused);
  23486. if (variableFetchFileName)
  23487. {
  23488. bool isFetchOpt = (helper.getFetchFlags() & FFdatafileoptional) != 0;
  23489. OwnedRoxieString fname(helper.getFileName());
  23490. varFetchFileInfo.setown(resolveLFNFlat(fname, isFetchOpt));
  23491. if (varFetchFileInfo)
  23492. {
  23493. // Note - we don't need to do any translation on the disk part of full-keyed joins
  23494. map.setown(varFetchFileInfo->getFileMap());
  23495. }
  23496. }
  23497. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().keyedJoinPreload, false, ctx);
  23498. }
  23499. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  23500. {
  23501. head.setInput(idx, _sourceIdx, _in);
  23502. }
  23503. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  23504. {
  23505. connectInputStreams(consumerOrdered);
  23506. return head.getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
  23507. }
  23508. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  23509. {
  23510. return head.queryInput(idx);
  23511. }
  23512. virtual void processRow(const void *_rhs)
  23513. {
  23514. // called from puller thread
  23515. KeyedJoinHeader *rhs = (KeyedJoinHeader *) _rhs;
  23516. CJoinGroup *jg = rhs->thisGroup;
  23517. if (rhs->partNo != (unsigned short) -1)
  23518. {
  23519. unsigned partNo = map->mapOffset(rhs->fpos);
  23520. RtlDynamicRowBuilder fetchBuilder(fetchInputAllocator, true);
  23521. size32_t fisize = helper.extractFetchFields(fetchBuilder, jg->queryLeft());
  23522. if (fetchInputFields.isVariableSize())
  23523. {
  23524. KeyedJoinHeader *outRow = (KeyedJoinHeader *) remote.getMem(partNo, 0, KEYEDJOIN_RECORD_SIZE(fisize + sizeof(fisize)));
  23525. memcpy(outRow, rhs, KEYEDJOIN_RECORD_SIZE(0)); // MORE - copy constructor might be more appropriate....
  23526. ReleaseRoxieRow(rhs);
  23527. jg->notePending();
  23528. memcpy(&outRow->rhsdata, &fisize, sizeof(fisize));
  23529. memcpy((&outRow->rhsdata)+sizeof(fisize), fetchBuilder.row(), fisize);
  23530. }
  23531. else
  23532. {
  23533. KeyedJoinHeader *outRow = (KeyedJoinHeader *) remote.getMem(partNo, 0, KEYEDJOIN_RECORD_SIZE(fisize));
  23534. memcpy(outRow, rhs, KEYEDJOIN_RECORD_SIZE(0)); // MORE - copy constructor might be more appropriate....
  23535. ReleaseRoxieRow(rhs);
  23536. jg->notePending();
  23537. memcpy(&outRow->rhsdata, fetchBuilder.row(), fisize);
  23538. }
  23539. }
  23540. else
  23541. {
  23542. unsigned candidateCount = (unsigned) rhs->fpos;
  23543. // CTXLOG("Full keyed join - all results back from index");
  23544. ReleaseRoxieRow(rhs);
  23545. noteEndReceived(jg, candidateCount); // may throw exception - so release row before calling
  23546. }
  23547. }
  23548. virtual void processEOG()
  23549. {
  23550. // called from front puller thread
  23551. if (preserveGroups)
  23552. endGroup();
  23553. }
  23554. void processGroup(const ConstPointerArray &)
  23555. {
  23556. throwUnexpected();
  23557. }
  23558. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  23559. {
  23560. CRoxieServerKeyedJoinBase::gatherStats(merged);
  23561. if (fetchInputAllocator)
  23562. fetchInputAllocator->gatherStats(merged);
  23563. }
  23564. };
  23565. #ifdef _MSC_VER
  23566. #pragma warning ( pop )
  23567. #endif
  23568. class CRoxieServerHalfKeyedJoinActivity : public CRoxieServerKeyedJoinBase
  23569. {
  23570. IOutputMetaData *indexReadMeta;
  23571. Owned<IEngineRowAllocator> indexReadAllocator;
  23572. Owned<IKeyManager> tlk;
  23573. bool variableIndexFileName;
  23574. bool indexReadInputRecordVariable;
  23575. Owned<const IResolvedFile> varFileInfo;
  23576. Linked<ITranslatorSet> translators;
  23577. Linked<IKeyArray> keySet;
  23578. Owned<IOutputMetaData> joinPrefixedMeta;
  23579. Owned<IEngineRowAllocator> joinFieldsAllocator;
  23580. public:
  23581. CRoxieServerHalfKeyedJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IKeyArray * _keySet, ITranslatorSet *_translators,
  23582. IOutputMetaData *_indexReadMeta, unsigned _joinFlags, bool _isSimple, bool _isLocal)
  23583. : CRoxieServerKeyedJoinBase(_ctx, _factory, _probeManager, _remoteId, _joinFlags, false, _isSimple, _isLocal),
  23584. indexReadMeta(_indexReadMeta),
  23585. tlk(createLocalKeyManager(helper.queryIndexRecordSize()->queryRecordAccessor(true), NULL, this, helper.hasNewSegmentMonitors())),
  23586. keySet(_keySet),
  23587. translators(_translators)
  23588. {
  23589. variableIndexFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getJoinFlags() & (JFvarindexfilename|JFdynamicindexfilename|JFindexfromactivity)) != 0);
  23590. indexReadInputRecordVariable = indexReadMeta->isVariableSize();
  23591. }
  23592. virtual void serializeExtra(MemoryBuffer &out)
  23593. {
  23594. if (helper.getJoinFlags() & JFindexfromactivity)
  23595. {
  23596. assertex(rootIndex);
  23597. const RemoteActivityId& indexId = rootIndex->queryRemoteId();
  23598. indexId.serialize(out);
  23599. // could mess about reserving space for length then patching it again, to avoid copy, but probably not worth it
  23600. MemoryBuffer tmp;
  23601. rootIndex->queryActivity()->serializeCreateStartContext(tmp);
  23602. if (rootIndex->queryActivity()->queryVarFileInfo())
  23603. {
  23604. rootIndex->queryActivity()->queryVarFileInfo()->queryTimeStamp().serialize(tmp);
  23605. tmp.append(rootIndex->queryActivity()->queryVarFileInfo()->queryCheckSum());
  23606. }
  23607. unsigned ctxlen = tmp.length();
  23608. out.append(ctxlen).append(tmp);
  23609. }
  23610. }
  23611. virtual void onCreate(IHThorArg *_colocalParent)
  23612. {
  23613. CRoxieServerKeyedJoinBase::onCreate(_colocalParent);
  23614. indexReadAllocator.setown(createRowAllocator(indexReadMeta));
  23615. IOutputMetaData *joinFieldsMeta = helper.queryJoinFieldsRecordSize();
  23616. joinPrefixedMeta.setown(new CPrefixedOutputMeta(KEYEDJOIN_RECORD_SIZE(0), joinFieldsMeta)); // MORE - not sure if we really need this
  23617. joinFieldsAllocator.setown(createRowAllocator(joinPrefixedMeta));
  23618. }
  23619. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  23620. {
  23621. CRoxieServerKeyedJoinBase::start(parentExtractSize, parentExtract, paused);
  23622. if (rootIndex)
  23623. {
  23624. varFileInfo.setown(rootIndex->getVarFileInfo());
  23625. translators.setown(rootIndex->getTranslators());
  23626. keySet.setown(rootIndex->getKeySet());
  23627. }
  23628. else if (variableIndexFileName)
  23629. {
  23630. OwnedRoxieString indexFileName(helper.getIndexFileName());
  23631. varFileInfo.setown(resolveLFNIndex(indexFileName, (helper.getJoinFlags() & JFindexoptional) != 0));
  23632. if (varFileInfo)
  23633. {
  23634. unsigned formatCrc = helper.getIndexFormatCrc();
  23635. translators.setown(varFileInfo->getTranslators(formatCrc, skipFileFormatCrcCheck(), helper.queryProjectedIndexRecordSize(), helper.queryIndexRecordSize(), getEnableFieldTranslation(), true));
  23636. keySet.setown(varFileInfo->getKeyArray(false, isLocal ? factory->queryQueryFactory().queryChannel() : 0));
  23637. }
  23638. }
  23639. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().keyedJoinPreload, isSimple, ctx);
  23640. }
  23641. virtual const IResolvedFile *queryVarFileInfo() const
  23642. {
  23643. return varFileInfo;
  23644. }
  23645. virtual void reset()
  23646. {
  23647. CRoxieServerKeyedJoinBase::reset();
  23648. if (varFileInfo)
  23649. {
  23650. keySet.clear();
  23651. varFileInfo.clear();
  23652. }
  23653. }
  23654. virtual void processRow(const void *row)
  23655. {
  23656. // called from front puller thread
  23657. // buffer up an IndexRead request
  23658. if (keySet && helper.leftCanMatch(row))
  23659. {
  23660. RtlDynamicRowBuilder extractBuilder(indexReadAllocator);
  23661. unsigned indexReadRecordSize = helper.extractIndexReadFields(extractBuilder, row);
  23662. OwnedConstRoxieRow extracted;
  23663. if (indexReadRecordSize)
  23664. extracted.setown(extractBuilder.finalizeRowClear(indexReadRecordSize));
  23665. CJoinGroup *jg = createJoinGroup(row);
  23666. for (unsigned partNo = 0; partNo < keySet->length(); partNo++)
  23667. {
  23668. IKeyIndexBase *thisBase = keySet->queryKeyPart(partNo);
  23669. if (thisBase)
  23670. {
  23671. unsigned fileNo = 0;
  23672. IKeyIndex *thisKey = thisBase->queryPart(fileNo);
  23673. tlk->setKey(thisKey);
  23674. if (thisKey && !thisKey->isTopLevelKey())
  23675. tlk->setLayoutTranslator(translators->queryTranslator(fileNo));
  23676. else
  23677. tlk->setLayoutTranslator(nullptr);
  23678. helper.createSegmentMonitors(tlk, extracted);
  23679. if (rootIndex)
  23680. rootIndex->mergeSegmentMonitors(tlk);
  23681. tlk->finishSegmentMonitors();
  23682. try
  23683. {
  23684. tlk->reset();
  23685. for (;;)
  23686. {
  23687. typedef const void * cvp;
  23688. if (thisKey && thisKey->isTopLevelKey())
  23689. {
  23690. bool locallySorted = (!thisKey->isFullySorted());
  23691. while (locallySorted || tlk->lookup(false))
  23692. {
  23693. unsigned slavePart = locallySorted ? tlk->getPartition() : (unsigned)extractFpos(tlk);
  23694. if (locallySorted || slavePart)
  23695. {
  23696. cvp *outputBuffer = (cvp *) remote.getMem(slavePart, fileNo, indexReadRecordSize + sizeof(cvp) + (indexReadInputRecordVariable ? sizeof(unsigned) : 0));
  23697. *outputBuffer++ = jg;
  23698. if (indexReadInputRecordVariable)
  23699. {
  23700. *(unsigned *) outputBuffer = indexReadRecordSize;
  23701. outputBuffer = (cvp *) (((unsigned *) outputBuffer) + 1);
  23702. }
  23703. jg->notePending();
  23704. memcpy(outputBuffer, extracted, indexReadRecordSize);
  23705. if (!slavePart)
  23706. {
  23707. for (unsigned i = 1; i < numChannels; i++)
  23708. jg->notePending();
  23709. }
  23710. if (locallySorted)
  23711. break;
  23712. }
  23713. }
  23714. }
  23715. else
  23716. {
  23717. unsigned accepted = 0;
  23718. unsigned rejected = 0;
  23719. Owned<CRowArrayMessageResult> result;
  23720. if (!isSimple)
  23721. result.setown(new CRowArrayMessageResult(ctx->queryRowManager(), true));
  23722. // MORE - This code seems to be duplicated in keyedJoinHead
  23723. jg->notePending();
  23724. unsigned candidateCount = 0;
  23725. ScopedAtomic<unsigned> indexRecordsRead(::indexRecordsRead);
  23726. ScopedAtomic<unsigned> postFiltered(::postFiltered);
  23727. while (tlk->lookup(true))
  23728. {
  23729. candidateCount++;
  23730. indexRecordsRead++;
  23731. KLBlobProviderAdapter adapter(tlk);
  23732. const byte *indexRow = tlk->queryKeyBuffer();
  23733. size_t fposOffset = tlk->queryRowSize() - sizeof(offset_t);
  23734. offset_t fpos = rtlReadBigUInt8(indexRow + fposOffset);
  23735. if (helper.indexReadMatch(extracted, indexRow, &adapter))
  23736. {
  23737. RtlDynamicRowBuilder rb(joinFieldsAllocator, true);
  23738. CPrefixedRowBuilder pb(KEYEDJOIN_RECORD_SIZE(0), rb);
  23739. accepted++;
  23740. KLBlobProviderAdapter adapter(tlk);
  23741. size32_t joinFieldsSize = helper.extractJoinFields(pb, indexRow, &adapter);
  23742. KeyedJoinHeader *rec = (KeyedJoinHeader *) rb.getUnfinalizedClear(); // lack of finalize ok as unserialized data here.
  23743. rec->fpos = fpos;
  23744. rec->thisGroup = jg;
  23745. rec->partNo = partNo;
  23746. if (isSimple)
  23747. remote.injected.enqueue(rec);
  23748. else
  23749. result->append(rec);
  23750. }
  23751. else
  23752. {
  23753. rejected++;
  23754. postFiltered++;
  23755. }
  23756. }
  23757. // output an end marker for the matches to this group
  23758. KeyedJoinHeader *rec = (KeyedJoinHeader *) ctx->queryRowManager().allocate(KEYEDJOIN_RECORD_SIZE(0), activityId);
  23759. rec->fpos = (offset_t) candidateCount;
  23760. rec->thisGroup = jg;
  23761. rec->partNo = (unsigned short) -1;
  23762. if (isSimple)
  23763. remote.injected.enqueue(rec);
  23764. else
  23765. {
  23766. result->append(rec);
  23767. remote.injectResult(result.getClear());
  23768. }
  23769. if (accepted)
  23770. noteStatistic(StNumIndexAccepted, accepted);
  23771. if (rejected)
  23772. noteStatistic(StNumIndexRejected, rejected);
  23773. }
  23774. if (++fileNo < thisBase->numParts())
  23775. {
  23776. thisKey = thisBase->queryPart(fileNo);
  23777. tlk->setKey(thisKey);
  23778. if (thisKey && !thisKey->isTopLevelKey())
  23779. tlk->setLayoutTranslator(translators->queryTranslator(fileNo));
  23780. else
  23781. tlk->setLayoutTranslator(nullptr);
  23782. tlk->reset();
  23783. }
  23784. else
  23785. break;
  23786. }
  23787. tlk->releaseSegmentMonitors();
  23788. tlk->setKey(NULL);
  23789. }
  23790. catch (...)
  23791. {
  23792. tlk->releaseSegmentMonitors();
  23793. tlk->setKey(NULL);
  23794. throw;
  23795. }
  23796. }
  23797. }
  23798. noteEndReceived(jg, 0);
  23799. }
  23800. else
  23801. {
  23802. noteEndReceived(createJoinGroup(row), 0);
  23803. }
  23804. }
  23805. virtual void processEOG()
  23806. {
  23807. // called from front puller thread
  23808. if (preserveGroups)
  23809. endGroup();
  23810. }
  23811. void processGroup(const ConstPointerArray &)
  23812. {
  23813. throwUnexpected();
  23814. }
  23815. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  23816. {
  23817. CRoxieServerKeyedJoinBase::gatherStats(merged);
  23818. if (indexReadAllocator)
  23819. indexReadAllocator->gatherStats(merged);
  23820. if (joinFieldsAllocator)
  23821. joinFieldsAllocator->gatherStats(merged);
  23822. }
  23823. };
  23824. class CRoxieServerKeyedJoinActivityFactory : public CRoxieServerMultiInputFactory
  23825. {
  23826. Owned<const IResolvedFile> indexfile;
  23827. Owned<const IResolvedFile> datafile;
  23828. Owned<IKeyArray> keySet;
  23829. Owned<ITranslatorSet> keyTranslators; // For the indexes
  23830. RemoteActivityId headId;
  23831. RemoteActivityId tailId;
  23832. IOutputMetaData *indexReadMeta;
  23833. Owned<IFilePartMap> map;
  23834. Owned<ITranslatorSet> translators; // for the disk files on local full keyed joins
  23835. Owned<IFileIOArray> files;
  23836. unsigned joinFlags;
  23837. bool isHalfKeyed;
  23838. bool isLocal;
  23839. bool variableFetchFileName;
  23840. bool variableIndexFileName;
  23841. bool isSimple;
  23842. public:
  23843. CRoxieServerKeyedJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_headId, const RemoteActivityId &_tailId)
  23844. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), headId(_headId), tailId(_tailId)
  23845. {
  23846. Owned<IHThorKeyedJoinArg> helper = (IHThorKeyedJoinArg *) helperFactory();
  23847. isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  23848. isSimple = isLocal;
  23849. rtlDataAttr indexLayoutMeta;
  23850. size32_t indexLayoutSize = 0;
  23851. if(!helper->getIndexLayout(indexLayoutSize, indexLayoutMeta.refdata()))
  23852. assertex(indexLayoutSize== 0);
  23853. joinFlags = helper->getJoinFlags();
  23854. variableIndexFileName = allFilesDynamic || _queryFactory.isDynamic() || ((joinFlags & (JFvarindexfilename|JFdynamicindexfilename|JFindexfromactivity)) != 0);
  23855. variableFetchFileName = allFilesDynamic || _queryFactory.isDynamic() || ((helper->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  23856. if (!variableIndexFileName)
  23857. {
  23858. bool isOpt = (joinFlags & JFindexoptional) != 0;
  23859. OwnedRoxieString indexFileName(helper->getIndexFileName());
  23860. indexfile.setown(queryFactory.queryPackage().lookupFileName(indexFileName, isOpt, true, true, queryFactory.queryWorkUnit(), true));
  23861. if (indexfile)
  23862. {
  23863. unsigned formatCrc = helper->getIndexFormatCrc();
  23864. keyTranslators.setown(indexfile->getTranslators(formatCrc, skipFileFormatCrcCheck(), helper->queryProjectedIndexRecordSize(), helper->queryIndexRecordSize(), getEnableFieldTranslation(), true));
  23865. keySet.setown(indexfile->getKeyArray(isOpt, isLocal ? queryFactory.queryChannel() : 0));
  23866. }
  23867. }
  23868. if (keySet && keySet->length()==1 && !isSimple)
  23869. {
  23870. IKeyIndexBase *thisBase = keySet->queryKeyPart(0);
  23871. if (thisBase->numParts()==1 && !thisBase->queryPart(0)->isTopLevelKey() && !_queryFactory.queryOptions().disableLocalOptimizations)
  23872. isSimple = true;
  23873. // MORE - if it's a variable filename then it MAY be simple, we don't know. Tough.
  23874. }
  23875. if (!simpleLocalKeyedJoins)
  23876. isSimple = false;
  23877. isHalfKeyed = !helper->diskAccessRequired();
  23878. indexReadMeta = QUERYINTERFACE(helper->queryIndexReadInputRecordSize(), IOutputMetaData);
  23879. if (!isHalfKeyed && !variableFetchFileName)
  23880. {
  23881. bool isFetchOpt = (helper->getFetchFlags() & FFdatafileoptional) != 0;
  23882. datafile.setown(_queryFactory.queryPackage().lookupFileName(queryNodeFileName(_graphNode, _kind), isFetchOpt, true, true, _queryFactory.queryWorkUnit(), true));
  23883. if (datafile)
  23884. {
  23885. if (isLocal) // Not sure this works
  23886. {
  23887. unsigned diskFormatCrc = helper->getDiskFormatCrc();
  23888. translators.setown(datafile->getTranslators(diskFormatCrc, skipFileFormatCrcCheck(), helper->queryProjectedDiskRecordSize(), helper->queryDiskRecordSize(), getEnableFieldTranslation(), false));
  23889. files.setown(datafile->getIFileIOArray(isFetchOpt, queryFactory.queryChannel()));
  23890. }
  23891. else
  23892. map.setown(datafile->getFileMap());
  23893. }
  23894. }
  23895. }
  23896. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  23897. {
  23898. if (isHalfKeyed)
  23899. return new CRoxieServerHalfKeyedJoinActivity(_ctx, this, _probeManager,
  23900. headId, keySet, keyTranslators, indexReadMeta, joinFlags, isSimple, isLocal);
  23901. else
  23902. return new CRoxieServerKeyedJoinActivity(_ctx, this, _probeManager,
  23903. headId, keySet, keyTranslators, indexReadMeta,
  23904. tailId, map, joinFlags, isLocal); // MORE - not sure local variant actually works - should be using files not map, for example?
  23905. }
  23906. virtual const StatisticsMapping &queryStatsMapping() const
  23907. {
  23908. return keyedJoinStatistics;
  23909. }
  23910. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  23911. {
  23912. if (datafile)
  23913. addXrefFileInfo(reply, datafile);
  23914. if (indexfile)
  23915. addXrefFileInfo(reply, indexfile);
  23916. }
  23917. };
  23918. IRoxieServerActivityFactory *createRoxieServerKeyedJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId, const RemoteActivityId &_remoteId2)
  23919. {
  23920. return new CRoxieServerKeyedJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId, _remoteId2);
  23921. }
  23922. //=================================================================================
  23923. class CRoxieServerSoapActivityBase : public CRoxieServerActivity, implements ISoapCallRowProvider, implements IRoxieAbortMonitor
  23924. {
  23925. protected:
  23926. Owned<ISoapCallHelper> soaphelper;
  23927. IHThorSoapActionArg & helper;
  23928. StringBuffer authToken;
  23929. bool eof;
  23930. CriticalSection crit;
  23931. ClientCertificate *pClientCert;
  23932. public:
  23933. IMPLEMENT_IINTERFACE_USING(CRoxieServerActivity)
  23934. CRoxieServerSoapActivityBase(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  23935. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorSoapActionArg &)basehelper)
  23936. {
  23937. eof = false;
  23938. if (clientCert.certificate.length() > 0 && clientCert.privateKey.length() > 0 && clientCert.passphrase.length() > 0)
  23939. pClientCert = &clientCert;
  23940. else
  23941. pClientCert = NULL;
  23942. }
  23943. // ISoapCallRowProvider
  23944. virtual IHThorSoapActionArg * queryActionHelper() { return &helper; };
  23945. virtual IHThorSoapCallArg * queryCallHelper() { return NULL; };
  23946. virtual const void * getNextRow() { return NULL; };
  23947. virtual void releaseRow(const void * r) { ReleaseRoxieRow(r); };
  23948. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  23949. {
  23950. eof = false;
  23951. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  23952. authToken.append(ctx->queryAuthToken());
  23953. }
  23954. virtual void reset()
  23955. {
  23956. // MORE - Shouldn't we make sure thread is stopped etc???
  23957. soaphelper.clear();
  23958. CRoxieServerActivity::reset();
  23959. }
  23960. // IRoxieAbortMonitor
  23961. virtual void checkForAbort() { checkAbort(); }
  23962. };
  23963. //---------------------------------------------------------------------------
  23964. class CRoxieServerSoapRowCallActivity : public CRoxieServerSoapActivityBase
  23965. {
  23966. IHThorSoapCallArg & callHelper;
  23967. public:
  23968. CRoxieServerSoapRowCallActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  23969. : CRoxieServerSoapActivityBase(_ctx, _factory, _probeManager), callHelper((IHThorSoapCallArg &)basehelper)
  23970. {
  23971. }
  23972. virtual IHThorSoapCallArg * queryCallHelper()
  23973. {
  23974. return &callHelper;
  23975. }
  23976. virtual bool needsAllocator() const { return true; }
  23977. virtual const void *nextRow()
  23978. {
  23979. ActivityTimer t(totalCycles, timeActivities);
  23980. if(eof) return NULL;
  23981. if (soaphelper == NULL)
  23982. {
  23983. if (factory->getKind()==TAKhttp_rowdataset)
  23984. soaphelper.setown(createHttpCallHelper(this, rowAllocator, authToken.str(), SCrow, pClientCert, *this, this));
  23985. else
  23986. soaphelper.setown(createSoapCallHelper(this, rowAllocator, authToken.str(), SCrow, pClientCert, *this, this));
  23987. soaphelper->start();
  23988. }
  23989. OwnedConstRoxieRow ret = soaphelper->getRow();
  23990. if (!ret)
  23991. {
  23992. eof = true;
  23993. return NULL;
  23994. }
  23995. ++processed;
  23996. return ret.getClear();
  23997. }
  23998. };
  23999. class CRoxieServerSoapRowCallActivityFactory : public CRoxieServerActivityFactory
  24000. {
  24001. public:
  24002. CRoxieServerSoapRowCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  24003. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  24004. {
  24005. }
  24006. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  24007. {
  24008. return new CRoxieServerSoapRowCallActivity(_ctx, this, _probeManager);
  24009. }
  24010. virtual const StatisticsMapping &queryStatsMapping() const
  24011. {
  24012. return soapStatistics;
  24013. }
  24014. };
  24015. IRoxieServerActivityFactory *createRoxieServerSoapRowCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  24016. {
  24017. return new CRoxieServerSoapRowCallActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  24018. }
  24019. //---------------------------------------------------------------------------
  24020. class CRoxieServerSoapRowActionActivity : public CRoxieServerSoapActivityBase
  24021. {
  24022. public:
  24023. CRoxieServerSoapRowActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  24024. : CRoxieServerSoapActivityBase(_ctx, _factory, _probeManager)
  24025. {}
  24026. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  24027. {
  24028. //MORE: parentExtract not passed to start - although shouldn't be a problem.
  24029. soaphelper.setown(createSoapCallHelper(this, NULL, ctx->queryAuthToken(), SCrow, pClientCert, *this, this));
  24030. soaphelper->start();
  24031. soaphelper->waitUntilDone();
  24032. IException *e = soaphelper->getError();
  24033. soaphelper.clear();
  24034. if (e)
  24035. throw e;
  24036. }
  24037. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  24038. {
  24039. return NULL;
  24040. }
  24041. virtual const void *nextRow()
  24042. {
  24043. throwUnexpected(); // I am nobody's input
  24044. }
  24045. };
  24046. class CRoxieServerSoapRowActionActivityFactory : public CRoxieServerActivityFactory
  24047. {
  24048. bool isRoot;
  24049. public:
  24050. CRoxieServerSoapRowActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  24051. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  24052. {
  24053. }
  24054. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  24055. {
  24056. return new CRoxieServerSoapRowActionActivity(_ctx, this, _probeManager);
  24057. }
  24058. virtual bool isSink() const
  24059. {
  24060. return isRoot;
  24061. }
  24062. virtual const StatisticsMapping &queryStatsMapping() const
  24063. {
  24064. return soapStatistics;
  24065. }
  24066. };
  24067. IRoxieServerActivityFactory *createRoxieServerSoapRowActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  24068. {
  24069. return new CRoxieServerSoapRowActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  24070. }
  24071. //---------------------------------------------------------------------------
  24072. class CRoxieServerSoapDatasetCallActivity : public CRoxieServerSoapActivityBase
  24073. {
  24074. IHThorSoapCallArg & callHelper;
  24075. public:
  24076. CRoxieServerSoapDatasetCallActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  24077. : CRoxieServerSoapActivityBase(_ctx, _factory, _probeManager), callHelper((IHThorSoapCallArg &)basehelper)
  24078. {
  24079. }
  24080. virtual IHThorSoapCallArg * queryCallHelper()
  24081. {
  24082. return &callHelper;
  24083. }
  24084. virtual const void *getNextRow()
  24085. {
  24086. CriticalBlock b(crit); // MORE - why ?
  24087. return inputStream->ungroupedNextRow();
  24088. }
  24089. virtual bool needsAllocator() const { return true; }
  24090. virtual const void *nextRow()
  24091. {
  24092. ActivityTimer t(totalCycles, timeActivities);
  24093. if(eof) return NULL;
  24094. if (soaphelper == NULL)
  24095. {
  24096. soaphelper.setown(createSoapCallHelper(this, rowAllocator, authToken.str(), SCdataset, pClientCert, *this, this));
  24097. soaphelper->start();
  24098. }
  24099. OwnedConstRoxieRow ret = soaphelper->getRow();
  24100. if (!ret)
  24101. {
  24102. eof = true;
  24103. return NULL;
  24104. }
  24105. ++processed;
  24106. return ret.getClear();
  24107. }
  24108. };
  24109. class CRoxieServerSoapDatasetCallActivityFactory : public CRoxieServerActivityFactory
  24110. {
  24111. public:
  24112. CRoxieServerSoapDatasetCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  24113. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  24114. {
  24115. }
  24116. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  24117. {
  24118. return new CRoxieServerSoapDatasetCallActivity(_ctx, this, _probeManager);
  24119. }
  24120. virtual const StatisticsMapping &queryStatsMapping() const
  24121. {
  24122. return soapStatistics;
  24123. }
  24124. };
  24125. IRoxieServerActivityFactory *createRoxieServerSoapDatasetCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  24126. {
  24127. return new CRoxieServerSoapDatasetCallActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  24128. }
  24129. //---------------------------------------------------------------------------
  24130. class CRoxieServerSoapDatasetActionActivity : public CRoxieServerSoapActivityBase
  24131. {
  24132. public:
  24133. CRoxieServerSoapDatasetActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  24134. : CRoxieServerSoapActivityBase(_ctx, _factory, _probeManager)
  24135. {}
  24136. virtual const void *getNextRow()
  24137. {
  24138. CriticalBlock b(crit); // MORE - Why?
  24139. const void *nextrec = inputStream->ungroupedNextRow();
  24140. if (nextrec)
  24141. processed++;
  24142. return nextrec;
  24143. }
  24144. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  24145. {
  24146. try
  24147. {
  24148. start(parentExtractSize, parentExtract, false);
  24149. soaphelper.setown(createSoapCallHelper(this, NULL, ctx->queryAuthToken(), SCdataset, pClientCert, *this, this));
  24150. soaphelper->start();
  24151. soaphelper->waitUntilDone();
  24152. IException *e = soaphelper->getError();
  24153. soaphelper.clear();
  24154. if (e)
  24155. throw e;
  24156. stop();
  24157. }
  24158. catch (IException *E)
  24159. {
  24160. ctx->notifyAbort(E);
  24161. abort();
  24162. throw;
  24163. }
  24164. catch(...)
  24165. {
  24166. Owned<IException> E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught at %s:%d", sanitizeSourceFile(__FILE__), __LINE__);
  24167. ctx->notifyAbort(E);
  24168. abort();
  24169. throw;
  24170. }
  24171. }
  24172. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  24173. {
  24174. return NULL;
  24175. }
  24176. virtual const void *nextRow()
  24177. {
  24178. throwUnexpected(); // I am nobody's input
  24179. }
  24180. };
  24181. class CRoxieServerSoapDatasetActionActivityFactory : public CRoxieServerActivityFactory
  24182. {
  24183. bool isRoot;
  24184. public:
  24185. CRoxieServerSoapDatasetActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  24186. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  24187. {
  24188. }
  24189. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  24190. {
  24191. return new CRoxieServerSoapDatasetActionActivity(_ctx, this, _probeManager);
  24192. }
  24193. virtual bool isSink() const
  24194. {
  24195. return isRoot;
  24196. }
  24197. virtual const StatisticsMapping &queryStatsMapping() const
  24198. {
  24199. return soapStatistics;
  24200. }
  24201. };
  24202. IRoxieServerActivityFactory *createRoxieServerSoapDatasetActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  24203. {
  24204. return new CRoxieServerSoapDatasetActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  24205. }
  24206. //=====================================================================================================
  24207. class CGraphResults : implements IRoxieGraphResults, public CInterface
  24208. {
  24209. IArrayOf<IGraphResult> results;
  24210. CriticalSection cs;
  24211. IGraphResult & select(unsigned idx)
  24212. {
  24213. CriticalBlock procedure(cs);
  24214. if (idx >= results.ordinality())
  24215. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Error reading graph result %d before it is calculated", idx);
  24216. return results.item(idx);
  24217. }
  24218. public:
  24219. IMPLEMENT_IINTERFACE
  24220. void clear()
  24221. {
  24222. CriticalBlock procedure(cs);
  24223. results.kill();
  24224. }
  24225. virtual IEngineRowStream * createIterator(unsigned id)
  24226. {
  24227. return select(id).createIterator();
  24228. }
  24229. virtual void getLinkedResult(unsigned & count, const byte * * & ret, unsigned id) override
  24230. {
  24231. select(id).getLinkedResult(count, ret);
  24232. }
  24233. virtual void getDictionaryResult(unsigned & count, const byte * * & ret, unsigned id) override
  24234. {
  24235. select(id).getLinkedResult(count, ret);
  24236. }
  24237. virtual const void * getLinkedRowResult(unsigned id)
  24238. {
  24239. return select(id).getLinkedRowResult();
  24240. }
  24241. void setResult(unsigned id, IGraphResult * result)
  24242. {
  24243. CriticalBlock procedure(cs);
  24244. if (results.ordinality() <= id)
  24245. {
  24246. while (results.ordinality() < id)
  24247. results.append(*new CGraphResult);
  24248. results.append(*LINK(result));
  24249. }
  24250. else
  24251. results.replace(*LINK(result), id);
  24252. }
  24253. void appendResult(IGraphResult * result)
  24254. {
  24255. CriticalBlock procedure(cs);
  24256. results.append(*LINK(result));
  24257. }
  24258. };
  24259. //===================================================================================================================
  24260. class CPseudoArg : implements CThorSinkArgOf<IHThorArg>
  24261. {
  24262. };
  24263. class CPseudoActivity : public CRoxieServerActivity
  24264. {
  24265. public:
  24266. CPseudoActivity(IRoxieSlaveContext *_ctx, IHThorArg & _helper) : CRoxieServerActivity(_ctx, _helper) {}
  24267. virtual const void *nextRow()
  24268. {
  24269. throwUnexpected(); // I am nobody's input
  24270. }
  24271. };
  24272. class CActivityGraph : implements IActivityGraph, implements IThorChildGraph, implements ILocalGraphEx, implements IRoxieServerChildGraph, public CInterface
  24273. {
  24274. protected:
  24275. class ActivityGraphSlaveContext : public IndirectSlaveContext
  24276. {
  24277. SpinLock abortLock;
  24278. bool aborted;
  24279. Owned<IException> exception;
  24280. public:
  24281. ActivityGraphSlaveContext(IRoxieSlaveContext *_ctx, const IRoxieContextLogger &_logctx) : IndirectSlaveContext(_ctx), logctx(_logctx), loopCounter(0), codeContext(NULL)
  24282. {
  24283. aborted = false;
  24284. }
  24285. // Note - we must track exceptions at the child level in case there is a CATCH in parent
  24286. virtual void notifyAbort(IException *E)
  24287. {
  24288. SpinBlock b(abortLock);
  24289. if (!aborted && QUERYINTERFACE(E, InterruptedSemaphoreException) == NULL)
  24290. {
  24291. aborted = true;
  24292. exception.set(E);
  24293. }
  24294. }
  24295. virtual void checkAbort()
  24296. {
  24297. if (aborted) // NOTE - don't bother getting lock before reading this (for speed) - a false read is very unlikely and not a problem
  24298. {
  24299. SpinBlock b(abortLock);
  24300. if (!exception)
  24301. exception.setown(MakeStringException(ROXIE_INTERNAL_ERROR, "Query was aborted"));
  24302. throw exception.getLink();
  24303. }
  24304. IndirectSlaveContext::checkAbort();
  24305. }
  24306. virtual ICodeContext *queryCodeContext()
  24307. {
  24308. return codeContext;
  24309. }
  24310. void setCodeContext(ICodeContext * _codeContext)
  24311. {
  24312. codeContext = _codeContext;
  24313. }
  24314. void setLoopCounter(unsigned _loopCounter)
  24315. {
  24316. loopCounter = _loopCounter;
  24317. }
  24318. virtual void noteChildGraph(unsigned id, IActivityGraph *childGraph)
  24319. {
  24320. childGraphs.setValue(id, childGraph);
  24321. }
  24322. virtual IActivityGraph * queryChildGraph(unsigned id)
  24323. {
  24324. if (queryTraceLevel() > 10)
  24325. CTXLOG("resolveChildGraph %d", id);
  24326. IActivityGraph *childGraph = childGraphs.getValue(id);
  24327. assertex(childGraph);
  24328. return childGraph;
  24329. }
  24330. // 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
  24331. virtual StringBuffer &getLogPrefix(StringBuffer &ret) const
  24332. {
  24333. logctx.getLogPrefix(ret);
  24334. if (loopCounter)
  24335. ret.appendf("{%u}", loopCounter);
  24336. return ret;
  24337. }
  24338. protected:
  24339. const IRoxieContextLogger &logctx;
  24340. unsigned loopCounter;
  24341. ICodeContext * codeContext;
  24342. MapXToMyClass<unsigned, unsigned, IActivityGraph> childGraphs;
  24343. } graphSlaveContext;
  24344. class ActivityGraphCodeContext : public IndirectCodeContext
  24345. {
  24346. public:
  24347. virtual IEclGraphResults * resolveLocalQuery(__int64 activityId)
  24348. {
  24349. if ((unsigned) activityId == container->queryId())
  24350. return container;
  24351. IActivityGraph * match = slaveContext->queryChildGraph((unsigned) activityId);
  24352. if (match)
  24353. return match->queryLocalGraph();
  24354. return IndirectCodeContext::resolveLocalQuery(activityId);
  24355. }
  24356. virtual IThorChildGraph * resolveChildQuery(__int64 activityId, IHThorArg * colocal)
  24357. {
  24358. IActivityGraph * match = slaveContext->queryChildGraph((unsigned) activityId);
  24359. return LINK(match->queryChildGraph());
  24360. }
  24361. virtual unsigned getGraphLoopCounter() const
  24362. {
  24363. return container->queryLoopCounter(); // only called if value is valid
  24364. }
  24365. void setContainer(IRoxieSlaveContext * _slaveContext, CActivityGraph * _container)
  24366. {
  24367. slaveContext = _slaveContext;
  24368. container = _container;
  24369. }
  24370. protected:
  24371. IRoxieSlaveContext * slaveContext;
  24372. CActivityGraph * container;
  24373. } graphCodeContext;
  24374. // NOTE - destructor order is significant - need to destroy graphCodeContext and graphSlaveContext last
  24375. IArrayOf<IRoxieServerActivity> activities;
  24376. IArrayOf<IRoxieProbe> probes;
  24377. IRoxieServerActivityCopyArray sinks;
  24378. StringAttr graphName;
  24379. Owned<CGraphResults> results;
  24380. CGraphResults graphLoopResults;
  24381. const ActivityArray & graphDefinition;
  24382. CriticalSection evaluateCrit;
  24383. IProbeManager *probeManager;
  24384. unsigned id;
  24385. unsigned loopCounter;
  24386. public:
  24387. IMPLEMENT_IINTERFACE;
  24388. CActivityGraph(IRoxieSlaveContext *_ctx, const char *_graphName, unsigned _id, const ActivityArray &x, IProbeManager *_probeManager, const IRoxieContextLogger &_logctx)
  24389. : probeManager(_probeManager), graphDefinition(x), graphName(_graphName), graphSlaveContext(_ctx, _logctx)
  24390. {
  24391. id = x.getLibraryGraphId();
  24392. if (!id)
  24393. id = _id;
  24394. loopCounter = 0;
  24395. graphSlaveContext.setCodeContext(&graphCodeContext);
  24396. graphCodeContext.setContainer(&graphSlaveContext, this);
  24397. }
  24398. ~CActivityGraph()
  24399. {
  24400. if (probeManager)
  24401. probeManager->deleteGraph((IArrayOf<IActivityBase>*)&activities, (IArrayOf<IInputBase>*)&probes);
  24402. }
  24403. virtual const char *queryName() const
  24404. {
  24405. return graphName.get();
  24406. }
  24407. void createGraph(IRoxieSlaveContext *_ctx)
  24408. {
  24409. if (graphDefinition.isMultiInstance())
  24410. {
  24411. graphCodeContext.set(_ctx->queryCodeContext());
  24412. _ctx = &graphSlaveContext;
  24413. }
  24414. ForEachItemIn(idx, graphDefinition)
  24415. {
  24416. IRoxieServerActivityFactory &donor = graphDefinition.serverItem(idx);
  24417. IRoxieServerActivity &activity = *donor.createActivity(_ctx, probeManager);
  24418. activities.append(activity);
  24419. if (donor.isSink())
  24420. {
  24421. sinks.append(activity);
  24422. if (probeManager)
  24423. probeManager->noteSink(&activity);
  24424. }
  24425. }
  24426. ForEachItemIn(idx1, graphDefinition)
  24427. {
  24428. IRoxieServerActivityFactory &donor = graphDefinition.serverItem(idx1);
  24429. IRoxieServerActivity &activity = activities.item(idx1);
  24430. unsigned inputidx = 0;
  24431. for (;;)
  24432. {
  24433. unsigned outputidx;
  24434. unsigned source = donor.getInput(inputidx, outputidx);
  24435. if (source==(unsigned) -1)
  24436. break;
  24437. connectInput(idx1, inputidx, source, outputidx, 0);
  24438. inputidx++;
  24439. }
  24440. IntArray &dependencies = donor.queryDependencies();
  24441. IntArray &dependencyIndexes = donor.queryDependencyIndexes();
  24442. IntArray &dependencyControlIds = donor.queryDependencyControlIds();
  24443. StringArray &dependencyEdgeIds = donor.queryDependencyEdgeIds();
  24444. ForEachItemIn(idx2, dependencies)
  24445. {
  24446. IRoxieServerActivity &dependencySourceActivity = activities.item(dependencies.item(idx2));
  24447. unsigned dependencySourceIndex = dependencyIndexes.item(idx2);
  24448. unsigned dependencyControlId = dependencyControlIds.item(idx2);
  24449. activity.addDependency(dependencySourceActivity, dependencySourceIndex, dependencyControlId);
  24450. if (probeManager)
  24451. probeManager->noteDependency( &dependencySourceActivity, dependencySourceIndex, dependencyControlId, dependencyEdgeIds.item(idx2), &activity);
  24452. }
  24453. }
  24454. ForEachItemIn(idx2, sinks)
  24455. {
  24456. IRoxieServerActivity &sink = sinks.item(idx2);
  24457. sink.connectInputStreams(true);
  24458. }
  24459. }
  24460. void connectInput(unsigned target, unsigned targetIdx, unsigned source, unsigned sourceIdx, unsigned iteration)
  24461. {
  24462. IRoxieServerActivity &targetActivity = activities.item(target);
  24463. IRoxieServerActivity &sourceActivity = activities.item(source);
  24464. IFinalRoxieInput * output = sourceActivity.queryOutput(sourceIdx);
  24465. if (probeManager)
  24466. {
  24467. IRoxieProbe * inputProbe = probeManager->createProbe(static_cast<IInputBase*>(output), &sourceActivity, &targetActivity, sourceIdx, targetIdx, iteration);
  24468. probes.append(*LINK(inputProbe));
  24469. output = &dynamic_cast<IFinalRoxieInput &>(inputProbe->queryInput());
  24470. }
  24471. targetActivity.setInput(targetIdx, sourceIdx, output);
  24472. }
  24473. virtual void onCreate(IHThorArg *_colocalParent)
  24474. {
  24475. ForEachItemIn(idx, activities)
  24476. {
  24477. IRoxieServerActivity *activity = &activities.item(idx);
  24478. if (activity)
  24479. activity->onCreate(_colocalParent);
  24480. }
  24481. }
  24482. virtual void abort()
  24483. {
  24484. ForEachItemIn(idx, sinks)
  24485. {
  24486. IRoxieServerActivity &sink = sinks.item(idx);
  24487. sink.abort();
  24488. }
  24489. }
  24490. virtual void reset()
  24491. {
  24492. ForEachItemIn(idx, sinks)
  24493. {
  24494. IRoxieServerActivity &sink = sinks.item(idx);
  24495. sink.reset();
  24496. }
  24497. }
  24498. Linked<IException> exception;
  24499. CriticalSection eCrit;
  24500. virtual void noteException(IException *E)
  24501. {
  24502. CriticalBlock b(eCrit);
  24503. if (!exception)
  24504. {
  24505. if (graphSlaveContext.queryDebugContext())
  24506. {
  24507. graphSlaveContext.queryDebugContext()->checkBreakpoint(DebugStateException, NULL, exception);
  24508. }
  24509. exception.set(E);
  24510. }
  24511. }
  24512. virtual void checkAbort()
  24513. {
  24514. CriticalBlock b(eCrit);
  24515. if (exception)
  24516. throw exception.getLink();
  24517. }
  24518. virtual void execute()
  24519. {
  24520. results.setown(new CGraphResults);
  24521. doExecute(0, NULL);
  24522. }
  24523. //New child query code...
  24524. virtual IThorChildGraph * queryChildGraph()
  24525. {
  24526. return this;
  24527. }
  24528. virtual IEclGraphResults * queryLocalGraph()
  24529. {
  24530. return this;
  24531. }
  24532. virtual IRoxieServerChildGraph * queryLoopGraph()
  24533. {
  24534. return this;
  24535. }
  24536. inline unsigned queryId() const
  24537. {
  24538. return id;
  24539. }
  24540. inline unsigned queryLoopCounter() const
  24541. {
  24542. return loopCounter;
  24543. }
  24544. void doExecute(unsigned parentExtractSize, const byte * parentExtract)
  24545. {
  24546. if (sinks.ordinality()==1)
  24547. sinks.item(0).execute(parentExtractSize, parentExtract);
  24548. #ifdef PARALLEL_EXECUTE
  24549. else if (!probeManager && !graphDefinition.isSequential())
  24550. {
  24551. class casyncfor: public CAsyncFor
  24552. {
  24553. public:
  24554. IActivityGraph &parent;
  24555. unsigned parentExtractSize;
  24556. const byte * parentExtract;
  24557. casyncfor(IRoxieServerActivityCopyArray &_sinks, IActivityGraph &_parent, unsigned _parentExtractSize, const byte * _parentExtract) :
  24558. sinks(_sinks), parent(_parent), parentExtractSize(_parentExtractSize), parentExtract(_parentExtract) { }
  24559. void Do(unsigned i)
  24560. {
  24561. try
  24562. {
  24563. sinks.item(i).execute(parentExtractSize, parentExtract);
  24564. }
  24565. catch (IException *E)
  24566. {
  24567. parent.noteException(E);
  24568. throw;
  24569. }
  24570. }
  24571. private:
  24572. IRoxieServerActivityCopyArray &sinks;
  24573. } afor(sinks, *this, parentExtractSize, parentExtract);
  24574. afor.For(sinks.ordinality(), sinks.ordinality());
  24575. }
  24576. #endif
  24577. else
  24578. {
  24579. ForEachItemIn(idx, sinks)
  24580. {
  24581. IRoxieServerActivity &sink = sinks.item(idx);
  24582. sink.execute(parentExtractSize, parentExtract);
  24583. }
  24584. }
  24585. }
  24586. virtual IEclGraphResults *evaluate(unsigned parentExtractSize, const byte * parentExtract)
  24587. {
  24588. CriticalBlock block(evaluateCrit);
  24589. results.setown(new CGraphResults);
  24590. try
  24591. {
  24592. doExecute(parentExtractSize, parentExtract);
  24593. }
  24594. catch (...)
  24595. {
  24596. DBGLOG("Exception thrown in child query - cleaning up");
  24597. reset();
  24598. throw;
  24599. }
  24600. reset();
  24601. return results.getClear();
  24602. }
  24603. virtual void updateFactoryStatistics() const override
  24604. {
  24605. ForEachItemIn(i, activities)
  24606. activities.item(i).updateFactoryStatistics();
  24607. }
  24608. //interface IRoxieServerChildGraph
  24609. virtual void beforeExecute()
  24610. {
  24611. results.setown(new CGraphResults);
  24612. }
  24613. virtual IFinalRoxieInput * startOutput(unsigned id, unsigned parentExtractSize, const byte *parentExtract, bool paused)
  24614. {
  24615. IFinalRoxieInput * ret = selectOutput(id);
  24616. ret->start(parentExtractSize, parentExtract, paused);
  24617. return ret;
  24618. }
  24619. virtual IFinalRoxieInput * selectOutput(unsigned id)
  24620. {
  24621. ForEachItemIn(i, sinks)
  24622. {
  24623. IFinalRoxieInput * ret = sinks.item(i).querySelectOutput(id);
  24624. if (ret)
  24625. return ret;
  24626. }
  24627. throwUnexpected();
  24628. return NULL;
  24629. }
  24630. virtual void setInputResult(unsigned id, IGraphResult * result)
  24631. {
  24632. results->setResult(id, result);
  24633. }
  24634. virtual bool querySetInputResult(unsigned id, unsigned _sourceIdx, IFinalRoxieInput * input)
  24635. {
  24636. ForEachItemIn(i, activities)
  24637. {
  24638. if (activities.item(i).querySetStreamInput(id, _sourceIdx, input))
  24639. return true;
  24640. }
  24641. return false;
  24642. }
  24643. virtual void stopUnusedOutputs()
  24644. {
  24645. //Hmm not sure how to do this...
  24646. }
  24647. virtual void afterExecute()
  24648. {
  24649. ForEachItemIn(i, sinks)
  24650. {
  24651. sinks.item(i).stop();
  24652. }
  24653. if (graphSlaveContext.queryDebugContext())
  24654. {
  24655. graphSlaveContext.queryDebugContext()->checkBreakpoint(DebugStateGraphFinished, NULL, NULL);
  24656. }
  24657. reset();
  24658. }
  24659. virtual IRoxieGraphResults * execute(size32_t parentExtractSize, const byte *parentExtract)
  24660. {
  24661. doExecute(parentExtractSize, parentExtract);
  24662. return LINK(results);
  24663. }
  24664. virtual void getLinkedResult(unsigned & count, const byte * * & ret, unsigned id) override
  24665. {
  24666. results->getLinkedResult(count, ret, id);
  24667. }
  24668. virtual void getDictionaryResult(unsigned & count, const byte * * & ret, unsigned id) override
  24669. {
  24670. results->getLinkedResult(count, ret, id);
  24671. }
  24672. virtual const void * getLinkedRowResult(unsigned id)
  24673. {
  24674. return results->getLinkedRowResult(id);
  24675. }
  24676. virtual void setResult(unsigned id, IGraphResult * result)
  24677. {
  24678. results->setResult(id, result);
  24679. }
  24680. virtual IEngineRowStream * createResultIterator(unsigned id)
  24681. {
  24682. return results->createIterator(id);
  24683. }
  24684. virtual void setGraphLoopResult(IGraphResult * result)
  24685. {
  24686. graphLoopResults.appendResult(result);
  24687. }
  24688. virtual IEngineRowStream * createGraphLoopResultIterator(unsigned id)
  24689. {
  24690. try
  24691. {
  24692. return graphLoopResults.createIterator(id);
  24693. }
  24694. catch (IException * e)
  24695. {
  24696. e->Release();
  24697. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Error reading graph result %d before it is calculated", id);
  24698. }
  24699. }
  24700. virtual void clearGraphLoopResults()
  24701. {
  24702. graphLoopResults.clear();
  24703. }
  24704. virtual void executeGraphLoop(size32_t parentExtractSize, const byte *parentExtract)
  24705. {
  24706. doExecute(parentExtractSize, parentExtract);
  24707. }
  24708. virtual void setGraphLoopResult(unsigned id, IGraphResult * result)
  24709. {
  24710. graphLoopResults.setResult(id, result);
  24711. }
  24712. virtual IEngineRowStream * getGraphLoopResult(unsigned id)
  24713. {
  24714. return graphLoopResults.createIterator(id);
  24715. }
  24716. virtual void getProbeResponse(IPropertyTree *query)
  24717. {
  24718. if (probeManager)
  24719. probeManager->getProbeResponse(query);
  24720. }
  24721. virtual IRoxieServerChildGraph * createGraphLoopInstance(IRoxieSlaveContext *ctx, unsigned loopCounter, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &logctx)
  24722. {
  24723. throwUnexpected();
  24724. }
  24725. virtual CGraphIterationInfo *selectGraphLoopOutput()
  24726. {
  24727. return NULL;
  24728. }
  24729. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor)
  24730. {
  24731. throwUnexpected();
  24732. }
  24733. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor)
  24734. {
  24735. throwUnexpected();
  24736. }
  24737. };
  24738. class CProxyActivityGraph : implements IActivityGraph, implements IThorChildGraph, public CInterface
  24739. {
  24740. public:
  24741. IMPLEMENT_IINTERFACE;
  24742. CProxyActivityGraph(IRoxieSlaveContext *_ctx, const char *_graphName, unsigned _id, ActivityArray &_graphDefinition, const IRoxieContextLogger &_logctx, unsigned _numParallel)
  24743. : ctx(_ctx), graphName(_graphName), id(_id), graphDefinition(_graphDefinition), logctx(_logctx), numParallel(_numParallel)
  24744. {
  24745. }
  24746. virtual void abort() override { throwUnexpected(); }
  24747. virtual void reset() override { throwUnexpected(); }
  24748. virtual void execute() override { throwUnexpected(); }
  24749. virtual void getProbeResponse(IPropertyTree *query) override { throwUnexpected(); }
  24750. virtual void onCreate(IHThorArg *_colocalArg) override
  24751. {
  24752. colocalArg = _colocalArg;
  24753. }
  24754. virtual void noteException(IException *E) override { throwUnexpected(); }
  24755. virtual void checkAbort() override { throwUnexpected(); }
  24756. virtual IThorChildGraph * queryChildGraph() override { return this; }
  24757. virtual IEclGraphResults * queryLocalGraph() override { throwUnexpected(); }
  24758. virtual IRoxieServerChildGraph * queryLoopGraph() override { throwUnexpected(); }
  24759. virtual IRoxieServerChildGraph * createGraphLoopInstance(IRoxieSlaveContext *ctx, unsigned loopCounter, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &logctx) override { throwUnexpected(); }
  24760. virtual const char *queryName() const override { throwUnexpected(); }
  24761. virtual void updateFactoryStatistics() const override
  24762. {
  24763. CriticalBlock b(graphCrit);
  24764. ForEachItemIn(i, stack)
  24765. stack.item(i).updateFactoryStatistics();
  24766. }
  24767. virtual IEclGraphResults * evaluate(unsigned parentExtractSize, const byte * parentExtract) override
  24768. {
  24769. Owned<CActivityGraph> realGraph;
  24770. {
  24771. CriticalBlock b(graphCrit);
  24772. if (stack.length())
  24773. realGraph.setown(&stack.popGet());
  24774. }
  24775. if (!realGraph)
  24776. {
  24777. realGraph.setown(new CActivityGraph(ctx, graphName, id, graphDefinition, NULL, logctx));
  24778. realGraph->createGraph(ctx);
  24779. realGraph->onCreate(colocalArg);
  24780. }
  24781. Owned<IEclGraphResults> results = realGraph->evaluate(parentExtractSize, parentExtract);
  24782. {
  24783. CriticalBlock b(graphCrit);
  24784. stack.append(*realGraph.getClear());
  24785. }
  24786. return results.getClear();
  24787. }
  24788. protected:
  24789. IRoxieSlaveContext *ctx;
  24790. StringAttr graphName;
  24791. unsigned id;
  24792. ActivityArray &graphDefinition;
  24793. const IRoxieContextLogger &logctx;
  24794. unsigned numParallel;
  24795. IHThorArg *colocalArg = nullptr;
  24796. mutable CriticalSection graphCrit;
  24797. CIArrayOf<CActivityGraph> stack;
  24798. };
  24799. class CIterationActivityGraph : public CActivityGraph
  24800. {
  24801. IHThorArg * colocalParent;
  24802. unsigned fixedParentExtractSize;
  24803. const byte * fixedParentExtract;
  24804. unsigned graphOutputActivityIndex;
  24805. public:
  24806. CIterationActivityGraph(const char *_graphName, unsigned _id, ActivityArray &x, IProbeManager *_probeManager,
  24807. unsigned _loopCounter, IRoxieSlaveContext *_ctx, IHThorArg * _colocalParent, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &_logctx)
  24808. : CActivityGraph(_ctx, _graphName, _id, x, _probeManager, _logctx)
  24809. {
  24810. graphOutputActivityIndex = 0;
  24811. loopCounter = _loopCounter;
  24812. colocalParent = _colocalParent;
  24813. graphSlaveContext.setLoopCounter(loopCounter);
  24814. graphCodeContext.set(_ctx->queryCodeContext());
  24815. fixedParentExtractSize = parentExtractSize;
  24816. fixedParentExtract = parentExtract;
  24817. }
  24818. void createIterationGraph(IRoxieSlaveContext *_ctx)
  24819. {
  24820. Owned<IRoxieServerActivity> pseudoActivity = new CPseudoActivity(_ctx, *new CPseudoArg);
  24821. ForEachItemIn(idx1, graphDefinition)
  24822. activities.append(*LINK(pseudoActivity));
  24823. graphOutputActivityIndex = queryGraphOutputIndex();
  24824. recursiveCreateGraph(_ctx, graphOutputActivityIndex);
  24825. }
  24826. unsigned queryGraphOutputIndex() const
  24827. {
  24828. ForEachItemIn(i, graphDefinition)
  24829. if (graphDefinition.serverItem(i).getKind() == TAKgraphloopresultwrite)
  24830. return i;
  24831. throwUnexpected();
  24832. }
  24833. void recursiveCreateGraph(IRoxieSlaveContext *_ctx, unsigned whichActivity)
  24834. {
  24835. //Check to see if already created
  24836. IRoxieServerActivity & prevActivity = activities.item(whichActivity);
  24837. if (prevActivity.queryId() != 0)
  24838. {
  24839. prevActivity.noteOutputUsed(); //We need to patch up the number of outputs for splitters.
  24840. return;
  24841. }
  24842. IRoxieServerActivityFactory &donor = graphDefinition.serverItem(whichActivity);
  24843. IRoxieServerActivity * activity = NULL;
  24844. if (donor.isGraphInvariant())
  24845. {
  24846. ThorActivityKind kind = donor.getKind();
  24847. switch (kind)
  24848. {
  24849. case TAKif:
  24850. case TAKchildif:
  24851. case TAKcase:
  24852. case TAKchildcase: // MORE RKC->GH - what about FILTER with a graph-invariant condition and other latestart activities?
  24853. {
  24854. Owned<IHThorArg> helper = &donor.getHelper();
  24855. helper->onCreate(&graphCodeContext, colocalParent, NULL);
  24856. helper->onStart(fixedParentExtract, NULL);
  24857. unsigned branch;
  24858. switch (kind)
  24859. {
  24860. case TAKif: case TAKchildif:
  24861. branch = static_cast<IHThorIfArg *>(helper.get())->getCondition() ? 0 : 1;
  24862. break;
  24863. case TAKcase: case TAKchildcase:
  24864. branch = static_cast<IHThorCaseArg *>(helper.get())->getBranch();
  24865. if (branch >= donor.numInputs())
  24866. branch = donor.numInputs() - 1;
  24867. break;
  24868. default:
  24869. throwUnexpected();
  24870. }
  24871. helper.clear();
  24872. unsigned outputidx;
  24873. unsigned source = donor.getInput(branch, outputidx);
  24874. if (source ==(unsigned) -1)
  24875. activity = createRoxieServerNullActivity(&graphSlaveContext, &donor, probeManager);
  24876. else
  24877. activity = createRoxieServerPassThroughActivity(&graphSlaveContext, &donor, probeManager);
  24878. activities.replace(*activity, whichActivity);
  24879. activity->onCreate(colocalParent);
  24880. if (source ==(unsigned) -1)
  24881. return;
  24882. recursiveCreateGraph(_ctx, source);
  24883. connectInput(whichActivity, 0, source, outputidx, loopCounter);
  24884. break;
  24885. }
  24886. }
  24887. }
  24888. if (!activity)
  24889. {
  24890. activity = donor.createActivity(&graphSlaveContext, probeManager);
  24891. activities.replace(*activity, whichActivity);
  24892. activity->onCreate(colocalParent);
  24893. activity->resetOutputsUsed();
  24894. unsigned inputidx = 0;
  24895. for (;;)
  24896. {
  24897. unsigned outputidx;
  24898. unsigned source = donor.getInput(inputidx, outputidx);
  24899. if (source==(unsigned) -1)
  24900. break;
  24901. recursiveCreateGraph(_ctx, source);
  24902. connectInput(whichActivity, inputidx, source, outputidx, loopCounter);
  24903. inputidx++;
  24904. }
  24905. }
  24906. IntArray &dependencies = donor.queryDependencies();
  24907. IntArray &dependencyIndexes = donor.queryDependencyIndexes();
  24908. IntArray &dependencyControlIds = donor.queryDependencyControlIds();
  24909. ForEachItemIn(idx2, dependencies)
  24910. {
  24911. unsigned input = dependencies.item(idx2);
  24912. recursiveCreateGraph(_ctx, input);
  24913. activity->addDependency(activities.item(input),dependencyIndexes.item(idx2),dependencyControlIds.item(idx2));
  24914. }
  24915. }
  24916. virtual CGraphIterationInfo *selectGraphLoopOutput()
  24917. {
  24918. IRoxieServerActivity &sourceActivity = activities.item(graphOutputActivityIndex);
  24919. IFinalRoxieInput *sourceInput = sourceActivity.queryOutput(0);
  24920. return new CGraphIterationInfo(&sourceActivity, sourceInput, 0, loopCounter);
  24921. }
  24922. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor)
  24923. {
  24924. ForEachItemIn(i, activities)
  24925. activities.item(i).gatherIterationUsage(processor, fixedParentExtractSize, fixedParentExtract);
  24926. }
  24927. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor)
  24928. {
  24929. ForEachItemIn(i, activities)
  24930. activities.item(i).associateIterationOutputs(processor, fixedParentExtractSize, fixedParentExtract, probeManager, probes);
  24931. }
  24932. };
  24933. class CDelayedActivityGraph : implements IActivityGraph, public CInterface
  24934. {
  24935. StringAttr graphName;
  24936. ActivityArray & graphDefinition;
  24937. IProbeManager *probeManager;
  24938. unsigned id;
  24939. IRoxieSlaveContext * ctx;
  24940. IHThorArg * colocalParent;
  24941. public:
  24942. IMPLEMENT_IINTERFACE;
  24943. CDelayedActivityGraph(const char *_graphName, unsigned _id, ActivityArray &x, IProbeManager *_probeManager)
  24944. : probeManager(_probeManager), graphDefinition(x)
  24945. {
  24946. graphName.set(_graphName);
  24947. id = _id;
  24948. ctx = NULL;
  24949. colocalParent = NULL;
  24950. }
  24951. virtual const char *queryName() const override { return graphName.get(); }
  24952. virtual void abort() override { throwUnexpected(); }
  24953. virtual void reset() override { }
  24954. virtual void execute() override { throwUnexpected(); }
  24955. virtual void getProbeResponse(IPropertyTree *query) override { throwUnexpected(); }
  24956. virtual void noteException(IException *E) override { throwUnexpected(); }
  24957. virtual void checkAbort() override { throwUnexpected(); }
  24958. virtual IThorChildGraph * queryChildGraph() override { throwUnexpected(); }
  24959. virtual IEclGraphResults * queryLocalGraph() override { throwUnexpected(); }
  24960. virtual IRoxieServerChildGraph * queryLoopGraph() override { throwUnexpected(); }
  24961. virtual void updateFactoryStatistics() const override { }
  24962. virtual void onCreate(IHThorArg *_colocalParent) override
  24963. {
  24964. colocalParent = _colocalParent;
  24965. }
  24966. virtual IRoxieServerChildGraph * createGraphLoopInstance(IRoxieSlaveContext *ctx, unsigned loopCounter, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &logctx) override
  24967. {
  24968. Owned<CIterationActivityGraph> ret = new CIterationActivityGraph(graphName, id, graphDefinition, probeManager, loopCounter, ctx, colocalParent, parentExtractSize, parentExtract, logctx);
  24969. ret->createIterationGraph(ctx);
  24970. return ret.getClear();
  24971. }
  24972. };
  24973. IActivityGraph *createActivityGraph(IRoxieSlaveContext *ctx, const char *_graphName, unsigned id, ActivityArray &childFactories, IRoxieServerActivity *parentActivity, IProbeManager *_probeManager, const IRoxieContextLogger &_logctx, unsigned numParallel)
  24974. {
  24975. if (childFactories.isDelayed())
  24976. {
  24977. assertex(numParallel==1);
  24978. return new CDelayedActivityGraph(_graphName, id, childFactories, _probeManager);
  24979. }
  24980. else
  24981. {
  24982. if (numParallel==1 || _probeManager != nullptr)
  24983. {
  24984. Owned<IProbeManager> childProbe;
  24985. if (_probeManager)
  24986. childProbe.setown(_probeManager->startChildGraph(id, parentActivity));
  24987. Owned<CActivityGraph> ret = new CActivityGraph(ctx, _graphName, id, childFactories, childProbe, _logctx);
  24988. ret->createGraph(ctx);
  24989. if (_probeManager)
  24990. _probeManager->endChildGraph(childProbe, parentActivity);
  24991. return ret.getClear();
  24992. }
  24993. else
  24994. return new CProxyActivityGraph(ctx, _graphName, id, childFactories, _logctx, numParallel);
  24995. }
  24996. }
  24997. //================================================================================================================
  24998. #ifdef _USE_CPPUNIT
  24999. #include "unittests.hpp"
  25000. // 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...
  25001. #if _MSC_VER==1200
  25002. #undef protected
  25003. #endif
  25004. static const char *sortAlgorithm;
  25005. class TestMetaData : public CInterface, implements IOutputMetaData
  25006. {
  25007. public:
  25008. IMPLEMENT_IINTERFACE;
  25009. virtual size32_t getRecordSize(const void *) { return 10; }
  25010. virtual size32_t getMinRecordSize() const { return 10; }
  25011. virtual size32_t getFixedSize() const { return 10; }
  25012. virtual void toXML(const byte * self, IXmlWriter & out) {}
  25013. virtual unsigned getVersion() const { return OUTPUTMETADATA_VERSION; }
  25014. virtual unsigned getMetaFlags() { return 0; }
  25015. virtual void destruct(byte * self) {}
  25016. virtual IOutputRowSerializer * createDiskSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  25017. virtual IOutputRowDeserializer * createDiskDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  25018. virtual ISourceRowPrefetcher * createDiskPrefetcher() { return NULL; }
  25019. virtual IOutputMetaData * querySerializedDiskMeta() { return NULL; }
  25020. virtual IOutputRowSerializer * createInternalSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  25021. virtual IOutputRowDeserializer * createInternalDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  25022. virtual void walkIndirectMembers(const byte * self, IIndirectMemberVisitor & visitor) {}
  25023. virtual IOutputMetaData * queryChildMeta(unsigned i) { return NULL; }
  25024. virtual const RtlRecord &queryRecordAccessor(bool expand) const { throwUnexpected(); }
  25025. } testMeta;
  25026. class TestInput : public CInterface, implements IFinalRoxieInput, implements IEngineRowStream
  25027. {
  25028. char const * const *input;
  25029. IRoxieSlaveContext *ctx;
  25030. unsigned endSeen;
  25031. bool eof;
  25032. unsigned count;
  25033. ActivityTimeAccumulator totalCycles;
  25034. size32_t recordSize;
  25035. unsigned activityId;
  25036. public:
  25037. enum { STATEreset, STATEstarted, STATEstopped } state;
  25038. bool allRead;
  25039. unsigned repeat;
  25040. IMPLEMENT_IINTERFACE;
  25041. TestInput(IRoxieSlaveContext *_ctx, char const * const *_input)
  25042. {
  25043. ctx = _ctx;
  25044. input = _input;
  25045. count = 0;
  25046. eof = false;
  25047. allRead = false;
  25048. endSeen = 0;
  25049. recordSize = testMeta.getFixedSize();
  25050. state = STATEreset;
  25051. activityId = 1;
  25052. repeat = 0;
  25053. }
  25054. virtual IOutputMetaData * queryOutputMeta() const { return &testMeta; }
  25055. virtual void prestart(unsigned parentExtractSize, const byte *parentExtract)
  25056. {
  25057. ASSERT(state == STATEreset);
  25058. }
  25059. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  25060. {
  25061. ASSERT(state == STATEreset);
  25062. state = STATEstarted;
  25063. }
  25064. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  25065. {
  25066. streams.append(this);
  25067. return NULL;
  25068. }
  25069. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { assertex(whichInput==0); return this; }
  25070. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { assertex(idx==0); return nullptr; }
  25071. virtual IRoxieServerActivity *queryActivity()
  25072. {
  25073. throwUnexpected();
  25074. }
  25075. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  25076. {
  25077. throwUnexpected();
  25078. }
  25079. virtual void stop()
  25080. {
  25081. state = STATEstopped;
  25082. }
  25083. virtual void reset()
  25084. {
  25085. ASSERT(state == STATEstopped);
  25086. eof = false; count = 0; endSeen = 0; allRead = false; state = STATEreset;
  25087. }
  25088. virtual void resetEOF()
  25089. {
  25090. throwUnexpected();
  25091. }
  25092. virtual void checkAbort() {}
  25093. virtual unsigned queryId() const { return activityId; };
  25094. virtual const void *nextRow()
  25095. {
  25096. ActivityTimer t(totalCycles, ctx->queryOptions().timeActivities);
  25097. ASSERT(state == STATEstarted);
  25098. ASSERT(allRead || !eof);
  25099. if (eof)
  25100. return NULL;
  25101. again:
  25102. const char *nextSource = input[count++];
  25103. if (nextSource)
  25104. {
  25105. endSeen = 0;
  25106. void *ret = ctx->queryRowManager().ALLOCATE(recordSize);
  25107. memset(ret, 0, recordSize);
  25108. strncpy((char *) ret, nextSource, recordSize);
  25109. return ret;
  25110. }
  25111. else if (repeat)
  25112. {
  25113. repeat--;
  25114. count = 0;
  25115. goto again;
  25116. }
  25117. else
  25118. {
  25119. endSeen++;
  25120. if (endSeen==2)
  25121. eof = true;
  25122. return NULL;
  25123. }
  25124. }
  25125. virtual bool nextGroup(ConstPointerArray & group)
  25126. {
  25127. const void * next;
  25128. while ((next = nextRow()) != NULL)
  25129. group.append(next);
  25130. if (group.ordinality())
  25131. return true;
  25132. return false;
  25133. }
  25134. virtual unsigned __int64 queryTotalCycles() const { return totalCycles.totalCycles; }
  25135. virtual unsigned __int64 queryLocalCycles() const { return totalCycles.totalCycles; }
  25136. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  25137. {
  25138. return NULL;
  25139. }
  25140. };
  25141. struct SortActivityTest : public CThorSortArg {
  25142. public:
  25143. struct CompareClass : public ICompare {
  25144. virtual int docompare(const void * _left, const void * _right) const {
  25145. return memcmp(_left, _right, 5);
  25146. }
  25147. } compare;
  25148. virtual ICompare * queryCompare() { return &compare; }
  25149. virtual IOutputMetaData * queryOutputMeta()
  25150. {
  25151. return &testMeta;
  25152. }
  25153. virtual unsigned getAlgorithmFlags() { return TAFunstable; }
  25154. virtual const char * getAlgorithm() { return sortAlgorithm; }
  25155. };
  25156. extern "C" IHThorArg * sortActivityTestFactory() { return new SortActivityTest; }
  25157. struct MergeActivityTest : public CThorMergeArg {
  25158. static bool isDedup;
  25159. public:
  25160. struct CompareClass : public ICompare {
  25161. virtual int docompare(const void * _left, const void * _right) const {
  25162. return memcmp(_left, _right, 5);
  25163. }
  25164. } compare;
  25165. virtual ICompare * queryCompare() { return &compare; }
  25166. virtual IOutputMetaData * queryOutputMeta()
  25167. {
  25168. return &testMeta;
  25169. }
  25170. virtual bool dedup() { return isDedup; }
  25171. };
  25172. bool MergeActivityTest::isDedup = false;
  25173. extern "C" IHThorArg * mergeActivityTestFactory() { return new MergeActivityTest; }
  25174. struct SplitActivityTest : public CThorSplitArg {
  25175. public:
  25176. virtual unsigned numBranches() { return 2; }
  25177. virtual IOutputMetaData * queryOutputMeta()
  25178. {
  25179. return &testMeta;
  25180. }
  25181. };
  25182. extern "C" IHThorArg * splitActivityTestFactory() { return new SplitActivityTest; }
  25183. class CcdServerTest : public CppUnit::TestFixture
  25184. {
  25185. CPPUNIT_TEST_SUITE(CcdServerTest);
  25186. CPPUNIT_TEST(testSetup);
  25187. CPPUNIT_TEST(testHeapSort);
  25188. CPPUNIT_TEST(testQuickSort);
  25189. CPPUNIT_TEST(testMerge);
  25190. CPPUNIT_TEST(testMergeDedup);
  25191. CPPUNIT_TEST(testMiscellaneous);
  25192. CPPUNIT_TEST(testSplitter);
  25193. CPPUNIT_TEST(testCleanup);
  25194. CPPUNIT_TEST_SUITE_END();
  25195. protected:
  25196. SlaveContextLogger logctx;
  25197. Owned<const IQueryDll> queryDll;
  25198. Owned<IRoxiePackage> package;
  25199. Owned<IPropertyTree> stateInfo;
  25200. Owned<IQueryFactory> queryFactory;
  25201. Owned<IRoxieSlaveContext> ctx;
  25202. void testSetup()
  25203. {
  25204. selfTestMode = true;
  25205. roxiemem::setTotalMemoryLimit(false, true, false, 100 * 1024 * 1024, 0, NULL, NULL);
  25206. }
  25207. void testCleanup()
  25208. {
  25209. roxiemem::releaseRoxieHeap();
  25210. }
  25211. void init()
  25212. {
  25213. package.setown(createRoxiePackage(NULL, NULL));
  25214. queryDll.setown(createExeQueryDll("roxie"));
  25215. stateInfo.setown(createPTreeFromXMLString("<test memoryLimit='50000000'/>"));
  25216. queryFactory.setown(createServerQueryFactory("test", queryDll.getLink(), *package, stateInfo, false, false));
  25217. ctx.setown(createSlaveContext(queryFactory, logctx, NULL, false));
  25218. queryActiveTimer()->reset();
  25219. }
  25220. void testActivity(IRoxieServerActivity *activity, char const * const *input, char const * const *output)
  25221. {
  25222. testActivity(activity, input, NULL, output);
  25223. }
  25224. void testActivity(IRoxieServerActivity *activity, char const * const *input, char const * const *input2, char const * const *output, unsigned outputIdx = 0)
  25225. {
  25226. TestInput in(ctx, input);
  25227. TestInput in2(ctx, input2);
  25228. activity->setInput(0, 0, &in);
  25229. if (input2)
  25230. activity->setInput(1, 0, &in2);
  25231. IFinalRoxieInput *out = activity->queryOutput(outputIdx);
  25232. IEngineRowStream *outStream = connectSingleStream(ctx, out, outputIdx, true);
  25233. IOutputMetaData *meta = out->queryOutputMeta();
  25234. void *buf = alloca(meta->getFixedSize());
  25235. for (unsigned iteration = 0; iteration < 8; iteration++)
  25236. {
  25237. // 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)
  25238. // This should be true whether we read all, some, or none of the data.
  25239. // Should not matter if an activity is not started
  25240. if (iteration % 4 == 0)
  25241. activity->onCreate(NULL);
  25242. unsigned count = 0;
  25243. if (iteration % 4 != 3)
  25244. {
  25245. activity->start(0, NULL, false);
  25246. ASSERT(in.state == TestInput::STATEstarted);
  25247. ASSERT(!input2 || in2.state == TestInput::STATEstarted);
  25248. for (;;)
  25249. {
  25250. const void *next = outStream->nextRow();
  25251. if (!next)
  25252. {
  25253. ASSERT(output[count++] == NULL);
  25254. next = outStream->nextRow();
  25255. if (!next)
  25256. {
  25257. ASSERT(output[count++] == NULL);
  25258. break;
  25259. }
  25260. }
  25261. ASSERT(output[count] != NULL);
  25262. unsigned outsize = meta->getRecordSize(next);
  25263. memset(buf, 0, outsize);
  25264. strncpy((char *) buf, output[count++], outsize);
  25265. ASSERT(memcmp(next, buf, outsize) == 0);
  25266. ReleaseRoxieRow(next);
  25267. if (iteration % 4 == 2)
  25268. break;
  25269. }
  25270. if (iteration % 4 != 2)
  25271. {
  25272. // Check that reading after end is harmless
  25273. in.allRead = true;
  25274. const void *next = outStream->nextRow();
  25275. ASSERT(next == NULL);
  25276. }
  25277. }
  25278. activity->stop();
  25279. ASSERT(in.state == TestInput::STATEstopped);
  25280. ASSERT(!input2 || in2.state == TestInput::STATEstopped);
  25281. activity->reset();
  25282. ASSERT(in.state == TestInput::STATEreset);
  25283. ASSERT(!input2 || in2.state == TestInput::STATEreset);
  25284. ctx->queryRowManager().reportLeaks();
  25285. ASSERT(ctx->queryRowManager().numPagesAfterCleanup(true) == 0);
  25286. }
  25287. }
  25288. void testSplitActivity(IRoxieServerActivityFactory *factory, char const * const *input, char const * const *output, unsigned numOutputs, unsigned repeat)
  25289. {
  25290. Owned <IRoxieServerActivity> activity = factory->createActivity(ctx, NULL);
  25291. TestInput in(ctx, input);
  25292. in.repeat = repeat;
  25293. activity->setInput(0, 0, &in);
  25294. ArrayOf<IFinalRoxieInput *> out;
  25295. for (unsigned i = 0; i < numOutputs; i++)
  25296. {
  25297. out.append(activity->queryOutput(i));
  25298. }
  25299. activity->onCreate(NULL);
  25300. class casyncfor: public CAsyncFor
  25301. {
  25302. public:
  25303. casyncfor(CcdServerTest *_parent, IRoxieServerActivity *_activity, ArrayOf<IFinalRoxieInput *> &_outputs, char const * const *_input, char const * const *_output, unsigned _repeat)
  25304. : parent(_parent), activity(_activity), outputs(_outputs), input(_input), output(_output), repeat(_repeat)
  25305. {}
  25306. void Do(unsigned i)
  25307. {
  25308. IFinalRoxieInput *out = outputs.item(i);
  25309. IEngineRowStream *outStream = connectSingleStream(NULL, out, 0, true);
  25310. out->start(0, NULL, false);
  25311. IOutputMetaData *meta = out->queryOutputMeta();
  25312. void *buf = alloca(meta->getFixedSize());
  25313. unsigned count = 0;
  25314. unsigned repeats = repeat;
  25315. for (;;)
  25316. {
  25317. const void *next = outStream->nextRow();
  25318. if (!next)
  25319. {
  25320. ASSERT(repeats==0);
  25321. ASSERT(output[count] == NULL);
  25322. count++;
  25323. next = outStream->nextRow();
  25324. if (!next)
  25325. {
  25326. ASSERT(output[count] == NULL);
  25327. count++;
  25328. break;
  25329. }
  25330. }
  25331. if (output[count] == NULL && repeats)
  25332. {
  25333. repeats--;
  25334. count = 0;
  25335. }
  25336. ASSERT(output[count] != NULL);
  25337. unsigned outsize = meta->getRecordSize(next);
  25338. memset(buf, 0, outsize);
  25339. strncpy((char *) buf, output[count++], outsize);
  25340. ASSERT(memcmp(next, buf, outsize) == 0);
  25341. ReleaseRoxieRow(next);
  25342. }
  25343. outStream->stop();
  25344. }
  25345. private:
  25346. IRoxieServerActivity *activity;
  25347. ArrayOf<IFinalRoxieInput *> &outputs;
  25348. char const * const *input;
  25349. char const * const *output;
  25350. unsigned repeat;
  25351. CcdServerTest *parent;
  25352. } afor(this, activity, out, input, output, repeat);
  25353. afor.For(numOutputs, numOutputs);
  25354. ASSERT(in.state == TestInput::STATEstopped);
  25355. for (unsigned i2 = 0; i2 < numOutputs; i2++)
  25356. {
  25357. out.item(i2)->reset();
  25358. }
  25359. ASSERT(in.state == TestInput::STATEreset);
  25360. ctx->queryRowManager().reportLeaks();
  25361. ASSERT(ctx->queryRowManager().numPagesAfterCleanup(true) == 0);
  25362. }
  25363. static int compareFunc(const void *l, const void *r)
  25364. {
  25365. return strcmp(*(char **) l, *(char **) r);
  25366. }
  25367. void testSort(unsigned type)
  25368. {
  25369. init();
  25370. sortAlgorithm = NULL;
  25371. if (type==2)
  25372. sortAlgorithm = "heapSort";
  25373. else
  25374. sortAlgorithm = "quickSort";
  25375. DBGLOG("Testing %s activity", sortAlgorithm);
  25376. Owned<IPropertyTree> dummyNode = createPTree("node");
  25377. Owned <IRoxieServerActivityFactory> factory = createRoxieServerSortActivityFactory(1, 1, *queryFactory, sortActivityTestFactory, TAKsort, *dummyNode);
  25378. Owned <IRoxieServerActivity> activity = factory->createActivity(ctx, NULL);
  25379. const char * test[] = { NULL, NULL };
  25380. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  25381. const char * test54321[] = { "5", "4", "3", "2", "1", NULL, NULL };
  25382. const char * test11111[] = { "1", "1", "1", "1", "1", NULL, NULL };
  25383. const char * test11111_12345[] = { "1", "1", "1", "1", "1", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  25384. const char * test11111_54321[] = { "1", "1", "1", "1", "1", NULL, "5", "4", "3", "2", "1", NULL, NULL };
  25385. const char * test54321_54321[] = { "5", "4", "3", "2", "1", NULL, "5", "4", "3", "2", "1", NULL, NULL };
  25386. const char * test12345_12345[] = { "1", "2", "3", "4", "5", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  25387. testActivity(activity, test, test);
  25388. testActivity(activity, test12345, test12345);
  25389. testActivity(activity, test54321, test12345);
  25390. testActivity(activity, test11111, test11111);
  25391. testActivity(activity, test11111_12345, test11111_12345);
  25392. testActivity(activity, test11111_54321, test11111_12345);
  25393. testActivity(activity, test54321_54321, test12345_12345);
  25394. // A few larger tests
  25395. char *input[2002];
  25396. char *output[2002];
  25397. input[2000] = input[2001] = output[2000] = output[2001] = NULL;
  25398. unsigned i;
  25399. // identical
  25400. for (i=0; i<2000; i++)
  25401. {
  25402. input[i] = new char[11];
  25403. output[i] = new char[11];
  25404. sprintf(input[i], "1");
  25405. sprintf(output[i], "1");
  25406. }
  25407. testActivity(activity, input, output);
  25408. // Ascending
  25409. for (i=0; i<2000; i++)
  25410. {
  25411. sprintf(input[i], "%04d", i);
  25412. sprintf(output[i], "%04d", i);
  25413. }
  25414. testActivity(activity, input, output);
  25415. // Almost sorted
  25416. for (i=0; i<20; i++)
  25417. {
  25418. unsigned h = i*100;
  25419. sprintf(input[h], "%04d", 1900-h);
  25420. }
  25421. testActivity(activity, input, output);
  25422. // Descending
  25423. for (i=0; i<2000; i++)
  25424. {
  25425. sprintf(input[i], "%04d", 1999-i);
  25426. sprintf(output[i], "%04d", i);
  25427. }
  25428. testActivity(activity, input, output);
  25429. // Random
  25430. for (i=0; i<2000; i++)
  25431. {
  25432. unsigned r = fastRand() % 1500;
  25433. sprintf(input[i], "%04d", r);
  25434. sprintf(output[i], "%04d", r);
  25435. }
  25436. qsort(output, 2000, sizeof(output[0]), compareFunc);
  25437. testActivity(activity, input, output);
  25438. unsigned __int64 us = factory->queryLocalTimeNs();
  25439. DBGLOG("Simple %s sorts: activity time %u.%u ms", type==2?"Heap" : (type==1 ? "Insertion" : "Quick"), (int)(us/1000), (int)(us%1000));
  25440. factory->resetNodeProgressInfo();
  25441. if (type)
  25442. {
  25443. // Other than quicksort, it's supposed to be stable. Let's check that it is
  25444. // All sort identical
  25445. for (i=0; i<2000; i++)
  25446. {
  25447. sprintf(input[i], "1 %d", i);
  25448. sprintf(output[i], "1 %d", i);
  25449. }
  25450. testActivity(activity, input, output);
  25451. // Already sorted
  25452. for (i=0; i<2000; i++)
  25453. {
  25454. sprintf(input[i], "%04d %d", i / 10, i);
  25455. sprintf(output[i], "%04d %d", i / 10, i);
  25456. }
  25457. testActivity(activity, input, output);
  25458. // Reverse order
  25459. for (i=0; i<2000; i++)
  25460. {
  25461. sprintf(input[i], "%04d %d", 199 - (i / 10), i%10);
  25462. sprintf(output[i], "%04d %d", i / 10, i%10);
  25463. }
  25464. testActivity(activity, input, output);
  25465. }
  25466. for (i=0; i<2000; i++)
  25467. {
  25468. delete [] input[i];
  25469. delete [] output[i];
  25470. }
  25471. DBGLOG("Finished testing %s sort", type==2?"Heap" : (type==1 ? "Insertion" : "Quick"));
  25472. }
  25473. void testQuickSort()
  25474. {
  25475. testSort(0);
  25476. }
  25477. void testHeapSort()
  25478. {
  25479. testSort(2);
  25480. }
  25481. void testMerge()
  25482. {
  25483. DBGLOG("testMerge");
  25484. init();
  25485. Owned<IPropertyTree> splitterNode = createPTree();
  25486. Owned <IRoxieServerActivityFactory> factory = createRoxieServerMergeActivityFactory(1, 1, *queryFactory, mergeActivityTestFactory, TAKmerge, *splitterNode);
  25487. factory->setInput(0,0,0);
  25488. factory->setInput(1,0,0);
  25489. Owned <IRoxieServerActivity> activity = factory->createActivity(ctx, NULL);
  25490. const char * test[] = { NULL, NULL };
  25491. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  25492. const char * test1122334455[] = { "1", "1", "2", "2", "3", "3", "4", "4", "5", "5", NULL, NULL };
  25493. const char * test11111[] = { "1", "1", "1", "1", "1", NULL, NULL };
  25494. const char * test1111111111[] = { "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", NULL, NULL };
  25495. const char * test11111_12345[] = { "1", "1", "1", "1", "1", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  25496. const char * test1111112345[] = { "1", "1", "1", "1", "1", "1", "2", "3", "4", "5", NULL, NULL };
  25497. 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 };
  25498. testActivity(activity, test, test, test);
  25499. testActivity(activity, test12345, test, test12345);
  25500. testActivity(activity, test, test12345, test12345);
  25501. testActivity(activity, test12345, test12345, test1122334455);
  25502. testActivity(activity, test11111, test, test11111);
  25503. testActivity(activity, test, test11111, test11111);
  25504. testActivity(activity, test11111, test11111, test1111111111);
  25505. testActivity(activity, test11111_12345, test, test1111112345);
  25506. testActivity(activity, test11111_12345, test11111_12345, test11111111111122334455);
  25507. // Should really test WHICH side gets kept...
  25508. // Should test with more than 2 inputs...
  25509. DBGLOG("testMerge done");
  25510. }
  25511. void testMergeDedup()
  25512. {
  25513. DBGLOG("testMergeDedup");
  25514. init();
  25515. MergeActivityTest::isDedup = true;
  25516. Owned<IPropertyTree> splitterNode = createPTree();
  25517. Owned <IRoxieServerActivityFactory> factory = createRoxieServerMergeActivityFactory(1, 1, *queryFactory, mergeActivityTestFactory, TAKmerge, *splitterNode);
  25518. factory->setInput(0,0,0);
  25519. factory->setInput(1,0,0);
  25520. Owned <IRoxieServerActivity> activity = factory->createActivity(ctx, NULL);
  25521. const char * test[] = { NULL, NULL };
  25522. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  25523. const char * test11111[] = { "1", "1", "1", "1", "1", NULL, NULL };
  25524. const char * test11111_12345[] = { "1", "1", "1", "1", "1", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  25525. const char * test1111112345[] = { "1", "1", "1", "1", "1", "1", "2", "3", "4", "5", NULL, NULL };
  25526. testActivity(activity, test11111, test, test11111); // No dedup within a stream
  25527. testActivity(activity, test11111, test11111, test11111); // No dedup within a stream
  25528. testActivity(activity, test, test11111, test11111);
  25529. testActivity(activity, test, test, test);
  25530. testActivity(activity, test12345, test, test12345);
  25531. testActivity(activity, test, test12345, test12345);
  25532. testActivity(activity, test12345, test12345, test12345);
  25533. testActivity(activity, test11111_12345, test, test1111112345);
  25534. testActivity(activity, test11111_12345, test11111_12345, test1111112345);
  25535. // Should really test WHICH side gets kept...
  25536. // Should test with more than 2 inputs...
  25537. DBGLOG("testMergeDedup done");
  25538. }
  25539. void doTestSplitter(unsigned numOutputs)
  25540. {
  25541. DBGLOG("testSplit %d", numOutputs);
  25542. init();
  25543. Owned<IPropertyTree> splitterNode = createPTree();
  25544. Owned <IRoxieServerActivityFactory> factory = createRoxieServerThroughSpillActivityFactory(*queryFactory, splitActivityTestFactory, numOutputs, *splitterNode);
  25545. factory->setInput(0,0,0);
  25546. Owned <IRoxieServerActivity> activity = factory->createActivity(ctx, NULL);
  25547. const char * test[] = { NULL, NULL };
  25548. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  25549. unsigned start = msTick();
  25550. testSplitActivity(factory, test, test, numOutputs, 0);
  25551. testSplitActivity(factory, test12345, test12345, numOutputs, 0);
  25552. testSplitActivity(factory, test12345, test12345, numOutputs, 100);
  25553. unsigned elapsed = msTick() - start;
  25554. DBGLOG("testSplit %d done in %dms", numOutputs, elapsed);
  25555. }
  25556. void testSplitter()
  25557. {
  25558. doTestSplitter(1);
  25559. doTestSplitter(2);
  25560. doTestSplitter(3);
  25561. doTestSplitter(10);
  25562. }
  25563. void testMiscellaneous()
  25564. {
  25565. DBGLOG("sizeof(CriticalSection)=%u", (unsigned) sizeof(CriticalSection));
  25566. DBGLOG("sizeof(SpinLock)=%u", (unsigned) sizeof(SpinLock));
  25567. DBGLOG("sizeof(CJoinGroup)=%u", (unsigned) sizeof(CJoinGroup));
  25568. ASSERT(sizeof(CJoinGroup) <= 120);
  25569. }
  25570. };
  25571. CPPUNIT_TEST_SUITE_REGISTRATION( CcdServerTest );
  25572. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( CcdServerTest, "CcdServerTest" );
  25573. #endif