ccdserver.cpp 998 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461
  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. OwnedConstRoxieRow in = inputStream->nextRow();
  10172. if (!in)
  10173. {
  10174. if (anyThisGroup)
  10175. {
  10176. anyThisGroup = false;
  10177. return NULL;
  10178. }
  10179. in.setown(inputStream->nextRow());
  10180. if (!in)
  10181. {
  10182. eof = true;
  10183. return NULL; // eof...
  10184. }
  10185. }
  10186. if (likely(helper.canMatch(in)))
  10187. {
  10188. unsigned outSize;
  10189. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  10190. try
  10191. {
  10192. outSize = helper.transform(rowBuilder, in);
  10193. }
  10194. catch (IException *E)
  10195. {
  10196. throw makeWrappedException(E);
  10197. }
  10198. if (outSize)
  10199. {
  10200. anyThisGroup = true;
  10201. processed++;
  10202. if (processed==rowLimit)
  10203. {
  10204. if (traceLevel > 4)
  10205. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  10206. helper.onLimitExceeded();
  10207. }
  10208. return rowBuilder.finalizeRowClear(outSize);
  10209. }
  10210. }
  10211. }
  10212. }
  10213. else
  10214. {
  10215. const void *ret = inputStream->nextRow();
  10216. if (ret)
  10217. {
  10218. processed++;
  10219. if (processed==rowLimit)
  10220. {
  10221. if (traceLevel > 4)
  10222. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  10223. ReleaseClearRoxieRow(ret);
  10224. helper.onLimitExceeded(); // should not return
  10225. throwUnexpected();
  10226. }
  10227. }
  10228. return ret;
  10229. }
  10230. }
  10231. };
  10232. class CRoxieServerSpillReadActivityFactory : public CRoxieServerActivityFactory
  10233. {
  10234. public:
  10235. CRoxieServerSpillReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  10236. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  10237. {
  10238. }
  10239. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  10240. {
  10241. return new CRoxieServerSpillReadActivity(_ctx, this, _probeManager);
  10242. }
  10243. virtual void addDependency(unsigned source, ThorActivityKind sourceKind, unsigned sourceIdx, int controlId, const char *edgeId)
  10244. {
  10245. if (sourceKind==TAKspill || sourceKind==TAKdiskwrite || sourceKind==TAKspillwrite) // Bit of a hack - codegen probably should differentiate
  10246. setInput(0, source, sourceIdx);
  10247. else
  10248. CRoxieServerActivityFactory::addDependency(source, kind, sourceIdx, controlId, edgeId);
  10249. }
  10250. };
  10251. IRoxieServerActivityFactory *createRoxieServerSpillReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  10252. {
  10253. return new CRoxieServerSpillReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  10254. }
  10255. //=================================================================================
  10256. class CRoxieServerSpillWriteActivity : public CRoxieServerActivity
  10257. {
  10258. public:
  10259. CRoxieServerSpillWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  10260. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  10261. {
  10262. }
  10263. ~CRoxieServerSpillWriteActivity()
  10264. {
  10265. }
  10266. virtual const void *nextRow()
  10267. {
  10268. ActivityTimer t(totalCycles, timeActivities);
  10269. return inputStream->nextRow();
  10270. }
  10271. };
  10272. //==================================================================================
  10273. class CRoxieServerDiskWriteActivity : public CRoxieServerInternalSinkActivity, implements IRoxiePublishCallback
  10274. {
  10275. protected:
  10276. Owned<IExtRowWriter> outSeq;
  10277. Owned<IOutputRowSerializer> rowSerializer;
  10278. Linked<IFileIOStream> diskout;
  10279. bool blockcompressed;
  10280. bool extend;
  10281. bool overwrite;
  10282. bool encrypted;
  10283. bool grouped;
  10284. IHThorDiskWriteArg &helper;
  10285. Owned<IRecordSize> diskmeta;
  10286. Owned<IRoxieWriteHandler> writer;
  10287. bool tallycrc;
  10288. unsigned __int64 uncompressedBytesWritten;
  10289. CRC32 crc;
  10290. void updateWorkUnitResult(unsigned __int64 reccount)
  10291. {
  10292. assertex(writer);
  10293. // MORE - a lot of this is common with hthor
  10294. WorkunitUpdate wu = ctx->updateWorkUnit();
  10295. if (wu)
  10296. {
  10297. OwnedRoxieString rawLogicalName = helper.getFileName();
  10298. StringBuffer lfn; // logical filename
  10299. expandLogicalFilename(lfn, rawLogicalName, wu, false, false);
  10300. if (lfn.length())
  10301. {
  10302. unsigned flags = helper.getFlags();
  10303. WUFileKind fileKind;
  10304. if (TDXtemporary & flags)
  10305. fileKind = WUFileTemporary;
  10306. else if(TDXjobtemp & flags)
  10307. fileKind = WUFileJobOwned;
  10308. else if(TDWowned & flags)
  10309. fileKind = WUFileOwned;
  10310. else
  10311. fileKind = WUFileStandard;
  10312. StringArray clusters;
  10313. writer->getClusters(clusters);
  10314. wu->addFile(lfn.str(), &clusters, helper.getTempUsageCount(), fileKind, NULL);
  10315. if (!(flags & TDXtemporary) && helper.getSequence() >= 0)
  10316. {
  10317. Owned<IWUResult> result = wu->updateResultBySequence(helper.getSequence());
  10318. if (result)
  10319. {
  10320. result->setResultTotalRowCount(reccount);
  10321. result->setResultStatus(ResultStatusCalculated);
  10322. if (helper.getFlags() & TDWresult)
  10323. result->setResultFilename(lfn.str());
  10324. else
  10325. result->setResultLogicalName(lfn.str());
  10326. }
  10327. }
  10328. }
  10329. }
  10330. }
  10331. void resolve()
  10332. {
  10333. OwnedRoxieString rawLogicalName = helper.getFileName();
  10334. assertex(rawLogicalName);
  10335. assertex((helper.getFlags() & TDXtemporary) == 0);
  10336. StringArray clusters;
  10337. unsigned clusterIdx = 0;
  10338. while(true)
  10339. {
  10340. OwnedRoxieString cluster(helper.getCluster(clusterIdx));
  10341. if(!cluster)
  10342. break;
  10343. clusters.append(cluster);
  10344. clusterIdx++;
  10345. }
  10346. if (clusters.length())
  10347. {
  10348. if (extend)
  10349. throw MakeStringException(0, "Cannot combine EXTEND and CLUSTER flags on disk write of file %s", rawLogicalName.get());
  10350. }
  10351. else
  10352. {
  10353. if (roxieName.length())
  10354. clusters.append(roxieName.str());
  10355. else
  10356. clusters.append(".");
  10357. }
  10358. writer.setown(ctx->createLFN(rawLogicalName, overwrite, extend, clusters));
  10359. // MORE - need to check somewhere that single part if it's an existing file or an external one...
  10360. }
  10361. public:
  10362. CRoxieServerDiskWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  10363. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, 0), helper((IHThorDiskWriteArg &) basehelper)
  10364. {
  10365. extend = ((helper.getFlags() & TDWextend) != 0);
  10366. overwrite = ((helper.getFlags() & TDWoverwrite) != 0);
  10367. grouped = (helper.getFlags() & TDXgrouped) != 0;
  10368. diskmeta.set(helper.queryDiskRecordSize()->querySerializedDiskMeta());
  10369. if (grouped)
  10370. diskmeta.setown(createDeltaRecordSize(diskmeta, +1));
  10371. blockcompressed = (((helper.getFlags() & TDWnewcompress) != 0) || (((helper.getFlags() & TDXcompress) != 0) && (diskmeta->getFixedSize() >= MIN_ROWCOMPRESS_RECSIZE))); //always use new compression
  10372. encrypted = false; // set later
  10373. tallycrc = true;
  10374. uncompressedBytesWritten = 0;
  10375. }
  10376. ~CRoxieServerDiskWriteActivity()
  10377. {
  10378. }
  10379. virtual bool needsAllocator() const
  10380. {
  10381. return true;
  10382. }
  10383. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10384. {
  10385. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  10386. resolve();
  10387. Owned<IFileIO> io;
  10388. void *ekey;
  10389. size32_t ekeylen;
  10390. helper.getEncryptKey(ekeylen, ekey);
  10391. Owned<ICompressor> ecomp;
  10392. if (ekeylen!=0)
  10393. {
  10394. ecomp.setown(createAESCompressor256(ekeylen,ekey));
  10395. memset(ekey,0,ekeylen);
  10396. rtlFree(ekey);
  10397. encrypted = true;
  10398. blockcompressed = true;
  10399. }
  10400. if (blockcompressed)
  10401. io.setown(createCompressedFileWriter(writer->queryFile(), (diskmeta->isFixedSize() ? diskmeta->getFixedSize() : 0), extend, true, ecomp));
  10402. else
  10403. io.setown(writer->queryFile()->open(extend ? IFOwrite : IFOcreate));
  10404. if (!io)
  10405. throw MakeStringException(errno, "Failed to create%s file %s for writing", (encrypted ? " encrypted" : (blockcompressed ? " compressed" : "")), writer->queryFile()->queryFilename());
  10406. diskout.setown(createBufferedIOStream(io));
  10407. if (extend)
  10408. diskout->seek(0, IFSend);
  10409. tallycrc = !(helper.getFlags() & TDRnocrccheck) && !blockcompressed;
  10410. Owned<IRowInterfaces> rowIf = createRowInterfaces(input->queryOutputMeta(), activityId, factory->getHeapFlags(), ctx->queryCodeContext());
  10411. rowSerializer.set(rowIf->queryRowSerializer());
  10412. unsigned rwFlags = rw_autoflush;
  10413. if(grouped)
  10414. rwFlags |= rw_grouped;
  10415. if(tallycrc)
  10416. rwFlags |= rw_crc;
  10417. outSeq.setown(createRowWriter(diskout, rowIf, rwFlags));
  10418. }
  10419. virtual void stop()
  10420. {
  10421. if (aborted)
  10422. {
  10423. if (writer)
  10424. writer->finish(false, this);
  10425. }
  10426. else
  10427. {
  10428. if (outSeq)
  10429. outSeq->flush(&crc);
  10430. if (outSeq)
  10431. uncompressedBytesWritten = outSeq->getPosition();
  10432. outSeq.clear();
  10433. diskout.clear(); // Make sure file is properly closed or date may not match published info
  10434. if (writer)
  10435. {
  10436. updateWorkUnitResult(processed);
  10437. writer->finish(true, this);
  10438. }
  10439. }
  10440. writer.clear();
  10441. CRoxieServerActivity::stop();
  10442. }
  10443. virtual void reset()
  10444. {
  10445. CRoxieServerActivity::reset();
  10446. diskout.clear();
  10447. outSeq.clear();
  10448. writer.clear();
  10449. uncompressedBytesWritten = 0;
  10450. crc.reset();
  10451. }
  10452. virtual void onExecute()
  10453. {
  10454. for (;;)
  10455. {
  10456. const void *row = inputStream->nextRow();
  10457. if (!row)
  10458. {
  10459. row = inputStream->nextRow();
  10460. if (!row)
  10461. break;
  10462. if (grouped)
  10463. outSeq->putRow(NULL);
  10464. }
  10465. processed++;
  10466. outSeq->putRow(row);
  10467. }
  10468. }
  10469. virtual void setFileProperties(IFileDescriptor *desc) const
  10470. {
  10471. IPropertyTree &partProps = desc->queryPart(0)->queryProperties(); //properties of the first file part.
  10472. IPropertyTree &fileProps = desc->queryProperties(); // properties of the logical file
  10473. if (blockcompressed)
  10474. {
  10475. // caller has already set @size from file size...
  10476. fileProps.setPropBool("@blockCompressed", true);
  10477. fileProps.setPropInt64("@compressedSize", partProps.getPropInt64("@size", 0));
  10478. partProps.setPropInt64("@compressedSize", partProps.getPropInt64("@size", 0));
  10479. fileProps.setPropInt64("@size", uncompressedBytesWritten);
  10480. partProps.setPropInt64("@size", uncompressedBytesWritten);
  10481. }
  10482. else if (tallycrc && crc.get())
  10483. partProps.setPropInt64("@fileCrc", crc.get());
  10484. if (encrypted)
  10485. fileProps.setPropBool("@encrypted", true);
  10486. fileProps.setPropInt64("@recordCount", processed);
  10487. unsigned flags = helper.getFlags();
  10488. if (flags & TDWpersist)
  10489. fileProps.setPropBool("@persistent", true);
  10490. if (grouped)
  10491. fileProps.setPropBool("@grouped", true);
  10492. if (flags & (TDWowned|TDXjobtemp|TDXtemporary))
  10493. fileProps.setPropBool("@owned", true);
  10494. if (flags & TDWresult)
  10495. fileProps.setPropBool("@result", true);
  10496. IConstWorkUnit *workUnit = ctx->queryWorkUnit();
  10497. if (workUnit)
  10498. {
  10499. fileProps.setProp("@owner", workUnit->queryUser());
  10500. fileProps.setProp("@workunit", workUnit->queryWuid());
  10501. fileProps.setProp("@job", workUnit->queryJobName());
  10502. }
  10503. if (flags & TDWexpires)
  10504. setExpiryTime(fileProps, helper.getExpiryDays());
  10505. if (flags & TDWupdate)
  10506. {
  10507. unsigned eclCRC;
  10508. unsigned __int64 totalCRC;
  10509. helper.getUpdateCRCs(eclCRC, totalCRC);
  10510. fileProps.setPropInt("@eclCRC", eclCRC);
  10511. fileProps.setPropInt64("@totalCRC", totalCRC);
  10512. }
  10513. fileProps.setPropInt("@formatCrc", helper.getFormatCrc());
  10514. IRecordSize * inputMeta = input->queryOutputMeta();
  10515. if ((inputMeta->isFixedSize()) && !isOutputTransformed())
  10516. fileProps.setPropInt("@recordSize", inputMeta->getFixedSize() + (grouped ? 1 : 0));
  10517. const char *recordECL = helper.queryRecordECL();
  10518. if (recordECL && *recordECL)
  10519. fileProps.setProp("ECL", recordECL);
  10520. setRtlFormat(fileProps, helper.queryDiskRecordSize());
  10521. fileProps.setProp("@kind", "flat"); // default, derivitives may override
  10522. }
  10523. virtual IUserDescriptor *queryUserDescriptor() const
  10524. {
  10525. IConstWorkUnit *workUnit = ctx->queryWorkUnit();
  10526. if (workUnit)
  10527. return workUnit->queryUserDescriptor();//ad-hoc mode
  10528. else
  10529. {
  10530. Owned<IRoxieDaliHelper> daliHelper = connectToDali(false);
  10531. if (daliHelper)
  10532. return daliHelper->queryUserDescriptor();//predeployed query mode
  10533. }
  10534. return NULL;
  10535. }
  10536. virtual bool isOutputTransformed() const { return false; }
  10537. };
  10538. //=================================================================================
  10539. class CRoxieServerCsvWriteActivity : public CRoxieServerDiskWriteActivity
  10540. {
  10541. IHThorCsvWriteArg &csvHelper;
  10542. CSVOutputStream csvOutput;
  10543. public:
  10544. CRoxieServerCsvWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  10545. : CRoxieServerDiskWriteActivity(_ctx, _factory, _probeManager), csvHelper(static_cast<IHThorCsvWriteArg &>(helper))
  10546. {
  10547. csvOutput.init(csvHelper.queryCsvParameters(), false);
  10548. }
  10549. virtual void onExecute()
  10550. {
  10551. OwnedRoxieString header(csvHelper.queryCsvParameters()->getHeader());
  10552. if (header)
  10553. {
  10554. csvOutput.beginLine();
  10555. csvOutput.writeHeaderLn(strlen(header), header);
  10556. diskout->write(csvOutput.length(), csvOutput.str());
  10557. }
  10558. for (;;)
  10559. {
  10560. const void *nextrec = inputStream->ungroupedNextRow();
  10561. if (!nextrec)
  10562. break;
  10563. processed++;
  10564. csvOutput.beginLine();
  10565. csvHelper.writeRow((const byte *)nextrec, &csvOutput);
  10566. csvOutput.endLine();
  10567. diskout->write(csvOutput.length(), csvOutput.str());
  10568. ReleaseRoxieRow(nextrec);
  10569. }
  10570. OwnedRoxieString footer(csvHelper.queryCsvParameters()->getFooter());
  10571. if (footer)
  10572. {
  10573. csvOutput.beginLine();
  10574. csvOutput.writeHeaderLn(strlen(footer), footer);
  10575. diskout->write(csvOutput.length(), csvOutput.str());
  10576. }
  10577. }
  10578. virtual void setFileProperties(IFileDescriptor *desc) const
  10579. {
  10580. CRoxieServerDiskWriteActivity::setFileProperties(desc);
  10581. IPropertyTree &props = desc->queryProperties();
  10582. props.setProp("@format","utf8n");
  10583. ICsvParameters *csvParameters = csvHelper.queryCsvParameters();
  10584. StringBuffer separator;
  10585. OwnedRoxieString rs(csvParameters->getSeparator(0));
  10586. const char *s = rs;
  10587. while (s && *s)
  10588. {
  10589. if (',' == *s)
  10590. separator.append("\\,");
  10591. else
  10592. separator.append(*s);
  10593. ++s;
  10594. }
  10595. props.setProp("@csvSeparate", separator.str());
  10596. props.setProp("@csvQuote", rs.setown(csvParameters->getQuote(0)));
  10597. props.setProp("@csvTerminate", rs.setown(csvParameters->getTerminator(0)));
  10598. props.setProp("@csvEscape", rs.setown(csvParameters->getEscape(0)));
  10599. props.setProp("@kind", "csv");
  10600. }
  10601. virtual bool isOutputTransformed() const { return true; }
  10602. };
  10603. class CRoxieServerXmlWriteActivity : public CRoxieServerDiskWriteActivity
  10604. {
  10605. IHThorXmlWriteArg &xmlHelper;
  10606. StringAttr rowTag;
  10607. ThorActivityKind kind;
  10608. unsigned headerLength;
  10609. unsigned footerLength;
  10610. public:
  10611. CRoxieServerXmlWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, ThorActivityKind _kind)
  10612. : CRoxieServerDiskWriteActivity(_ctx, _factory, _probeManager), xmlHelper(static_cast<IHThorXmlWriteArg &>(helper)), kind(_kind), headerLength(0), footerLength(0)
  10613. {
  10614. }
  10615. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10616. {
  10617. CRoxieServerDiskWriteActivity::start(parentExtractSize, parentExtract, paused);
  10618. OwnedRoxieString xmlpath(xmlHelper.getXmlIteratorPath());
  10619. if (!xmlpath)
  10620. rowTag.set(DEFAULTXMLROWTAG);
  10621. else
  10622. {
  10623. const char *path = xmlpath;
  10624. if (*path == '/') path++;
  10625. if (strchr(path, '/')) UNIMPLEMENTED; // more what do we do with /mydata/row
  10626. rowTag.set(path);
  10627. }
  10628. }
  10629. virtual void onExecute()
  10630. {
  10631. StringBuffer header;
  10632. OwnedRoxieString suppliedHeader(xmlHelper.getHeader());
  10633. if (kind==TAKjsonwrite)
  10634. buildJsonHeader(header, suppliedHeader, rowTag);
  10635. else if (suppliedHeader)
  10636. header.set(suppliedHeader);
  10637. else
  10638. header.append(DEFAULTXMLHEADER).newline();
  10639. headerLength = header.length();
  10640. diskout->write(header.length(), header.str());
  10641. Owned<IXmlWriterExt> writer = createIXmlWriterExt(xmlHelper.getXmlFlags(), 0, NULL, (kind==TAKjsonwrite) ? WTJSON : WTStandard);
  10642. writer->outputBeginArray(rowTag); //need to set this
  10643. writer->clear(); //but not output it
  10644. for (;;)
  10645. {
  10646. OwnedConstRoxieRow nextrec = inputStream->ungroupedNextRow();
  10647. if (!nextrec)
  10648. break;
  10649. processed++;
  10650. writer->clear().outputBeginNested(rowTag, false);
  10651. xmlHelper.toXML((const byte *)nextrec.get(), *writer);
  10652. writer->outputEndNested(rowTag);
  10653. diskout->write(writer->length(), writer->str());
  10654. }
  10655. OwnedRoxieString suppliedFooter(xmlHelper.getFooter());
  10656. StringBuffer footer;
  10657. if (kind==TAKjsonwrite)
  10658. buildJsonFooter(footer.newline(), suppliedFooter, rowTag);
  10659. else if (suppliedFooter)
  10660. footer.append(suppliedFooter);
  10661. else
  10662. footer.append(DEFAULTXMLFOOTER);
  10663. footerLength=footer.length();
  10664. diskout->write(footer.length(), footer);
  10665. }
  10666. virtual void reset()
  10667. {
  10668. CRoxieServerDiskWriteActivity::reset();
  10669. rowTag.clear();
  10670. }
  10671. virtual void setFileProperties(IFileDescriptor *desc) const
  10672. {
  10673. CRoxieServerDiskWriteActivity::setFileProperties(desc);
  10674. desc->queryProperties().setProp("@format","utf8n");
  10675. desc->queryProperties().setProp("@rowTag",rowTag.get());
  10676. desc->queryProperties().setProp("@kind", (kind==TAKjsonwrite) ? "json" : "xml");
  10677. desc->queryProperties().setPropInt(FPheaderLength, headerLength);
  10678. desc->queryProperties().setPropInt(FPfooterLength, footerLength);
  10679. }
  10680. virtual bool isOutputTransformed() const { return true; }
  10681. };
  10682. class CRoxieServerDiskWriteActivityFactory : public CRoxieServerMultiOutputFactory
  10683. {
  10684. bool isRoot;
  10685. bool isTemp;
  10686. public:
  10687. CRoxieServerDiskWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  10688. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  10689. {
  10690. Owned<IHThorDiskWriteArg> helper = (IHThorDiskWriteArg *) helperFactory();
  10691. isTemp = (helper->getFlags() & TDXtemporary) != 0;
  10692. setNumOutputs(helper->getTempUsageCount());
  10693. if (_kind != TAKspillwrite)
  10694. assertex(numOutputs == 0);
  10695. }
  10696. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  10697. {
  10698. switch (numOutputs)
  10699. {
  10700. case 0:
  10701. switch (kind)
  10702. {
  10703. case TAKdiskwrite: return new CRoxieServerDiskWriteActivity(_ctx, this, _probeManager);
  10704. case TAKcsvwrite: return new CRoxieServerCsvWriteActivity(_ctx, this, _probeManager);
  10705. case TAKxmlwrite:
  10706. case TAKjsonwrite:
  10707. return new CRoxieServerXmlWriteActivity(_ctx, this, _probeManager, kind);
  10708. };
  10709. throwUnexpected();
  10710. case 1:
  10711. return new CRoxieServerSpillWriteActivity(_ctx, this, _probeManager);
  10712. default:
  10713. return new CRoxieServerThroughSpillActivity(_ctx, this, _probeManager, numOutputs);
  10714. }
  10715. }
  10716. virtual bool isSink() const
  10717. {
  10718. return numOutputs == 0 && !isTemp; // MORE - check with Gavin if this is right if not a temp but reread in same job...
  10719. }
  10720. };
  10721. IRoxieServerActivityFactory *createRoxieServerDiskWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  10722. {
  10723. return new CRoxieServerDiskWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  10724. }
  10725. //=================================================================================
  10726. class CRoxieServerIndexWriteActivity : public CRoxieServerInternalSinkActivity, implements IRoxiePublishCallback
  10727. {
  10728. IHThorIndexWriteArg &helper;
  10729. bool overwrite;
  10730. Owned<ClusterWriteHandler> clusterHandler;
  10731. Owned<IRoxieWriteHandler> writer;
  10732. unsigned __int64 reccount;
  10733. unsigned int fileCrc;
  10734. StringBuffer filename;
  10735. unsigned __int64 duplicateKeyCount = 0;
  10736. unsigned __int64 cummulativeDuplicateKeyCount = 0;
  10737. void updateWorkUnitResult()
  10738. {
  10739. // MORE - a lot of this is common with hthor
  10740. WorkunitUpdate wu = ctx->updateWorkUnit();
  10741. if (wu)
  10742. {
  10743. OwnedRoxieString rawLogicalName = helper.getFileName();
  10744. StringBuffer lfn; // logical filename
  10745. expandLogicalFilename(lfn, rawLogicalName, wu, false, false);
  10746. if (lfn.length())
  10747. {
  10748. if (helper.getSequence() >= 0)
  10749. {
  10750. Owned<IWUResult> result = wu->updateResultBySequence(helper.getSequence());
  10751. if (result)
  10752. {
  10753. result->setResultTotalRowCount(reccount);
  10754. result->setResultStatus(ResultStatusCalculated);
  10755. result->setResultLogicalName(lfn.str());
  10756. }
  10757. }
  10758. if(clusterHandler)
  10759. clusterHandler->finish(writer->queryFile());
  10760. CTXLOG("Created roxie index file %s", lfn.str());
  10761. }
  10762. }
  10763. }
  10764. virtual void resolve()
  10765. {
  10766. StringArray clusters;
  10767. unsigned clusterIdx = 0;
  10768. while(true)
  10769. {
  10770. OwnedRoxieString cluster(helper.getCluster(clusterIdx));
  10771. if(!cluster)
  10772. break;
  10773. clusters.append(cluster);
  10774. clusterIdx++;
  10775. }
  10776. if (roxieName.length())
  10777. clusters.append(roxieName.str());
  10778. else
  10779. clusters.append(".");
  10780. OwnedRoxieString fname(helper.getFileName());
  10781. writer.setown(ctx->createLFN(fname, overwrite, false, clusters)); // MORE - if there's a workunit, use if for scope.
  10782. filename.set(writer->queryFile()->queryFilename());
  10783. if (writer->queryFile()->exists())
  10784. {
  10785. if (overwrite)
  10786. {
  10787. CTXLOG("Removing existing %s from DFS",filename.str());
  10788. writer->queryFile()->remove();
  10789. }
  10790. else
  10791. throw MakeStringException(99, "Cannot write index file %s, file already exists (missing OVERWRITE attribute?)", filename.str());
  10792. }
  10793. }
  10794. void buildUserMetadata(Owned<IPropertyTree> & metadata)
  10795. {
  10796. size32_t nameLen;
  10797. char * nameBuff;
  10798. size32_t valueLen;
  10799. char * valueBuff;
  10800. unsigned idx = 0;
  10801. while(helper.getIndexMeta(nameLen, nameBuff, valueLen, valueBuff, idx++))
  10802. {
  10803. StringBuffer name(nameLen, nameBuff);
  10804. StringBuffer value(valueLen, valueBuff);
  10805. if(*nameBuff == '_' && strcmp(name, "_nodeSize") != 0)
  10806. {
  10807. OwnedRoxieString fname(helper.getFileName());
  10808. throw MakeStringException(0, "Invalid name %s in user metadata for index %s (names beginning with underscore are reserved)", name.str(), fname.get());
  10809. }
  10810. if(!validateXMLTag(name.str()))
  10811. {
  10812. OwnedRoxieString fname(helper.getFileName());
  10813. throw MakeStringException(0, "Invalid name %s in user metadata for index %s (not legal XML element name)", name.str(), fname.get());
  10814. }
  10815. if(!metadata)
  10816. metadata.setown(createPTree("metadata", ipt_fast));
  10817. metadata->setProp(name.str(), value.str());
  10818. }
  10819. }
  10820. void buildLayoutMetadata(Owned<IPropertyTree> & metadata)
  10821. {
  10822. if(!metadata)
  10823. metadata.setown(createPTree("metadata", ipt_fast));
  10824. metadata->setProp("_record_ECL", helper.queryRecordECL());
  10825. setRtlFormat(*metadata, helper.queryDiskRecordSize());
  10826. }
  10827. public:
  10828. CRoxieServerIndexWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  10829. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, 0), helper(static_cast<IHThorIndexWriteArg &>(basehelper))
  10830. {
  10831. overwrite = ((helper.getFlags() & TIWoverwrite) != 0);
  10832. reccount = 0;
  10833. fileCrc = 0;
  10834. }
  10835. ~CRoxieServerIndexWriteActivity()
  10836. {
  10837. }
  10838. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10839. {
  10840. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  10841. resolve();
  10842. }
  10843. virtual void onExecute()
  10844. {
  10845. bool isVariable = helper.queryDiskRecordSize()->isVariableSize();
  10846. size32_t fileposSize = hasTrailingFileposition(helper.queryDiskRecordSize()->queryTypeInfo()) ? sizeof(offset_t) : 0;
  10847. size32_t maxDiskRecordSize;
  10848. if (isVariable)
  10849. {
  10850. if (helper.getFlags() & TIWmaxlength)
  10851. maxDiskRecordSize = helper.getMaxKeySize();
  10852. else
  10853. maxDiskRecordSize = KEYBUILD_MAXLENGTH; // Current default behaviour, could be improved in the future
  10854. }
  10855. else
  10856. maxDiskRecordSize = helper.queryDiskRecordSize()->getFixedSize()-fileposSize;
  10857. if (maxDiskRecordSize > KEYBUILD_MAXLENGTH)
  10858. throw MakeStringException(99, "Index maximum record length (%d) exceeds 32k internal limit", maxDiskRecordSize);
  10859. OwnedMalloc<char> rowBuffer(maxDiskRecordSize, true);
  10860. fileCrc = -1;
  10861. {
  10862. Owned<IFileIO> io;
  10863. try
  10864. {
  10865. io.setown(writer->queryFile()->open(IFOcreate));
  10866. }
  10867. catch(IException * e)
  10868. {
  10869. e->Release();
  10870. clearKeyStoreCache(false);
  10871. io.setown(writer->queryFile()->open(IFOcreate));
  10872. }
  10873. if(!io)
  10874. throw MakeStringException(errno, "Failed to create file %s for writing", filename.str());
  10875. Owned<IFileIOStream> out = createIOStream(io);
  10876. unsigned flags = COL_PREFIX | HTREE_FULLSORT_KEY;
  10877. if (helper.getFlags() & TIWrowcompress)
  10878. flags |= HTREE_COMPRESSED_KEY|HTREE_QUICK_COMPRESSED_KEY;
  10879. else if (!(helper.getFlags() & TIWnolzwcompress))
  10880. flags |= HTREE_COMPRESSED_KEY;
  10881. if (isVariable)
  10882. flags |= HTREE_VARSIZE;
  10883. Owned<IPropertyTree> metadata;
  10884. buildUserMetadata(metadata);
  10885. buildLayoutMetadata(metadata);
  10886. unsigned nodeSize = metadata ? metadata->getPropInt("_nodeSize", NODESIZE) : NODESIZE;
  10887. Owned<IKeyBuilder> builder = createKeyBuilder(out, flags, maxDiskRecordSize, nodeSize, helper.getKeyedSize(), 0, &helper, true, false);
  10888. class BcWrapper : implements IBlobCreator
  10889. {
  10890. IKeyBuilder *builder;
  10891. public:
  10892. BcWrapper(IKeyBuilder *_builder) : builder(_builder) {}
  10893. virtual unsigned __int64 createBlob(size32_t size, const void * ptr)
  10894. {
  10895. return builder->createBlob(size, (const char *) ptr);
  10896. }
  10897. } bc(builder);
  10898. // Loop thru the results
  10899. for (;;)
  10900. {
  10901. OwnedConstRoxieRow nextrec(inputStream->ungroupedNextRow());
  10902. if (!nextrec)
  10903. break;
  10904. try
  10905. {
  10906. unsigned __int64 fpos=0;
  10907. RtlStaticRowBuilder rowBuilder(rowBuffer, maxDiskRecordSize);
  10908. size32_t thisSize = helper.transform(rowBuilder, nextrec, &bc, fpos);
  10909. builder->processKeyData(rowBuffer, fpos, thisSize);
  10910. }
  10911. catch(IException * e)
  10912. {
  10913. throw makeWrappedException(e);
  10914. }
  10915. reccount++;
  10916. }
  10917. duplicateKeyCount = builder->getDuplicateCount();
  10918. cummulativeDuplicateKeyCount += duplicateKeyCount;
  10919. builder->finish(metadata, &fileCrc);
  10920. }
  10921. }
  10922. virtual void stop()
  10923. {
  10924. if (writer)
  10925. {
  10926. if (!aborted)
  10927. updateWorkUnitResult();
  10928. writer->finish(!aborted, this);
  10929. writer.clear();
  10930. }
  10931. CRoxieServerActivity::stop();
  10932. }
  10933. virtual void reset()
  10934. {
  10935. noteStatistic(StNumDuplicateKeys, cummulativeDuplicateKeyCount);
  10936. CRoxieServerActivity::reset();
  10937. writer.clear();
  10938. }
  10939. //interface IRoxiePublishCallback
  10940. virtual void setFileProperties(IFileDescriptor *desc) const
  10941. {
  10942. IPropertyTree &partProps = desc->queryPart(0)->queryProperties(); //properties of the first file part.
  10943. IPropertyTree &fileProps = desc->queryProperties(); // properties of the logical file
  10944. // Now publish to name services
  10945. StringBuffer dir,base;
  10946. offset_t indexFileSize = writer->queryFile()->size();
  10947. if(clusterHandler)
  10948. clusterHandler->splitPhysicalFilename(dir, base);
  10949. else
  10950. {
  10951. // Check filename is URL and get localpath, only actually necessary if force remote reads are are on
  10952. RemoteFilename rfn;
  10953. rfn.setRemotePath(filename);
  10954. StringBuffer localPath;
  10955. rfn.getLocalPath(localPath);
  10956. splitFilename(localPath, &dir, &dir, &base, &base);
  10957. }
  10958. desc->setDefaultDir(dir.str());
  10959. //properties of the first file part.
  10960. Owned<IPropertyTree> attrs;
  10961. if(clusterHandler)
  10962. attrs.setown(createPTree("Part", ipt_fast)); // clusterHandler is going to set attributes
  10963. else
  10964. {
  10965. // add cluster
  10966. StringBuffer mygroupname;
  10967. desc->setNumParts(1);
  10968. desc->setPartMask(base.str());
  10969. attrs.set(&desc->queryPart(0)->queryProperties());
  10970. }
  10971. attrs->setPropInt64("@size", indexFileSize);
  10972. CDateTime createTime, modifiedTime, accessedTime;
  10973. writer->queryFile()->getTime(&createTime, &modifiedTime, &accessedTime);
  10974. // round file time down to nearest sec. Nanosec accurancy is not preserved elsewhere and can lead to mismatch later.
  10975. unsigned hour, min, sec, nanosec;
  10976. modifiedTime.getTime(hour, min, sec, nanosec);
  10977. modifiedTime.setTime(hour, min, sec, 0);
  10978. StringBuffer timestr;
  10979. modifiedTime.getString(timestr);
  10980. if(timestr.length())
  10981. attrs->setProp("@modified", timestr.str());
  10982. if(clusterHandler)
  10983. clusterHandler->setDescriptorParts(desc, base.str(), attrs);
  10984. // properties of the logical file
  10985. IPropertyTree & properties = desc->queryProperties();
  10986. properties.setProp("@kind", "key");
  10987. properties.setPropInt64("@size", indexFileSize);
  10988. properties.setPropInt64("@recordCount", reccount);
  10989. properties.setPropInt64("@duplicateKeyCount", duplicateKeyCount);
  10990. WorkunitUpdate workUnit = ctx->updateWorkUnit();
  10991. if (workUnit)
  10992. {
  10993. properties.setProp("@owner", workUnit->queryUser());
  10994. properties.setProp("@workunit", workUnit->queryWuid());
  10995. properties.setProp("@job", workUnit->queryJobName());
  10996. }
  10997. char const * rececl = helper.queryRecordECL();
  10998. if(rececl && *rececl)
  10999. properties.setProp("ECL", rececl);
  11000. if (helper.getFlags() & TIWexpires)
  11001. setExpiryTime(properties, helper.getExpiryDays());
  11002. if (helper.getFlags() & TIWupdate)
  11003. {
  11004. unsigned eclCRC;
  11005. unsigned __int64 totalCRC;
  11006. helper.getUpdateCRCs(eclCRC, totalCRC);
  11007. properties.setPropInt("@eclCRC", eclCRC);
  11008. properties.setPropInt64("@totalCRC", totalCRC);
  11009. }
  11010. properties.setPropInt("@fileCrc", fileCrc);
  11011. properties.setPropInt("@formatCrc", helper.getFormatCrc());
  11012. // Legacy record layout info
  11013. void * layoutMetaBuff;
  11014. size32_t layoutMetaSize;
  11015. if(helper.getIndexLayout(layoutMetaSize, layoutMetaBuff))
  11016. {
  11017. properties.setPropBin("_record_layout", layoutMetaSize, layoutMetaBuff);
  11018. rtlFree(layoutMetaBuff);
  11019. }
  11020. // New record layout info
  11021. setRtlFormat(properties, helper.queryDiskRecordSize());
  11022. // Bloom info
  11023. const IBloomBuilderInfo * const *bloomFilters = helper.queryBloomInfo();
  11024. while (bloomFilters && *bloomFilters)
  11025. {
  11026. const IBloomBuilderInfo *info = *bloomFilters++;
  11027. IPropertyTree *bloom = properties.addPropTree("Bloom");
  11028. bloom->setPropInt64("@bloomFieldMask", info->getBloomFields());
  11029. bloom->setPropInt64("@bloomLimit", info->getBloomLimit()); // MORE - if we didn't actually build because of the limit that might be interesting. Though that's going to vary by part.
  11030. VStringBuffer pval("%f", info->getBloomProbability());
  11031. bloom->setProp("@bloomProbability", pval.str());
  11032. }
  11033. }
  11034. IUserDescriptor *queryUserDescriptor() const
  11035. {
  11036. IConstWorkUnit *workUnit = ctx->queryWorkUnit();
  11037. if (workUnit)
  11038. return workUnit->queryUserDescriptor();//ad-hoc mode
  11039. else
  11040. {
  11041. Owned<IRoxieDaliHelper> daliHelper = connectToDali(false);
  11042. if (daliHelper)
  11043. return daliHelper->queryUserDescriptor();//predeployed query mode
  11044. }
  11045. return NULL;
  11046. }
  11047. };
  11048. //=================================================================================
  11049. class CRoxieServerIndexWriteActivityFactory : public CRoxieServerMultiOutputFactory
  11050. {
  11051. public:
  11052. CRoxieServerIndexWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  11053. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  11054. {
  11055. setNumOutputs(0);
  11056. }
  11057. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  11058. {
  11059. return new CRoxieServerIndexWriteActivity(_ctx, this, _probeManager);
  11060. }
  11061. virtual bool isSink() const
  11062. {
  11063. return true;
  11064. }
  11065. virtual const StatisticsMapping &queryStatsMapping() const
  11066. {
  11067. return indexWriteStatistics; // Overridden by anyone that needs more
  11068. }
  11069. };
  11070. IRoxieServerActivityFactory *createRoxieServerIndexWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  11071. {
  11072. return new CRoxieServerIndexWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  11073. }
  11074. //=================================================================================
  11075. static inline void getLimitType(unsigned flags, bool & limitFail, bool & limitOnFail)
  11076. {
  11077. if((flags & JFmatchAbortLimitSkips) != 0)
  11078. {
  11079. limitFail = false;
  11080. limitOnFail = false;
  11081. }
  11082. else
  11083. {
  11084. limitOnFail = ((flags & JFonfail) != 0);
  11085. limitFail = !limitOnFail;
  11086. }
  11087. }
  11088. class CRoxieServerJoinActivity : public CRoxieServerTwoInputActivity
  11089. {
  11090. enum { JSfill, JSfillleft, JSfillright, JScollate, JScompare, JSleftonly, JSrightonly } state;
  11091. IHThorJoinArg &helper;
  11092. ICompare * collate;
  11093. ICompare * collateupper;
  11094. ThorActivityKind activityKind;
  11095. bool leftOuterJoin;
  11096. bool rightOuterJoin;
  11097. bool exclude;
  11098. bool limitFail;
  11099. bool limitOnFail;
  11100. bool forceSpill;
  11101. unsigned keepLimit;
  11102. unsigned joinLimit;
  11103. unsigned atmostLimit;
  11104. unsigned abortLimit;
  11105. unsigned atmostsTriggered;
  11106. bool betweenjoin;
  11107. OwnedRowArray right;
  11108. const void * left;
  11109. const void * pendingRight;
  11110. unsigned rightIndex;
  11111. unsigned joinCounter;
  11112. BoolArray matchedRight;
  11113. bool matchedLeft;
  11114. Owned<IException> failingLimit;
  11115. ConstPointerArray filteredRight;
  11116. Owned<IRHLimitedCompareHelper> limitedhelper;
  11117. OwnedConstRoxieRow defaultLeft;
  11118. OwnedConstRoxieRow defaultRight;
  11119. Owned<IEngineRowAllocator> defaultLeftAllocator;
  11120. Owned<IEngineRowAllocator> defaultRightAllocator;
  11121. Owned<IGroupedInput> sortedLeft;
  11122. Owned<IGroupedInput> groupedSortedRight;
  11123. bool cloneLeft;
  11124. void createDefaultLeft()
  11125. {
  11126. if (!defaultLeft)
  11127. {
  11128. if (!defaultLeftAllocator)
  11129. defaultLeftAllocator.setown(createRowAllocator(input->queryOutputMeta()));
  11130. RtlDynamicRowBuilder rowBuilder(defaultLeftAllocator);
  11131. size32_t thisSize = helper.createDefaultLeft(rowBuilder);
  11132. defaultLeft.setown(rowBuilder.finalizeRowClear(thisSize));
  11133. }
  11134. }
  11135. void createDefaultRight()
  11136. {
  11137. if (!defaultRight)
  11138. {
  11139. if (!defaultRightAllocator)
  11140. defaultRightAllocator.setown(createRowAllocator(input1->queryOutputMeta()));
  11141. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  11142. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  11143. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  11144. }
  11145. }
  11146. public:
  11147. CRoxieServerJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _forceSpill)
  11148. : CRoxieServerTwoInputActivity(_ctx, _factory, _probeManager), helper((IHThorJoinArg &)basehelper), forceSpill(_forceSpill)
  11149. {
  11150. // MORE - some of this should be done in factory
  11151. unsigned joinFlags = helper.getJoinFlags();
  11152. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  11153. rightOuterJoin = (joinFlags & JFrightouter) != 0;
  11154. exclude = (joinFlags & JFexclude) != 0;
  11155. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  11156. getLimitType(joinFlags, limitFail, limitOnFail);
  11157. if (joinFlags & JFslidingmatch)
  11158. {
  11159. betweenjoin = true;
  11160. collate = helper.queryCompareLeftRightLower();
  11161. collateupper = helper.queryCompareLeftRightUpper();
  11162. }
  11163. else
  11164. {
  11165. betweenjoin = false;
  11166. collate = collateupper = helper.queryCompareLeftRight();
  11167. }
  11168. rightIndex = 0;
  11169. joinCounter = 0;
  11170. state = JSfill;
  11171. matchedLeft = false;
  11172. joinLimit = 0;
  11173. keepLimit = 0; // wait until ctx available
  11174. atmostLimit = 0; // wait until ctx available
  11175. abortLimit = 0; // wait until ctx available
  11176. atmostsTriggered = 0;
  11177. assertex((joinFlags & (JFfirst | JFfirstleft | JFfirstright)) == 0);
  11178. left = NULL;
  11179. pendingRight = NULL;
  11180. activityKind = _factory->getKind();
  11181. }
  11182. virtual bool needsAllocator() const { return true; }
  11183. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11184. {
  11185. left = NULL;
  11186. rightIndex = 0;
  11187. joinCounter = 0;
  11188. state = JSfill;
  11189. matchedLeft = false;
  11190. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  11191. keepLimit = helper.getKeepLimit();
  11192. if (keepLimit == 0)
  11193. keepLimit = (unsigned)-1;
  11194. atmostsTriggered = 0;
  11195. atmostLimit = helper.getJoinLimit();
  11196. if(atmostLimit == 0)
  11197. atmostLimit = (unsigned)-1;
  11198. else
  11199. assertex(!rightOuterJoin && !betweenjoin);
  11200. abortLimit = helper.getMatchAbortLimit();
  11201. if (abortLimit == 0)
  11202. abortLimit = (unsigned)-1;
  11203. if (rightOuterJoin)
  11204. createDefaultLeft();
  11205. if ((leftOuterJoin && (activityKind==TAKjoin || activityKind==TAKjoinlight || activityKind==TAKdenormalizegroup)) || limitOnFail)
  11206. createDefaultRight();
  11207. bool isStable = (helper.getJoinFlags() & JFunstable) == 0;
  11208. RoxieSortAlgorithm sortAlgorithm;
  11209. if (forceSpill)
  11210. sortAlgorithm = isStable ? stableSpillingQuickSortAlgorithm : spillingQuickSortAlgorithm;
  11211. else
  11212. sortAlgorithm = isStable ? stableQuickSortAlgorithm : quickSortAlgorithm;
  11213. if (helper.isLeftAlreadySorted())
  11214. sortedLeft.setown(createDegroupedInputReader(inputStream));
  11215. else
  11216. sortedLeft.setown(createSortedInputReader(inputStream, createSortAlgorithm(sortAlgorithm, helper.queryCompareLeft(), ctx->queryRowManager(), input->queryOutputMeta(), ctx->queryCodeContext(), tempDirectory, activityId)));
  11217. ICompare *compareRight = helper.queryCompareRight();
  11218. if (helper.isRightAlreadySorted())
  11219. groupedSortedRight.setown(createGroupedInputReader(inputStream1, compareRight));
  11220. else
  11221. groupedSortedRight.setown(createSortedGroupedInputReader(inputStream1, compareRight, createSortAlgorithm(sortAlgorithm, compareRight, ctx->queryRowManager(), input1->queryOutputMeta(), ctx->queryCodeContext(), tempDirectory, activityId)));
  11222. if ((helper.getJoinFlags() & JFlimitedprefixjoin) && helper.getJoinLimit())
  11223. { //limited match join (s[1..n])
  11224. limitedhelper.setown(createRHLimitedCompareHelper());
  11225. limitedhelper->init( helper.getJoinLimit(), groupedSortedRight, collate, helper.queryPrefixCompare() );
  11226. }
  11227. }
  11228. virtual void reset()
  11229. {
  11230. if (atmostsTriggered)
  11231. noteStatistic(StNumAtmostTriggered, atmostsTriggered);
  11232. right.clear();
  11233. ReleaseClearRoxieRow(left);
  11234. ReleaseClearRoxieRow(pendingRight);
  11235. defaultRight.clear();
  11236. defaultLeft.clear();
  11237. sortedLeft.clear();
  11238. groupedSortedRight.clear();
  11239. CRoxieServerTwoInputActivity::reset();
  11240. }
  11241. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  11242. {
  11243. if (!idx && (helper.getJoinFlags() & JFparallel) != 0)
  11244. {
  11245. puller.setown(new CRoxieServerReadAheadInput(ctx, ctx->queryOptions().parallelJoinPreload));
  11246. puller->setInput(0, _sourceIdx, _in);
  11247. _in = puller;
  11248. _sourceIdx = 0;
  11249. }
  11250. CRoxieServerTwoInputActivity::setInput(idx, _sourceIdx, _in);
  11251. }
  11252. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  11253. {
  11254. if (idx==(unsigned)-1)
  11255. idx = 0;
  11256. return idx ? NULL : this;
  11257. }
  11258. void fillLeft()
  11259. {
  11260. matchedLeft = false;
  11261. left = sortedLeft->nextRow(); // NOTE: already degrouped by the IGroupedInput we attached
  11262. if (betweenjoin && left && pendingRight && (collate->docompare(left, pendingRight) >= 0))
  11263. fillRight();
  11264. if (limitedhelper && 0==rightIndex)
  11265. {
  11266. rightIndex = 0;
  11267. joinCounter = 0;
  11268. right.clear();
  11269. matchedRight.kill();
  11270. if (left)
  11271. {
  11272. limitedhelper->getGroup(right,left);
  11273. ForEachItemIn(idx, right)
  11274. matchedRight.append(false);
  11275. }
  11276. }
  11277. }
  11278. void fillRight()
  11279. {
  11280. if (limitedhelper)
  11281. return;
  11282. failingLimit.clear();
  11283. if(betweenjoin && left)
  11284. {
  11285. aindex_t start = 0;
  11286. while(right.isItem(start) && (collateupper->docompare(left, right.item(start)) > 0))
  11287. start++;
  11288. if(start>0)
  11289. right.clearPart(0, start);
  11290. }
  11291. else
  11292. right.clear();
  11293. rightIndex = 0;
  11294. joinCounter = 0;
  11295. unsigned groupCount = 0;
  11296. const void * next;
  11297. while(true)
  11298. {
  11299. if(pendingRight)
  11300. {
  11301. next = pendingRight;
  11302. pendingRight = NULL;
  11303. }
  11304. else
  11305. {
  11306. next = groupedSortedRight->nextRow();
  11307. }
  11308. if(!rightOuterJoin && next && (!left || (collateupper->docompare(left, next) > 0))) // if right is less than left, and not right outer, can skip group
  11309. {
  11310. while(next)
  11311. {
  11312. ReleaseClearRoxieRow(next);
  11313. next = groupedSortedRight->nextRow();
  11314. }
  11315. continue;
  11316. }
  11317. while(next)
  11318. {
  11319. if(groupCount==abortLimit)
  11320. {
  11321. if(limitFail)
  11322. failLimit();
  11323. if (ctx->queryDebugContext())
  11324. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  11325. if(limitOnFail)
  11326. {
  11327. assertex(!failingLimit);
  11328. try
  11329. {
  11330. failLimit();
  11331. }
  11332. catch(IException * except)
  11333. {
  11334. failingLimit.setown(except);
  11335. }
  11336. assertex(failingLimit != NULL);
  11337. }
  11338. right.append(next);
  11339. do
  11340. {
  11341. next = groupedSortedRight->nextRow();
  11342. ReleaseRoxieRow(next);
  11343. } while(next);
  11344. break;
  11345. }
  11346. else if(groupCount==atmostLimit)
  11347. {
  11348. atmostsTriggered++;
  11349. right.clear();
  11350. groupCount = 0;
  11351. while(next)
  11352. {
  11353. ReleaseRoxieRow(next);
  11354. next = groupedSortedRight->nextRow();
  11355. }
  11356. }
  11357. else
  11358. {
  11359. right.append(next);
  11360. groupCount++;
  11361. }
  11362. next = groupedSortedRight->nextRow();
  11363. }
  11364. // 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
  11365. if(betweenjoin && left)
  11366. {
  11367. pendingRight = groupedSortedRight->nextRow();
  11368. if(!pendingRight || (collate->docompare(left, pendingRight) < 0))
  11369. break;
  11370. }
  11371. else
  11372. break;
  11373. }
  11374. matchedRight.kill();
  11375. ForEachItemIn(idx, right)
  11376. matchedRight.append(false);
  11377. }
  11378. const void * joinRecords(const void * curLeft, const void * curRight, unsigned counter, unsigned flags)
  11379. {
  11380. if (cloneLeft)
  11381. {
  11382. LinkRoxieRow(curLeft);
  11383. return curLeft;
  11384. }
  11385. try
  11386. {
  11387. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11388. size32_t thisSize = helper.transform(rowBuilder, curLeft, curRight, counter, flags);
  11389. if (thisSize)
  11390. return rowBuilder.finalizeRowClear(thisSize);
  11391. else
  11392. return NULL;
  11393. }
  11394. catch (IException *E)
  11395. {
  11396. throw makeWrappedException(E);
  11397. }
  11398. }
  11399. const void * denormalizeRecords(const void * curLeft, ConstPointerArray & rows, unsigned flags)
  11400. {
  11401. try
  11402. {
  11403. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11404. unsigned numRows = rows.ordinality();
  11405. const void * right = numRows ? rows.item(0) : defaultRight.get();
  11406. if (numRows>0)
  11407. flags |= JTFmatchedright;
  11408. size32_t thisSize = helper.transform(rowBuilder, curLeft, right, numRows, (const void * *)rows.getArray(), flags);
  11409. if (thisSize)
  11410. return rowBuilder.finalizeRowClear(thisSize);
  11411. else
  11412. return NULL;
  11413. }
  11414. catch (IException *E)
  11415. {
  11416. throw makeWrappedException(E);
  11417. }
  11418. }
  11419. const void * joinException(const void * curLeft, IException * except)
  11420. {
  11421. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11422. size32_t thisSize = helper.onFailTransform(rowBuilder, curLeft, defaultRight, except, JTFmatchedleft);
  11423. return rowBuilder.finalizeRowClear(thisSize);
  11424. }
  11425. void failLimit()
  11426. {
  11427. helper.onMatchAbortLimitExceeded();
  11428. CommonXmlWriter xmlwrite(0);
  11429. if (input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  11430. {
  11431. input->queryOutputMeta()->toXML((byte *) left, xmlwrite);
  11432. }
  11433. throw MakeStringException(ROXIE_TOO_MANY_RESULTS, "More than %d match candidates in join %d for row %s", abortLimit, queryId(), xmlwrite.str());
  11434. }
  11435. virtual const void * nextRow()
  11436. {
  11437. ActivityTimer t(totalCycles, timeActivities);
  11438. for (;;)
  11439. {
  11440. switch (state)
  11441. {
  11442. case JSfill:
  11443. fillLeft();
  11444. state = JSfillright;
  11445. break;
  11446. case JSfillright:
  11447. fillRight();
  11448. state = JScollate;
  11449. break;
  11450. case JSfillleft:
  11451. fillLeft();
  11452. state = JScollate;
  11453. break;
  11454. case JScollate:
  11455. if (right.ordinality() == 0)
  11456. {
  11457. if (left == NULL)
  11458. return NULL;
  11459. state = JSleftonly;
  11460. }
  11461. else
  11462. {
  11463. if (!left)
  11464. state = JSrightonly;
  11465. else
  11466. {
  11467. int diff;
  11468. if(betweenjoin)
  11469. diff = ((collate->docompare(left, right.item(0)) < 0) ? -1 : ((collateupper->docompare(left, right.item(right.ordinality()-1)) > 0) ? +1 : 0));
  11470. else
  11471. diff = collate->docompare(left, right.item(0));
  11472. bool limitExceeded = right.ordinality()>abortLimit;
  11473. if (diff == 0)
  11474. {
  11475. if (limitExceeded)
  11476. {
  11477. const void * ret = NULL;
  11478. if(failingLimit)
  11479. ret = joinException(left, failingLimit);
  11480. ReleaseRoxieRow(left);
  11481. left = NULL;
  11482. state = JSfillleft;
  11483. ForEachItemIn(idx, right)
  11484. matchedRight.replace(true, idx);
  11485. if(ret)
  11486. {
  11487. processed++;
  11488. return ret;
  11489. }
  11490. }
  11491. else
  11492. {
  11493. state = JScompare;
  11494. joinLimit = keepLimit;
  11495. }
  11496. }
  11497. else if (diff < 0)
  11498. state = JSleftonly;
  11499. else if (limitExceeded)
  11500. {
  11501. // MORE - Roxie code seems to think there should be a destroyRowset(right) here....
  11502. state = JSfillright;
  11503. }
  11504. else
  11505. state = JSrightonly;
  11506. }
  11507. }
  11508. break;
  11509. case JSrightonly:
  11510. if (rightOuterJoin)
  11511. {
  11512. switch (activityKind)
  11513. {
  11514. case TAKjoin:
  11515. {
  11516. while (right.isItem(rightIndex))
  11517. {
  11518. if (!matchedRight.item(rightIndex))
  11519. {
  11520. const void * rhs = right.item(rightIndex++);
  11521. const void *ret = joinRecords(defaultLeft, rhs, 0, JTFmatchedright);
  11522. if (ret)
  11523. {
  11524. processed++;
  11525. return ret;
  11526. }
  11527. }
  11528. else
  11529. rightIndex++;
  11530. }
  11531. break;
  11532. }
  11533. //Probably excessive to implement the following, but possibly useful
  11534. case TAKdenormalize:
  11535. {
  11536. OwnedConstRoxieRow newLeft;
  11537. newLeft.set(defaultLeft);
  11538. unsigned rowSize = 0;
  11539. unsigned leftCount = 0;
  11540. while (right.isItem(rightIndex))
  11541. {
  11542. if (!matchedRight.item(rightIndex))
  11543. {
  11544. const void * rhs = right.item(rightIndex);
  11545. try
  11546. {
  11547. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11548. unsigned thisSize = helper.transform(rowBuilder, newLeft, rhs, ++leftCount, JTFmatchedright);
  11549. if (thisSize)
  11550. {
  11551. rowSize = thisSize;
  11552. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  11553. }
  11554. }
  11555. catch (IException *E)
  11556. {
  11557. throw makeWrappedException(E);
  11558. }
  11559. }
  11560. rightIndex++;
  11561. }
  11562. state = JSfillright;
  11563. if (rowSize)
  11564. {
  11565. processed++;
  11566. return newLeft.getClear();
  11567. }
  11568. break;
  11569. }
  11570. case TAKdenormalizegroup:
  11571. {
  11572. filteredRight.kill();
  11573. while (right.isItem(rightIndex))
  11574. {
  11575. if (!matchedRight.item(rightIndex))
  11576. filteredRight.append(right.item(rightIndex));
  11577. rightIndex++;
  11578. }
  11579. state = JSfillright;
  11580. if (filteredRight.ordinality())
  11581. {
  11582. const void * ret = denormalizeRecords(defaultLeft, filteredRight, 0);
  11583. filteredRight.kill();
  11584. if (ret)
  11585. {
  11586. processed++;
  11587. return ret;
  11588. }
  11589. }
  11590. break;
  11591. }
  11592. }
  11593. }
  11594. state = JSfillright;
  11595. break;
  11596. case JSleftonly:
  11597. {
  11598. const void * ret = NULL;
  11599. if (!matchedLeft && leftOuterJoin)
  11600. {
  11601. switch (activityKind)
  11602. {
  11603. case TAKjoin:
  11604. ret = joinRecords(left, defaultRight, 0, JTFmatchedleft);
  11605. break;
  11606. case TAKdenormalize:
  11607. ret = left;
  11608. left = NULL;
  11609. break;
  11610. case TAKdenormalizegroup:
  11611. filteredRight.kill();
  11612. ret = denormalizeRecords(left, filteredRight, JTFmatchedleft);
  11613. break;
  11614. }
  11615. }
  11616. ReleaseRoxieRow(left);
  11617. left = NULL;
  11618. state = JSfillleft;
  11619. if (ret)
  11620. {
  11621. processed++;
  11622. return ret;
  11623. }
  11624. break;
  11625. }
  11626. case JScompare:
  11627. if (joinLimit != 0)
  11628. {
  11629. switch (activityKind)
  11630. {
  11631. case TAKjoin:
  11632. {
  11633. while (right.isItem(rightIndex))
  11634. {
  11635. const void * rhs = right.item(rightIndex++);
  11636. if (helper.match(left, rhs))
  11637. {
  11638. matchedRight.replace(true, rightIndex-1);
  11639. matchedLeft = true;
  11640. if (!exclude)
  11641. {
  11642. const void *ret = joinRecords(left, rhs, ++joinCounter, JTFmatchedleft|JTFmatchedright);
  11643. if (ret)
  11644. {
  11645. processed++;
  11646. joinLimit--;
  11647. return ret;
  11648. }
  11649. }
  11650. }
  11651. }
  11652. break;
  11653. }
  11654. case TAKdenormalize:
  11655. {
  11656. OwnedConstRoxieRow newLeft;
  11657. newLeft.set(left);
  11658. unsigned rowSize = 0;
  11659. unsigned leftCount = 0;
  11660. while (right.isItem(rightIndex) && joinLimit)
  11661. {
  11662. try
  11663. {
  11664. const void * rhs = right.item(rightIndex++);
  11665. if (helper.match(left, rhs))
  11666. {
  11667. matchedRight.replace(true, rightIndex-1);
  11668. matchedLeft = true;
  11669. if (!exclude)
  11670. {
  11671. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11672. unsigned thisSize = helper.transform(rowBuilder, newLeft, rhs, ++leftCount, JTFmatchedleft|JTFmatchedright);
  11673. if (thisSize)
  11674. {
  11675. rowSize = thisSize;
  11676. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  11677. joinLimit--;
  11678. }
  11679. }
  11680. }
  11681. }
  11682. catch (IException *E)
  11683. {
  11684. throw makeWrappedException(E);
  11685. }
  11686. }
  11687. state = JSleftonly;
  11688. rightIndex = 0;
  11689. if (rowSize)
  11690. {
  11691. processed++;
  11692. return newLeft.getClear();
  11693. }
  11694. break;
  11695. }
  11696. case TAKdenormalizegroup:
  11697. {
  11698. filteredRight.kill();
  11699. while (right.isItem(rightIndex))
  11700. {
  11701. const void * rhs = right.item(rightIndex++);
  11702. if (helper.match(left, rhs))
  11703. {
  11704. matchedRight.replace(true, rightIndex-1);
  11705. filteredRight.append(rhs);
  11706. matchedLeft = true;
  11707. if (filteredRight.ordinality()==joinLimit)
  11708. break;
  11709. }
  11710. }
  11711. state = JSleftonly;
  11712. rightIndex = 0;
  11713. if (!exclude && filteredRight.ordinality())
  11714. {
  11715. const void * ret = denormalizeRecords(left, filteredRight, JTFmatchedleft);
  11716. filteredRight.kill();
  11717. if (ret)
  11718. {
  11719. processed++;
  11720. return ret;
  11721. }
  11722. }
  11723. break;
  11724. }
  11725. }
  11726. }
  11727. state = JSleftonly;
  11728. rightIndex = 0;
  11729. joinCounter = 0;
  11730. break;
  11731. }
  11732. }
  11733. }
  11734. };
  11735. class CRoxieServerJoinActivityFactory : public CRoxieServerActivityFactory
  11736. {
  11737. unsigned input2;
  11738. unsigned input2idx;
  11739. bool forceSpill;
  11740. public:
  11741. CRoxieServerJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  11742. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  11743. {
  11744. forceSpill = _graphNode.getPropBool("hint[@name='spill']/@value", _queryFactory.queryOptions().allSortsMaySpill);
  11745. input2 = 0;
  11746. input2idx = 0;
  11747. }
  11748. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  11749. {
  11750. return new CRoxieServerJoinActivity(_ctx, this, _probeManager, forceSpill);
  11751. }
  11752. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  11753. {
  11754. if (idx==1)
  11755. {
  11756. input2 = source;
  11757. input2idx = sourceidx;
  11758. }
  11759. else
  11760. CRoxieServerActivityFactory::setInput(idx, source, sourceidx);
  11761. }
  11762. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  11763. {
  11764. switch (idx)
  11765. {
  11766. case 1:
  11767. sourceidx = input2idx;
  11768. return input2;
  11769. case 0:
  11770. return CRoxieServerActivityFactory::getInput(idx, sourceidx);
  11771. default:
  11772. return (unsigned) -1;
  11773. }
  11774. }
  11775. virtual unsigned numInputs() const { return 2; }
  11776. virtual const StatisticsMapping &queryStatsMapping() const
  11777. {
  11778. return joinStatistics;
  11779. }
  11780. };
  11781. IRoxieServerActivityFactory *createRoxieServerJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  11782. {
  11783. return new CRoxieServerJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  11784. }
  11785. //=================================================================================
  11786. #define CONCAT_READAHEAD 1000
  11787. class CRoxieThreadedConcatReader : implements IRecordPullerCallback, public CInterface
  11788. {
  11789. public:
  11790. IMPLEMENT_IINTERFACE;
  11791. CRoxieThreadedConcatReader(InterruptableSemaphore &_ready, bool _grouped)
  11792. : puller(false), grouped(_grouped), atEog(true), ready(_ready), eof(false)
  11793. {
  11794. }
  11795. void start(unsigned parentExtractSize, const byte *parentExtract, bool paused, IRoxieSlaveContext *ctx)
  11796. {
  11797. space.reinit(CONCAT_READAHEAD);
  11798. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().concatPreload, false, ctx);
  11799. }
  11800. void stop()
  11801. {
  11802. space.interrupt();
  11803. puller.stop();
  11804. }
  11805. IFinalRoxieInput *queryInput() const
  11806. {
  11807. return puller.queryInput();
  11808. }
  11809. void reset()
  11810. {
  11811. puller.reset();
  11812. ForEachItemIn(idx, buffer)
  11813. ReleaseRoxieRow(buffer.item(idx));
  11814. buffer.clear();
  11815. eof = false;
  11816. atEog = true;
  11817. }
  11818. void setInput(unsigned _sourceIdx, IFinalRoxieInput *_in)
  11819. {
  11820. puller.setInput(this, _sourceIdx, _in);
  11821. }
  11822. void connectInputStreams(IRoxieSlaveContext *ctx, bool consumerOrdered)
  11823. {
  11824. puller.connectInputStreams(ctx, consumerOrdered);
  11825. }
  11826. virtual void processRow(const void *row)
  11827. {
  11828. buffer.enqueue(row);
  11829. ready.signal();
  11830. space.wait();
  11831. }
  11832. virtual void processGroup(const ConstPointerArray &rows)
  11833. {
  11834. // We use record-by-record input mode of the puller thread even in grouped mode.
  11835. throwUnexpected();
  11836. }
  11837. virtual void processEOG()
  11838. {
  11839. if (grouped)
  11840. processRow(NULL);
  11841. }
  11842. virtual void processDone()
  11843. {
  11844. processRow(NULL);
  11845. }
  11846. virtual bool fireException(IException *e)
  11847. {
  11848. // called from puller thread on failure
  11849. ready.interrupt(LINK(e));
  11850. space.interrupt(e);
  11851. return true;
  11852. }
  11853. bool peek(const void * &row, bool &anyActive)
  11854. {
  11855. if (!eof)
  11856. {
  11857. if (buffer.ordinality())
  11858. {
  11859. space.signal();
  11860. row = buffer.dequeue();
  11861. if (row==NULL)
  11862. {
  11863. if (atEog)
  11864. {
  11865. eof = true;
  11866. return false;
  11867. }
  11868. else
  11869. atEog = true;
  11870. }
  11871. else if (grouped)
  11872. atEog = false;
  11873. return true;
  11874. }
  11875. anyActive = true;
  11876. }
  11877. return false;
  11878. }
  11879. protected:
  11880. RecordPullerThread puller;
  11881. InterruptableSemaphore space;
  11882. InterruptableSemaphore &ready;
  11883. SafeQueueOf<const void, true> buffer;
  11884. bool atEog;
  11885. bool eof;
  11886. bool grouped;
  11887. };
  11888. typedef CopyReferenceArrayOf<CRoxieThreadedConcatReader> ReaderArray;
  11889. class CRoxieServerThreadedConcatActivity : public CRoxieServerActivity
  11890. {
  11891. InterruptableSemaphore ready;
  11892. ReaderArray pullers;
  11893. unsigned numInputs;
  11894. unsigned nextPuller; // for round robin
  11895. unsigned readyPending;
  11896. bool eof;
  11897. bool inGroup;
  11898. bool grouped;
  11899. public:
  11900. CRoxieServerThreadedConcatActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _grouped, unsigned _numInputs)
  11901. : CRoxieServerActivity(_ctx, _factory, _probeManager), grouped(_grouped)
  11902. {
  11903. numInputs = _numInputs;
  11904. eof = (numInputs==0);
  11905. inGroup = false;
  11906. nextPuller = 0;
  11907. readyPending = 0;
  11908. for (unsigned i = 0; i < numInputs; i++)
  11909. pullers.append(*new CRoxieThreadedConcatReader(ready, _grouped));
  11910. }
  11911. ~CRoxieServerThreadedConcatActivity()
  11912. {
  11913. ForEachItemIn(idx, pullers)
  11914. delete &pullers.item(idx);
  11915. }
  11916. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11917. {
  11918. eof = (numInputs==0);
  11919. inGroup = false;
  11920. nextPuller = 0;
  11921. readyPending = 0;
  11922. ready.reinit();
  11923. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  11924. ForEachItemIn(idx, pullers)
  11925. {
  11926. pullers.item(idx).start(parentExtractSize, parentExtract, paused, ctx);
  11927. // NOTE - it is ok to start the thread running while parts of the subgraph are still being started, since everything
  11928. // in the part of the subgraph that the thread uses has been started.
  11929. // Note that splitters are supposed to cope with being used when only some outputs have been started.
  11930. }
  11931. }
  11932. virtual void stop()
  11933. {
  11934. ready.interrupt();
  11935. ForEachItemIn(idx, pullers)
  11936. pullers.item(idx).stop();
  11937. CRoxieServerActivity::stop();
  11938. }
  11939. virtual unsigned __int64 queryLocalCycles() const
  11940. {
  11941. return 0;
  11942. }
  11943. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  11944. {
  11945. if (pullers.isItem(idx))
  11946. return pullers.item(idx).queryInput();
  11947. else
  11948. return NULL;
  11949. }
  11950. virtual void reset()
  11951. {
  11952. CRoxieServerActivity::reset();
  11953. ForEachItemIn(idx, pullers)
  11954. pullers.item(idx).reset();
  11955. eof = false;
  11956. inGroup = false;
  11957. nextPuller = 0;
  11958. readyPending = 0;
  11959. }
  11960. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  11961. {
  11962. if (pullers.isItem(idx))
  11963. pullers.item(idx).setInput(_sourceIdx, _in);
  11964. else
  11965. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
  11966. }
  11967. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  11968. {
  11969. ForEachItemIn(i, pullers)
  11970. pullers.item(i).connectInputStreams(ctx, consumerOrdered);
  11971. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, nullptr, consumerOrdered, nullptr); // No input actually connected
  11972. }
  11973. virtual const void * nextRow()
  11974. {
  11975. ActivityTimer t(totalCycles, timeActivities);
  11976. if (eof)
  11977. return NULL;
  11978. for (;;)
  11979. {
  11980. if (readyPending && !inGroup)
  11981. {
  11982. if (readyPending > 1)
  11983. ready.signal(readyPending-1);
  11984. readyPending = 0;
  11985. }
  11986. else
  11987. ready.wait();
  11988. bool anyActive = false;
  11989. ForEachItemIn(unused_index, pullers)
  11990. {
  11991. // NOTE - we round robin not just because it's more efficient, but because it ensures the preservation of grouping information
  11992. const void *ret;
  11993. bool fetched = pullers.item(nextPuller).peek(ret, anyActive);
  11994. if (fetched)
  11995. {
  11996. inGroup = (ret != NULL);
  11997. return ret;
  11998. }
  11999. if (inGroup && grouped)
  12000. {
  12001. // Some other puller has data, but we can't consume it until the group we are reading is complete.
  12002. readyPending++;
  12003. anyActive = true;
  12004. break;
  12005. }
  12006. nextPuller++;
  12007. if (nextPuller==pullers.ordinality())
  12008. nextPuller = 0;
  12009. }
  12010. if (!anyActive)
  12011. break;
  12012. // A ready signal without anything being ready means someone reached end-of-file.
  12013. }
  12014. eof = true;
  12015. return NULL;
  12016. }
  12017. };
  12018. class CRoxieServerOrderedConcatActivity : public CRoxieServerMultiInputActivity
  12019. {
  12020. IEngineRowStream *curStream;
  12021. bool eogSeen;
  12022. bool anyThisGroup;
  12023. bool grouped;
  12024. unsigned streamIdx;
  12025. public:
  12026. CRoxieServerOrderedConcatActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _grouped, unsigned _numInputs)
  12027. : CRoxieServerMultiInputActivity(_ctx, _factory, _probeManager, _numInputs)
  12028. {
  12029. eogSeen = false;
  12030. anyThisGroup = false;
  12031. grouped = _grouped;
  12032. streamIdx = 0;
  12033. curStream = NULL;
  12034. }
  12035. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12036. {
  12037. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  12038. streamIdx = 0;
  12039. curStream = streamArray[streamIdx];
  12040. eogSeen = false;
  12041. anyThisGroup = false;
  12042. }
  12043. virtual const void * nextRow()
  12044. {
  12045. ActivityTimer t(totalCycles, timeActivities);
  12046. if (!curStream)
  12047. return NULL; // eof
  12048. const void * next = curStream->nextRow();
  12049. if (next)
  12050. {
  12051. anyThisGroup = true;
  12052. eogSeen = false;
  12053. processed++;
  12054. return next;
  12055. }
  12056. else if (!eogSeen)
  12057. {
  12058. eogSeen = true;
  12059. if (grouped)
  12060. {
  12061. if (anyThisGroup)
  12062. {
  12063. anyThisGroup = false;
  12064. return NULL;
  12065. }
  12066. else
  12067. return nextRow();
  12068. }
  12069. else
  12070. return nextRow();
  12071. }
  12072. else if (streamIdx < numStreams-1)
  12073. {
  12074. streamIdx++;
  12075. curStream = streamArray[streamIdx];
  12076. eogSeen = false;
  12077. return nextRow();
  12078. }
  12079. else
  12080. {
  12081. curStream = NULL;
  12082. return NULL;
  12083. }
  12084. }
  12085. };
  12086. class CRoxieServerConcatActivityFactory : public CRoxieServerMultiInputFactory
  12087. {
  12088. bool ordered;
  12089. bool grouped;
  12090. public:
  12091. CRoxieServerConcatActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12092. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12093. {
  12094. Owned <IHThorFunnelArg> helper = (IHThorFunnelArg *) helperFactory();
  12095. ordered = helper->isOrdered();
  12096. grouped = helper->queryOutputMeta()->isGrouped();
  12097. }
  12098. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12099. {
  12100. if (ordered || (_probeManager && _probeManager->queryDebugManager()))
  12101. return new CRoxieServerOrderedConcatActivity(_ctx, this, _probeManager, grouped, numInputs());
  12102. else
  12103. return new CRoxieServerThreadedConcatActivity(_ctx, this, _probeManager, grouped, numInputs());
  12104. }
  12105. };
  12106. IRoxieServerActivityFactory *createRoxieServerConcatActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12107. {
  12108. return new CRoxieServerConcatActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12109. }
  12110. //=================================================================================
  12111. class CRoxieServerNonEmptyActivity : public CRoxieServerMultiInputBaseActivity
  12112. {
  12113. IEngineRowStream* selectedStream;
  12114. unsigned savedParentExtractSize;
  12115. const byte * savedParentExtract;
  12116. bool foundInput;
  12117. bool unusedStopped;
  12118. public:
  12119. CRoxieServerNonEmptyActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  12120. : CRoxieServerMultiInputBaseActivity(_ctx, _factory, _probeManager, _numInputs)
  12121. {
  12122. foundInput = false;
  12123. unusedStopped = false;
  12124. selectedStream = NULL;
  12125. savedParentExtractSize = 0;;
  12126. savedParentExtract = NULL;
  12127. }
  12128. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12129. {
  12130. //Don't start the inputs yet so we can short-circuit...
  12131. CRoxieServerMultiInputBaseActivity::start(parentExtractSize, parentExtract, paused);
  12132. savedParentExtractSize = parentExtractSize;
  12133. savedParentExtract = parentExtract;
  12134. }
  12135. virtual void stop()
  12136. {
  12137. if (unusedStopped)
  12138. {
  12139. if (selectedStream)
  12140. selectedStream->stop();
  12141. }
  12142. else
  12143. {
  12144. //May possibly call stop too many times if input->start() throws an exception (e.g. due to a dependency)
  12145. for (unsigned i = 0; i < numStreams; i++)
  12146. streamArray[i]->stop();
  12147. }
  12148. CRoxieServerMultiInputBaseActivity::stop();
  12149. }
  12150. virtual void reset()
  12151. {
  12152. CRoxieServerMultiInputBaseActivity::reset();
  12153. foundInput = false;
  12154. unusedStopped = false;
  12155. selectedStream = NULL;
  12156. }
  12157. virtual unsigned __int64 queryLocalCycles() const
  12158. {
  12159. return 0; // Can't easily calculate anything reliable but local processing is negligible
  12160. }
  12161. virtual const void * nextRow()
  12162. {
  12163. ActivityTimer t(totalCycles, timeActivities);
  12164. if (!foundInput)
  12165. {
  12166. foundInput = true;
  12167. assertex(numInputs == numStreams); // If this ceases to be true we will need to rethink some of this
  12168. //If we get an exception in this loop then stop() will stop any started inputs
  12169. for (unsigned i=0; i < numStreams; i++)
  12170. {
  12171. selectedStream = streamArray[i];
  12172. inputArray[i]->start(savedParentExtractSize, savedParentExtract, false); // Assumes 1:1 mapping streams to inputs
  12173. startJunction(junctionArray[i]);
  12174. const void * next = selectedStream->nextRow();
  12175. if (next)
  12176. {
  12177. //Found a row so stop remaining
  12178. for (unsigned j=i+1; j < numInputs; j++)
  12179. streamArray[j]->stop();
  12180. unusedStopped = true;
  12181. processed++;
  12182. return next;
  12183. }
  12184. selectedStream->stop();
  12185. }
  12186. unusedStopped = true;
  12187. selectedStream = NULL;
  12188. return NULL;
  12189. }
  12190. if (!selectedStream)
  12191. return NULL;
  12192. const void * next = selectedStream->nextRow();
  12193. if (next)
  12194. processed++;
  12195. return next;
  12196. }
  12197. };
  12198. class CRoxieServerNonEmptyActivityFactory : public CRoxieServerMultiInputFactory
  12199. {
  12200. public:
  12201. CRoxieServerNonEmptyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12202. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12203. {
  12204. }
  12205. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12206. {
  12207. return new CRoxieServerNonEmptyActivity(_ctx, this, _probeManager, numInputs());
  12208. }
  12209. };
  12210. IRoxieServerActivityFactory *createRoxieServerNonEmptyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12211. {
  12212. return new CRoxieServerNonEmptyActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12213. }
  12214. //=================================================================================
  12215. class SingleNodeActivityContext : public IThorActivityContext
  12216. {
  12217. public:
  12218. SingleNodeActivityContext(unsigned _numStrands, unsigned _curStrand) : strands(_numStrands), curStrand(_curStrand) { assertex(curStrand < strands); }
  12219. virtual bool isLocal() const override { return false; }
  12220. virtual unsigned numSlaves() const override { return 1; }
  12221. virtual unsigned numStrands() const override { return strands; }
  12222. virtual unsigned querySlave() const override { return 0; }
  12223. virtual unsigned queryStrand() const override { return curStrand; }
  12224. protected:
  12225. unsigned strands;
  12226. unsigned curStrand;
  12227. };
  12228. class CRoxieServerExternalActivity : public CRoxieServerMultiInputActivity
  12229. {
  12230. Owned<IRowStream> rows;
  12231. SingleNodeActivityContext activityContext;
  12232. public:
  12233. CRoxieServerExternalActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  12234. : CRoxieServerMultiInputActivity(_ctx, _factory, _probeManager, _numInputs), activityContext(1, 0)
  12235. {
  12236. }
  12237. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  12238. {
  12239. Owned<IStrandJunction> junction = CRoxieServerMultiInputActivity::getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
  12240. associateInputsWithHelper();
  12241. return junction.getClear();
  12242. }
  12243. virtual void connectInputStreams(bool consumerOrdered)
  12244. {
  12245. CRoxieServerMultiInputActivity::connectInputStreams(consumerOrdered);
  12246. associateInputsWithHelper();
  12247. }
  12248. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12249. {
  12250. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  12251. if (factory->getKind() != TAKexternalsink)
  12252. {
  12253. IHThorExternalArg & helper = static_cast<IHThorExternalArg &>(basehelper);
  12254. rows.setown(helper.createOutput(&activityContext));
  12255. }
  12256. }
  12257. virtual void stop()
  12258. {
  12259. if (rows)
  12260. {
  12261. rows->stop();
  12262. rows.clear();
  12263. }
  12264. CRoxieServerMultiInputBaseActivity::stop();
  12265. }
  12266. virtual void reset()
  12267. {
  12268. rows.clear();
  12269. }
  12270. virtual const void * nextRow()
  12271. {
  12272. ActivityTimer t(totalCycles, timeActivities);
  12273. assertex(rows);
  12274. const void * next = rows->nextRow();
  12275. if (next)
  12276. processed++;
  12277. return next;
  12278. }
  12279. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  12280. {
  12281. try
  12282. {
  12283. start(parentExtractSize, parentExtract, false);
  12284. assertex(!rows);
  12285. IHThorExternalArg & helper = static_cast<IHThorExternalArg &>(basehelper);
  12286. helper.execute(&activityContext);
  12287. stop();
  12288. }
  12289. catch (IException * E)
  12290. {
  12291. ctx->notifyAbort(E);
  12292. abort();
  12293. throw;
  12294. }
  12295. }
  12296. protected:
  12297. void associateInputsWithHelper()
  12298. {
  12299. IHThorExternalArg & helper = static_cast<IHThorExternalArg &>(basehelper);
  12300. for (unsigned i = 0; i < numInputs; i++)
  12301. helper.setInput(i, streamArray[i]);
  12302. }
  12303. };
  12304. class CRoxieServerExternalActivityFactory : public CRoxieServerMultiInputFactory
  12305. {
  12306. bool isRoot;
  12307. public:
  12308. CRoxieServerExternalActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  12309. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  12310. {
  12311. }
  12312. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12313. {
  12314. return new CRoxieServerExternalActivity(_ctx, this, _probeManager, numInputs());
  12315. }
  12316. virtual bool isSink() const
  12317. {
  12318. return (kind == TAKexternalsink) && isRoot;
  12319. }
  12320. };
  12321. IRoxieServerActivityFactory *createRoxieServerExternalActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  12322. {
  12323. return new CRoxieServerExternalActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  12324. }
  12325. //=================================================================================
  12326. class CRoxieServerMergeActivity : public CRoxieServerMultiInputActivity
  12327. {
  12328. IHThorMergeArg &helper;
  12329. unsigned *mergeheap;
  12330. unsigned activeInputs;
  12331. const void **pending;
  12332. bool first;
  12333. ICompare *compare;
  12334. bool dedup;
  12335. void permute()
  12336. {
  12337. assertex(activeInputs == 0);
  12338. for(unsigned i = 0; i < numStreams; i++)
  12339. if(pullInput(i))
  12340. mergeheap[activeInputs++] = i;
  12341. // the tree structure: element p has children p*2+1 and p*2+2, or element c has parent (unsigned)(c-1)/2
  12342. // the heap property: no element should be smaller than its parent
  12343. // the dedup variant: if(dedup), the top of the heap should also not be equal to either child
  12344. // 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
  12345. if (activeInputs >= 2)
  12346. for(unsigned p = (activeInputs-2)/2; p > 0; --p)
  12347. siftDown(p);
  12348. if(dedup)
  12349. siftDownDedupTop();
  12350. else
  12351. siftDown(0);
  12352. }
  12353. void readNext()
  12354. {
  12355. if(!pullInput(mergeheap[0]))
  12356. if(!promote(0))
  12357. return;
  12358. // we have changed the element at the top of the heap, so need to sift it down to maintain the heap property
  12359. if(dedup)
  12360. siftDownDedupTop();
  12361. else
  12362. siftDown(0);
  12363. }
  12364. bool pullInput(unsigned i)
  12365. {
  12366. const void *next = streamArray[i]->ungroupedNextRow();
  12367. pending[i] = next;
  12368. return (next != NULL);
  12369. }
  12370. bool promote(unsigned p)
  12371. {
  12372. activeInputs--;
  12373. if(activeInputs == p)
  12374. return false;
  12375. mergeheap[p] = mergeheap[activeInputs];
  12376. return true;
  12377. }
  12378. bool siftDown(unsigned p)
  12379. {
  12380. // assuming that all descendants of p form a heap, sift p down to its correct position, and so include it in the heap
  12381. bool nochange = true;
  12382. while(1)
  12383. {
  12384. unsigned c = p*2 + 1;
  12385. if(c >= activeInputs)
  12386. return nochange;
  12387. if(c+1 < activeInputs)
  12388. {
  12389. int childcmp = BuffCompare(c+1, c);
  12390. if((childcmp < 0) || ((childcmp == 0) && (mergeheap[c+1] < mergeheap[c])))
  12391. ++c;
  12392. }
  12393. int cmp = BuffCompare(c, p);
  12394. if((cmp > 0) || ((cmp == 0) && (mergeheap[c] > mergeheap[p])))
  12395. return nochange;
  12396. nochange = false;
  12397. unsigned r = mergeheap[c];
  12398. mergeheap[c] = mergeheap[p];
  12399. mergeheap[p] = r;
  12400. p = c;
  12401. }
  12402. }
  12403. void siftDownDedupTop()
  12404. {
  12405. // same as siftDown(0), except that it also ensures that the top of the heap is not equal to either of its children
  12406. if(activeInputs < 2)
  12407. return;
  12408. unsigned c = 1;
  12409. int childcmp = 1;
  12410. if(activeInputs >= 3)
  12411. {
  12412. childcmp = BuffCompare(2, 1);
  12413. if(childcmp < 0)
  12414. c = 2;
  12415. }
  12416. int cmp = BuffCompare(c, 0);
  12417. if(cmp > 0)
  12418. return;
  12419. // the following loop ensures the correct property holds on the smaller branch, and that childcmp==0 iff the top matches the other branch
  12420. while(cmp <= 0)
  12421. {
  12422. if(cmp == 0)
  12423. {
  12424. if(mergeheap[c] < mergeheap[0])
  12425. {
  12426. unsigned r = mergeheap[c];
  12427. mergeheap[c] = mergeheap[0];
  12428. mergeheap[0] = r;
  12429. }
  12430. ReleaseClearRoxieRow(pending[mergeheap[c]]);
  12431. if(!pullInput(mergeheap[c]))
  12432. if(!promote(c))
  12433. break;
  12434. siftDown(c);
  12435. }
  12436. else
  12437. {
  12438. unsigned r = mergeheap[c];
  12439. mergeheap[c] = mergeheap[0];
  12440. mergeheap[0] = r;
  12441. if(siftDown(c))
  12442. break;
  12443. }
  12444. cmp = BuffCompare(c, 0);
  12445. }
  12446. // the following loop ensures the uniqueness property holds on the other branch too
  12447. c = 3-c;
  12448. if(activeInputs <= c)
  12449. return;
  12450. while(childcmp == 0)
  12451. {
  12452. if(mergeheap[c] < mergeheap[0])
  12453. {
  12454. unsigned r = mergeheap[c];
  12455. mergeheap[c] = mergeheap[0];
  12456. mergeheap[0] = r;
  12457. }
  12458. ReleaseClearRoxieRow(pending[mergeheap[c]]);
  12459. if(!pullInput(mergeheap[c]))
  12460. if(!promote(c))
  12461. break;
  12462. siftDown(c);
  12463. childcmp = BuffCompare(c, 0);
  12464. }
  12465. }
  12466. inline int BuffCompare(unsigned a, unsigned b)
  12467. {
  12468. return compare->docompare(pending[mergeheap[a]], pending[mergeheap[b]]);
  12469. }
  12470. public:
  12471. CRoxieServerMergeActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  12472. : CRoxieServerMultiInputActivity(_ctx, _factory, _probeManager, _numInputs), helper((IHThorMergeArg &)basehelper)
  12473. {
  12474. activeInputs = 0;
  12475. first = true;
  12476. mergeheap = new unsigned[numInputs];
  12477. pending = new const void *[numStreams];
  12478. compare = helper.queryCompare();
  12479. dedup = helper.dedup();
  12480. for (unsigned i = 0; i < numStreams; i++)
  12481. pending[i] = NULL;
  12482. }
  12483. ~CRoxieServerMergeActivity()
  12484. {
  12485. delete [] mergeheap;
  12486. delete [] pending;
  12487. }
  12488. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12489. {
  12490. activeInputs = 0;
  12491. first = true;
  12492. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  12493. }
  12494. virtual void reset()
  12495. {
  12496. for (unsigned i = 0; i < numStreams; i++)
  12497. ReleaseClearRoxieRow(pending[i]);
  12498. CRoxieServerMultiInputActivity::reset();
  12499. }
  12500. virtual const void * nextRow()
  12501. {
  12502. ActivityTimer t(totalCycles, timeActivities);
  12503. if (first)
  12504. {
  12505. permute();
  12506. first = false;
  12507. }
  12508. if (activeInputs)
  12509. {
  12510. const void *next = pending[mergeheap[0]];
  12511. readNext();
  12512. if (next)
  12513. processed++;
  12514. return next;
  12515. }
  12516. else
  12517. return NULL;
  12518. }
  12519. };
  12520. class CRoxieServerMergeActivityFactory : public CRoxieServerMultiInputFactory
  12521. {
  12522. public:
  12523. CRoxieServerMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12524. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12525. {
  12526. }
  12527. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12528. {
  12529. return new CRoxieServerMergeActivity(_ctx, this, _probeManager, numInputs());
  12530. }
  12531. };
  12532. IRoxieServerActivityFactory *createRoxieServerMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12533. {
  12534. return new CRoxieServerMergeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12535. }
  12536. //=================================================================================
  12537. class CRoxieServerRegroupActivity : public CRoxieServerMultiInputActivity
  12538. {
  12539. IHThorRegroupArg &helper;
  12540. unsigned streamIndex;
  12541. bool eof;
  12542. unsigned __int64 numProcessedLastGroup;
  12543. public:
  12544. CRoxieServerRegroupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  12545. : CRoxieServerMultiInputActivity(_ctx, _factory, _probeManager, _numInputs), helper((IHThorRegroupArg &)basehelper)
  12546. {
  12547. streamIndex = 0;
  12548. eof = false;
  12549. numProcessedLastGroup = 0;
  12550. }
  12551. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12552. {
  12553. streamIndex = 0;
  12554. eof = false;
  12555. numProcessedLastGroup = processed;
  12556. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  12557. }
  12558. const void * nextFromInputs()
  12559. {
  12560. unsigned initialStream = streamIndex;
  12561. while (streamIndex < numStreams)
  12562. {
  12563. const void * next = streamArray[streamIndex]->nextRow();
  12564. if (next)
  12565. {
  12566. if ((streamIndex != initialStream) && (streamIndex != initialStream+1))
  12567. {
  12568. ReleaseRoxieRow(next);
  12569. throw MakeStringException(ROXIE_MISMATCH_GROUP_ERROR, "Mismatched groups supplied to Regroup (%d)", factory->queryId());
  12570. }
  12571. return next;
  12572. }
  12573. streamIndex++;
  12574. }
  12575. if ((initialStream != 0) && (initialStream+1 != numStreams))
  12576. throw MakeStringException(ROXIE_MISMATCH_GROUP_ERROR, "Mismatched groups supplied to Regroup (%d)", factory->queryId());
  12577. streamIndex = 0;
  12578. return NULL;
  12579. }
  12580. virtual const void * nextRow()
  12581. {
  12582. ActivityTimer t(totalCycles, timeActivities);
  12583. if (eof)
  12584. return NULL;
  12585. const void * ret = nextFromInputs();
  12586. if (ret)
  12587. {
  12588. processed++;
  12589. return ret;
  12590. }
  12591. if (numProcessedLastGroup != processed)
  12592. {
  12593. numProcessedLastGroup = processed;
  12594. return NULL;
  12595. }
  12596. eof = true;
  12597. return NULL;
  12598. }
  12599. };
  12600. class CRoxieServerRegroupActivityFactory : public CRoxieServerMultiInputFactory
  12601. {
  12602. public:
  12603. CRoxieServerRegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12604. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12605. {
  12606. }
  12607. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12608. {
  12609. return new CRoxieServerRegroupActivity(_ctx, this, _probeManager, numInputs());
  12610. }
  12611. };
  12612. IRoxieServerActivityFactory *createRoxieServerRegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12613. {
  12614. return new CRoxieServerRegroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12615. }
  12616. //=================================================================================
  12617. class CRoxieServerCombineActivity : public CRoxieServerMultiInputActivity
  12618. {
  12619. IHThorCombineArg &helper;
  12620. unsigned __int64 numProcessedLastGroup;
  12621. public:
  12622. CRoxieServerCombineActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  12623. : CRoxieServerMultiInputActivity(_ctx, _factory, _probeManager, _numInputs), helper((IHThorCombineArg &)basehelper)
  12624. {
  12625. numProcessedLastGroup = 0;
  12626. }
  12627. ~CRoxieServerCombineActivity()
  12628. {
  12629. }
  12630. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12631. {
  12632. numProcessedLastGroup = processed;
  12633. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  12634. }
  12635. void nextInputs(ConstPointerArray & out)
  12636. {
  12637. for (unsigned i=0; i < numStreams; i++)
  12638. {
  12639. const void * next = streamArray[i]->nextRow();
  12640. if (next)
  12641. out.append(next);
  12642. }
  12643. }
  12644. virtual bool needsAllocator() const { return true; }
  12645. virtual const void * nextRow()
  12646. {
  12647. ActivityTimer t(totalCycles, timeActivities);
  12648. for (;;)
  12649. {
  12650. ConstPointerArray group;
  12651. nextInputs(group);
  12652. if ((group.ordinality() == 0) && (numProcessedLastGroup == processed))
  12653. nextInputs(group);
  12654. if (group.ordinality() == 0)
  12655. {
  12656. numProcessedLastGroup = processed;
  12657. return NULL;
  12658. }
  12659. else if (group.ordinality() != numInputs)
  12660. {
  12661. ReleaseRoxieRows(group);
  12662. throw MakeStringException(ROXIE_MISMATCH_GROUP_ERROR, "Mismatched group input for Combine Activity(%d)", factory->queryId());
  12663. }
  12664. try
  12665. {
  12666. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12667. size32_t outSize = helper.transform(rowBuilder, group.ordinality(), group.getArray());
  12668. ReleaseRoxieRows(group);
  12669. if (outSize)
  12670. {
  12671. processed++;
  12672. return rowBuilder.finalizeRowClear(outSize);
  12673. }
  12674. }
  12675. catch (IException *E)
  12676. {
  12677. ReleaseRoxieRows(group);
  12678. throw makeWrappedException(E);
  12679. }
  12680. }
  12681. }
  12682. };
  12683. class CRoxieServerCombineActivityFactory : public CRoxieServerMultiInputFactory
  12684. {
  12685. public:
  12686. CRoxieServerCombineActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12687. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12688. {
  12689. }
  12690. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12691. {
  12692. return new CRoxieServerCombineActivity(_ctx, this, _probeManager, numInputs());
  12693. }
  12694. };
  12695. IRoxieServerActivityFactory *createRoxieServerCombineActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12696. {
  12697. return new CRoxieServerCombineActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12698. }
  12699. //=================================================================================
  12700. class CRoxieServerCombineGroupActivity : public CRoxieServerTwoInputActivity
  12701. {
  12702. IHThorCombineGroupArg &helper;
  12703. unsigned __int64 numProcessedLastGroup;
  12704. public:
  12705. CRoxieServerCombineGroupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  12706. : CRoxieServerTwoInputActivity(_ctx, _factory, _probeManager), helper((IHThorCombineGroupArg &)basehelper)
  12707. {
  12708. numProcessedLastGroup = 0;
  12709. }
  12710. ~CRoxieServerCombineGroupActivity()
  12711. {
  12712. }
  12713. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12714. {
  12715. numProcessedLastGroup = processed;
  12716. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  12717. }
  12718. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  12719. {
  12720. if (idx==(unsigned)-1)
  12721. idx = 0;
  12722. return idx ? NULL : this;
  12723. }
  12724. virtual bool needsAllocator() const { return true; }
  12725. virtual const void * nextRow()
  12726. {
  12727. ActivityTimer t(totalCycles, timeActivities);
  12728. for (;;)
  12729. {
  12730. const void * left = inputStream->nextRow();
  12731. if (!left && (numProcessedLastGroup == processed))
  12732. left = inputStream->nextRow();
  12733. if (!left)
  12734. {
  12735. if (numProcessedLastGroup == processed)
  12736. {
  12737. const void * nextRight = inputStream1->nextRow();
  12738. if (nextRight)
  12739. {
  12740. ReleaseRoxieRow(nextRight);
  12741. throw MakeStringException(ROXIE_MISSING_GROUP_ERROR, "Missing LEFT record for Combine Group (%d)", factory->queryId());
  12742. }
  12743. }
  12744. else
  12745. numProcessedLastGroup = processed;
  12746. return NULL;
  12747. }
  12748. ConstPointerArray group;
  12749. for (;;)
  12750. {
  12751. const void * in = inputStream1->nextRow();
  12752. if (!in)
  12753. break;
  12754. group.append(in);
  12755. }
  12756. if (group.ordinality() == 0)
  12757. {
  12758. ReleaseRoxieRow(left);
  12759. ReleaseRoxieRows(group);
  12760. throw MakeStringException(ROXIE_MISSING_GROUP_ERROR, "Missing RIGHT group for Combine Group (%d)", factory->queryId());
  12761. }
  12762. try
  12763. {
  12764. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12765. size32_t outSize = helper.transform(rowBuilder, left, group.ordinality(), (const void * *)group.getArray());
  12766. ReleaseRoxieRow(left);
  12767. ReleaseRoxieRows(group);
  12768. if (outSize)
  12769. {
  12770. processed++;
  12771. return rowBuilder.finalizeRowClear(outSize);
  12772. }
  12773. }
  12774. catch (IException *E)
  12775. {
  12776. ReleaseRoxieRow(left);
  12777. ReleaseRoxieRows(group);
  12778. throw makeWrappedException(E);
  12779. }
  12780. }
  12781. }
  12782. };
  12783. class CRoxieServerCombineGroupActivityFactory : public CRoxieServerActivityFactory
  12784. {
  12785. unsigned input2;
  12786. unsigned input2idx;
  12787. public:
  12788. CRoxieServerCombineGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12789. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12790. {
  12791. input2 = 0;
  12792. input2idx = 0;
  12793. }
  12794. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12795. {
  12796. return new CRoxieServerCombineGroupActivity(_ctx, this, _probeManager);
  12797. }
  12798. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  12799. {
  12800. if (idx==1)
  12801. {
  12802. input2 = source;
  12803. input2idx = sourceidx;
  12804. }
  12805. else
  12806. CRoxieServerActivityFactory::setInput(idx, source, sourceidx);
  12807. }
  12808. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  12809. {
  12810. switch (idx)
  12811. {
  12812. case 1:
  12813. sourceidx = input2idx;
  12814. return input2;
  12815. case 0:
  12816. return CRoxieServerActivityFactory::getInput(idx, sourceidx);
  12817. default:
  12818. return (unsigned) -1;
  12819. }
  12820. }
  12821. virtual unsigned numInputs() const { return 2; }
  12822. };
  12823. IRoxieServerActivityFactory *createRoxieServerCombineGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12824. {
  12825. return new CRoxieServerCombineGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12826. }
  12827. //=================================================================================
  12828. class CRoxieServerRollupGroupActivity : public CRoxieServerActivity
  12829. {
  12830. IHThorRollupGroupArg &helper;
  12831. bool eof;
  12832. public:
  12833. CRoxieServerRollupGroupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  12834. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  12835. helper((IHThorRollupGroupArg &)basehelper)
  12836. {
  12837. eof = false;
  12838. }
  12839. ~CRoxieServerRollupGroupActivity()
  12840. {
  12841. }
  12842. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12843. {
  12844. eof = false;
  12845. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  12846. }
  12847. virtual bool needsAllocator() const { return true; }
  12848. virtual const void * nextRow()
  12849. {
  12850. ActivityTimer t(totalCycles, timeActivities);
  12851. if (eof)
  12852. return NULL;
  12853. for (;;)
  12854. {
  12855. ConstPointerArray group;
  12856. for (;;)
  12857. {
  12858. const void * in = inputStream->nextRow();
  12859. if (!in)
  12860. break;
  12861. group.append(in);
  12862. }
  12863. if (group.ordinality() == 0)
  12864. {
  12865. eof = true;
  12866. return NULL;
  12867. }
  12868. try
  12869. {
  12870. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12871. size32_t outSize = helper.transform(rowBuilder, group.ordinality(), (const void * *)group.getArray());
  12872. ReleaseRoxieRows(group);
  12873. if (outSize)
  12874. {
  12875. processed++;
  12876. return rowBuilder.finalizeRowClear(outSize);
  12877. }
  12878. }
  12879. catch (IException * E)
  12880. {
  12881. ReleaseRoxieRows(group);
  12882. throw makeWrappedException(E);
  12883. }
  12884. }
  12885. }
  12886. };
  12887. class CRoxieServerRollupGroupActivityFactory : public CRoxieServerActivityFactory
  12888. {
  12889. public:
  12890. CRoxieServerRollupGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12891. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12892. {
  12893. }
  12894. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12895. {
  12896. return new CRoxieServerRollupGroupActivity(_ctx, this, _probeManager);
  12897. }
  12898. };
  12899. IRoxieServerActivityFactory *createRoxieServerRollupGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12900. {
  12901. return new CRoxieServerRollupGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12902. }
  12903. //=================================================================================
  12904. class CRoxieServerFilterProjectActivity : public CRoxieServerLateStartActivity
  12905. {
  12906. IHThorFilterProjectArg &helper;
  12907. unsigned numProcessedLastGroup;
  12908. unsigned __int64 recordCount;
  12909. public:
  12910. CRoxieServerFilterProjectActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  12911. : CRoxieServerLateStartActivity(_ctx, _factory, _probeManager), helper((IHThorFilterProjectArg &)basehelper)
  12912. {
  12913. numProcessedLastGroup = 0;
  12914. recordCount = 0;
  12915. }
  12916. ~CRoxieServerFilterProjectActivity()
  12917. {
  12918. }
  12919. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12920. {
  12921. numProcessedLastGroup = 0;
  12922. recordCount = 0;
  12923. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  12924. lateStart(parentExtractSize, parentExtract, helper.canMatchAny()); //sets eof
  12925. }
  12926. virtual bool needsAllocator() const { return true; }
  12927. virtual const void * nextRow()
  12928. {
  12929. ActivityTimer t(totalCycles, timeActivities);
  12930. if (eof)
  12931. return NULL;
  12932. for (;;)
  12933. {
  12934. const void * in = inputStream->nextRow();
  12935. if (!in)
  12936. {
  12937. recordCount = 0;
  12938. if (numProcessedLastGroup == processed)
  12939. in = inputStream->nextRow();
  12940. if (!in)
  12941. {
  12942. numProcessedLastGroup = processed;
  12943. return NULL;
  12944. }
  12945. }
  12946. try
  12947. {
  12948. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12949. size32_t outSize = helper.transform(rowBuilder, in, ++recordCount);
  12950. ReleaseRoxieRow(in);
  12951. if (outSize)
  12952. {
  12953. processed++;
  12954. return rowBuilder.finalizeRowClear(outSize);
  12955. }
  12956. }
  12957. catch (IException *E)
  12958. {
  12959. throw makeWrappedException(E);
  12960. }
  12961. }
  12962. }
  12963. };
  12964. class CRoxieServerFilterProjectActivityFactory : public CRoxieServerActivityFactory
  12965. {
  12966. public:
  12967. CRoxieServerFilterProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12968. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12969. {
  12970. //MORE: Code generator needs to indicate if the count is used.
  12971. //optStableInput = false;
  12972. }
  12973. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12974. {
  12975. return new CRoxieServerFilterProjectActivity(_ctx, this, _probeManager);
  12976. }
  12977. };
  12978. IRoxieServerActivityFactory *createRoxieServerFilterProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12979. {
  12980. return new CRoxieServerFilterProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12981. }
  12982. //=====================================================
  12983. class CRoxieServerStrandedProjectActivity : public CRoxieServerStrandedActivity
  12984. {
  12985. class ProjectProcessor : public StrandProcessor
  12986. {
  12987. protected:
  12988. IHThorProjectArg &helper;
  12989. public:
  12990. ProjectProcessor(CRoxieServerActivity &_parent, IEngineRowStream *_inputStream, IHThorProjectArg &_helper)
  12991. : StrandProcessor(_parent, _inputStream, true), helper(_helper)
  12992. {
  12993. }
  12994. virtual const void * nextRow()
  12995. {
  12996. ActivityTimer t(totalCycles, timeActivities);
  12997. for (;;)
  12998. {
  12999. OwnedConstRoxieRow in = inputStream->nextRow();
  13000. if (!in)
  13001. {
  13002. if (numProcessedLastGroup == processed)
  13003. in.setown(inputStream->nextRow());
  13004. if (!in)
  13005. {
  13006. numProcessedLastGroup = processed;
  13007. return NULL;
  13008. }
  13009. }
  13010. try
  13011. {
  13012. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  13013. size32_t outSize;
  13014. outSize = helper.transform(rowBuilder, in);
  13015. if (outSize)
  13016. {
  13017. processed++;
  13018. return rowBuilder.finalizeRowClear(outSize);
  13019. }
  13020. }
  13021. catch (IException *E)
  13022. {
  13023. throw parent.makeWrappedException(E);
  13024. }
  13025. }
  13026. }
  13027. };
  13028. public:
  13029. CRoxieServerStrandedProjectActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const StrandOptions &_strandOptions)
  13030. : CRoxieServerStrandedActivity(_ctx, _factory, _probeManager, _strandOptions)
  13031. {
  13032. }
  13033. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13034. {
  13035. CRoxieServerStrandedActivity::start(parentExtractSize, parentExtract, paused);
  13036. onStartStrands();
  13037. }
  13038. virtual StrandProcessor *createStrandProcessor(IEngineRowStream *instream)
  13039. {
  13040. return new ProjectProcessor(*this, instream, (IHThorProjectArg &) basehelper);
  13041. }
  13042. virtual StrandProcessor *createStrandSourceProcessor(bool inputOrdered) { throwUnexpected(); }
  13043. };
  13044. class CRoxieServerProjectActivity : public CRoxieServerActivity
  13045. {
  13046. unsigned numProcessedLastGroup;
  13047. unsigned __int64 recordCount;
  13048. bool count;
  13049. public:
  13050. CRoxieServerProjectActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _count)
  13051. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  13052. count(_count)
  13053. {
  13054. numProcessedLastGroup = 0;
  13055. recordCount = 0;
  13056. }
  13057. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13058. {
  13059. numProcessedLastGroup = 0;
  13060. recordCount = 0;
  13061. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  13062. }
  13063. virtual bool needsAllocator() const { return true; }
  13064. virtual const void * nextRow()
  13065. {
  13066. ActivityTimer t(totalCycles, timeActivities);
  13067. for (;;)
  13068. {
  13069. OwnedConstRoxieRow in = inputStream->nextRow();
  13070. if (!in)
  13071. {
  13072. recordCount = 0;
  13073. if (numProcessedLastGroup == processed)
  13074. in.setown(inputStream->nextRow());
  13075. if (!in)
  13076. {
  13077. numProcessedLastGroup = processed;
  13078. return NULL;
  13079. }
  13080. }
  13081. try
  13082. {
  13083. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  13084. size32_t outSize;
  13085. if (count)
  13086. outSize = ((IHThorCountProjectArg &) basehelper).transform(rowBuilder, in, ++recordCount);
  13087. else
  13088. outSize = ((IHThorProjectArg &) basehelper).transform(rowBuilder, in);
  13089. if (outSize)
  13090. {
  13091. processed++;
  13092. return rowBuilder.finalizeRowClear(outSize);
  13093. }
  13094. }
  13095. catch (IException *E)
  13096. {
  13097. throw makeWrappedException(E);
  13098. }
  13099. }
  13100. }
  13101. };
  13102. class CRoxieServerProjectActivityFactory : public CRoxieServerActivityFactory
  13103. {
  13104. protected:
  13105. StrandOptions strandOptions;
  13106. bool count;
  13107. public:
  13108. CRoxieServerProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  13109. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), strandOptions(_graphNode)
  13110. {
  13111. count = (kind==TAKcountproject || kind==TAKprefetchcountproject);
  13112. optStableInput = count;
  13113. }
  13114. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  13115. {
  13116. // 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.
  13117. if (kind == TAKproject) // Not supported on prefetch or count projects
  13118. return new CRoxieServerStrandedProjectActivity(_ctx, this, _probeManager, strandOptions);
  13119. else
  13120. return new CRoxieServerProjectActivity(_ctx, this, _probeManager, count);
  13121. }
  13122. };
  13123. IRoxieServerActivityFactory *createRoxieServerProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  13124. {
  13125. return new CRoxieServerProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  13126. }
  13127. //=================================================================================
  13128. class CRoxieServerPrefetchProjectActivity : public CRoxieServerActivity, implements IRecordPullerCallback
  13129. {
  13130. unsigned numProcessedLastGroup;
  13131. bool count;
  13132. bool eof;
  13133. bool allPulled;
  13134. bool isThreaded;
  13135. unsigned preload;
  13136. unsigned __int64 recordCount;
  13137. IHThorPrefetchProjectArg &helper;
  13138. RecordPullerThread puller;
  13139. InterruptableSemaphore ready;
  13140. InterruptableSemaphore space;
  13141. class PrefetchInfo : public CInterface
  13142. {
  13143. public:
  13144. inline PrefetchInfo(IHThorPrefetchProjectArg &helper, const void *_in, unsigned __int64 _recordCount)
  13145. {
  13146. if (helper.preTransform(extract, _in, _recordCount))
  13147. {
  13148. in.setown(_in);
  13149. recordCount = _recordCount;
  13150. }
  13151. else
  13152. {
  13153. ReleaseRoxieRow(_in);
  13154. recordCount = 0;
  13155. }
  13156. }
  13157. OwnedConstRoxieRow in;
  13158. unsigned __int64 recordCount;
  13159. rtlRowBuilder extract;
  13160. };
  13161. QueueOf<PrefetchInfo, true> pulled;
  13162. CriticalSection pulledCrit;
  13163. public:
  13164. CRoxieServerPrefetchProjectActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _count)
  13165. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  13166. helper((IHThorPrefetchProjectArg &) basehelper),
  13167. puller(false),
  13168. count(_count)
  13169. {
  13170. numProcessedLastGroup = 0;
  13171. recordCount = 0;
  13172. eof = false;
  13173. allPulled = false;
  13174. isThreaded = (helper.getFlags() & PPFparallel) != 0;
  13175. preload = 0;
  13176. }
  13177. ~CRoxieServerPrefetchProjectActivity()
  13178. {
  13179. while (pulled.ordinality())
  13180. ::Release(pulled.dequeue());
  13181. }
  13182. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  13183. {
  13184. if (idx)
  13185. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
  13186. puller.setInput(this, _sourceIdx, _in);
  13187. }
  13188. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  13189. {
  13190. puller.connectInputStreams(ctx, consumerOrdered);
  13191. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
  13192. }
  13193. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  13194. {
  13195. if (idx==0)
  13196. return puller.queryInput();
  13197. else
  13198. return NULL;
  13199. }
  13200. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13201. {
  13202. numProcessedLastGroup = 0;
  13203. recordCount = 0;
  13204. eof = false;
  13205. allPulled = false;
  13206. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  13207. preload = helper.getLookahead();
  13208. if (!preload)
  13209. preload = ctx->queryOptions().prefetchProjectPreload;
  13210. space.reinit(preload);
  13211. ready.reinit();
  13212. puller.start(parentExtractSize, parentExtract, paused, preload, !isThreaded, ctx);
  13213. }
  13214. virtual void stop()
  13215. {
  13216. space.interrupt();
  13217. ready.interrupt();
  13218. CRoxieServerActivity::stop();
  13219. puller.stop();
  13220. }
  13221. virtual void reset()
  13222. {
  13223. CRoxieServerActivity::reset();
  13224. puller.reset();
  13225. allPulled = false;
  13226. while (pulled.ordinality())
  13227. ::Release(pulled.dequeue());
  13228. }
  13229. virtual PrefetchInfo *readNextRecord()
  13230. {
  13231. if (!isThreaded)
  13232. {
  13233. if (!allPulled) // This looks like it's thread unsafe but we are inside the if(!isThreaded) so should be ok
  13234. puller.pullRecords(1);
  13235. }
  13236. else
  13237. ready.wait();
  13238. CriticalBlock b(pulledCrit);
  13239. PrefetchInfo *ret = pulled.ordinality() ? pulled.dequeue() : NULL;
  13240. space.signal();
  13241. return ret;
  13242. }
  13243. virtual bool needsAllocator() const { return true; }
  13244. virtual const void * nextRow()
  13245. {
  13246. ActivityTimer t(totalCycles, timeActivities);
  13247. if (eof)
  13248. return NULL;
  13249. for (;;)
  13250. {
  13251. Owned<PrefetchInfo> in = readNextRecord();
  13252. if (!in)
  13253. {
  13254. recordCount = 0;
  13255. if (numProcessedLastGroup == processed)
  13256. in.setown(readNextRecord());
  13257. if (!in)
  13258. {
  13259. numProcessedLastGroup = processed;
  13260. eof = true;
  13261. return NULL;
  13262. }
  13263. }
  13264. try
  13265. {
  13266. if (in->in)
  13267. {
  13268. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  13269. size32_t outSize;
  13270. IThorChildGraph *child = helper.queryChild();
  13271. Owned<IEclGraphResults> results;
  13272. if (child)
  13273. results.setown(child->evaluate(in->extract.size(), in->extract.getbytes()));
  13274. outSize = helper.transform(rowBuilder, in->in, results, in->recordCount);
  13275. if (outSize)
  13276. {
  13277. processed++;
  13278. return rowBuilder.finalizeRowClear(outSize);
  13279. }
  13280. }
  13281. }
  13282. catch (IException *E)
  13283. {
  13284. throw makeWrappedException(E);
  13285. }
  13286. }
  13287. }
  13288. // interface IExceptionHandler
  13289. virtual bool fireException(IException *e)
  13290. {
  13291. // called from puller thread on failure
  13292. ready.interrupt(LINK(e));
  13293. space.interrupt(e);
  13294. return true;
  13295. }
  13296. // interface IRecordPullerCallback
  13297. virtual void processRow(const void *row)
  13298. {
  13299. {
  13300. CriticalBlock b(pulledCrit);
  13301. pulled.enqueue(new PrefetchInfo(helper, row, ++recordCount));
  13302. }
  13303. if (isThreaded)
  13304. {
  13305. ready.signal();
  13306. space.wait();
  13307. }
  13308. }
  13309. virtual void processEOG()
  13310. {
  13311. {
  13312. CriticalBlock b(pulledCrit);
  13313. pulled.enqueue(NULL);
  13314. }
  13315. if (isThreaded)
  13316. {
  13317. ready.signal();
  13318. space.wait();
  13319. }
  13320. }
  13321. virtual void processGroup(const ConstPointerArray &rows)
  13322. {
  13323. throwUnexpected();
  13324. }
  13325. virtual void processDone()
  13326. {
  13327. CriticalBlock b(pulledCrit);
  13328. allPulled = true;
  13329. if (isThreaded)
  13330. ready.signal();
  13331. }
  13332. };
  13333. class CRoxieServerPrefetchProjectActivityFactory : public CRoxieServerProjectActivityFactory
  13334. {
  13335. public:
  13336. CRoxieServerPrefetchProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  13337. : CRoxieServerProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  13338. {
  13339. }
  13340. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  13341. {
  13342. return new CRoxieServerPrefetchProjectActivity(_ctx, this, _probeManager, count);
  13343. }
  13344. };
  13345. extern IRoxieServerActivityFactory *createRoxieServerPrefetchProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  13346. {
  13347. return new CRoxieServerPrefetchProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  13348. }
  13349. //=================================================================================
  13350. class CPointerArrayRoxieInput : public CPseudoRoxieInput
  13351. {
  13352. public:
  13353. CPointerArrayRoxieInput()
  13354. {
  13355. rowset = NULL;
  13356. rowcount = 0;
  13357. curRow = 0;
  13358. }
  13359. void init(size32_t _rowcount, const byte **_rowset)
  13360. {
  13361. rowset = _rowset;
  13362. rowcount = _rowcount;
  13363. curRow = 0;
  13364. }
  13365. virtual const void * nextRow()
  13366. {
  13367. if (curRow < rowcount)
  13368. {
  13369. const void * ret = rowset[curRow];
  13370. if (ret)
  13371. LinkRoxieRow(ret);
  13372. curRow++;
  13373. return ret;
  13374. }
  13375. return NULL;
  13376. }
  13377. protected:
  13378. const byte **rowset;
  13379. size32_t rowcount;
  13380. size32_t curRow;
  13381. };
  13382. class CRoxieServerLoopActivity : public CRoxieServerActivity
  13383. {
  13384. protected:
  13385. IHThorLoopArg &helper;
  13386. ThorActivityKind activityKind;
  13387. unsigned maxIterations;
  13388. bool finishedLooping;
  13389. unsigned flags;
  13390. bool eof;
  13391. rtlRowBuilder loopExtractBuilder;
  13392. unsigned loopGraphId;
  13393. Linked<IOutputMetaData> counterMeta;
  13394. public:
  13395. CRoxieServerLoopActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _loopGraphId, IOutputMetaData * _counterMeta)
  13396. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  13397. helper((IHThorLoopArg &)basehelper), loopGraphId(_loopGraphId), counterMeta(_counterMeta)
  13398. {
  13399. eof = false;
  13400. finishedLooping = false;
  13401. activityKind = factory->getKind();
  13402. flags = helper.getFlags();
  13403. maxIterations = 0;
  13404. }
  13405. virtual bool needsAllocator() const { return true; }
  13406. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13407. {
  13408. eof = false;
  13409. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  13410. int iterations = (int) helper.numIterations();
  13411. maxIterations = (iterations >= 0) ? iterations : 0;
  13412. finishedLooping = ((activityKind == TAKloopcount) && (maxIterations == 0));
  13413. if ((flags & IHThorLoopArg::LFnewloopagain) && !helper.loopFirstTime())
  13414. finishedLooping = true;
  13415. loopExtractBuilder.clear();
  13416. helper.createParentExtract(loopExtractBuilder); // could possibly delay this until execution actually happens
  13417. }
  13418. virtual void stop()
  13419. {
  13420. CRoxieServerActivity::stop();
  13421. loopExtractBuilder.clear();
  13422. }
  13423. void createCounterResult(IRoxieServerChildGraph * graph, unsigned counter)
  13424. {
  13425. if (flags & IHThorLoopArg::LFcounter)
  13426. {
  13427. void * counterRow = ctx->queryRowManager().allocate(sizeof(thor_loop_counter_t), activityId);
  13428. *((thor_loop_counter_t *)counterRow) = counter;
  13429. RtlLinkedDatasetBuilder builder(rowAllocator);
  13430. builder.appendOwn(counterRow);
  13431. Owned<CGraphResult> counterResult = new CGraphResult(builder.getcount(), builder.linkrows());
  13432. graph->setInputResult(2, counterResult);
  13433. }
  13434. }
  13435. };
  13436. //=================================================================================
  13437. class CRoxieServerSequentialLoopActivity : public CRoxieServerLoopActivity
  13438. {
  13439. Owned<IActivityGraph> loopQuery;
  13440. Owned<IRoxieServerChildGraph> loopGraph;
  13441. IEngineRowStream * curStream;
  13442. RtlLinkedDatasetBuilder *loopInputBuilder;
  13443. CPointerArrayRoxieInput arrayInput;
  13444. Linked<IEngineRowStream> resultStream;
  13445. unsigned loopCounter;
  13446. public:
  13447. CRoxieServerSequentialLoopActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _loopGraphId, IOutputMetaData * _counterMeta)
  13448. : CRoxieServerLoopActivity(_ctx, _factory, _probeManager, _loopGraphId, _counterMeta)
  13449. {
  13450. curStream = NULL;
  13451. loopCounter = 0;
  13452. loopInputBuilder = NULL;
  13453. }
  13454. virtual bool needsAllocator() const { return true; }
  13455. virtual void onCreate(IHThorArg *_colocalParent)
  13456. {
  13457. CRoxieServerLoopActivity::onCreate(_colocalParent);
  13458. loopQuery.set(ctx->queryChildGraph(loopGraphId));
  13459. }
  13460. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13461. {
  13462. curStream = inputStream;
  13463. loopCounter = 1;
  13464. CRoxieServerLoopActivity::start(parentExtractSize, parentExtract, paused);
  13465. //MORE: Not sure about this, should IRoxieServerChildGraph be combined with IActivityGraph?
  13466. loopGraph.set(loopQuery->queryLoopGraph());
  13467. loopInputBuilder = new RtlLinkedDatasetBuilder(rowAllocator);
  13468. }
  13469. virtual void stop()
  13470. {
  13471. delete loopInputBuilder;
  13472. loopInputBuilder = NULL;
  13473. CRoxieServerLoopActivity::stop();
  13474. }
  13475. virtual const void * nextRow()
  13476. {
  13477. ActivityTimer t(totalCycles, timeActivities);
  13478. if (eof)
  13479. return NULL;
  13480. unsigned emptyIterations = 0;
  13481. for (;;)
  13482. {
  13483. for (;;)
  13484. {
  13485. const void * ret = curStream->nextRow();
  13486. if (!ret)
  13487. {
  13488. ret = curStream->nextRow(); // more cope with groups somehow....
  13489. if (!ret)
  13490. {
  13491. if (finishedLooping)
  13492. {
  13493. eof = true;
  13494. return NULL;
  13495. }
  13496. break;
  13497. }
  13498. }
  13499. if (finishedLooping ||
  13500. ((flags & IHThorLoopArg::LFfiltered) && !helper.sendToLoop(loopCounter, ret)))
  13501. {
  13502. processed++;
  13503. return ret;
  13504. }
  13505. loopInputBuilder->appendOwn(ret);
  13506. }
  13507. switch (activityKind)
  13508. {
  13509. case TAKloopdataset:
  13510. {
  13511. if (!(flags & IHThorLoopArg::LFnewloopagain))
  13512. {
  13513. if (!helper.loopAgain(loopCounter, loopInputBuilder->getcount(), (const void**) loopInputBuilder->queryrows()))
  13514. {
  13515. if (loopInputBuilder->getcount() == 0)
  13516. {
  13517. eof = true;
  13518. return NULL;
  13519. }
  13520. arrayInput.init(loopInputBuilder->getcount(), loopInputBuilder->linkrows());
  13521. // MORE - should builder be cleared here?
  13522. curStream = &arrayInput;
  13523. finishedLooping = true;
  13524. continue; // back to the input loop again
  13525. }
  13526. }
  13527. break;
  13528. }
  13529. case TAKlooprow:
  13530. if (!loopInputBuilder->getcount())
  13531. {
  13532. finishedLooping = true;
  13533. eof = true;
  13534. return NULL;
  13535. }
  13536. break;
  13537. }
  13538. if (loopInputBuilder->getcount())
  13539. emptyIterations = 0;
  13540. else
  13541. {
  13542. //note: any outputs which didn't go around the loop again, would return the record, reinitializing emptyIterations
  13543. emptyIterations++;
  13544. if (emptyIterations > maxEmptyLoopIterations)
  13545. throw MakeStringException(ROXIE_TOO_MANY_EMPTY_LOOP, "Executed LOOP with empty input and output %u times", emptyIterations);
  13546. if (emptyIterations % 32 == 0)
  13547. CTXLOG("Executing LOOP with empty input and output %u times", emptyIterations);
  13548. }
  13549. checkAbort();
  13550. try
  13551. {
  13552. Owned<IRoxieGraphResults> results = executeIteration(loopExtractBuilder.size(), loopExtractBuilder.getbytes(), loopCounter);
  13553. resultStream.setown(results->createIterator(0));
  13554. if (flags & IHThorLoopArg::LFnewloopagain)
  13555. {
  13556. Owned<IEngineRowStream> againResult = results->createIterator(helper.loopAgainResult());
  13557. OwnedConstRoxieRow row = againResult->nextRow();
  13558. assertex(row);
  13559. //Result is a row which contains a single boolean field.
  13560. if (!((const bool *)row.get())[0])
  13561. finishedLooping = true;
  13562. }
  13563. }
  13564. catch (IException *E)
  13565. {
  13566. throw makeWrappedException(E);
  13567. }
  13568. curStream = resultStream.get();
  13569. loopCounter++;
  13570. if ((activityKind == TAKloopcount) && (loopCounter > maxIterations))
  13571. finishedLooping = true;
  13572. }
  13573. }
  13574. IRoxieGraphResults * executeIteration(unsigned parentExtractSize, const byte *parentExtract, unsigned counter)
  13575. {
  13576. try
  13577. {
  13578. loopGraph->beforeExecute();
  13579. Owned<IGraphResult> inputRowsResult = new CGraphResult(loopInputBuilder->getcount(), loopInputBuilder->linkrows());
  13580. loopInputBuilder->clear();
  13581. loopGraph->setInputResult(1, inputRowsResult);
  13582. createCounterResult(loopGraph, counter);
  13583. Owned<IRoxieGraphResults> ret = loopGraph->execute(parentExtractSize, parentExtract);
  13584. loopGraph->afterExecute();
  13585. return ret.getClear();
  13586. }
  13587. catch (...)
  13588. {
  13589. CTXLOG("Exception thrown in loop body - cleaning up");
  13590. loopGraph->afterExecute();
  13591. throw;
  13592. }
  13593. }
  13594. };
  13595. //=================================================================================
  13596. typedef SafeQueueOf<const void, true> SafeRowQueue;
  13597. class CRowQueuePseudoInput : public CPseudoRoxieInput
  13598. {
  13599. public:
  13600. CRowQueuePseudoInput(SafeRowQueue & _input, IOutputMetaData * _meta)
  13601. : meta(_meta), input(_input)
  13602. {
  13603. eof = false;
  13604. }
  13605. virtual const void * nextRow()
  13606. {
  13607. if (eof)
  13608. return NULL;
  13609. const void * ret = input.dequeue();
  13610. if (!ret)
  13611. eof = true;
  13612. return ret;
  13613. }
  13614. virtual IOutputMetaData * queryOutputMeta() const { return meta; }
  13615. protected:
  13616. SafeRowQueue & input;
  13617. IOutputMetaData * meta;
  13618. bool eof;
  13619. };
  13620. class CRoxieServerParallelLoopActivity;
  13621. class LoopFilterPseudoInput : public CIndirectRoxieInput
  13622. {
  13623. public:
  13624. LoopFilterPseudoInput(CRoxieServerParallelLoopActivity * _activity, unsigned _counter) :
  13625. activity(_activity), counter(_counter)
  13626. {
  13627. }
  13628. virtual const void * nextRow();
  13629. protected:
  13630. CRoxieServerParallelLoopActivity * activity;
  13631. unsigned counter;
  13632. };
  13633. class LoopExecutorThread : public RestartableThread
  13634. {
  13635. protected:
  13636. Owned<CSafeRoxieInput> safeInput;
  13637. CRoxieServerParallelLoopActivity * activity;
  13638. bool eof;
  13639. CriticalSection crit;
  13640. unsigned flags;
  13641. SafeRowQueue tempResults[2];
  13642. unsigned savedParentExtractSize;
  13643. const byte * savedParentExtract;
  13644. IArrayOf<IActivityGraph> cachedGraphs;
  13645. IRoxieSlaveContext *ctx;
  13646. public:
  13647. LoopExecutorThread()
  13648. : RestartableThread("LoopExecutorThread")
  13649. {
  13650. activity = NULL;
  13651. eof = false;
  13652. flags = 0;
  13653. ctx = NULL;
  13654. savedParentExtract = NULL;
  13655. savedParentExtractSize = 0;
  13656. }
  13657. void setInput(CRoxieServerParallelLoopActivity * _activity, unsigned _sourceIdx, IFinalRoxieInput *_input, unsigned _flags)
  13658. {
  13659. activity = _activity;
  13660. flags = _flags;
  13661. // 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.
  13662. safeInput.setown(new CSafeRoxieInput(_sourceIdx, _input));
  13663. }
  13664. void connectInputStreams(bool consumerOrdered)
  13665. {
  13666. safeInput->connectInputStreams(ctx, consumerOrdered);
  13667. }
  13668. IFinalRoxieInput *queryInput() const
  13669. {
  13670. return safeInput;
  13671. }
  13672. void onCreate(IRoxieSlaveContext * _ctx);
  13673. void start(unsigned parentExtractSize, const byte *parentExtract, bool paused);
  13674. void stop();
  13675. void reset();
  13676. virtual int run();
  13677. protected:
  13678. void executeLoop();
  13679. void executeLoopInstance(unsigned counter, unsigned numIterations, unsigned inputIdx, IFinalRoxieInput * input, SafeRowQueue * spillOutput);
  13680. IFinalRoxieInput * createLoopIterationGraph(unsigned i, unsigned inputIdx, IFinalRoxieInput * input, unsigned counter);
  13681. };
  13682. class CRoxieServerParallelLoopActivity : public CRoxieServerLoopActivity
  13683. {
  13684. friend class LoopFilterPseudoInput;
  13685. friend class LoopExecutorThread;
  13686. QueueOf<const void, true> ready;
  13687. CriticalSection helperCS;
  13688. CriticalSection cs;
  13689. unsigned defaultNumParallel;
  13690. LoopExecutorThread executor;
  13691. IProbeManager* probeManager;
  13692. CriticalSection canAccess;
  13693. CriticalSection scrit;
  13694. InterruptableSemaphore readySpace;
  13695. InterruptableSemaphore recordsReady;
  13696. protected:
  13697. bool includeInLoop(unsigned counter, const void * row)
  13698. {
  13699. CriticalBlock b(helperCS);
  13700. return helper.sendToLoop(counter, row);
  13701. }
  13702. public:
  13703. CRoxieServerParallelLoopActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _loopGraphId, IOutputMetaData * _counterMeta)
  13704. : CRoxieServerLoopActivity(_ctx, _factory, _probeManager, _loopGraphId, _counterMeta),
  13705. readySpace(parallelLoopFlowLimit)
  13706. {
  13707. probeManager = _probeManager;
  13708. defaultNumParallel = 0;
  13709. }
  13710. virtual void onCreate(IHThorArg *_colocalParent)
  13711. {
  13712. CRoxieServerActivity::onCreate(_colocalParent);
  13713. executor.onCreate(ctx);
  13714. }
  13715. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13716. {
  13717. CriticalBlock b(scrit); // can stop while still starting, if unlucky...
  13718. readySpace.reinit(parallelLoopFlowLimit);
  13719. recordsReady.reinit();
  13720. CRoxieServerLoopActivity::start(parentExtractSize, parentExtract, paused);
  13721. defaultNumParallel = helper.defaultParallelIterations();
  13722. if (!defaultNumParallel)
  13723. defaultNumParallel = DEFAULT_PARALLEL_LOOP_THREADS;
  13724. //MORE: If numIterations <= number of parallel iterations[1],
  13725. //then we don't need to create a separate thread to do the processing, and the results will also avoid
  13726. //being transferred via a queue
  13727. executor.start(parentExtractSize, parentExtract, paused);
  13728. }
  13729. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  13730. {
  13731. if (idx)
  13732. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
  13733. executor.setInput(this, _sourceIdx, _in, flags);
  13734. }
  13735. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  13736. {
  13737. executor.connectInputStreams(consumerOrdered);
  13738. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, nullptr, consumerOrdered, nullptr);
  13739. }
  13740. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  13741. {
  13742. if (idx==0)
  13743. return executor.queryInput();
  13744. else
  13745. return NULL;
  13746. }
  13747. virtual void stop()
  13748. {
  13749. CriticalBlock b(scrit); // can stop while still starting, if unlucky...
  13750. readySpace.interrupt();
  13751. recordsReady.interrupt();
  13752. executor.join(); // MORE - may not be needed given stop/reset split
  13753. CRoxieServerLoopActivity::stop();
  13754. }
  13755. virtual void reset()
  13756. {
  13757. while (ready.ordinality())
  13758. ReleaseRoxieRow(ready.dequeue());
  13759. executor.reset();
  13760. CRoxieServerActivity::reset();
  13761. }
  13762. virtual const void * nextRow()
  13763. {
  13764. ActivityTimer t(totalCycles, timeActivities);
  13765. for (;;)
  13766. {
  13767. if (eof)
  13768. return NULL;
  13769. recordsReady.wait();
  13770. CriticalBlock procedure(canAccess);
  13771. if (ready.ordinality())
  13772. {
  13773. const void *result = ready.dequeue();
  13774. readySpace.signal();
  13775. if (result)
  13776. processed++;
  13777. return result;
  13778. }
  13779. else
  13780. eof = true;
  13781. }
  13782. }
  13783. unsigned getNumParallel(unsigned iter)
  13784. {
  13785. return defaultNumParallel;
  13786. }
  13787. inline void enqueueResult(const void * row)
  13788. {
  13789. try
  13790. {
  13791. while(!readySpace.wait(1000))
  13792. {
  13793. CTXLOG("Blocked waiting for space in loop %p activity id: %d output queue: %d records in queue", this, queryId(), ready.ordinality());
  13794. }
  13795. }
  13796. catch (...)
  13797. {
  13798. ReleaseRoxieRow(row);
  13799. throw;
  13800. }
  13801. CriticalBlock b2(canAccess);
  13802. ready.enqueue(row);
  13803. recordsReady.signal();
  13804. }
  13805. inline void finishResults()
  13806. {
  13807. recordsReady.signal();
  13808. }
  13809. virtual bool fireException(IException *e)
  13810. {
  13811. readySpace.interrupt(LINK(e));
  13812. recordsReady.interrupt(e);
  13813. return true;
  13814. }
  13815. IActivityGraph * createChildGraphInstance()
  13816. {
  13817. return factory->createChildGraph(ctx, &helper, loopGraphId, this, probeManager, *this);
  13818. }
  13819. IActivityGraph * queryChildGraph()
  13820. {
  13821. return ctx->queryChildGraph(loopGraphId);
  13822. }
  13823. };
  13824. //=================================================================================
  13825. const void * LoopFilterPseudoInput::nextRow()
  13826. {
  13827. for (;;)
  13828. {
  13829. const void * next = stream->nextRow();
  13830. if (!next || activity->includeInLoop(counter, next))
  13831. return next;
  13832. activity->enqueueResult(next);
  13833. }
  13834. }
  13835. void LoopExecutorThread::onCreate(IRoxieSlaveContext * _ctx)
  13836. {
  13837. //Initialise the cached graph list with the child instance that will always be created. Other iterations will be created on demand.
  13838. ctx = _ctx;
  13839. cachedGraphs.append(*LINK(activity->queryChildGraph()));
  13840. }
  13841. void LoopExecutorThread::start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13842. {
  13843. savedParentExtractSize = parentExtractSize;
  13844. savedParentExtract = parentExtract;
  13845. eof = false;
  13846. StringBuffer logPrefix("[");
  13847. ctx->getLogPrefix(logPrefix).append("] ");
  13848. RestartableThread::start(logPrefix);
  13849. }
  13850. int LoopExecutorThread::run()
  13851. {
  13852. try
  13853. {
  13854. executeLoop();
  13855. }
  13856. catch (IException *e)
  13857. {
  13858. activity->fireException(e);
  13859. }
  13860. catch (...)
  13861. {
  13862. activity->fireException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unexpected exception caught in LoopExecutorThread::run"));
  13863. }
  13864. return 0;
  13865. }
  13866. void LoopExecutorThread::stop()
  13867. {
  13868. safeInput->stop();
  13869. RestartableThread::join();
  13870. }
  13871. void LoopExecutorThread::reset()
  13872. {
  13873. safeInput->reset();
  13874. }
  13875. void LoopExecutorThread::executeLoop()
  13876. {
  13877. unsigned iterations = 0;
  13878. unsigned counter = 0;
  13879. unsigned outputIndex = 0;
  13880. //Note, activities don't link inputs, so need to be careful that special inputs remain linked while the activity is executing.
  13881. for (;;)
  13882. {
  13883. if (activity->activityKind == TAKloopcount)
  13884. {
  13885. if (counter == activity->maxIterations)
  13886. break;
  13887. }
  13888. else
  13889. {
  13890. //This condition isn't quite right because it needs to be whether the filtered
  13891. //input is empty. May be ok if we include that in the semantics,
  13892. if (tempResults[1-outputIndex].ordinality() == 0)
  13893. break;
  13894. }
  13895. unsigned numParallel = activity->getNumParallel(iterations);
  13896. Linked<IFinalRoxieInput> curInput;
  13897. if (iterations == 0)
  13898. curInput.set(safeInput);
  13899. else
  13900. {
  13901. SafeRowQueue & inputQueue = tempResults[1-outputIndex];
  13902. inputQueue.enqueue(NULL);
  13903. curInput.setown(new CRowQueuePseudoInput(inputQueue, activity->queryOutputMeta()));
  13904. }
  13905. SafeRowQueue * curOutput = NULL;
  13906. if (counter+numParallel > activity->maxIterations)
  13907. numParallel = activity->maxIterations - counter;
  13908. else if (counter+numParallel < activity->maxIterations)
  13909. curOutput = &tempResults[outputIndex];
  13910. executeLoopInstance(counter, numParallel, 0, curInput, curOutput); // CurInput is always SOME sort of proxy so idx always 0
  13911. outputIndex = 1-outputIndex;
  13912. counter += numParallel;
  13913. iterations++;
  13914. }
  13915. //Check for TAKlooprow, where end of loop couldn't be determined ahead of time
  13916. SafeRowQueue & inputQueue = tempResults[1-outputIndex];
  13917. while (inputQueue.ordinality())
  13918. {
  13919. const void * next = inputQueue.dequeue();
  13920. activity->enqueueResult(next);
  13921. }
  13922. activity->finishResults();
  13923. }
  13924. void LoopExecutorThread::executeLoopInstance(unsigned counter, unsigned numIterations, unsigned inputIdx, IFinalRoxieInput * input, SafeRowQueue * spillOutput)
  13925. {
  13926. IArrayOf<IFinalRoxieInput> savedInputs; // activities don't link their inputs, so this list keeps filters alive.
  13927. Linked<IFinalRoxieInput> curInput = input;
  13928. unsigned i;
  13929. for (i= 0; i != numIterations; i++)
  13930. {
  13931. unsigned thisCounter = counter+i+1;
  13932. IFinalRoxieInput * filtered = curInput;
  13933. if (flags & IHThorLoopArg::LFfiltered)
  13934. {
  13935. LoopFilterPseudoInput *newFiltered = new LoopFilterPseudoInput(activity, thisCounter);
  13936. newFiltered->setInput(inputIdx, curInput);
  13937. filtered = newFiltered;
  13938. savedInputs.append(*filtered);
  13939. inputIdx = 0;
  13940. }
  13941. //graph is kept, so new curInput will be guaranteed to exist
  13942. curInput.setown(createLoopIterationGraph(i, inputIdx, filtered, thisCounter));
  13943. inputIdx = 0;
  13944. }
  13945. Owned<IStrandJunction> curJunction;
  13946. IEngineRowStream *curStream = connectSingleStream(ctx, curInput, inputIdx, curJunction, true);
  13947. Owned<IException> failure;
  13948. try
  13949. {
  13950. curInput->start(savedParentExtractSize, savedParentExtract, false);
  13951. if (spillOutput)
  13952. {
  13953. for (;;)
  13954. {
  13955. const void * next = curStream->nextRow();
  13956. if (!next)
  13957. break;
  13958. spillOutput->enqueue(next);
  13959. }
  13960. }
  13961. else
  13962. {
  13963. for (;;)
  13964. {
  13965. const void * next = curStream->nextRow();
  13966. if (!next)
  13967. break;
  13968. activity->enqueueResult(next);
  13969. }
  13970. }
  13971. }
  13972. catch (IException *E)
  13973. {
  13974. ctx->notifyAbort(E);
  13975. failure.setown(E);
  13976. }
  13977. for (i= 0; i != numIterations; i++)
  13978. {
  13979. IRoxieServerChildGraph * loopGraph = cachedGraphs.item(i).queryLoopGraph();
  13980. loopGraph->afterExecute();
  13981. //NOTE: inputIdx is always 0 - the code above could be cleaned up.
  13982. loopGraph->querySetInputResult(1, 0, nullptr);
  13983. }
  13984. curStream->stop();
  13985. curInput->reset();
  13986. if (failure)
  13987. throw failure.getClear();
  13988. }
  13989. IFinalRoxieInput * LoopExecutorThread::createLoopIterationGraph(unsigned i, unsigned inputIdx, IFinalRoxieInput * input, unsigned counter)
  13990. {
  13991. if (!cachedGraphs.isItem(i))
  13992. cachedGraphs.append(*activity->createChildGraphInstance());
  13993. Linked<IRoxieServerChildGraph> loopGraph = cachedGraphs.item(i).queryLoopGraph();
  13994. loopGraph->beforeExecute();
  13995. if (!loopGraph->querySetInputResult(1, inputIdx, input))
  13996. throwUnexpected(); // a loop which doesn't use the value from the previous iteration. Should probably handle even if daft.
  13997. activity->createCounterResult(loopGraph, counter);
  13998. return loopGraph->selectOutput(0);
  13999. }
  14000. //=================================================================================
  14001. class CCounterRowMetaData : implements IOutputMetaData, public CInterface
  14002. {
  14003. public:
  14004. IMPLEMENT_IINTERFACE
  14005. virtual size32_t getRecordSize(const void *) { return sizeof(thor_loop_counter_t); }
  14006. virtual size32_t getMinRecordSize() const { return sizeof(thor_loop_counter_t); }
  14007. virtual size32_t getFixedSize() const { return sizeof(thor_loop_counter_t); }
  14008. virtual void toXML(const byte * self, IXmlWriter & out) { }
  14009. virtual unsigned getVersion() const { return OUTPUTMETADATA_VERSION; }
  14010. virtual unsigned getMetaFlags() { return 0; }
  14011. virtual void destruct(byte * self) {}
  14012. virtual IOutputRowSerializer * createDiskSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  14013. virtual IOutputRowDeserializer * createDiskDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  14014. virtual ISourceRowPrefetcher * createDiskPrefetcher() { return NULL; }
  14015. virtual IOutputMetaData * querySerializedDiskMeta() { return this; }
  14016. virtual IOutputRowSerializer * createInternalSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  14017. virtual IOutputRowDeserializer * createInternalDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  14018. virtual void walkIndirectMembers(const byte * self, IIndirectMemberVisitor & visitor) {}
  14019. virtual IOutputMetaData * queryChildMeta(unsigned i) { return NULL; }
  14020. virtual const RtlRecord &queryRecordAccessor(bool expand) const { throwUnexpected(); } // could provide a static implementation if needed
  14021. };
  14022. class CRoxieServerLoopActivityFactory : public CRoxieServerActivityFactory
  14023. {
  14024. unsigned loopGraphId;
  14025. unsigned flags;
  14026. Linked<IOutputMetaData> counterMeta;
  14027. public:
  14028. CRoxieServerLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _loopGraphId)
  14029. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), loopGraphId(_loopGraphId)
  14030. {
  14031. Owned<IHThorLoopArg> helper = (IHThorLoopArg *) helperFactory();
  14032. flags = helper->getFlags();
  14033. counterMeta.setown(new CCounterRowMetaData);
  14034. }
  14035. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  14036. {
  14037. if (flags & IHThorLoopArg::LFparallel)
  14038. return new CRoxieServerParallelLoopActivity(_ctx, this, _probeManager, loopGraphId, counterMeta);
  14039. else
  14040. return new CRoxieServerSequentialLoopActivity(_ctx, this, _probeManager, loopGraphId, counterMeta);
  14041. }
  14042. };
  14043. IRoxieServerActivityFactory *createRoxieServerLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _loopGraphId)
  14044. {
  14045. return new CRoxieServerLoopActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _loopGraphId);
  14046. }
  14047. //=================================================================================
  14048. class CRoxieServerGraphLoopActivity : public CRoxieServerActivity
  14049. {
  14050. protected:
  14051. IHThorGraphLoopArg &helper;
  14052. unsigned maxIterations;
  14053. unsigned flags;
  14054. rtlRowBuilder GraphExtractBuilder;
  14055. unsigned loopGraphId;
  14056. Linked<IOutputMetaData> counterMeta;
  14057. public:
  14058. CRoxieServerGraphLoopActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _GraphGraphId, IOutputMetaData * _counterMeta)
  14059. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  14060. helper((IHThorGraphLoopArg &)basehelper), loopGraphId(_GraphGraphId), counterMeta(_counterMeta)
  14061. {
  14062. flags = helper.getFlags();
  14063. maxIterations = 0;
  14064. }
  14065. virtual bool needsAllocator() const { return true; }
  14066. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14067. {
  14068. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14069. int iterations = (int) helper.numIterations();
  14070. maxIterations = (iterations >= 0) ? iterations : 0;
  14071. if (maxIterations > maxGraphLoopIterations)
  14072. throw MakeStringException(ROXIE_TOO_MANY_GRAPH_LOOP, "Attempt to execute graph %u times", maxIterations);
  14073. if (maxIterations != 0)
  14074. {
  14075. GraphExtractBuilder.clear();
  14076. helper.createParentExtract(GraphExtractBuilder);
  14077. }
  14078. }
  14079. virtual void stop()
  14080. {
  14081. CRoxieServerActivity::stop();
  14082. GraphExtractBuilder.clear();
  14083. }
  14084. void createCounterResult(IRoxieServerChildGraph * graph, unsigned counter)
  14085. {
  14086. if (flags & IHThorGraphLoopArg::GLFcounter)
  14087. {
  14088. void * counterRow = ctx->queryRowManager().allocate(sizeof(thor_loop_counter_t), activityId);
  14089. *((thor_loop_counter_t *)counterRow) = counter;
  14090. RtlLinkedDatasetBuilder builder(rowAllocator);
  14091. builder.appendOwn(counterRow);
  14092. Owned<CGraphResult> counterResult = new CGraphResult(builder.getcount(), builder.linkrows());
  14093. graph->setInputResult(0, counterResult);
  14094. }
  14095. }
  14096. };
  14097. //=================================================================================
  14098. class CRoxieServerSequentialGraphLoopActivity : public CRoxieServerGraphLoopActivity
  14099. {
  14100. Owned<IActivityGraph> GraphQuery;
  14101. Owned<IRoxieServerChildGraph> loopGraph;
  14102. Linked<IEngineRowStream> resultStream;
  14103. bool evaluated;
  14104. public:
  14105. CRoxieServerSequentialGraphLoopActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _GraphGraphId, IOutputMetaData * _counterMeta)
  14106. : CRoxieServerGraphLoopActivity(_ctx, _factory, _probeManager, _GraphGraphId, _counterMeta)
  14107. {
  14108. evaluated = false;
  14109. }
  14110. virtual void onCreate(IHThorArg *_colocalParent)
  14111. {
  14112. CRoxieServerGraphLoopActivity::onCreate(_colocalParent);
  14113. GraphQuery.set(ctx->queryChildGraph(loopGraphId));
  14114. }
  14115. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14116. {
  14117. CRoxieServerGraphLoopActivity::start(parentExtractSize, parentExtract, paused);
  14118. //MORE: Not sure about this, should IRoxieServerChildGraph be combined with IActivityGraph?
  14119. loopGraph.set(GraphQuery->queryLoopGraph());
  14120. evaluated = false;
  14121. }
  14122. virtual void stop()
  14123. {
  14124. if (loopGraph)
  14125. loopGraph->clearGraphLoopResults();
  14126. CRoxieServerGraphLoopActivity::stop();
  14127. }
  14128. virtual const void * nextRow()
  14129. {
  14130. ActivityTimer t(totalCycles, timeActivities);
  14131. if (!evaluated)
  14132. {
  14133. executeEntireGraph();
  14134. evaluated = true;
  14135. }
  14136. const void * ret = resultStream->nextRow();
  14137. if (ret)
  14138. processed++;
  14139. return ret;
  14140. }
  14141. void executeIteration(unsigned parentExtractSize, const byte *parentExtract, unsigned counter)
  14142. {
  14143. try
  14144. {
  14145. loopGraph->beforeExecute();
  14146. createCounterResult(loopGraph, counter);
  14147. loopGraph->executeGraphLoop(parentExtractSize, parentExtract);
  14148. loopGraph->afterExecute();
  14149. }
  14150. catch (...)
  14151. {
  14152. CTXLOG("Exception thrown in graph body - cleaning up");
  14153. loopGraph->afterExecute();
  14154. throw;
  14155. }
  14156. }
  14157. void createInitialGraphInput()
  14158. {
  14159. loopGraph->clearGraphLoopResults();
  14160. RtlLinkedDatasetBuilder builder(rowAllocator);
  14161. inputStream->readAll(builder);
  14162. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  14163. loopGraph->setGraphLoopResult(0, result);
  14164. }
  14165. void executeEntireGraph()
  14166. {
  14167. createInitialGraphInput();
  14168. for (unsigned loopCounter=1; loopCounter <= maxIterations; loopCounter++)
  14169. {
  14170. executeIteration(GraphExtractBuilder.size(), GraphExtractBuilder.getbytes(), loopCounter);
  14171. }
  14172. resultStream.setown(loopGraph->getGraphLoopResult(maxIterations));
  14173. }
  14174. };
  14175. //=================================================================================
  14176. struct GraphOutputSplitterArg : public CThorSplitArg
  14177. {
  14178. public:
  14179. virtual unsigned numBranches()
  14180. {
  14181. return 0;
  14182. }
  14183. virtual IOutputMetaData * queryOutputMeta()
  14184. {
  14185. return NULL;// get it from the parent..
  14186. }
  14187. };
  14188. extern "C" IHThorArg * createGraphOutputSplitter() { return new GraphOutputSplitterArg; }
  14189. class CGraphIterationInfo : public CInterface
  14190. {
  14191. private:
  14192. Owned<IRoxieServerActivityFactory> factory; // Note - before sourceAct, so destroyed last
  14193. unsigned sourceIdx;
  14194. Linked<IRoxieServerActivity> sourceAct;
  14195. Linked<IFinalRoxieInput> sourceInput;
  14196. unsigned numUses;
  14197. unsigned iteration;
  14198. public:
  14199. CGraphIterationInfo(IRoxieServerActivity * _sourceAct, IFinalRoxieInput *_input, unsigned _sourceIdx, unsigned _iteration)
  14200. : sourceAct(_sourceAct), sourceInput(_input), sourceIdx(_sourceIdx), iteration(_iteration)
  14201. {
  14202. numUses = 0;
  14203. }
  14204. inline void noteUsed()
  14205. {
  14206. numUses++;
  14207. }
  14208. void createSplitter(IRoxieSlaveContext *ctx, IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes)
  14209. {
  14210. if (numUses > 1)
  14211. {
  14212. Owned<IPropertyTree> splitterNode = createPTree(ipt_fast);
  14213. factory.setown(createRoxieServerThroughSpillActivityFactory(sourceAct->queryFactory()->queryQueryFactory(), createGraphOutputSplitter, numUses, *splitterNode));
  14214. IRoxieServerActivity *splitter = factory->createActivity(ctx, NULL);
  14215. splitter->onCreate(NULL);
  14216. IFinalRoxieInput *input = sourceAct->queryOutput(sourceIdx);
  14217. if (probeManager)
  14218. {
  14219. IRoxieProbe * inputProbe = probeManager->createProbe(static_cast<IInputBase*>(input), sourceAct, splitter, sourceIdx, 0, iteration);
  14220. probes.append(*LINK(inputProbe));
  14221. input = &dynamic_cast<IFinalRoxieInput &>(inputProbe->queryInput());
  14222. sourceIdx = 0;
  14223. }
  14224. sourceAct.setown(splitter);
  14225. sourceAct->setInput(0, sourceIdx, input);
  14226. sourceIdx = 0;
  14227. sourceInput.clear();
  14228. }
  14229. }
  14230. IFinalRoxieInput *connectOutput(IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes, IRoxieServerActivity *targetAct, unsigned targetIdx)
  14231. {
  14232. // MORE - not really necessary to create splitters in separate pass, is it?
  14233. if (factory) // we created a splitter....
  14234. sourceInput.set(sourceAct->queryOutput(sourceIdx));
  14235. IFinalRoxieInput *ret = sourceInput;
  14236. if (probeManager)
  14237. {
  14238. IRoxieProbe * inputProbe = probeManager->createProbe(sourceInput, sourceAct, targetAct, sourceIdx, targetIdx, iteration);
  14239. probes.append(*LINK(inputProbe));
  14240. ret = &dynamic_cast<IFinalRoxieInput &>(inputProbe->queryInput());
  14241. // MORE - do we need to connect the stream in the probe?
  14242. }
  14243. if (factory) // we created a splitter....
  14244. sourceIdx++;
  14245. return ret;
  14246. }
  14247. };
  14248. class CRoxieServerParallelGraphLoopActivity : public CRoxieServerGraphLoopActivity, implements IRoxieServerLoopResultProcessor
  14249. {
  14250. Owned<IActivityGraph> childGraph;
  14251. IFinalRoxieInput * resultInput;
  14252. IEngineRowStream * resultStream;
  14253. Owned<IStrandJunction> resultJunction;
  14254. CIArrayOf<CGraphIterationInfo> outputs;
  14255. IArrayOf<IRoxieServerChildGraph> iterationGraphs;
  14256. Owned<CExtractMapperInput> inputExtractMapper;
  14257. IProbeManager *probeManager;
  14258. unsigned createLoopCounter;
  14259. IArrayOf<IRoxieProbe> probes;
  14260. public:
  14261. CRoxieServerParallelGraphLoopActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _GraphGraphId, IOutputMetaData * _counterMeta)
  14262. : CRoxieServerGraphLoopActivity(_ctx, _factory, _probeManager, _GraphGraphId, _counterMeta), probeManager(_probeManager)
  14263. {
  14264. inputExtractMapper.setown(new CExtractMapperInput);
  14265. resultInput = NULL;
  14266. resultStream = NULL;
  14267. createLoopCounter = 0;
  14268. }
  14269. virtual void onCreate(IHThorArg *_colocalParent)
  14270. {
  14271. CRoxieServerGraphLoopActivity::onCreate(_colocalParent);
  14272. childGraph.set(ctx->queryChildGraph(loopGraphId));
  14273. }
  14274. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  14275. {
  14276. //Input needs to be handled very carefully.....
  14277. //We don't want to call onStart on the input unless it is actually used, so don't use the base CRoxieServerActivity implementation.
  14278. //This activity's input needs to be started with (parentExtractSize, parentExtract), but the elements in the graph need to be started with the
  14279. //GraphExtractBuilder parent extract. So we need to wrap the input in a pseudo-input (inputExtractMapper) that passes through a different
  14280. //parentExtract. Something very similar will be needed for query library calls with streaming inputs when they are implemented.
  14281. assertex(idx == 0);
  14282. inputExtractMapper->setInput(_sourceIdx, _in);
  14283. }
  14284. virtual void connectInputStreams(bool consumerOrdered)
  14285. {
  14286. //NB: inputExtractMapper is not connected at this point - only if/when it is used from within the graph
  14287. CRoxieServerActivity::connectInputStreams(consumerOrdered);
  14288. }
  14289. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  14290. {
  14291. if (idx==0)
  14292. return inputExtractMapper->queryInput();
  14293. else
  14294. return NULL;
  14295. }
  14296. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14297. {
  14298. CRoxieServerGraphLoopActivity::start(parentExtractSize, parentExtract, paused); // initialises GraphExtractBuilder
  14299. inputExtractMapper->setParentExtract(parentExtractSize, parentExtract);
  14300. createExpandedGraph(GraphExtractBuilder.size(), GraphExtractBuilder.getbytes(), probeManager);
  14301. resultInput->start(GraphExtractBuilder.size(), GraphExtractBuilder.getbytes(), paused);
  14302. startJunction(resultJunction);
  14303. }
  14304. virtual void stop()
  14305. {
  14306. if (resultStream)
  14307. resultStream->stop();
  14308. CRoxieServerGraphLoopActivity::stop();
  14309. }
  14310. virtual void reset()
  14311. {
  14312. if (resultInput)
  14313. resultInput->reset();
  14314. resetJunction(resultJunction);
  14315. resultInput = NULL;
  14316. resultStream = NULL;
  14317. resultJunction.clear();
  14318. ForEachItemIn(i, iterationGraphs)
  14319. iterationGraphs.item(i).updateFactoryStatistics();
  14320. outputs.kill();
  14321. iterationGraphs.kill(); // must be done after all activities killed
  14322. if (probeManager)
  14323. {
  14324. probeManager->deleteGraph(NULL, (IArrayOf<IInputBase>*)&probes);
  14325. probes.kill();
  14326. }
  14327. CRoxieServerGraphLoopActivity::reset();
  14328. }
  14329. virtual const void * nextRow()
  14330. {
  14331. ActivityTimer t(totalCycles, timeActivities);
  14332. const void * ret = resultStream->nextRow();
  14333. if (ret)
  14334. processed++;
  14335. return ret;
  14336. }
  14337. void createExpandedGraph(unsigned parentExtractSize, const byte *parentExtract, IProbeManager *probeManager)
  14338. {
  14339. //result(0) is the input to the graph.
  14340. resultInput = inputExtractMapper;
  14341. outputs.append(* new CGraphIterationInfo(resultInput->queryActivity(), resultInput, 0, 1));
  14342. for (createLoopCounter=1; createLoopCounter <= maxIterations; createLoopCounter++)
  14343. {
  14344. IRoxieServerChildGraph * graph = childGraph->createGraphLoopInstance(ctx, createLoopCounter, parentExtractSize, parentExtract, *this);
  14345. graph->beforeExecute();
  14346. iterationGraphs.append(*graph);
  14347. graph->gatherIterationUsage(*this);
  14348. CGraphIterationInfo *iteration = graph->selectGraphLoopOutput();
  14349. outputs.append(*iteration);
  14350. }
  14351. createLoopCounter = 0;
  14352. createSplitters(probeManager, probes);
  14353. ForEachItemIn(i2, iterationGraphs)
  14354. iterationGraphs.item(i2).associateIterationOutputs(*this);
  14355. resultInput = outputs.tos().connectOutput(probeManager, probes, this, 0);
  14356. resultStream = connectSingleStream(ctx, resultInput, 0, resultJunction, true);
  14357. }
  14358. void createSplitters(IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes)
  14359. {
  14360. ForEachItemIn(i, outputs)
  14361. {
  14362. CGraphIterationInfo & next = outputs.item(i);
  14363. next.createSplitter(ctx, probeManager, probes);
  14364. }
  14365. }
  14366. //IRoxieServerLoopResultProcessor
  14367. virtual void noteUseIteration(unsigned _whichIteration)
  14368. {
  14369. int whichIteration = (int) _whichIteration; // May go negative - API is unsigned for historical reasons
  14370. if (whichIteration >= 0)
  14371. {
  14372. if (!outputs.isItem(whichIteration))
  14373. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Error reading graph result %d from iteration %d", whichIteration, createLoopCounter);
  14374. outputs.item(whichIteration).noteUsed();
  14375. }
  14376. }
  14377. virtual IFinalRoxieInput* connectIterationOutput(unsigned whichIteration, IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes, IRoxieServerActivity *targetAct, unsigned targetIdx)
  14378. {
  14379. if (outputs.isItem(whichIteration))
  14380. {
  14381. CGraphIterationInfo & next = outputs.item(whichIteration);
  14382. return next.connectOutput(probeManager, probes, targetAct, targetIdx);
  14383. }
  14384. return NULL;
  14385. }
  14386. };
  14387. //=================================================================================
  14388. class CRoxieServerGraphLoopActivityFactory : public CRoxieServerActivityFactory
  14389. {
  14390. unsigned loopGraphId;
  14391. unsigned flags;
  14392. Linked<IOutputMetaData> counterMeta;
  14393. public:
  14394. CRoxieServerGraphLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _loopGraphId)
  14395. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), loopGraphId(_loopGraphId)
  14396. {
  14397. Owned<IHThorGraphLoopArg> helper = (IHThorGraphLoopArg *) helperFactory();
  14398. flags = helper->getFlags();
  14399. counterMeta.setown(new CCounterRowMetaData);
  14400. }
  14401. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  14402. {
  14403. if (kind == TAKparallelgraphloop)
  14404. return new CRoxieServerParallelGraphLoopActivity(_ctx, this, _probeManager, loopGraphId, counterMeta);
  14405. else
  14406. return new CRoxieServerSequentialGraphLoopActivity(_ctx, this, _probeManager, loopGraphId, counterMeta);
  14407. }
  14408. };
  14409. IRoxieServerActivityFactory *createRoxieServerGraphLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _loopGraphId)
  14410. {
  14411. return new CRoxieServerGraphLoopActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _loopGraphId);
  14412. }
  14413. //=====================================================================================================
  14414. class CRoxieServerLibraryCallActivity : public CRoxieServerActivity
  14415. {
  14416. class OutputAdaptor : public CExtractMapperInput
  14417. {
  14418. bool stopped;
  14419. public:
  14420. CRoxieServerLibraryCallActivity *parent;
  14421. IOutputMetaData * meta = nullptr;
  14422. unsigned oid;
  14423. unsigned processed;
  14424. public:
  14425. OutputAdaptor()
  14426. {
  14427. parent = NULL;
  14428. oid = 0;
  14429. init();
  14430. }
  14431. ~OutputAdaptor()
  14432. {
  14433. if (traceStartStop)
  14434. DBGLOG("%p ~OutputAdaptor %d", this, oid);
  14435. if (processed && parent && parent->factory)
  14436. {
  14437. parent->factory->noteProcessed(oid, processed);
  14438. if (parent->ctx)
  14439. parent->ctx->noteProcessed(parent->querySubgraphId(), parent->activityId, oid, processed, 0);
  14440. }
  14441. }
  14442. void setParent(CRoxieServerLibraryCallActivity * _parent, IOutputMetaData * _meta, unsigned _oid)
  14443. {
  14444. parent = _parent;
  14445. meta = _meta;
  14446. oid = _oid;
  14447. }
  14448. void init()
  14449. {
  14450. processed = 0;
  14451. stopped = false;
  14452. }
  14453. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14454. {
  14455. parent->start(oid, parentExtractSize, parentExtract, paused);
  14456. CExtractMapperInput::start(parentExtractSize, parentExtract, paused);
  14457. }
  14458. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  14459. {
  14460. //MORE value of consumerOrdered depends on whether this activity is marked as ordered.
  14461. if (!oid) // Only need to set up once
  14462. {
  14463. parent->connectInputStreams(true); // To handle dependencies etc
  14464. }
  14465. return CExtractMapperInput::getOutputStreams(ctx, 0, streams, nullptr, true, nullptr);
  14466. }
  14467. //This override should not really be needed, but input is set up too late for the call to connect strands
  14468. virtual IOutputMetaData * queryOutputMeta() const
  14469. {
  14470. return meta;
  14471. }
  14472. virtual void stop()
  14473. {
  14474. if (!stopped)
  14475. {
  14476. stopped = true;
  14477. parent->stop(oid); // parent code relies on stop being called exactly once per adaptor, so make sure it is!
  14478. CExtractMapperInput::stop();
  14479. }
  14480. };
  14481. virtual void reset()
  14482. {
  14483. parent->reset(oid);
  14484. CExtractMapperInput::reset();
  14485. init();
  14486. };
  14487. virtual void checkAbort()
  14488. {
  14489. parent->checkAbort();
  14490. }
  14491. };
  14492. IHThorLibraryCallArg &helper;
  14493. unsigned numInputs;
  14494. unsigned numOutputs;
  14495. unsigned numActiveOutputs;
  14496. bool started;
  14497. OutputAdaptor* outputAdaptors;
  14498. CExtractMapperInput * * inputAdaptors;
  14499. bool * inputUsed;
  14500. bool * outputUsed;
  14501. Owned<IException> error;
  14502. CriticalSection crit;
  14503. rtlRowBuilder libraryExtractBuilder;
  14504. Owned<IActivityGraph> libraryGraph;
  14505. const LibraryCallFactoryExtra & extra;
  14506. public:
  14507. CRoxieServerLibraryCallActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs, unsigned _numOutputs, const LibraryCallFactoryExtra & _extra)
  14508. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  14509. helper((IHThorLibraryCallArg &)basehelper), extra(_extra)
  14510. {
  14511. numInputs = _numInputs;
  14512. numOutputs = _numOutputs;
  14513. numActiveOutputs = numOutputs;
  14514. inputAdaptors = new CExtractMapperInput*[numInputs];
  14515. inputUsed = new bool[numInputs];
  14516. for (unsigned i1 = 0; i1 < numInputs; i1++)
  14517. {
  14518. inputAdaptors[i1] = new CExtractMapperInput;
  14519. inputUsed[i1] = false;
  14520. }
  14521. outputAdaptors = new OutputAdaptor[numOutputs];
  14522. outputUsed = new bool[numOutputs];
  14523. for (unsigned i2 = 0; i2 < numOutputs; i2++)
  14524. {
  14525. outputAdaptors[i2].setParent(this, helper.queryOutputMeta(i2), i2);
  14526. outputUsed[i2] = false;
  14527. }
  14528. started = false;
  14529. }
  14530. ~CRoxieServerLibraryCallActivity()
  14531. {
  14532. for (unsigned i1 = 0; i1 < numInputs; i1++)
  14533. ::Release(inputAdaptors[i1]);
  14534. delete [] inputAdaptors;
  14535. delete [] inputUsed;
  14536. delete [] outputAdaptors;
  14537. delete [] outputUsed;
  14538. }
  14539. virtual void onCreate(IHThorArg *_colocalParent)
  14540. {
  14541. CRoxieServerActivity::onCreate(_colocalParent);
  14542. libraryGraph.setown(ctx->getLibraryGraph(extra, this));
  14543. libraryGraph->onCreate(_colocalParent);
  14544. //Now map the inputs and outputs to the adapters
  14545. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  14546. for (unsigned i1=0; i1<numInputs; i1++)
  14547. inputUsed[i1] = graph->querySetInputResult(i1, 0, inputAdaptors[i1]);
  14548. for (unsigned i2=0; i2<numOutputs; i2++)
  14549. {
  14550. unsigned outputIndex = extra.outputs.item(i2);
  14551. Owned<IFinalRoxieInput> output = graph->selectOutput(numInputs+outputIndex);
  14552. outputAdaptors[i2].setInput(0, output); // MORE - no idea if this 0 is right??
  14553. outputAdaptors[i2].connectInputStreams(ctx, true);
  14554. }
  14555. }
  14556. virtual void start(unsigned oid, unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14557. {
  14558. CriticalBlock b(crit);
  14559. if (error)
  14560. throw error.getLink();
  14561. if (factory)
  14562. factory->noteStarted(oid);
  14563. if (!started)
  14564. {
  14565. // even though it is not complete, we don't want to run this again if it fails.
  14566. started = true;
  14567. //see notes on splitter above
  14568. try
  14569. {
  14570. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14571. }
  14572. catch (IException *E)
  14573. {
  14574. #ifdef TRACE_SPLIT
  14575. CTXLOG("spill %d caught exception in start", activityId);
  14576. #endif
  14577. error.set(E);
  14578. throw;
  14579. }
  14580. catch (...)
  14581. {
  14582. IException *E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught in CRoxieServerLibraryCallActivity::start");
  14583. error.set(E);
  14584. throw E;
  14585. }
  14586. //recreate the parent extract, and use it to reinitialize the graphs...
  14587. libraryExtractBuilder.clear();
  14588. helper.createParentExtract(libraryExtractBuilder);
  14589. // 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
  14590. // some inputs before we see start on others.
  14591. for (unsigned i1 = 0; i1 < numInputs; i1++)
  14592. {
  14593. if (inputUsed[i1])
  14594. inputAdaptors[i1]->setParentExtract(parentExtractSize, parentExtract);
  14595. else
  14596. inputAdaptors[i1]->queryInput()->stopall();
  14597. }
  14598. for (unsigned i2 = 0; i2 < numOutputs; i2++)
  14599. outputAdaptors[i2].setParentExtract(libraryExtractBuilder.size(), libraryExtractBuilder.getbytes());
  14600. //call stop on all the unused inputs.
  14601. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  14602. graph->beforeExecute();
  14603. ForEachItemIn(i3, extra.unusedOutputs)
  14604. {
  14605. Owned<IFinalRoxieInput> output = graph->selectOutput(numInputs+extra.unusedOutputs.item(i3));
  14606. output->stopall();
  14607. }
  14608. }
  14609. }
  14610. virtual void stop(unsigned oid)
  14611. {
  14612. CriticalBlock b(crit);
  14613. if (--numActiveOutputs == 0)
  14614. {
  14615. //call stop on all the unused inputs.
  14616. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  14617. graph->beforeExecute();
  14618. ForEachItemIn(i3, extra.unusedOutputs)
  14619. {
  14620. Owned<IFinalRoxieInput> output = graph->selectOutput(numInputs+extra.unusedOutputs.item(i3));
  14621. output->stopall();
  14622. }
  14623. CRoxieServerActivity::stop();
  14624. }
  14625. }
  14626. void reset(unsigned oid)
  14627. {
  14628. started = false;
  14629. error.clear();
  14630. numActiveOutputs = numOutputs;
  14631. if (state != STATEreset) // make sure input is only reset once
  14632. {
  14633. CRoxieServerActivity::reset();
  14634. libraryGraph->reset();
  14635. //Call reset on all unused inputs/outputs from the graph - no one else will.
  14636. for (unsigned i1 = 0; i1 < numInputs; i1++)
  14637. {
  14638. if (!inputUsed[i1])
  14639. inputAdaptors[i1]->reset();
  14640. }
  14641. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  14642. ForEachItemIn(i3, extra.unusedOutputs)
  14643. {
  14644. Owned<IFinalRoxieInput> output = graph->selectOutput(numInputs+extra.unusedOutputs.item(i3));
  14645. output->reset();
  14646. }
  14647. }
  14648. };
  14649. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  14650. {
  14651. inputAdaptors[idx]->setInput(_sourceIdx, _in);
  14652. }
  14653. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  14654. {
  14655. if (idx < numInputs && inputAdaptors[idx])
  14656. return inputAdaptors[idx]->queryInput();
  14657. else
  14658. return NULL;
  14659. }
  14660. public:
  14661. virtual const void *nextRow()
  14662. {
  14663. throwUnexpected(); // Internal logic error - we are not anybody's input
  14664. }
  14665. virtual IOutputMetaData * queryOutputMeta() const
  14666. {
  14667. throwUnexpected(); // should be called on outputs instead
  14668. }
  14669. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  14670. {
  14671. assertex(idx!=(unsigned)-1);
  14672. assertex(!outputUsed[idx]);
  14673. outputUsed[idx] = true;
  14674. return &outputAdaptors[idx];
  14675. }
  14676. virtual void updateFactoryStatistics() const override
  14677. {
  14678. if (libraryGraph)
  14679. libraryGraph->updateFactoryStatistics();
  14680. CRoxieServerActivity::updateFactoryStatistics();
  14681. }
  14682. };
  14683. void LibraryCallFactoryExtra::set(const LibraryCallFactoryExtra & _other)
  14684. {
  14685. ForEachItemIn(i1, _other.outputs)
  14686. outputs.append(_other.outputs.item(i1));
  14687. ForEachItemIn(i2, _other.unusedOutputs)
  14688. unusedOutputs.append(_other.unusedOutputs.item(i2));
  14689. maxOutputs = _other.maxOutputs;
  14690. graphid = _other.graphid;
  14691. libraryName.set(_other.libraryName);
  14692. embeddedGraphName.set(_other.embeddedGraphName);
  14693. interfaceHash = _other.interfaceHash;
  14694. embedded = _other.embedded;
  14695. }
  14696. void LibraryCallFactoryExtra::calcUnused()
  14697. {
  14698. for (unsigned i=0; i < maxOutputs; i++)
  14699. if (!outputs.contains(i))
  14700. unusedOutputs.append(i);
  14701. }
  14702. class CRoxieServerLibraryCallActivityFactory : public CRoxieServerMultiOutputFactory
  14703. {
  14704. private:
  14705. CRoxieServerMultiInputInfo inputs;
  14706. LibraryCallFactoryExtra extra;
  14707. public:
  14708. CRoxieServerLibraryCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, LibraryCallFactoryExtra & _extra)
  14709. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  14710. {
  14711. extra.set(_extra);
  14712. extra.calcUnused();
  14713. setNumOutputs(extra.outputs.ordinality());
  14714. }
  14715. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  14716. {
  14717. return new CRoxieServerLibraryCallActivity(_ctx, this, _probeManager, numInputs(), numOutputs, extra);
  14718. }
  14719. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  14720. {
  14721. inputs.set(idx, source, sourceidx);
  14722. }
  14723. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  14724. {
  14725. return inputs.get(idx, sourceidx);
  14726. }
  14727. virtual unsigned numInputs() const { return inputs.ordinality(); }
  14728. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  14729. {
  14730. addXrefLibraryInfo(reply, extra.libraryName);
  14731. }
  14732. };
  14733. IRoxieServerActivityFactory *createRoxieServerLibraryCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, LibraryCallFactoryExtra & _extra)
  14734. {
  14735. return new CRoxieServerLibraryCallActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _extra);
  14736. }
  14737. //=====================================================================================================
  14738. // CRoxieServerNWayInputActivity is a multi-input, multi-output activity, where the outputs are a subset of the inputs
  14739. // Used to implement RANGE(<rowset-expression>, [set-of-indices])
  14740. class CRoxieServerNWayInputBaseActivity : public CRoxieServerMultiInputBaseActivity
  14741. {
  14742. protected:
  14743. PointerArrayOf<IFinalRoxieInput> selectedInputs;
  14744. PointerArrayOf<IEngineRowStream> selectedStreams;
  14745. PointerArrayOf<IStrandJunction> selectedJunctions;
  14746. public:
  14747. CRoxieServerNWayInputBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14748. : CRoxieServerMultiInputBaseActivity(_ctx, _factory, _probeManager, _numInputs)
  14749. {
  14750. }
  14751. virtual unsigned __int64 queryLocalCycles() const
  14752. {
  14753. __int64 localCycles = totalCycles.totalCycles;
  14754. ForEachItemIn(i, selectedInputs)
  14755. {
  14756. localCycles -= selectedInputs.item(i)->queryTotalCycles();
  14757. }
  14758. if (localCycles < 0)
  14759. localCycles = 0;
  14760. return localCycles;
  14761. }
  14762. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  14763. {
  14764. if (selectedInputs.isItem(idx))
  14765. return selectedInputs.item(idx);
  14766. else
  14767. return NULL;
  14768. }
  14769. virtual void reset()
  14770. {
  14771. ForEachItemIn(i, selectedInputs)
  14772. selectedInputs.item(i)->reset();
  14773. selectedInputs.kill();
  14774. selectedStreams.kill();
  14775. selectedJunctions.kill();
  14776. CRoxieServerMultiInputBaseActivity::reset();
  14777. }
  14778. virtual const void * nextRow()
  14779. {
  14780. throwUnexpected();
  14781. }
  14782. virtual unsigned numConcreteOutputs() const
  14783. {
  14784. return selectedInputs.ordinality();
  14785. }
  14786. virtual IFinalRoxieInput * queryConcreteInput(unsigned idx)
  14787. {
  14788. return queryInput(idx);
  14789. }
  14790. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput)
  14791. {
  14792. if (selectedStreams.isItem(whichInput))
  14793. return selectedStreams.item(whichInput);
  14794. return NULL;
  14795. }
  14796. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const
  14797. {
  14798. if (selectedJunctions.isItem(idx))
  14799. return selectedJunctions.item(idx);
  14800. return NULL;
  14801. }
  14802. };
  14803. class CRoxieServerNWayInputActivity : public CRoxieServerNWayInputBaseActivity
  14804. {
  14805. IHThorNWayInputArg & helper;
  14806. public:
  14807. CRoxieServerNWayInputActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14808. : CRoxieServerNWayInputBaseActivity(_ctx, _factory, _probeManager, _numInputs), helper((IHThorNWayInputArg &)basehelper)
  14809. {
  14810. }
  14811. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14812. {
  14813. CRoxieServerNWayInputBaseActivity::start(parentExtractSize, parentExtract, paused);
  14814. bool selectionIsAll;
  14815. size32_t selectionLen;
  14816. rtlDataAttr selection;
  14817. helper.getInputSelection(selectionIsAll, selectionLen, selection.refdata());
  14818. selectedInputs.kill();
  14819. selectedStreams.kill();
  14820. selectedJunctions.kill();
  14821. assertex(numInputs==numStreams); // Will need refactoring when that ceases to be true
  14822. if (selectionIsAll)
  14823. {
  14824. for (unsigned i=0; i < numInputs; i++)
  14825. {
  14826. selectedInputs.append(inputArray[i]);
  14827. selectedStreams.append(streamArray[i]); // Assumes 1:1 relationship - is that good?
  14828. selectedJunctions.append(junctionArray[i]);
  14829. }
  14830. }
  14831. else
  14832. {
  14833. const size32_t * selections = (const size32_t *)selection.getdata();
  14834. unsigned max = selectionLen/sizeof(size32_t);
  14835. for (unsigned i = 0; i < max; i++)
  14836. {
  14837. unsigned nextIndex = selections[i];
  14838. //Check there are no duplicates..... Assumes there are a fairly small number of inputs, so n^2 search is ok.
  14839. for (unsigned j=i+1; j < max; j++)
  14840. {
  14841. if (nextIndex == selections[j])
  14842. throw MakeStringException(ROXIE_NWAY_INPUT_ERROR, "Selection list for nway input can not contain duplicates");
  14843. }
  14844. if (nextIndex > numInputs || nextIndex > numStreams)
  14845. throw MakeStringException(ROXIE_NWAY_INPUT_ERROR, "Index %d in RANGE selection list is out of range", nextIndex);
  14846. selectedInputs.append(inputArray[nextIndex-1]);
  14847. selectedStreams.append(streamArray[nextIndex-1]); // Assumes 1:1 relationship - is that good?
  14848. selectedJunctions.append(junctionArray[nextIndex-1]);
  14849. }
  14850. }
  14851. // NB: Whatever pulls this nwayinput activity, starts and stops the selectedInputs and selectedJunctions
  14852. // But the N-Way input itself is now done with processing, and can stop itself/dependencies.
  14853. stop();
  14854. }
  14855. };
  14856. class CRoxieServerNWayInputActivityFactory : public CRoxieServerMultiInputFactory
  14857. {
  14858. public:
  14859. CRoxieServerNWayInputActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  14860. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  14861. {
  14862. }
  14863. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  14864. {
  14865. return new CRoxieServerNWayInputActivity(_ctx, this, _probeManager, numInputs());
  14866. }
  14867. };
  14868. IRoxieServerActivityFactory *createRoxieServerNWayInputActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  14869. {
  14870. return new CRoxieServerNWayInputActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  14871. }
  14872. //=====================================================================================================
  14873. class CRoxieServerNWayGraphLoopResultReadActivity : public CRoxieServerNWayInputBaseActivity
  14874. {
  14875. IHThorNWayGraphLoopResultReadArg & helper;
  14876. IArrayOf<IRoxieServerActivity> resultReaders;
  14877. Owned<IStrandJunction> *resultJunctions;
  14878. unsigned graphId;
  14879. bool grouped;
  14880. bool selectionIsAll;
  14881. size32_t selectionLen;
  14882. rtlDataAttr selection;
  14883. public:
  14884. CRoxieServerNWayGraphLoopResultReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId)
  14885. : CRoxieServerNWayInputBaseActivity(_ctx, _factory, _probeManager, 0), helper((IHThorNWayGraphLoopResultReadArg &)basehelper)
  14886. {
  14887. grouped = helper.isGrouped();
  14888. graphId = _graphId;
  14889. selectionIsAll = false;
  14890. selectionLen = 0;
  14891. resultJunctions = NULL;
  14892. }
  14893. ~CRoxieServerNWayGraphLoopResultReadActivity()
  14894. {
  14895. delete [] resultJunctions;
  14896. }
  14897. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14898. {
  14899. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14900. if (selectedInputs.ordinality() == 0)
  14901. {
  14902. initInputSelection();
  14903. unsigned max = selectionLen / sizeof(size32_t);
  14904. const size32_t * selections = (const size32_t *)selection.getdata();
  14905. IProbeManager * probeManager = NULL; // MORE!!
  14906. for (unsigned i = 0; i < max; i++)
  14907. {
  14908. CRoxieServerActivity * resultInput = new CRoxieServerInternalGraphLoopResultReadActivity(ctx, factory, probeManager, graphId, selections[i]);
  14909. resultReaders.append(*resultInput);
  14910. selectedInputs.append(resultInput);
  14911. resultInput->onCreate(colocalParent);
  14912. resultInput->start(parentExtractSize, parentExtract, paused);
  14913. selectedStreams.append(connectSingleStream(ctx, resultInput, 0, resultJunctions[i], true));
  14914. selectedJunctions.append(resultJunctions[i]);
  14915. }
  14916. }
  14917. // I have done with my processing - note that this won't stop my inputs
  14918. stop();
  14919. }
  14920. virtual void reset()
  14921. {
  14922. resultReaders.kill();
  14923. CRoxieServerNWayInputBaseActivity::reset();
  14924. ForEachItemIn(i, selectedStreams)
  14925. resetJunction(resultJunctions[i]);
  14926. }
  14927. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract)
  14928. {
  14929. ensureCreated();
  14930. basehelper.onStart(parentExtract, NULL);
  14931. initInputSelection();
  14932. unsigned max = selectionLen / sizeof(size32_t);
  14933. const size32_t * selections = (const size32_t *)selection.getdata();
  14934. for (unsigned i = 0; i < max; i++)
  14935. processor.noteUseIteration(selections[i]);
  14936. }
  14937. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract, IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes)
  14938. {
  14939. //selection etc. already initialised from the gatherIterationUsage() call.
  14940. unsigned max = selectionLen / sizeof(size32_t);
  14941. const size32_t * selections = (const size32_t *)selection.getdata();
  14942. resultJunctions = new Owned<IStrandJunction> [max];
  14943. for (unsigned i = 0; i < max; i++)
  14944. {
  14945. IFinalRoxieInput *in = processor.connectIterationOutput(selections[i], probeManager, probes, this, i);
  14946. selectedInputs.append(in);
  14947. selectedStreams.append(connectSingleStream(ctx, in, 0, resultJunctions[i], true));
  14948. selectedJunctions.append(resultJunctions[i]);
  14949. }
  14950. }
  14951. protected:
  14952. void initInputSelection()
  14953. {
  14954. helper.getInputSelection(selectionIsAll, selectionLen, selection.refdata());
  14955. if (selectionIsAll)
  14956. throw MakeStringException(ROXIE_NWAY_INPUT_ERROR, "ALL not yet supported for NWay graph inputs");
  14957. }
  14958. };
  14959. class CRoxieServerNWayGraphLoopResultReadActivityFactory : public CRoxieServerActivityFactory
  14960. {
  14961. unsigned graphId;
  14962. public:
  14963. CRoxieServerNWayGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _graphId)
  14964. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), graphId(_graphId)
  14965. {
  14966. }
  14967. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  14968. {
  14969. return new CRoxieServerNWayGraphLoopResultReadActivity(_ctx, this, _probeManager, graphId);
  14970. }
  14971. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  14972. {
  14973. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for NWay GraphLoopResultRead activity");
  14974. }
  14975. };
  14976. IRoxieServerActivityFactory *createRoxieServerNWayGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned graphId)
  14977. {
  14978. return new CRoxieServerNWayGraphLoopResultReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, graphId);
  14979. }
  14980. //=================================================================================
  14981. class RoxieSteppedInput : implements ISteppedInput, public CInterface
  14982. {
  14983. public:
  14984. RoxieSteppedInput(IFinalRoxieInput * _input, IEngineRowStream *_stream) { input = _input; inputStream = _stream; }
  14985. IMPLEMENT_IINTERFACE
  14986. protected:
  14987. virtual const void * nextInputRow()
  14988. {
  14989. #ifdef TRACE_SEEK_REQUESTS
  14990. IRoxieContextLogger * logger = input->queryActivity();
  14991. const void * ret = doNextInputRow();
  14992. {
  14993. CommonXmlWriter xmlwrite(XWFtrim|XWFopt|XWFnoindent);
  14994. if (!ret)
  14995. xmlwrite.outputBool(true,"eof");
  14996. else if (input->queryOutputMeta()->hasXML())
  14997. input->queryOutputMeta()->toXML((byte *) ret, xmlwrite);
  14998. logger->CTXLOG("next() returns (%s)", xmlwrite.str());
  14999. }
  15000. return ret;
  15001. #else
  15002. return inputStream->ungroupedNextRow();
  15003. #endif
  15004. }
  15005. virtual const void * nextInputRowGE(const void * seek, unsigned numFields, bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  15006. {
  15007. #ifdef TRACE_SEEK_REQUESTS
  15008. IRoxieContextLogger * logger = input->queryActivity();
  15009. {
  15010. CommonXmlWriter xmlwrite(XWFtrim|XWFopt|XWFnoindent);
  15011. if (input->queryOutputMeta()->hasXML())
  15012. input->queryOutputMeta()->toXML((byte *) seek, xmlwrite);
  15013. logger->CTXLOG("nextInputRowGE(%d, %s%s%s, %s) seek(%s)",
  15014. numFields,
  15015. stepExtra.readAheadManyResults() ? "readahead " : "",
  15016. stepExtra.returnMismatches() ? "mismatch" : "exact",
  15017. stepExtra.onlyReturnFirstSeekMatch() ? " single-match" : "",
  15018. stepExtra.queryExtraSeeks() ? "multi-seek":"",
  15019. xmlwrite.str());
  15020. }
  15021. const void * ret = doNextInputRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  15022. {
  15023. CommonXmlWriter xmlwrite(XWFtrim|XWFopt|XWFnoindent);
  15024. if (!ret)
  15025. xmlwrite.outputBool(true,"eof");
  15026. else if (input->queryOutputMeta()->hasXML())
  15027. input->queryOutputMeta()->toXML((byte *) ret, xmlwrite);
  15028. logger->CTXLOG("nextInputRowGE(%d, %s%s%s, %s) result(%s)",
  15029. numFields,
  15030. stepExtra.readAheadManyResults() ? "readahead " : "",
  15031. stepExtra.returnMismatches() ? "mismatch" : "exact",
  15032. stepExtra.onlyReturnFirstSeekMatch() ? " single-match" : "",
  15033. stepExtra.queryExtraSeeks() ? "multi-seek":"",
  15034. xmlwrite.str());
  15035. }
  15036. return ret;
  15037. #else
  15038. return doNextInputRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  15039. #endif
  15040. }
  15041. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  15042. {
  15043. return input->gatherConjunctions(collector);
  15044. }
  15045. virtual void resetEOF()
  15046. {
  15047. inputStream->resetEOF();
  15048. }
  15049. virtual IInputSteppingMeta * queryInputSteppingMeta()
  15050. {
  15051. return input->querySteppingMeta();
  15052. }
  15053. inline const void * doNextInputRowGE(const void * seek, unsigned numFields, bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  15054. {
  15055. assertex(wasCompleteMatch);
  15056. return inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  15057. }
  15058. protected:
  15059. IFinalRoxieInput * input;
  15060. IEngineRowStream * inputStream;
  15061. };
  15062. //=================================================================================
  15063. class CRoxieServerNWayBaseActivity : public CRoxieServerMultiInputBaseActivity
  15064. {
  15065. public:
  15066. CRoxieServerNWayBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  15067. : CRoxieServerMultiInputBaseActivity(_ctx, _factory, _probeManager, _numInputs)
  15068. {
  15069. }
  15070. void startExpandedInputs(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15071. {
  15072. ForEachItemIn(ei, expandedInputs)
  15073. expandedInputs.item(ei)->start(parentExtractSize, parentExtract, paused);
  15074. ForEachItemIn(idx, expandedInputs)
  15075. startJunction(expandedJunctions.item(idx));
  15076. }
  15077. virtual void stop()
  15078. {
  15079. ForEachItemIn(i, expandedStreams)
  15080. expandedStreams.item(i)->stop();
  15081. CRoxieServerMultiInputBaseActivity::stop();
  15082. }
  15083. virtual void reset()
  15084. {
  15085. ForEachItemIn(idx, expandedInputs)
  15086. resetJunction(expandedJunctions.item(idx));
  15087. expandedInputs.kill();
  15088. expandedStreams.kill();
  15089. expandedJunctions.kill();
  15090. CRoxieServerMultiInputBaseActivity::reset();
  15091. }
  15092. protected:
  15093. PointerArrayOf<IFinalRoxieInput> expandedInputs;
  15094. PointerArrayOf<IEngineRowStream> expandedStreams;
  15095. PointerArrayOf<IStrandJunction> expandedJunctions;
  15096. };
  15097. //=================================================================================
  15098. class CRoxieServerNaryActivity : public CRoxieServerNWayBaseActivity
  15099. {
  15100. public:
  15101. CRoxieServerNaryActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  15102. : CRoxieServerNWayBaseActivity(_ctx, _factory, _probeManager, _numInputs)
  15103. {
  15104. }
  15105. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15106. {
  15107. CRoxieServerNWayBaseActivity::start(parentExtractSize, parentExtract, paused);
  15108. for (unsigned i=0; i < numInputs; i++)
  15109. {
  15110. IFinalRoxieInput * cur = inputArray[i];
  15111. CRoxieServerNWayInputBaseActivity *nWayInput = dynamic_cast<CRoxieServerNWayInputBaseActivity *>(cur);
  15112. if (nWayInput)
  15113. {
  15114. nWayInput->start(parentExtractSize, parentExtract, paused);
  15115. unsigned numRealInputs = cur->numConcreteOutputs();
  15116. for (unsigned j = 0; j < numRealInputs; j++)
  15117. {
  15118. expandedInputs.append(cur->queryConcreteInput(j));
  15119. expandedStreams.append(cur->queryConcreteOutputStream(j));
  15120. expandedJunctions.append(cur->queryConcreteOutputJunction(j));
  15121. }
  15122. }
  15123. else
  15124. {
  15125. expandedInputs.append(cur);
  15126. // NB: this activities input streams + junction have been setup and held in CRoxieServerMultiInputActivity base
  15127. expandedStreams.append(queryConcreteOutputStream(i));
  15128. expandedJunctions.append(queryConcreteOutputJunction(i));
  15129. }
  15130. }
  15131. startExpandedInputs(parentExtractSize, parentExtract, paused);
  15132. }
  15133. };
  15134. //=================================================================================
  15135. class CRoxieStreamMerger : public CStreamMerger
  15136. {
  15137. public:
  15138. CRoxieStreamMerger() : CStreamMerger(true)
  15139. {
  15140. streamArray = NULL;
  15141. }
  15142. void initInputs(unsigned _numInputs, IEngineRowStream ** _streamArray)
  15143. {
  15144. CStreamMerger::initInputs(_numInputs);
  15145. streamArray = _streamArray;
  15146. }
  15147. virtual bool pullInput(unsigned i, const void * seek, unsigned numFields, const SmartStepExtra * stepExtra)
  15148. {
  15149. const void * next;
  15150. bool matches = true;
  15151. if (seek)
  15152. next = streamArray[i]->nextRowGE(seek, numFields, matches, *stepExtra);
  15153. else
  15154. next = streamArray[i]->ungroupedNextRow();
  15155. pending[i] = next;
  15156. pendingMatches[i] = matches;
  15157. return (next != NULL);
  15158. }
  15159. virtual void releaseRow(const void * row)
  15160. {
  15161. ReleaseRoxieRow(row);
  15162. }
  15163. protected:
  15164. IEngineRowStream **streamArray;
  15165. };
  15166. class CRoxieServerNWayMergeActivity : public CRoxieServerNaryActivity
  15167. {
  15168. public:
  15169. CRoxieServerNWayMergeActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  15170. : CRoxieServerNaryActivity(_ctx, _factory, _probeManager, _numInputs),
  15171. helper((IHThorNWayMergeArg &)basehelper)
  15172. {
  15173. initializedMeta = false;
  15174. }
  15175. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15176. {
  15177. CRoxieServerNaryActivity::start(parentExtractSize, parentExtract, paused);
  15178. merger.init(helper.queryCompare(), helper.dedup(), helper.querySteppingMeta()->queryCompare());
  15179. merger.initInputs(expandedStreams.length(), expandedStreams.getArray());
  15180. }
  15181. virtual void stop()
  15182. {
  15183. merger.done();
  15184. CRoxieServerNaryActivity::stop();
  15185. }
  15186. virtual void reset()
  15187. {
  15188. merger.cleanup();
  15189. CRoxieServerNaryActivity::reset();
  15190. initializedMeta = false;
  15191. }
  15192. virtual const void * nextRow()
  15193. {
  15194. ActivityTimer t(totalCycles, timeActivities);
  15195. const void * next = merger.nextRow();
  15196. if (next)
  15197. processed++;
  15198. return next;
  15199. }
  15200. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  15201. {
  15202. ActivityTimer t(totalCycles, timeActivities);
  15203. const void * next = merger.nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  15204. if (next)
  15205. processed++;
  15206. return next;
  15207. }
  15208. virtual IInputSteppingMeta * querySteppingMeta()
  15209. {
  15210. if (expandedStreams.ordinality() == 0)
  15211. return NULL;
  15212. if (!initializedMeta)
  15213. {
  15214. meta.init(helper.querySteppingMeta(), false);
  15215. ForEachItemIn(i, expandedStreams)
  15216. {
  15217. if (meta.getNumFields() == 0)
  15218. break;
  15219. IInputSteppingMeta * inputMeta = expandedInputs.item(i)->querySteppingMeta();
  15220. meta.intersect(inputMeta);
  15221. }
  15222. initializedMeta = true;
  15223. }
  15224. if (meta.getNumFields() == 0)
  15225. return NULL;
  15226. return &meta;
  15227. }
  15228. protected:
  15229. IHThorNWayMergeArg &helper;
  15230. CRoxieStreamMerger merger;
  15231. CSteppingMeta meta;
  15232. bool initializedMeta;
  15233. };
  15234. class CRoxieServerNWayMergeActivityFactory : public CRoxieServerMultiInputFactory
  15235. {
  15236. public:
  15237. CRoxieServerNWayMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15238. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15239. {
  15240. }
  15241. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15242. {
  15243. return new CRoxieServerNWayMergeActivity(_ctx, this, _probeManager, numInputs());
  15244. }
  15245. };
  15246. IRoxieServerActivityFactory *createRoxieServerNWayMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15247. {
  15248. return new CRoxieServerNWayMergeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15249. }
  15250. //=================================================================================
  15251. class CRoxieServerNWayMergeJoinActivity : public CRoxieServerNaryActivity
  15252. {
  15253. public:
  15254. CRoxieServerNWayMergeJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs, CMergeJoinProcessor & _processor)
  15255. : CRoxieServerNaryActivity(_ctx, _factory, _probeManager, _numInputs),processor(_processor),
  15256. helper((IHThorNWayMergeJoinArg &)basehelper)
  15257. {
  15258. }
  15259. virtual void onCreate(IHThorArg *_colocalParent)
  15260. {
  15261. CRoxieServerNaryActivity::onCreate(_colocalParent);
  15262. ICodeContext * codectx = ctx->queryCodeContext();
  15263. inputAllocator.setown(createRowAllocator(helper.queryInputMeta()));
  15264. outputAllocator.setown(createRowAllocator(helper.queryOutputMeta()));
  15265. }
  15266. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15267. {
  15268. CRoxieServerNaryActivity::start(parentExtractSize, parentExtract, paused);
  15269. ForEachItemIn(i1, expandedInputs)
  15270. {
  15271. Owned<RoxieSteppedInput> stepInput = new RoxieSteppedInput(expandedInputs.item(i1), expandedStreams.item(i1));
  15272. processor.addInput(stepInput);
  15273. }
  15274. processor.beforeProcessing(inputAllocator, outputAllocator);
  15275. }
  15276. virtual void stop()
  15277. {
  15278. processor.afterProcessing();
  15279. CRoxieServerNaryActivity::stop();
  15280. }
  15281. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  15282. {
  15283. return processor.gatherConjunctions(collector);
  15284. }
  15285. virtual void resetEOF()
  15286. {
  15287. processor.queryResetEOF();
  15288. }
  15289. virtual const void * nextRow()
  15290. {
  15291. ActivityTimer t(totalCycles, timeActivities);
  15292. const void * next = processor.nextRow();
  15293. if (next)
  15294. processed++;
  15295. return next;
  15296. }
  15297. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  15298. {
  15299. ActivityTimer t(totalCycles, timeActivities);
  15300. const void * next = processor.nextGE(seek, numFields, wasCompleteMatch, stepExtra);
  15301. if (next)
  15302. processed++;
  15303. return next;
  15304. }
  15305. virtual IInputSteppingMeta * querySteppingMeta()
  15306. {
  15307. return processor.queryInputSteppingMeta();
  15308. }
  15309. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  15310. {
  15311. CRoxieServerNaryActivity::gatherStats(merged);
  15312. if (inputAllocator)
  15313. inputAllocator->gatherStats(merged);
  15314. if (outputAllocator)
  15315. outputAllocator->gatherStats(merged);
  15316. }
  15317. protected:
  15318. IHThorNWayMergeJoinArg & helper;
  15319. CMergeJoinProcessor & processor;
  15320. Owned<IEngineRowAllocator> inputAllocator;
  15321. Owned<IEngineRowAllocator> outputAllocator;
  15322. };
  15323. class CRoxieServerAndMergeJoinActivity : public CRoxieServerNWayMergeJoinActivity
  15324. {
  15325. public:
  15326. CRoxieServerAndMergeJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  15327. : CRoxieServerNWayMergeJoinActivity(_ctx, _factory, _probeManager, _numInputs, andProcessor), andProcessor(helper)
  15328. {
  15329. }
  15330. protected:
  15331. CAndMergeJoinProcessor andProcessor;
  15332. };
  15333. class CRoxieServerAndLeftMergeJoinActivity : public CRoxieServerNWayMergeJoinActivity
  15334. {
  15335. public:
  15336. CRoxieServerAndLeftMergeJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  15337. : CRoxieServerNWayMergeJoinActivity(_ctx, _factory, _probeManager, _numInputs, andLeftProcessor), andLeftProcessor(helper)
  15338. {
  15339. }
  15340. protected:
  15341. CAndLeftMergeJoinProcessor andLeftProcessor;
  15342. };
  15343. class CRoxieServerMofNMergeJoinActivity : public CRoxieServerNWayMergeJoinActivity
  15344. {
  15345. public:
  15346. CRoxieServerMofNMergeJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  15347. : CRoxieServerNWayMergeJoinActivity(_ctx, _factory, _probeManager, _numInputs, mofnProcessor), mofnProcessor(helper)
  15348. {
  15349. }
  15350. protected:
  15351. CMofNMergeJoinProcessor mofnProcessor;
  15352. };
  15353. class CRoxieServerProximityJoinActivity : public CRoxieServerNWayMergeJoinActivity
  15354. {
  15355. public:
  15356. CRoxieServerProximityJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  15357. : CRoxieServerNWayMergeJoinActivity(_ctx, _factory, _probeManager, _numInputs, proximityProcessor), proximityProcessor(helper)
  15358. {
  15359. }
  15360. protected:
  15361. CProximityJoinProcessor proximityProcessor;
  15362. };
  15363. class CRoxieServerNWayMergeJoinActivityFactory : public CRoxieServerMultiInputFactory
  15364. {
  15365. unsigned flags;
  15366. public:
  15367. CRoxieServerNWayMergeJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15368. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15369. {
  15370. Owned<IHThorNWayMergeJoinArg> helper = (IHThorNWayMergeJoinArg *) helperFactory();
  15371. flags = helper->getJoinFlags();
  15372. }
  15373. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15374. {
  15375. if (flags & IHThorNWayMergeJoinArg::MJFhasrange)
  15376. return new CRoxieServerProximityJoinActivity(_ctx, this, _probeManager, numInputs());
  15377. switch (flags & IHThorNWayMergeJoinArg::MJFkindmask)
  15378. {
  15379. case IHThorNWayMergeJoinArg::MJFinner:
  15380. return new CRoxieServerAndMergeJoinActivity(_ctx, this, _probeManager, numInputs());
  15381. case IHThorNWayMergeJoinArg::MJFleftonly:
  15382. case IHThorNWayMergeJoinArg::MJFleftouter:
  15383. return new CRoxieServerAndLeftMergeJoinActivity(_ctx, this, _probeManager, numInputs());
  15384. case IHThorNWayMergeJoinArg::MJFmofn:
  15385. return new CRoxieServerMofNMergeJoinActivity(_ctx, this, _probeManager, numInputs());
  15386. default:
  15387. throwUnexpected();
  15388. }
  15389. }
  15390. };
  15391. IRoxieServerActivityFactory *createRoxieServerNWayMergeJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15392. {
  15393. return new CRoxieServerNWayMergeJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15394. }
  15395. //=================================================================================
  15396. class CRoxieServerNWaySelectActivity : public CRoxieServerNWayBaseActivity
  15397. {
  15398. IHThorNWaySelectArg &helper;
  15399. public:
  15400. CRoxieServerNWaySelectActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  15401. : CRoxieServerNWayBaseActivity(_ctx, _factory, _probeManager, _numInputs),
  15402. helper((IHThorNWaySelectArg &)basehelper)
  15403. {
  15404. }
  15405. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15406. {
  15407. CRoxieServerNWayBaseActivity::start(parentExtractSize, parentExtract, paused);
  15408. unsigned whichInput = helper.getInputIndex();
  15409. selectedInput = nullptr;
  15410. selectedStream = nullptr;
  15411. if (whichInput--)
  15412. {
  15413. for (unsigned i=0; i < numInputs; i++)
  15414. {
  15415. IFinalRoxieInput * cur = inputArray[i];
  15416. CRoxieServerNWayInputBaseActivity *nWayInput = dynamic_cast<CRoxieServerNWayInputBaseActivity *>(cur);
  15417. if (nWayInput)
  15418. {
  15419. nWayInput->start(parentExtractSize, parentExtract, paused);
  15420. unsigned numRealInputs = cur->numConcreteOutputs();
  15421. if (whichInput < numRealInputs)
  15422. {
  15423. expandedInputs.append(cur->queryConcreteInput(whichInput));
  15424. expandedStreams.append(cur->queryConcreteOutputStream(whichInput));
  15425. expandedJunctions.append(cur->queryConcreteOutputJunction(whichInput));
  15426. break;
  15427. }
  15428. whichInput -= numRealInputs;
  15429. }
  15430. else
  15431. {
  15432. if (whichInput == 0)
  15433. {
  15434. expandedInputs.append(cur);
  15435. // NB: this activities input streams + junction have been setup and held in CRoxieServerMultiInputActivity base
  15436. expandedStreams.append(queryConcreteOutputStream(i));
  15437. expandedJunctions.append(queryConcreteOutputJunction(i));
  15438. break;
  15439. }
  15440. whichInput -= 1;
  15441. }
  15442. }
  15443. }
  15444. if (expandedInputs.ordinality())
  15445. {
  15446. startExpandedInputs(parentExtractSize, parentExtract, paused);
  15447. selectedInput = expandedInputs.item(0);
  15448. selectedStream = expandedStreams.item(0);
  15449. }
  15450. }
  15451. const void * nextRow()
  15452. {
  15453. ActivityTimer t(totalCycles, timeActivities);
  15454. if (!selectedStream)
  15455. return NULL;
  15456. return selectedStream->nextRow();
  15457. }
  15458. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  15459. {
  15460. if (!selectedInput)
  15461. return false;
  15462. return selectedInput->gatherConjunctions(collector);
  15463. }
  15464. virtual void resetEOF()
  15465. {
  15466. if (selectedStream)
  15467. selectedStream->resetEOF();
  15468. }
  15469. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  15470. {
  15471. ActivityTimer t(totalCycles, timeActivities);
  15472. if (!selectedStream)
  15473. return NULL;
  15474. return selectedStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  15475. }
  15476. IInputSteppingMeta * querySteppingMeta()
  15477. {
  15478. if (selectedInput)
  15479. return selectedInput->querySteppingMeta();
  15480. return NULL;
  15481. }
  15482. protected:
  15483. IFinalRoxieInput * selectedInput = nullptr;
  15484. IEngineRowStream * selectedStream = nullptr;
  15485. Owned<IStrandJunction> selectedJunction;
  15486. };
  15487. class CRoxieServerNWaySelectActivityFactory : public CRoxieServerMultiInputFactory
  15488. {
  15489. public:
  15490. CRoxieServerNWaySelectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15491. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15492. {
  15493. }
  15494. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15495. {
  15496. return new CRoxieServerNWaySelectActivity(_ctx, this, _probeManager, numInputs());
  15497. }
  15498. };
  15499. IRoxieServerActivityFactory *createRoxieServerNWaySelectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15500. {
  15501. return new CRoxieServerNWaySelectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15502. }
  15503. //=================================================================================
  15504. class CRoxieServerRemoteActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler
  15505. {
  15506. protected:
  15507. IHThorRemoteArg &helper;
  15508. CRemoteResultAdaptor remote;
  15509. public:
  15510. CRoxieServerRemoteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteID)
  15511. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  15512. helper((IHThorRemoteArg &)basehelper),
  15513. remote(_ctx, this, _remoteID, meta.queryOriginal(), helper, *this, false, false) // MORE - if they need it stable we'll have to think!
  15514. {
  15515. }
  15516. virtual const IResolvedFile *queryVarFileInfo() const
  15517. {
  15518. return NULL;
  15519. }
  15520. virtual void onCreate(IHThorArg *_colocalParent)
  15521. {
  15522. CRoxieServerActivity::onCreate(_colocalParent);
  15523. remote.onCreate(_colocalParent);
  15524. }
  15525. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15526. {
  15527. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  15528. remote.onStart(parentExtractSize, parentExtract);
  15529. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  15530. unsigned fileNo = 0; // MORE - superfiles require us to do this per file part... maybe (needs thought)
  15531. remote.getMem(0, fileNo, 0); // the cached context is all we need to send
  15532. remote.flush();
  15533. remote.senddone();
  15534. }
  15535. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  15536. {
  15537. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  15538. }
  15539. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  15540. {
  15541. if (idx==(unsigned)-1)
  15542. idx = 0;
  15543. return idx ? NULL: &remote;
  15544. }
  15545. virtual void reset()
  15546. {
  15547. processed = remote.processed;
  15548. remote.processed = 0;
  15549. CRoxieServerActivity::reset();
  15550. }
  15551. virtual void onLimitExceeded(bool isKeyed)
  15552. {
  15553. if (traceLevel > 4)
  15554. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  15555. helper.onLimitExceeded();
  15556. }
  15557. virtual const void *createLimitFailRow(bool isKeyed)
  15558. {
  15559. UNIMPLEMENTED; // MORE - is there an ONFAIL for a limit folded into a remote?
  15560. }
  15561. virtual const void *nextRow()
  15562. {
  15563. throwUnexpected(); // I am nobody's input
  15564. }
  15565. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  15566. {
  15567. CRoxieServerActivity::gatherStats(merged);
  15568. remote.gatherStats(merged);
  15569. }
  15570. };
  15571. class CRoxieServerRemoteActivityFactory : public CRoxieServerActivityFactory
  15572. {
  15573. public:
  15574. RemoteActivityId remoteId;
  15575. bool isRoot;
  15576. CRoxieServerRemoteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId, bool _isRoot)
  15577. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), remoteId(_remoteId), isRoot(_isRoot)
  15578. {
  15579. }
  15580. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15581. {
  15582. return new CRoxieServerRemoteActivity(_ctx, this, _probeManager, remoteId);
  15583. }
  15584. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  15585. {
  15586. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  15587. }
  15588. virtual bool isSink() const
  15589. {
  15590. //I don't think the action version of this is implemented - but this would be the code
  15591. return isRoot && !meta.queryOriginal();
  15592. }
  15593. virtual const StatisticsMapping &queryStatsMapping() const
  15594. {
  15595. return allStatistics; // Child queries...
  15596. }
  15597. };
  15598. IRoxieServerActivityFactory *createRoxieServerRemoteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId, bool _isRoot)
  15599. {
  15600. return new CRoxieServerRemoteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId, _isRoot);
  15601. }
  15602. //=================================================================================
  15603. class CRoxieServerIterateActivity : public CRoxieServerActivity
  15604. {
  15605. IHThorIterateArg &helper;
  15606. OwnedConstRoxieRow defaultRecord;
  15607. OwnedConstRoxieRow left;
  15608. OwnedConstRoxieRow right;
  15609. unsigned counter;
  15610. public:
  15611. CRoxieServerIterateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  15612. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  15613. helper((IHThorIterateArg &)basehelper)
  15614. {
  15615. counter = 0;
  15616. }
  15617. virtual bool needsAllocator() const { return true; }
  15618. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15619. {
  15620. counter = 0;
  15621. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  15622. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15623. size32_t thisSize = helper.createDefault(rowBuilder);
  15624. defaultRecord.setown(rowBuilder.finalizeRowClear(thisSize));
  15625. }
  15626. virtual void reset()
  15627. {
  15628. defaultRecord.clear();
  15629. right.clear();
  15630. left.clear();
  15631. CRoxieServerActivity::reset();
  15632. }
  15633. virtual const void * nextRow()
  15634. {
  15635. ActivityTimer t(totalCycles, timeActivities);
  15636. for (;;)
  15637. {
  15638. right.setown(inputStream->nextRow());
  15639. if (!right)
  15640. {
  15641. bool skippedGroup = (left == NULL) && (counter > 0); //we have just skipped entire group, but shouldn't output a double null
  15642. left.clear();
  15643. counter = 0;
  15644. if (skippedGroup) continue;
  15645. return NULL;
  15646. }
  15647. try
  15648. {
  15649. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15650. unsigned outSize = helper.transform(rowBuilder, left ? left : defaultRecord, right, ++counter);
  15651. if (outSize)
  15652. {
  15653. left.setown(rowBuilder.finalizeRowClear(outSize));
  15654. processed++;
  15655. return left.getLink();
  15656. }
  15657. }
  15658. catch (IException *E)
  15659. {
  15660. throw makeWrappedException(E);
  15661. }
  15662. }
  15663. }
  15664. };
  15665. class CRoxieServerIterateActivityFactory : public CRoxieServerActivityFactory
  15666. {
  15667. public:
  15668. CRoxieServerIterateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15669. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15670. {
  15671. }
  15672. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15673. {
  15674. return new CRoxieServerIterateActivity(_ctx, this, _probeManager);
  15675. }
  15676. };
  15677. IRoxieServerActivityFactory *createRoxieServerIterateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15678. {
  15679. return new CRoxieServerIterateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15680. }
  15681. //=================================================================================
  15682. class CRoxieServerProcessActivity : public CRoxieServerActivity
  15683. {
  15684. IHThorProcessArg &helper;
  15685. OwnedConstRoxieRow curRight;
  15686. OwnedConstRoxieRow initialRight;
  15687. unsigned counter;
  15688. Owned<IEngineRowAllocator> rightRowAllocator;
  15689. public:
  15690. CRoxieServerProcessActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  15691. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorProcessArg &)basehelper)
  15692. {
  15693. counter = 0;
  15694. }
  15695. virtual bool needsAllocator() const { return true; }
  15696. virtual void onCreate(IHThorArg *_colocalParent)
  15697. {
  15698. CRoxieServerActivity::onCreate(_colocalParent);
  15699. rightRowAllocator.setown(createRowAllocator(helper.queryRightRecordSize()));
  15700. }
  15701. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15702. {
  15703. counter = 0;
  15704. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  15705. RtlDynamicRowBuilder rowBuilder(rightRowAllocator);
  15706. size32_t thisSize = helper.createInitialRight(rowBuilder);
  15707. initialRight.setown(rowBuilder.finalizeRowClear(thisSize));
  15708. curRight.set(initialRight);
  15709. }
  15710. virtual const void * nextRow()
  15711. {
  15712. ActivityTimer t(totalCycles, timeActivities);
  15713. try
  15714. {
  15715. for (;;)
  15716. {
  15717. const void * in = inputStream->nextRow();
  15718. if (!in)
  15719. {
  15720. bool eog = (curRight != initialRight); // processed any records?
  15721. counter = 0;
  15722. curRight.set(initialRight);
  15723. if (eog)
  15724. return NULL;
  15725. in = inputStream->nextRow();
  15726. if (!in)
  15727. return NULL;
  15728. }
  15729. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15730. RtlDynamicRowBuilder rightRowBuilder(rightRowAllocator);
  15731. size32_t outSize = helper.transform(rowBuilder, rightRowBuilder, in, curRight, ++counter);
  15732. ReleaseRoxieRow(in);
  15733. if (outSize)
  15734. {
  15735. //MORE: This should be returned...
  15736. size32_t rightSize = rightRowAllocator->queryOutputMeta()->getRecordSize(rightRowBuilder.getSelf());
  15737. curRight.setown(rightRowBuilder.finalizeRowClear(rightSize));
  15738. processed++;
  15739. return rowBuilder.finalizeRowClear(outSize);
  15740. }
  15741. }
  15742. }
  15743. catch (IException *E)
  15744. {
  15745. throw makeWrappedException(E);
  15746. }
  15747. }
  15748. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  15749. {
  15750. CRoxieServerActivity::gatherStats(merged);
  15751. if (rightRowAllocator)
  15752. rightRowAllocator->gatherStats(merged);
  15753. }
  15754. };
  15755. class CRoxieServerProcessActivityFactory : public CRoxieServerActivityFactory
  15756. {
  15757. public:
  15758. CRoxieServerProcessActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15759. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15760. {
  15761. }
  15762. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15763. {
  15764. return new CRoxieServerProcessActivity(_ctx, this, _probeManager);
  15765. }
  15766. };
  15767. IRoxieServerActivityFactory *createRoxieServerProcessActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15768. {
  15769. return new CRoxieServerProcessActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15770. }
  15771. //=================================================================================
  15772. class CRoxieServerGroupActivity : public CRoxieServerActivity
  15773. {
  15774. IHThorGroupArg &helper;
  15775. bool endPending;
  15776. bool eof;
  15777. bool first;
  15778. unsigned numGroups;
  15779. unsigned numGroupMax;
  15780. unsigned numProcessedLastGroup;
  15781. const void *next;
  15782. public:
  15783. CRoxieServerGroupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  15784. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorGroupArg &)basehelper)
  15785. {
  15786. next = NULL;
  15787. endPending = false;
  15788. eof = false;
  15789. first = true;
  15790. numGroups = 0;
  15791. numGroupMax = 0;
  15792. numProcessedLastGroup = 0;
  15793. }
  15794. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15795. {
  15796. endPending = false;
  15797. eof = false;
  15798. first = true;
  15799. numGroups = 0;
  15800. numGroupMax = 0;
  15801. numProcessedLastGroup = processed;
  15802. assertex(next == NULL);
  15803. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  15804. }
  15805. virtual void reset()
  15806. {
  15807. noteStatistic(StNumGroups, numGroups);
  15808. noteStatistic(StNumGroupMax, numGroupMax);
  15809. ReleaseClearRoxieRow(next);
  15810. CRoxieServerActivity::reset();
  15811. }
  15812. virtual const void * nextRow()
  15813. {
  15814. ActivityTimer t(totalCycles, timeActivities);
  15815. if (first)
  15816. {
  15817. next = inputStream->nextRow();
  15818. first = false;
  15819. }
  15820. if (eof || endPending)
  15821. {
  15822. endPending = false;
  15823. return NULL;
  15824. }
  15825. const void * prev = next;
  15826. next = inputStream->ungroupedNextRow();
  15827. if (next)
  15828. {
  15829. assertex(prev);
  15830. if (!helper.isSameGroup(prev, next))
  15831. {
  15832. noteEndOfGroup();
  15833. endPending = true;
  15834. }
  15835. }
  15836. else
  15837. {
  15838. noteEndOfGroup();
  15839. eof = true;
  15840. }
  15841. if (prev)
  15842. processed++;
  15843. return prev;
  15844. }
  15845. inline void noteEndOfGroup()
  15846. {
  15847. unsigned numThisGroup = processed - numProcessedLastGroup;
  15848. if (numThisGroup == 0)
  15849. return;
  15850. numProcessedLastGroup = processed;
  15851. if (numThisGroup > numGroupMax)
  15852. numGroupMax = numThisGroup;
  15853. numGroups++;
  15854. }
  15855. };
  15856. class CRoxieServerGroupActivityFactory : public CRoxieServerActivityFactory
  15857. {
  15858. public:
  15859. CRoxieServerGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15860. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15861. {
  15862. }
  15863. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15864. {
  15865. return new CRoxieServerGroupActivity(_ctx, this, _probeManager);
  15866. }
  15867. virtual const StatisticsMapping &queryStatsMapping() const
  15868. {
  15869. return groupStatistics;
  15870. }
  15871. };
  15872. IRoxieServerActivityFactory *createRoxieServerGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15873. {
  15874. return new CRoxieServerGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15875. }
  15876. //=================================================================================
  15877. class CRoxieServerFirstNActivity : public CRoxieServerLateStartActivity
  15878. {
  15879. unsigned __int64 limit;
  15880. unsigned __int64 skip;
  15881. unsigned doneThisGroup;
  15882. IHThorFirstNArg &helper;
  15883. public:
  15884. CRoxieServerFirstNActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  15885. : CRoxieServerLateStartActivity(_ctx, _factory, _probeManager), helper((IHThorFirstNArg &)basehelper)
  15886. {
  15887. doneThisGroup = 0;
  15888. limit = 0;
  15889. skip = 0;
  15890. }
  15891. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15892. {
  15893. doneThisGroup = 0;
  15894. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  15895. limit = helper.getLimit();
  15896. skip = helper.numToSkip();
  15897. lateStart(parentExtractSize, parentExtract, limit > 0);
  15898. if (limit + skip >= limit)
  15899. limit += skip;
  15900. }
  15901. const void * nextRow()
  15902. {
  15903. ActivityTimer t(totalCycles, timeActivities);
  15904. if (eof)
  15905. return NULL;
  15906. const void *ret;
  15907. for (;;)
  15908. {
  15909. ret = inputStream->nextRow();
  15910. if (!ret)
  15911. {
  15912. if (meta.isGrouped())
  15913. {
  15914. if (doneThisGroup > skip)
  15915. {
  15916. doneThisGroup = 0;
  15917. return NULL;
  15918. }
  15919. doneThisGroup = 0;
  15920. }
  15921. ret = inputStream->nextRow();
  15922. if (!ret)
  15923. {
  15924. eof = true;
  15925. return NULL;
  15926. }
  15927. }
  15928. doneThisGroup++;
  15929. if (doneThisGroup > skip)
  15930. break;
  15931. ReleaseRoxieRow(ret);
  15932. }
  15933. if (doneThisGroup <= limit)
  15934. {
  15935. processed++;
  15936. return ret;
  15937. }
  15938. ReleaseRoxieRow(ret);
  15939. if (meta.isGrouped())
  15940. {
  15941. while ((ret = inputStream->nextRow()) != NULL)
  15942. ReleaseRoxieRow(ret);
  15943. doneThisGroup = 0;
  15944. }
  15945. else
  15946. eof = true;
  15947. return NULL;
  15948. }
  15949. };
  15950. class CRoxieServerFirstNActivityFactory : public CRoxieServerActivityFactory
  15951. {
  15952. public:
  15953. CRoxieServerFirstNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15954. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15955. {
  15956. }
  15957. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15958. {
  15959. return new CRoxieServerFirstNActivity(_ctx, this, _probeManager);
  15960. }
  15961. };
  15962. IRoxieServerActivityFactory *createRoxieServerFirstNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15963. {
  15964. return new CRoxieServerFirstNActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15965. }
  15966. //=================================================================================
  15967. class CRoxieServerSelectNActivity : public CRoxieServerActivity
  15968. {
  15969. bool done;
  15970. IHThorSelectNArg &helper;
  15971. public:
  15972. CRoxieServerSelectNActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  15973. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorSelectNArg &)basehelper)
  15974. {
  15975. done = false;
  15976. }
  15977. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15978. {
  15979. done = false;
  15980. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  15981. }
  15982. const void *defaultRow()
  15983. {
  15984. if (!rowAllocator)
  15985. ensureRowAllocator(); // We delay as often not needed...
  15986. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15987. size32_t thisSize = helper.createDefault(rowBuilder);
  15988. return rowBuilder.finalizeRowClear(thisSize);
  15989. }
  15990. virtual const void * nextRow()
  15991. {
  15992. ActivityTimer t(totalCycles, timeActivities);
  15993. if (done)
  15994. return NULL;
  15995. done = true;
  15996. processed++; // always going to return a row!
  15997. unsigned __int64 index = helper.getRowToSelect();
  15998. while (--index)
  15999. {
  16000. const void * next = inputStream->ungroupedNextRow();
  16001. if (!next)
  16002. return defaultRow();
  16003. ReleaseRoxieRow(next);
  16004. }
  16005. const void * next = inputStream->ungroupedNextRow();
  16006. if (!next)
  16007. next = defaultRow();
  16008. return next;
  16009. }
  16010. };
  16011. class CRoxieServerSelectNActivityFactory : public CRoxieServerActivityFactory
  16012. {
  16013. public:
  16014. CRoxieServerSelectNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  16015. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  16016. {
  16017. }
  16018. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  16019. {
  16020. return new CRoxieServerSelectNActivity(_ctx, this, _probeManager);
  16021. }
  16022. };
  16023. IRoxieServerActivityFactory *createRoxieServerSelectNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  16024. {
  16025. return new CRoxieServerSelectNActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  16026. }
  16027. //=================================================================================
  16028. class CRoxieServerSelfJoinActivity : public CRoxieServerActivity
  16029. {
  16030. IHThorJoinArg &helper;
  16031. ICompare *collate;
  16032. OwnedRowArray group;
  16033. bool matchedLeft;
  16034. BoolArray matchedRight;
  16035. bool eof;
  16036. bool first;
  16037. unsigned leftIndex;
  16038. unsigned rightIndex;
  16039. unsigned rightOuterIndex;
  16040. unsigned joinLimit;
  16041. unsigned atmostLimit;
  16042. unsigned atmostsTriggered;
  16043. unsigned abortLimit;
  16044. unsigned keepLimit;
  16045. unsigned joinCounter;
  16046. bool leftOuterJoin;
  16047. bool rightOuterJoin;
  16048. bool exclude;
  16049. bool limitFail;
  16050. bool limitOnFail;
  16051. bool cloneLeft;
  16052. bool forceSpill;
  16053. OwnedConstRoxieRow defaultLeft;
  16054. OwnedConstRoxieRow defaultRight;
  16055. OwnedConstRoxieRow lhs;
  16056. Owned<IException> failingLimit;
  16057. bool failingOuterAtmost;
  16058. Owned<IEngineRowAllocator> defaultAllocator;
  16059. Owned<IRHLimitedCompareHelper> limitedhelper;
  16060. Owned<CRHDualCache> dualcache;
  16061. Owned<IGroupedInput> groupedInput;
  16062. IRowStream *dualCacheInput;
  16063. bool fillGroup()
  16064. {
  16065. group.clear();
  16066. matchedLeft = false;
  16067. matchedRight.kill();
  16068. failingOuterAtmost = false;
  16069. const void * next;
  16070. unsigned groupCount = 0;
  16071. while((next = groupedInput->nextRow()) != NULL)
  16072. {
  16073. if(groupCount==abortLimit)
  16074. {
  16075. if(limitFail)
  16076. failLimit(next);
  16077. if (ctx->queryDebugContext())
  16078. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  16079. if(limitOnFail)
  16080. {
  16081. assertex(!failingLimit);
  16082. try
  16083. {
  16084. failLimit(next);
  16085. }
  16086. catch(IException * except)
  16087. {
  16088. failingLimit.setown(except);
  16089. }
  16090. assertex(failingLimit != NULL);
  16091. group.append(next);
  16092. groupCount++;
  16093. break;
  16094. }
  16095. group.clear();
  16096. groupCount = 0;
  16097. while(next)
  16098. {
  16099. ReleaseRoxieRow(next);
  16100. next = groupedInput->nextRow();
  16101. }
  16102. }
  16103. else if(groupCount==atmostLimit)
  16104. {
  16105. atmostsTriggered++;
  16106. if(leftOuterJoin)
  16107. {
  16108. group.append(next);
  16109. groupCount++;
  16110. failingOuterAtmost = true;
  16111. break;
  16112. }
  16113. else
  16114. {
  16115. group.clear();
  16116. groupCount = 0;
  16117. while (next)
  16118. {
  16119. ReleaseRoxieRow(next);
  16120. next = groupedInput->nextRow();
  16121. }
  16122. }
  16123. }
  16124. else
  16125. {
  16126. group.append(next);
  16127. groupCount++;
  16128. }
  16129. }
  16130. if(group.ordinality()==0)
  16131. {
  16132. eof = true;
  16133. return false;
  16134. }
  16135. leftIndex = 0;
  16136. rightIndex = 0;
  16137. rightOuterIndex = 0;
  16138. joinCounter = 0;
  16139. joinLimit = keepLimit;
  16140. ForEachItemIn(idx, group)
  16141. matchedRight.append(false);
  16142. return true;
  16143. }
  16144. void failLimit(const void * next)
  16145. {
  16146. helper.onMatchAbortLimitExceeded();
  16147. CommonXmlWriter xmlwrite(XWFtrim|XWFopt );
  16148. if (!ctx->isBlind() && input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  16149. {
  16150. input->queryOutputMeta()->toXML((byte *) next, xmlwrite);
  16151. }
  16152. throw MakeStringException(ROXIE_TOO_MANY_RESULTS, "More than %d match candidates in self-join %d for row %s", abortLimit, queryId(), xmlwrite.str());
  16153. }
  16154. virtual bool needsAllocator() const { return true; }
  16155. const void *joinRecords(const void * curLeft, const void * curRight, unsigned counter, IException * except, unsigned flags)
  16156. {
  16157. try
  16158. {
  16159. if (cloneLeft && !except)
  16160. {
  16161. LinkRoxieRow(curLeft);
  16162. return curLeft;
  16163. }
  16164. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16165. size32_t outsize = except ? helper.onFailTransform(rowBuilder, curLeft, curRight, except, flags) : helper.transform(rowBuilder, curLeft, curRight, counter, flags);
  16166. if (outsize)
  16167. return rowBuilder.finalizeRowClear(outsize);
  16168. else
  16169. return NULL;
  16170. }
  16171. catch (IException *E)
  16172. {
  16173. throw makeWrappedException(E);
  16174. }
  16175. }
  16176. void createDefaultLeft()
  16177. {
  16178. if (!defaultLeft)
  16179. {
  16180. if (!defaultAllocator)
  16181. defaultAllocator.setown(createRowAllocator(input->queryOutputMeta()));
  16182. RtlDynamicRowBuilder rowBuilder(defaultAllocator);
  16183. size32_t thisSize = helper.createDefaultLeft(rowBuilder);
  16184. defaultLeft.setown(rowBuilder.finalizeRowClear(thisSize));
  16185. }
  16186. }
  16187. void createDefaultRight()
  16188. {
  16189. if (!defaultRight)
  16190. {
  16191. if (!defaultAllocator)
  16192. defaultAllocator.setown(createRowAllocator(input->queryOutputMeta()));
  16193. RtlDynamicRowBuilder rowBuilder(defaultAllocator);
  16194. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  16195. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  16196. }
  16197. }
  16198. public:
  16199. CRoxieServerSelfJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _forceSpill)
  16200. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorJoinArg &)basehelper), forceSpill(_forceSpill)
  16201. {
  16202. collate = helper.queryCompareLeftRight();
  16203. eof = false;
  16204. first = true;
  16205. keepLimit = 0;
  16206. atmostLimit = 0;
  16207. atmostsTriggered = 0;
  16208. unsigned joinFlags = helper.getJoinFlags();
  16209. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  16210. rightOuterJoin = (joinFlags & JFrightouter) != 0;
  16211. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  16212. exclude = (joinFlags & JFexclude) != 0;
  16213. abortLimit = 0;
  16214. joinLimit = 0;
  16215. assertex((joinFlags & (JFfirst | JFfirstleft | JFfirstright)) == 0); // no longer supported
  16216. getLimitType(joinFlags, limitFail, limitOnFail);
  16217. if((joinFlags & JFslidingmatch) != 0)
  16218. throw MakeStringException(ROXIE_UNIMPLEMENTED_ERROR, "Internal Error: Sliding self join not supported");
  16219. failingOuterAtmost = false;
  16220. matchedLeft = false;
  16221. leftIndex = 0;
  16222. rightIndex = 0;
  16223. rightOuterIndex = 0;
  16224. joinCounter = 0;
  16225. dualCacheInput = NULL;
  16226. }
  16227. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16228. {
  16229. eof = false;
  16230. first = true;
  16231. failingLimit.clear();
  16232. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  16233. keepLimit = helper.getKeepLimit();
  16234. if(keepLimit == 0)
  16235. keepLimit = (unsigned)-1;
  16236. atmostsTriggered = 0;
  16237. atmostLimit = helper.getJoinLimit();
  16238. if(atmostLimit == 0)
  16239. atmostLimit = (unsigned)-1;
  16240. else
  16241. assertex(!rightOuterJoin);
  16242. abortLimit = helper.getMatchAbortLimit();
  16243. if (abortLimit == 0)
  16244. abortLimit = (unsigned)-1;
  16245. if (rightOuterJoin)
  16246. createDefaultLeft();
  16247. if (leftOuterJoin || limitOnFail)
  16248. createDefaultRight();
  16249. ICompare *compareLeft = helper.queryCompareLeft();
  16250. if (helper.isLeftAlreadySorted())
  16251. groupedInput.setown(createGroupedInputReader(inputStream, compareLeft));
  16252. else
  16253. {
  16254. bool isStable = (helper.getJoinFlags() & JFunstable) == 0;
  16255. RoxieSortAlgorithm sortAlgorithm;
  16256. if (forceSpill)
  16257. sortAlgorithm = isStable ? stableSpillingQuickSortAlgorithm : spillingQuickSortAlgorithm;
  16258. else
  16259. sortAlgorithm = isStable ? stableQuickSortAlgorithm : quickSortAlgorithm;
  16260. groupedInput.setown(createSortedGroupedInputReader(inputStream, compareLeft, createSortAlgorithm(sortAlgorithm, compareLeft, ctx->queryRowManager(), input->queryOutputMeta(), ctx->queryCodeContext(), tempDirectory, activityId)));
  16261. }
  16262. if ((helper.getJoinFlags() & JFlimitedprefixjoin) && helper.getJoinLimit())
  16263. { //limited match join (s[1..n])
  16264. dualcache.setown(new CRHDualCache());
  16265. dualcache->init(groupedInput);
  16266. dualCacheInput = dualcache->queryOut1();
  16267. failingOuterAtmost = false;
  16268. matchedLeft = false;
  16269. leftIndex = 0;
  16270. rightOuterIndex = 0;
  16271. joinCounter = 0;
  16272. limitedhelper.setown(createRHLimitedCompareHelper());
  16273. limitedhelper->init( helper.getJoinLimit(), dualcache->queryOut2(), collate, helper.queryPrefixCompare() );
  16274. }
  16275. }
  16276. virtual void reset()
  16277. {
  16278. if (atmostsTriggered)
  16279. noteStatistic(StNumAtmostTriggered, atmostsTriggered);
  16280. group.clear();
  16281. groupedInput.clear();
  16282. CRoxieServerActivity::reset();
  16283. defaultLeft.clear();
  16284. defaultRight.clear();
  16285. }
  16286. virtual const void * nextRow()
  16287. {
  16288. ActivityTimer t(totalCycles, timeActivities);
  16289. if (limitedhelper)
  16290. {
  16291. while(!eof) //limited match join
  16292. {
  16293. if (!group.isItem(rightIndex))
  16294. {
  16295. lhs.setown(dualCacheInput->nextRow());
  16296. if (lhs)
  16297. {
  16298. rightIndex = 0;
  16299. joinCounter = 0;
  16300. group.clear();
  16301. limitedhelper->getGroup(group,lhs);
  16302. }
  16303. else
  16304. {
  16305. eof = true;
  16306. }
  16307. }
  16308. if (group.isItem(rightIndex))
  16309. {
  16310. const void * rhs = group.item(rightIndex++);
  16311. if(helper.match(lhs, rhs))
  16312. {
  16313. const void * ret = joinRecords(lhs, rhs, ++joinCounter, NULL, JTFmatchedleft|JTFmatchedright);
  16314. if(ret)
  16315. {
  16316. processed++;
  16317. return ret;
  16318. }
  16319. }
  16320. }
  16321. }
  16322. return NULL;
  16323. }
  16324. else
  16325. {
  16326. if (first)
  16327. {
  16328. first = false;
  16329. fillGroup();
  16330. }
  16331. while(!eof)
  16332. {
  16333. if(failingOuterAtmost)
  16334. while(group.isItem(leftIndex))
  16335. {
  16336. const void * ret = joinRecords(group.item(leftIndex++), defaultRight, 0, NULL, JTFmatchedleft);
  16337. if(ret)
  16338. {
  16339. processed++;
  16340. return ret;
  16341. }
  16342. }
  16343. if((joinLimit == 0) || !group.isItem(rightIndex))
  16344. {
  16345. if(leftOuterJoin && !matchedLeft && !failingLimit)
  16346. {
  16347. const void * ret = joinRecords(group.item(leftIndex), defaultRight, 0, NULL, JTFmatchedleft);
  16348. if(ret)
  16349. {
  16350. matchedLeft = true;
  16351. processed++;
  16352. return ret;
  16353. }
  16354. }
  16355. leftIndex++;
  16356. matchedLeft = false;
  16357. rightIndex = 0;
  16358. joinCounter = 0;
  16359. joinLimit = keepLimit;
  16360. }
  16361. if(!group.isItem(leftIndex))
  16362. {
  16363. if(failingLimit || failingOuterAtmost)
  16364. {
  16365. const void * lhs;
  16366. while((lhs = groupedInput->nextRow()) != NULL) // dualCache never active here
  16367. {
  16368. const void * ret = joinRecords(lhs, defaultRight, 0, failingLimit, JTFmatchedleft);
  16369. ReleaseRoxieRow(lhs);
  16370. if(ret)
  16371. {
  16372. processed++;
  16373. return ret;
  16374. }
  16375. }
  16376. failingLimit.clear();
  16377. }
  16378. if(rightOuterJoin && !failingLimit)
  16379. while(group.isItem(rightOuterIndex))
  16380. if(!matchedRight.item(rightOuterIndex++))
  16381. {
  16382. const void * ret = joinRecords(defaultLeft, group.item(rightOuterIndex-1), 0, NULL, JTFmatchedright);
  16383. if(ret)
  16384. {
  16385. processed++;
  16386. return ret;
  16387. }
  16388. }
  16389. if(!fillGroup())
  16390. return NULL;
  16391. continue;
  16392. }
  16393. const void * lhs = group.item(leftIndex);
  16394. if(failingLimit)
  16395. {
  16396. leftIndex++;
  16397. const void * ret = joinRecords(lhs, defaultRight, 0, failingLimit, JTFmatchedleft);
  16398. if(ret)
  16399. {
  16400. processed++;
  16401. return ret;
  16402. }
  16403. }
  16404. else
  16405. {
  16406. const void * rhs = group.item(rightIndex++);
  16407. if(helper.match(lhs, rhs))
  16408. {
  16409. matchedLeft = true;
  16410. matchedRight.replace(true, rightIndex-1);
  16411. if(!exclude)
  16412. {
  16413. const void * ret = joinRecords(lhs, rhs, ++joinCounter, NULL, JTFmatchedleft|JTFmatchedright);
  16414. if(ret)
  16415. {
  16416. processed++;
  16417. joinLimit--;
  16418. return ret;
  16419. }
  16420. }
  16421. }
  16422. }
  16423. }
  16424. return NULL;
  16425. }
  16426. }
  16427. };
  16428. class CRoxieServerSelfJoinActivityFactory : public CRoxieServerActivityFactory
  16429. {
  16430. bool forceSpill;
  16431. public:
  16432. CRoxieServerSelfJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  16433. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  16434. {
  16435. forceSpill = queryFactory.queryOptions().allSortsMaySpill || _graphNode.getPropBool("hint[@name='spill']/@value", false);;
  16436. }
  16437. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  16438. {
  16439. return new CRoxieServerSelfJoinActivity(_ctx, this, _probeManager, forceSpill);
  16440. }
  16441. virtual const StatisticsMapping &queryStatsMapping() const
  16442. {
  16443. return joinStatistics;
  16444. }
  16445. };
  16446. IRoxieServerActivityFactory *createRoxieServerSelfJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  16447. {
  16448. return new CRoxieServerSelfJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  16449. }
  16450. //=====================================================================================================
  16451. class CRoxieServerLookupJoinActivity : public CRoxieServerTwoInputActivity
  16452. {
  16453. private:
  16454. class LookupTable : public CInterface
  16455. {
  16456. public:
  16457. LookupTable(IHThorHashJoinArg &helper)
  16458. : leftRightCompare(helper.queryCompareLeftRight()), rightCompare(helper.queryCompareRight()),
  16459. leftHash(helper.queryHashLeft()), rightHash(helper.queryHashRight())
  16460. {
  16461. size = 0;
  16462. }
  16463. virtual const void *find(const void * left) const = 0;
  16464. virtual const void *findNext(const void * left) const = 0;
  16465. protected:
  16466. ICompare * leftRightCompare;
  16467. ICompare * rightCompare;
  16468. IHash * leftHash;
  16469. IHash * rightHash;
  16470. unsigned size;
  16471. };
  16472. class DedupLookupTable : public LookupTable
  16473. {
  16474. public:
  16475. DedupLookupTable(ConstPointerArray &rightRows, IHThorHashJoinArg &helper)
  16476. : LookupTable(helper)
  16477. {
  16478. size = (4*rightRows.length())/3 + 1;
  16479. table = (const void * *)calloc(size, sizeof(void *)); // This should probably be allocated from roxiemem (and size rounded up to actual available size)
  16480. ForEachItemIn(idx, rightRows)
  16481. add(rightRows.item(idx));
  16482. }
  16483. ~DedupLookupTable()
  16484. {
  16485. roxiemem::ReleaseRoxieRowArray(size, table);
  16486. free(table);
  16487. }
  16488. virtual const void *find(const void * left) const
  16489. {
  16490. unsigned index = leftHash->hash(left) % size;
  16491. unsigned start = index;
  16492. while (table[index])
  16493. {
  16494. if(leftRightCompare->docompare(left, table[index]) == 0)
  16495. return table[index];
  16496. index++;
  16497. if (index==size)
  16498. index = 0;
  16499. if (index==start)
  16500. throw MakeStringException(ROXIE_JOIN_ERROR, "Internal error in lookup join activity (hash table full on lookup)");
  16501. }
  16502. return NULL;
  16503. }
  16504. virtual const void *findNext(const void * left) const
  16505. {
  16506. return NULL;
  16507. }
  16508. protected:
  16509. void add(const void * right)
  16510. {
  16511. unsigned index = rightHash->hash(right) % size;
  16512. unsigned start = index;
  16513. while (table[index])
  16514. {
  16515. if (rightCompare->docompare(table[index], right) == 0)
  16516. {
  16517. ReleaseRoxieRow(right);
  16518. return;
  16519. }
  16520. index++;
  16521. if (index==size)
  16522. index = 0;
  16523. if (index==start)
  16524. throw MakeStringException(ROXIE_JOIN_ERROR, "Internal error in lookup join activity (hash table full on add)");
  16525. }
  16526. table[index] = right;
  16527. }
  16528. const void * * table;
  16529. };
  16530. class FewLookupTable : public LookupTable
  16531. {
  16532. public:
  16533. FewLookupTable(ConstPointerArray &rightRows, IHThorHashJoinArg &helper)
  16534. : LookupTable(helper)
  16535. {
  16536. size = (4*rightRows.length())/3 + 1;
  16537. table = (const void * *)calloc(size, sizeof(void *)); // This should probably be allocated from roxiemem
  16538. findex = fstart = BadIndex;
  16539. ForEachItemIn(idx, rightRows)
  16540. add(rightRows.item(idx));
  16541. }
  16542. ~FewLookupTable()
  16543. {
  16544. roxiemem::ReleaseRoxieRowArray(size, table);
  16545. free(table);
  16546. }
  16547. virtual const void *find(const void * left) const
  16548. {
  16549. fstart = leftHash->hash(left) % size;
  16550. findex = fstart;
  16551. return doFind(left);
  16552. }
  16553. virtual const void *findNext(const void * left) const
  16554. {
  16555. if (findex == BadIndex)
  16556. return NULL;
  16557. advance();
  16558. return doFind(left);
  16559. }
  16560. protected:
  16561. void add(const void * right)
  16562. {
  16563. unsigned start = rightHash->hash(right) % size;
  16564. unsigned index = start;
  16565. while (table[index])
  16566. {
  16567. index++;
  16568. if (index==size)
  16569. index = 0;
  16570. if (index==start)
  16571. throwUnexpected(); //table is full, should never happen
  16572. }
  16573. table[index] = right;
  16574. }
  16575. void advance() const
  16576. {
  16577. findex++;
  16578. if(findex==size)
  16579. findex = 0;
  16580. if(findex==fstart)
  16581. throw MakeStringException(ROXIE_JOIN_ERROR, "Internal error in lookup join activity (hash table full on lookup)");
  16582. }
  16583. const void *doFind(const void * left) const
  16584. {
  16585. while(table[findex])
  16586. {
  16587. if (leftRightCompare->docompare(left, table[findex]) == 0)
  16588. return table[findex];
  16589. advance();
  16590. }
  16591. findex = BadIndex;
  16592. return NULL;
  16593. }
  16594. const void * * table;
  16595. unsigned mutable fstart;
  16596. unsigned mutable findex;
  16597. static unsigned const BadIndex;
  16598. };
  16599. class ManyLookupTable : public LookupTable
  16600. {
  16601. public:
  16602. ManyLookupTable(ConstPointerArray &rightRows, IHThorHashJoinArg &helper)
  16603. : LookupTable(helper)
  16604. {
  16605. rightRows.swapWith(rowtable);
  16606. UInt64Array groups;
  16607. unsigned numRows = rowtable.length();
  16608. if (numRows)
  16609. {
  16610. unsigned groupStart = 0;
  16611. const void *groupStartRow = rowtable.item(0);
  16612. for (unsigned i=1; i < numRows; i++)
  16613. {
  16614. const void *thisRow = rowtable.item(i);
  16615. if (rightCompare->docompare(groupStartRow, thisRow))
  16616. {
  16617. groups.append(makeint64(groupStart, i-groupStart));
  16618. groupStart = i;
  16619. groupStartRow = thisRow;
  16620. }
  16621. }
  16622. groups.append(makeint64(groupStart, numRows-groupStart));
  16623. }
  16624. size = (4*groups.length())/3 + 1;
  16625. table = (__uint64 *) calloc(size, sizeof(__uint64)); // This should probably be allocated from roxiemem
  16626. ForEachItemIn(idx, groups)
  16627. {
  16628. unsigned __int64 group = groups.item(idx);
  16629. unsigned groupstart = high(group);
  16630. const void *row = rowtable.item(groupstart);
  16631. add(row, group);
  16632. }
  16633. }
  16634. ~ManyLookupTable()
  16635. {
  16636. roxiemem::ReleaseRoxieRows(rowtable);
  16637. free(table);
  16638. }
  16639. void add(const void *row, unsigned __int64 group)
  16640. {
  16641. unsigned start = rightHash->hash(row) % size;
  16642. unsigned index = start;
  16643. while (table[index])
  16644. {
  16645. index++;
  16646. if (index==size)
  16647. index = 0;
  16648. if (index==start)
  16649. throwUnexpected(); //table is full, should never happen
  16650. }
  16651. table[index] = group;
  16652. }
  16653. virtual const void *find(const void * left) const
  16654. {
  16655. unsigned index = leftHash->hash(left) % size;
  16656. unsigned start = index;
  16657. while (table[index])
  16658. {
  16659. __uint64 group = table[index];
  16660. currentMatch = high(group);
  16661. const void *right = rowtable.item(currentMatch);
  16662. if (leftRightCompare->docompare(left, right) == 0)
  16663. {
  16664. currentMatch++;
  16665. matchCount = low(group) - 1;
  16666. return right;
  16667. }
  16668. index++;
  16669. if (index==size)
  16670. index = 0;
  16671. if (index==start)
  16672. throw MakeStringException(ROXIE_JOIN_ERROR, "Internal error in lookup join activity (hash table full on lookup)");
  16673. }
  16674. matchCount = 0;
  16675. return NULL;
  16676. }
  16677. virtual const void *findNext(const void * left) const
  16678. {
  16679. if (!matchCount)
  16680. return NULL;
  16681. matchCount--;
  16682. return rowtable.item(currentMatch++);
  16683. }
  16684. protected:
  16685. __uint64 *table;
  16686. ConstPointerArray rowtable;
  16687. mutable unsigned currentMatch = 0;
  16688. mutable unsigned matchCount = 0;
  16689. };
  16690. IHThorHashJoinArg &helper;
  16691. bool leftOuterJoin;
  16692. bool exclude;
  16693. bool eog;
  16694. bool many;
  16695. bool dedupRHS;
  16696. bool useFewTable;
  16697. bool matchedGroup;
  16698. const void *left;
  16699. OwnedConstRoxieRow defaultRight;
  16700. Owned<LookupTable> table;
  16701. unsigned keepLimit;
  16702. unsigned atmostLimit;
  16703. unsigned atmostsTriggered;
  16704. unsigned limitLimit;
  16705. unsigned joinCounter;
  16706. bool limitFail;
  16707. bool limitOnFail;
  16708. bool hasGroupLimit;
  16709. bool isSmartJoin;
  16710. unsigned keepCount;
  16711. bool gotMatch;
  16712. bool cloneLeft;
  16713. ConstPointerArray rightGroup;
  16714. aindex_t rightGroupIndex;
  16715. Owned<IException> failingLimit;
  16716. ConstPointerArray filteredRight;
  16717. ThorActivityKind activityKind;
  16718. Owned<IEngineRowAllocator> defaultRightAllocator;
  16719. void createDefaultRight()
  16720. {
  16721. if (!defaultRight)
  16722. {
  16723. if (!defaultRightAllocator)
  16724. defaultRightAllocator.setown(createRowAllocator(input1->queryOutputMeta()));
  16725. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  16726. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  16727. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  16728. }
  16729. }
  16730. public:
  16731. CRoxieServerLookupJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _useFewTable)
  16732. : CRoxieServerTwoInputActivity(_ctx, _factory, _probeManager), helper((IHThorHashJoinArg &)basehelper), useFewTable(_useFewTable)
  16733. {
  16734. unsigned joinFlags = helper.getJoinFlags();
  16735. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  16736. assertex((joinFlags & JFrightouter) == 0);
  16737. exclude = (joinFlags & JFexclude) != 0;
  16738. many = (joinFlags & JFmanylookup) != 0;
  16739. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  16740. dedupRHS = (joinFlags & (JFmanylookup | JFmatchrequired | JFtransformMaySkip)) == 0; // optimisation: can implicitly dedup RHS unless is many lookup, or match required, or transform may skip
  16741. left = NULL;
  16742. activityKind = factory->getKind();
  16743. eog = false;
  16744. matchedGroup = false;
  16745. gotMatch = false;
  16746. keepLimit = 0;
  16747. keepCount = 0;
  16748. joinCounter = 0;
  16749. atmostLimit = 0;
  16750. atmostsTriggered = 0;
  16751. limitLimit = 0;
  16752. rightGroupIndex = 0;
  16753. hasGroupLimit = false;
  16754. isSmartJoin = (joinFlags & JFsmart) != 0;
  16755. getLimitType(joinFlags, limitFail, limitOnFail);
  16756. }
  16757. void loadRight()
  16758. {
  16759. ConstPointerArray rightset;
  16760. try
  16761. {
  16762. const void * next;
  16763. while(true)
  16764. {
  16765. next = inputStream1->ungroupedNextRow();
  16766. if(!next)
  16767. break;
  16768. rightset.append(next);
  16769. }
  16770. if (!dedupRHS)
  16771. {
  16772. if (useFewTable)
  16773. {
  16774. table.setown(new FewLookupTable(rightset, helper)); // NOTE - takes ownership of rightset
  16775. }
  16776. else
  16777. {
  16778. if (!helper.isRightAlreadySorted())
  16779. {
  16780. if (helper.getJoinFlags() & JFunstable)
  16781. {
  16782. qsortvec(const_cast<void * *>(rightset.getArray()), rightset.ordinality(), *helper.queryCompareRight());
  16783. }
  16784. else
  16785. {
  16786. unsigned rightord = rightset.ordinality();
  16787. MemoryAttr tempAttr(rightord*sizeof(void **)); // Temp storage for stable sort. This should probably be allocated from roxiemem
  16788. void **temp = (void **) tempAttr.bufferBase();
  16789. void **_rows = const_cast<void * *>(rightset.getArray());
  16790. msortvecstableinplace(_rows, rightord, *helper.queryCompareRight(), temp);
  16791. }
  16792. }
  16793. table.setown(new ManyLookupTable(rightset, helper)); // NOTE - takes ownership of rightset
  16794. }
  16795. }
  16796. else
  16797. {
  16798. table.setown(new DedupLookupTable(rightset, helper)); // NOTE - takes ownership of rightset
  16799. }
  16800. }
  16801. catch (...)
  16802. {
  16803. roxiemem::ReleaseRoxieRows(rightset);
  16804. throw;
  16805. }
  16806. };
  16807. virtual void reset()
  16808. {
  16809. if (atmostsTriggered)
  16810. noteStatistic(StNumAtmostTriggered, atmostsTriggered);
  16811. CRoxieServerTwoInputActivity::reset();
  16812. ReleaseClearRoxieRow(left);
  16813. defaultRight.clear();
  16814. table.clear();
  16815. }
  16816. virtual bool needsAllocator() const { return true; }
  16817. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16818. {
  16819. eog = false;
  16820. matchedGroup = false;
  16821. left = NULL;
  16822. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  16823. keepLimit = helper.getKeepLimit();
  16824. if(keepLimit==0) keepLimit = static_cast<unsigned>(-1);
  16825. atmostsTriggered = 0;
  16826. atmostLimit = helper.getJoinLimit();
  16827. limitLimit = helper.getMatchAbortLimit();
  16828. hasGroupLimit = ((atmostLimit > 0) || (limitLimit > 0));
  16829. if(atmostLimit==0) atmostLimit = static_cast<unsigned>(-1);
  16830. if(limitLimit==0) limitLimit = static_cast<unsigned>(-1);
  16831. getLimitType(helper.getJoinFlags(), limitFail, limitOnFail);
  16832. switch (activityKind)
  16833. {
  16834. case TAKlookupjoin:
  16835. case TAKlookupdenormalizegroup:
  16836. case TAKsmartjoin:
  16837. case TAKsmartdenormalizegroup:
  16838. if (leftOuterJoin)
  16839. createDefaultRight();
  16840. break;
  16841. }
  16842. if (limitOnFail)
  16843. createDefaultRight();
  16844. }
  16845. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  16846. {
  16847. if (!idx && (helper.getJoinFlags() & JFparallel) != 0)
  16848. {
  16849. puller.setown(new CRoxieServerReadAheadInput(ctx, ctx->queryOptions().parallelJoinPreload));
  16850. puller->setInput(0, _sourceIdx, _in);
  16851. _in = puller;
  16852. _sourceIdx = 0;
  16853. }
  16854. CRoxieServerTwoInputActivity::setInput(idx, _sourceIdx, _in);
  16855. }
  16856. virtual const void * nextRow()
  16857. {
  16858. ActivityTimer t(totalCycles, timeActivities);
  16859. if(!table)
  16860. loadRight();
  16861. switch (activityKind)
  16862. {
  16863. case TAKlookupjoin:
  16864. case TAKsmartjoin:
  16865. return nextRowJoin();
  16866. case TAKlookupdenormalize:
  16867. case TAKlookupdenormalizegroup:
  16868. case TAKsmartdenormalize:
  16869. case TAKsmartdenormalizegroup:
  16870. return nextRowDenormalize();
  16871. }
  16872. throwUnexpected();
  16873. }
  16874. private:
  16875. const void * nextRowJoin()
  16876. {
  16877. if(!table)
  16878. loadRight();
  16879. while(true)
  16880. {
  16881. const void * right = NULL;
  16882. if(!left)
  16883. {
  16884. left = inputStream->nextRow();
  16885. keepCount = keepLimit;
  16886. joinCounter = 0;
  16887. if(!left)
  16888. {
  16889. if (isSmartJoin)
  16890. left = inputStream->nextRow();
  16891. if (!left)
  16892. {
  16893. if(matchedGroup || eog)
  16894. {
  16895. matchedGroup = false;
  16896. eog = true;
  16897. return NULL;
  16898. }
  16899. eog = true;
  16900. continue;
  16901. }
  16902. }
  16903. eog = false;
  16904. gotMatch = false;
  16905. right = getRightFirst();
  16906. }
  16907. else
  16908. right = getRightNext();
  16909. const void * ret = NULL;
  16910. if(failingLimit)
  16911. {
  16912. ret = joinException(left, failingLimit);
  16913. }
  16914. else
  16915. {
  16916. while(right)
  16917. {
  16918. if(helper.match(left, right))
  16919. {
  16920. gotMatch = true;
  16921. if(exclude)
  16922. break;
  16923. ret = joinRecords(left, right, ++joinCounter, JTFmatchedleft|JTFmatchedright);
  16924. if(ret)
  16925. {
  16926. processed++;
  16927. break;
  16928. }
  16929. }
  16930. right = getRightNext();
  16931. ret = NULL;
  16932. }
  16933. if(leftOuterJoin && !gotMatch)
  16934. {
  16935. ret = joinRecords(left, defaultRight, 0, JTFmatchedleft);
  16936. gotMatch = true;
  16937. }
  16938. }
  16939. if(ret)
  16940. {
  16941. matchedGroup = true;
  16942. processed++;
  16943. if(!many || (--keepCount == 0) || failingLimit)
  16944. {
  16945. ReleaseClearRoxieRow(left);
  16946. failingLimit.clear();
  16947. }
  16948. return ret;
  16949. }
  16950. ReleaseClearRoxieRow(left);
  16951. }
  16952. }
  16953. const void * nextRowDenormalize()
  16954. {
  16955. while(true)
  16956. {
  16957. left = inputStream->nextRow();
  16958. if(!left)
  16959. {
  16960. if (!matchedGroup || isSmartJoin)
  16961. left = inputStream->nextRow();
  16962. if (!left)
  16963. {
  16964. matchedGroup = false;
  16965. return NULL;
  16966. }
  16967. }
  16968. gotMatch = false;
  16969. const void * right = getRightFirst();
  16970. const void * ret = NULL;
  16971. if (failingLimit)
  16972. ret = joinException(left, failingLimit);
  16973. else if (activityKind == TAKlookupdenormalize || activityKind == TAKsmartdenormalize)
  16974. {
  16975. OwnedConstRoxieRow newLeft;
  16976. newLeft.set(left);
  16977. unsigned rowSize = 0;
  16978. unsigned leftCount = 0;
  16979. keepCount = keepLimit;
  16980. while (right)
  16981. {
  16982. try
  16983. {
  16984. if (helper.match(left, right))
  16985. {
  16986. gotMatch = true;
  16987. if (exclude)
  16988. break;
  16989. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16990. unsigned thisSize = helper.transform(rowBuilder, newLeft, right, ++leftCount, JTFmatchedleft|JTFmatchedright);
  16991. if (thisSize)
  16992. {
  16993. rowSize = thisSize;
  16994. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  16995. }
  16996. if(!many || (--keepCount == 0))
  16997. break;
  16998. }
  16999. right = getRightNext();
  17000. }
  17001. catch (IException *E)
  17002. {
  17003. throw makeWrappedException(E);
  17004. }
  17005. }
  17006. if (rowSize)
  17007. ret = newLeft.getClear();
  17008. else if (leftOuterJoin && !gotMatch)
  17009. {
  17010. ret = left;
  17011. left = NULL;
  17012. }
  17013. }
  17014. else
  17015. {
  17016. filteredRight.kill();
  17017. keepCount = keepLimit;
  17018. while (right)
  17019. {
  17020. if (helper.match(left, right))
  17021. {
  17022. gotMatch = true;
  17023. if(exclude)
  17024. break;
  17025. filteredRight.append(right);
  17026. if(!many || (--keepCount == 0))
  17027. break;
  17028. }
  17029. right = getRightNext();
  17030. }
  17031. if((filteredRight.ordinality() > 0) || (leftOuterJoin && !gotMatch))
  17032. ret = denormalizeRecords(left, filteredRight, JTFmatchedleft);
  17033. filteredRight.kill();
  17034. }
  17035. ReleaseRoxieRow(left);
  17036. left = NULL;
  17037. failingLimit.clear();
  17038. if(ret)
  17039. {
  17040. matchedGroup = true;
  17041. processed++;
  17042. return ret;
  17043. }
  17044. }
  17045. }
  17046. const void * joinRecords(const void * left, const void * right, unsigned counter, unsigned flags)
  17047. {
  17048. if (cloneLeft)
  17049. {
  17050. LinkRoxieRow(left);
  17051. return left;
  17052. }
  17053. try
  17054. {
  17055. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17056. unsigned outSize = helper.transform(rowBuilder, left, right, counter, flags);
  17057. if (outSize)
  17058. return rowBuilder.finalizeRowClear(outSize);
  17059. else
  17060. return NULL;
  17061. }
  17062. catch (IException *E)
  17063. {
  17064. throw makeWrappedException(E);
  17065. }
  17066. }
  17067. const void * joinException(const void * left, IException * except)
  17068. {
  17069. try
  17070. {
  17071. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17072. unsigned outSize = helper.onFailTransform(rowBuilder, left, defaultRight, except, JTFmatchedleft);
  17073. if (outSize)
  17074. return rowBuilder.finalizeRowClear(outSize);
  17075. else
  17076. return NULL;
  17077. }
  17078. catch (IException *E)
  17079. {
  17080. throw makeWrappedException(E);
  17081. }
  17082. }
  17083. const void * denormalizeRecords(const void * left, ConstPointerArray & rows, unsigned flags)
  17084. {
  17085. try
  17086. {
  17087. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17088. unsigned numRows = rows.ordinality();
  17089. const void * right = numRows ? rows.item(0) : defaultRight.get();
  17090. if (numRows>0)
  17091. flags |= JTFmatchedright;
  17092. unsigned outSize = helper.transform(rowBuilder, left, right, numRows, (const void * *)rows.getArray(), flags);
  17093. if (outSize)
  17094. return rowBuilder.finalizeRowClear(outSize);
  17095. else
  17096. return NULL;
  17097. }
  17098. catch (IException *E)
  17099. {
  17100. throw makeWrappedException(E);
  17101. }
  17102. }
  17103. const void * getRightFirst() { if(hasGroupLimit) return fillRightGroup(); else return table->find(left); }
  17104. const void * getRightNext() { if(hasGroupLimit) return readRightGroup(); else return table->findNext(left); }
  17105. const void * readRightGroup() { if(rightGroup.isItem(rightGroupIndex)) return rightGroup.item(rightGroupIndex++); else return NULL; }
  17106. const void *fillRightGroup()
  17107. {
  17108. rightGroup.kill();
  17109. for(const void * right = table->find(left); right; right = table->findNext(left))
  17110. {
  17111. rightGroup.append(right);
  17112. if(rightGroup.ordinality() > limitLimit)
  17113. {
  17114. if(limitFail)
  17115. failLimit();
  17116. gotMatch = true;
  17117. if (ctx->queryDebugContext())
  17118. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  17119. if(limitOnFail)
  17120. {
  17121. assertex(!failingLimit);
  17122. try
  17123. {
  17124. failLimit();
  17125. }
  17126. catch(IException * e)
  17127. {
  17128. failingLimit.setown(e);
  17129. }
  17130. assertex(failingLimit != NULL);
  17131. }
  17132. else
  17133. {
  17134. rightGroup.kill();
  17135. }
  17136. break;
  17137. }
  17138. if(rightGroup.ordinality() > atmostLimit)
  17139. {
  17140. atmostsTriggered++;
  17141. rightGroup.kill();
  17142. break;
  17143. }
  17144. }
  17145. rightGroupIndex = 0;
  17146. return readRightGroup();
  17147. }
  17148. void failLimit()
  17149. {
  17150. helper.onMatchAbortLimitExceeded();
  17151. CommonXmlWriter xmlwrite(XWFtrim|XWFopt );
  17152. if(!ctx->isBlind() && input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  17153. {
  17154. input->queryOutputMeta()->toXML(static_cast<const unsigned char *>(left), xmlwrite);
  17155. }
  17156. throw MakeStringException(ROXIE_TOO_MANY_RESULTS, "More than %u match candidates in join %d for row %s", limitLimit, queryId(), xmlwrite.str());
  17157. }
  17158. };
  17159. unsigned const CRoxieServerLookupJoinActivity::FewLookupTable::BadIndex(static_cast<unsigned>(-1));
  17160. class CRoxieServerLookupJoinActivityFactory : public CRoxieServerJoinActivityFactory
  17161. {
  17162. public:
  17163. CRoxieServerLookupJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17164. : CRoxieServerJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  17165. {
  17166. Owned<IHThorHashJoinArg> helper = (IHThorHashJoinArg *) helperFactory();
  17167. useFewTable = _graphNode.getPropBool("hint[@name='usefewtable']/@value", false);
  17168. if((helper->getJoinFlags() & (JFfirst | JFfirstleft | JFfirstright | JFslidingmatch)) != 0)
  17169. throw MakeStringException(ROXIE_INVALID_FLAGS, "Invalid flags for lookup join activity"); // code generator should never create such an activity
  17170. }
  17171. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  17172. {
  17173. return new CRoxieServerLookupJoinActivity(_ctx, this, _probeManager, useFewTable);
  17174. }
  17175. virtual const StatisticsMapping &queryStatsMapping() const
  17176. {
  17177. return joinStatistics;
  17178. }
  17179. protected:
  17180. bool useFewTable;
  17181. };
  17182. IRoxieServerActivityFactory *createRoxieServerLookupJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17183. {
  17184. return new CRoxieServerLookupJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  17185. }
  17186. //=====================================================================================================
  17187. class CRoxieServerAllJoinActivity : public CRoxieServerTwoInputActivity
  17188. {
  17189. private:
  17190. IHThorAllJoinArg &helper;
  17191. bool leftOuterJoin;
  17192. bool rightOuterJoin;
  17193. bool exclude;
  17194. OwnedConstRoxieRow defaultRight;
  17195. OwnedConstRoxieRow defaultLeft;
  17196. Owned<IEngineRowAllocator> defaultRightAllocator;
  17197. Owned<IEngineRowAllocator> defaultLeftAllocator;
  17198. const void *left;
  17199. unsigned countForLeft;
  17200. ConstPointerArray rightset;
  17201. BoolArray matchedRight; // MORE - could use a bitset...
  17202. unsigned keepLimit;
  17203. bool started;
  17204. bool eog;
  17205. bool eos;
  17206. bool matchedLeft;
  17207. bool matchedGroup;
  17208. bool leftIsGrouped;
  17209. bool cloneLeft;
  17210. unsigned rightIndex;
  17211. unsigned joinCounter;
  17212. unsigned rightOrdinality;
  17213. ThorActivityKind activityKind;
  17214. ConstPointerArray filteredRight;
  17215. void createDefaultLeft()
  17216. {
  17217. if (!defaultLeft)
  17218. {
  17219. if (!defaultLeftAllocator)
  17220. defaultLeftAllocator.setown(createRowAllocator(input->queryOutputMeta()));
  17221. RtlDynamicRowBuilder rowBuilder(defaultLeftAllocator);
  17222. size32_t thisSize = helper.createDefaultLeft(rowBuilder);
  17223. defaultLeft.setown(rowBuilder.finalizeRowClear(thisSize));
  17224. }
  17225. }
  17226. void createDefaultRight()
  17227. {
  17228. if (!defaultRight)
  17229. {
  17230. if (!defaultRightAllocator)
  17231. defaultRightAllocator.setown(createRowAllocator(input1->queryOutputMeta()));
  17232. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  17233. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  17234. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  17235. }
  17236. }
  17237. public:
  17238. CRoxieServerAllJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17239. : CRoxieServerTwoInputActivity(_ctx, _factory, _probeManager), helper((IHThorAllJoinArg &)basehelper)
  17240. {
  17241. unsigned joinFlags = helper.getJoinFlags();
  17242. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  17243. rightOuterJoin = (joinFlags & JFrightouter) != 0;
  17244. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  17245. keepLimit = (unsigned) -1;
  17246. exclude = (joinFlags & JFexclude) != 0;
  17247. left = NULL;
  17248. started = true;
  17249. eog = false;
  17250. eos = false;
  17251. matchedLeft = false;
  17252. matchedGroup = false;
  17253. activityKind = factory->getKind();
  17254. rightIndex = 0;
  17255. rightOrdinality = 0;
  17256. leftIsGrouped = false;
  17257. countForLeft = 0;
  17258. joinCounter = 0;
  17259. }
  17260. virtual void reset()
  17261. {
  17262. defaultRight.clear();
  17263. defaultLeft.clear();
  17264. ReleaseRoxieRows(rightset);
  17265. matchedRight.kill();
  17266. CRoxieServerTwoInputActivity::reset();
  17267. }
  17268. virtual bool needsAllocator() const { return true; }
  17269. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17270. {
  17271. eog = false;
  17272. eos = false;
  17273. matchedLeft = false;
  17274. matchedGroup = false;
  17275. started = false;
  17276. left = NULL;
  17277. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  17278. keepLimit = helper.getKeepLimit();
  17279. if(keepLimit==0)
  17280. keepLimit = (unsigned) -1;
  17281. countForLeft = keepLimit;
  17282. joinCounter = 0;
  17283. leftIsGrouped = input->queryOutputMeta()->isGrouped();
  17284. if((activityKind==TAKalljoin || activityKind==TAKalldenormalizegroup) && leftOuterJoin)
  17285. createDefaultRight();
  17286. if(rightOuterJoin)
  17287. createDefaultLeft();
  17288. }
  17289. void loadRight()
  17290. {
  17291. const void * next;
  17292. while(true)
  17293. {
  17294. next = inputStream1->ungroupedNextRow();
  17295. if(!next)
  17296. break;
  17297. rightset.append(next);
  17298. matchedRight.append(false);
  17299. }
  17300. rightIndex = 0;
  17301. joinCounter = 0;
  17302. rightOrdinality = rightset.ordinality();
  17303. }
  17304. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  17305. {
  17306. if (!idx && (helper.getJoinFlags() & JFparallel) != 0)
  17307. {
  17308. puller.setown(new CRoxieServerReadAheadInput(ctx, ctx->queryOptions().parallelJoinPreload));
  17309. puller->setInput(0, _sourceIdx, _in);
  17310. _in = puller;
  17311. _sourceIdx = 0;
  17312. }
  17313. CRoxieServerTwoInputActivity::setInput(idx, _sourceIdx, _in);
  17314. }
  17315. const void * joinRecords(const void * left, const void * right, unsigned counter, unsigned flags)
  17316. {
  17317. // MORE - could share some code with lookup join
  17318. if (cloneLeft)
  17319. {
  17320. LinkRoxieRow(left);
  17321. return left;
  17322. }
  17323. try
  17324. {
  17325. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17326. unsigned outSize = helper.transform(rowBuilder, left, right, counter, flags);
  17327. if (outSize)
  17328. return rowBuilder.finalizeRowClear(outSize);
  17329. else
  17330. return NULL;
  17331. }
  17332. catch (IException *E)
  17333. {
  17334. throw makeWrappedException(E);
  17335. }
  17336. }
  17337. const void * denormalizeRecords(const void * curLeft, ConstPointerArray & rows, unsigned flags)
  17338. {
  17339. try
  17340. {
  17341. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17342. unsigned numRows = rows.ordinality();
  17343. const void * right = numRows ? rows.item(0) : defaultRight.get();
  17344. if (numRows>0)
  17345. flags |= JTFmatchedright;
  17346. unsigned outSize = helper.transform(rowBuilder, curLeft, right, numRows, rows.getArray(), flags);
  17347. if (outSize)
  17348. return rowBuilder.finalizeRowClear(outSize);
  17349. else
  17350. return NULL;
  17351. }
  17352. catch (IException *E)
  17353. {
  17354. throw makeWrappedException(E);
  17355. }
  17356. }
  17357. virtual const void *nextRow()
  17358. {
  17359. ActivityTimer t(totalCycles, timeActivities);
  17360. if(!started)
  17361. {
  17362. started = true;
  17363. left = inputStream->nextRow();
  17364. matchedLeft = false;
  17365. countForLeft = keepLimit;
  17366. joinCounter = 0;
  17367. if(left == NULL)
  17368. {
  17369. eos = true;
  17370. return NULL;
  17371. }
  17372. loadRight();
  17373. }
  17374. const void * ret;
  17375. const void * right;
  17376. if(eos)
  17377. return NULL;
  17378. while(true)
  17379. {
  17380. ret = NULL;
  17381. if((rightIndex == rightOrdinality) || (countForLeft==0))
  17382. {
  17383. if(leftOuterJoin && left && !matchedLeft)
  17384. {
  17385. switch(activityKind)
  17386. {
  17387. case TAKalljoin:
  17388. ret = joinRecords(left, defaultRight, 0, JTFmatchedleft);
  17389. break;
  17390. case TAKalldenormalize:
  17391. ret = left;
  17392. left = NULL;
  17393. break;
  17394. case TAKalldenormalizegroup:
  17395. filteredRight.kill();
  17396. ret = denormalizeRecords(left, filteredRight, JTFmatchedleft);
  17397. break;
  17398. default:
  17399. throwUnexpected();
  17400. }
  17401. }
  17402. rightIndex = 0;
  17403. joinCounter = 0;
  17404. ReleaseRoxieRow(left);
  17405. left = NULL;
  17406. if(ret)
  17407. {
  17408. matchedGroup = true;
  17409. processed++;
  17410. return ret;
  17411. }
  17412. }
  17413. if(!left)
  17414. {
  17415. left = inputStream->nextRow();
  17416. matchedLeft = false;
  17417. countForLeft = keepLimit;
  17418. joinCounter = 0;
  17419. }
  17420. if(!left)
  17421. {
  17422. if(eog)
  17423. {
  17424. eos = true;
  17425. matchedGroup = false;
  17426. return NULL;
  17427. }
  17428. eog = true;
  17429. if (matchedGroup && leftIsGrouped)
  17430. {
  17431. matchedGroup = false;
  17432. return NULL;
  17433. }
  17434. matchedGroup = false;
  17435. continue;
  17436. }
  17437. eog = false;
  17438. switch(activityKind)
  17439. {
  17440. case TAKalljoin:
  17441. while(rightIndex < rightOrdinality)
  17442. {
  17443. right = rightset.item(rightIndex);
  17444. if(helper.match(left, right))
  17445. {
  17446. matchedLeft = true;
  17447. matchedRight.replace(true, rightIndex);
  17448. if(!exclude)
  17449. ret = joinRecords(left, right, ++joinCounter, JTFmatchedleft|JTFmatchedright);
  17450. }
  17451. rightIndex++;
  17452. if(ret)
  17453. {
  17454. countForLeft--;
  17455. matchedGroup = true;
  17456. processed++;
  17457. return ret;
  17458. }
  17459. }
  17460. break;
  17461. case TAKalldenormalize:
  17462. {
  17463. OwnedConstRoxieRow newLeft;
  17464. newLeft.set(left);
  17465. unsigned rowSize = 0;
  17466. unsigned leftCount = 0;
  17467. while((rightIndex < rightOrdinality) && countForLeft)
  17468. {
  17469. right = rightset.item(rightIndex);
  17470. if(helper.match(left, right))
  17471. {
  17472. matchedLeft = true;
  17473. matchedRight.replace(true, rightIndex);
  17474. if(!exclude)
  17475. {
  17476. try
  17477. {
  17478. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17479. unsigned thisSize = helper.transform(rowBuilder, newLeft, right, ++leftCount, JTFmatchedleft|JTFmatchedright);
  17480. if(thisSize)
  17481. {
  17482. rowSize = thisSize;
  17483. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  17484. --countForLeft;
  17485. }
  17486. }
  17487. catch (IException *e)
  17488. {
  17489. throw makeWrappedException(e);
  17490. }
  17491. }
  17492. }
  17493. rightIndex++;
  17494. }
  17495. if(rowSize)
  17496. {
  17497. processed++;
  17498. return newLeft.getClear();
  17499. }
  17500. }
  17501. break;
  17502. case TAKalldenormalizegroup:
  17503. filteredRight.kill();
  17504. while((rightIndex < rightOrdinality) && countForLeft)
  17505. {
  17506. right = rightset.item(rightIndex);
  17507. if(helper.match(left, right))
  17508. {
  17509. matchedLeft = true;
  17510. matchedRight.replace(true, rightIndex);
  17511. filteredRight.append(right);
  17512. --countForLeft;
  17513. }
  17514. ++rightIndex;
  17515. }
  17516. if(!exclude && filteredRight.ordinality())
  17517. {
  17518. ret = denormalizeRecords(left, filteredRight, JTFmatchedleft);
  17519. filteredRight.kill();
  17520. if(ret)
  17521. {
  17522. processed++;
  17523. return ret;
  17524. }
  17525. }
  17526. break;
  17527. default:
  17528. throwUnexpected();
  17529. }
  17530. }
  17531. }
  17532. };
  17533. class CRoxieServerAllJoinActivityFactory : public CRoxieServerJoinActivityFactory
  17534. {
  17535. public:
  17536. CRoxieServerAllJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17537. : CRoxieServerJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  17538. {
  17539. Owned<IHThorAllJoinArg> helper = (IHThorAllJoinArg *) helperFactory();
  17540. if((helper->getJoinFlags() & (JFfirst | JFfirstleft | JFfirstright)) != 0)
  17541. throw MakeStringException(ROXIE_INVALID_FLAGS, "Invalid flags for join all activity"); // code generator should never create such an activity
  17542. }
  17543. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  17544. {
  17545. return new CRoxieServerAllJoinActivity(_ctx, this, _probeManager);
  17546. }
  17547. virtual const StatisticsMapping &queryStatsMapping() const
  17548. {
  17549. return joinStatistics;
  17550. }
  17551. };
  17552. IRoxieServerActivityFactory *createRoxieServerAllJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17553. {
  17554. return new CRoxieServerAllJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  17555. }
  17556. //=====================================================================================================
  17557. class CRoxieServerTopNActivity : public CRoxieServerLateStartActivity
  17558. {
  17559. unsigned limit;
  17560. bool hasBest;
  17561. bool eoi;
  17562. const void **sorted;
  17563. unsigned sortedCount;
  17564. unsigned curIndex;
  17565. IHThorTopNArg &helper;
  17566. ICompare &compare;
  17567. public:
  17568. CRoxieServerTopNActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17569. : CRoxieServerLateStartActivity(_ctx, _factory, _probeManager), helper((IHThorTopNArg &)basehelper), compare(*helper.queryCompare())
  17570. {
  17571. sorted = NULL;
  17572. sortedCount = 0;
  17573. curIndex = 0;
  17574. limit = 0;
  17575. eoi = false;
  17576. hasBest = false;
  17577. }
  17578. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17579. {
  17580. assertex(sorted == NULL);
  17581. sortedCount = 0;
  17582. curIndex = 0;
  17583. eoi = false;
  17584. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  17585. limit = (unsigned) helper.getLimit();
  17586. hasBest = helper.hasBest();
  17587. lateStart(parentExtractSize, parentExtract, limit > 0);
  17588. // MORE - should we use an expanding array instead?
  17589. if (limit > 0)
  17590. sorted = (const void **) ctx->queryRowManager().allocate((limit+1) * sizeof(const void *), activityId);
  17591. }
  17592. virtual void reset()
  17593. {
  17594. if (sorted)
  17595. {
  17596. roxiemem::ReleaseRoxieRowRange(sorted, curIndex, sortedCount);
  17597. curIndex = 0;
  17598. sortedCount = 0;
  17599. ReleaseRoxieRow(sorted);
  17600. sorted = NULL;
  17601. }
  17602. CRoxieServerLateStartActivity::reset();
  17603. }
  17604. bool abortEarly()
  17605. {
  17606. if (hasBest && (sortedCount == limit))
  17607. {
  17608. int compare = helper.compareBest(sorted[sortedCount-1]);
  17609. if (compare == 0)
  17610. {
  17611. if (meta.isGrouped())
  17612. {
  17613. //MORE: This would be more efficient if we had a away of skipping to the end of the incoming group.
  17614. const void * next;
  17615. while ((next = inputStream->nextRow()) != NULL)
  17616. ReleaseRoxieRow(next);
  17617. }
  17618. else
  17619. eoi = true;
  17620. return true;
  17621. }
  17622. //This only checks the lowest element - we could check all elements inserted, but it would increase the number of compares
  17623. if (compare < 0)
  17624. throw MakeStringException(ROXIE_TOPN_ROW_ERROR, "TOPN: row found that exceeds the best value");
  17625. }
  17626. return false;
  17627. }
  17628. void getSorted()
  17629. {
  17630. curIndex = 0;
  17631. sortedCount = 0;
  17632. if(eoi)
  17633. return;
  17634. const void * next;
  17635. while ((next = inputStream->nextRow()) != NULL)
  17636. {
  17637. if (sortedCount < limit)
  17638. {
  17639. binary_vec_insert_stable(next, sorted, sortedCount, compare);
  17640. sortedCount++;
  17641. if(abortEarly())
  17642. return;
  17643. }
  17644. else
  17645. {
  17646. if(limit && compare.docompare(sorted[sortedCount-1], next) > 0) // MORE - if stability is an issue, need to consider whether this should be > or >=
  17647. {
  17648. binary_vec_insert_stable(next, sorted, sortedCount, compare); // MORE - not sure this is stable!
  17649. ReleaseRoxieRow(sorted[sortedCount]);
  17650. if(abortEarly())
  17651. return;
  17652. }
  17653. else
  17654. {
  17655. ReleaseRoxieRow(next); // do not bother with insertion sort if we know next will fall off the end
  17656. }
  17657. }
  17658. }
  17659. }
  17660. virtual const void * nextRow()
  17661. {
  17662. ActivityTimer t(totalCycles, timeActivities);
  17663. if (eof)
  17664. return NULL;
  17665. if (curIndex >= sortedCount)
  17666. {
  17667. bool eog = sortedCount != 0;
  17668. getSorted();
  17669. if(sortedCount == 0)
  17670. {
  17671. eof = true;
  17672. return NULL;
  17673. }
  17674. if (eog)
  17675. return NULL;
  17676. }
  17677. processed++;
  17678. return sorted[curIndex++];
  17679. }
  17680. };
  17681. class CRoxieServerTopNActivityFactory : public CRoxieServerActivityFactory
  17682. {
  17683. public:
  17684. CRoxieServerTopNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17685. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  17686. {
  17687. }
  17688. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  17689. {
  17690. return new CRoxieServerTopNActivity(_ctx, this, _probeManager);
  17691. }
  17692. };
  17693. IRoxieServerActivityFactory *createRoxieServerTopNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17694. {
  17695. return new CRoxieServerTopNActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  17696. }
  17697. //=================================================================================
  17698. class CRoxieServerLimitActivity : public CRoxieServerActivity
  17699. {
  17700. protected:
  17701. unsigned __int64 rowLimit;
  17702. IHThorLimitArg &helper;
  17703. public:
  17704. CRoxieServerLimitActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17705. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorLimitArg &)basehelper)
  17706. {
  17707. rowLimit = 0;
  17708. }
  17709. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17710. {
  17711. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  17712. rowLimit = helper.getRowLimit(); // could conceivably depend on context so should not compute any earlier than this
  17713. }
  17714. virtual const void *nextRow()
  17715. {
  17716. ActivityTimer t(totalCycles, timeActivities);
  17717. const void * ret = inputStream->nextRow();
  17718. if (ret)
  17719. {
  17720. processed++;
  17721. if (processed > rowLimit)
  17722. {
  17723. ReleaseRoxieRow(ret);
  17724. if (traceLevel > 4)
  17725. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  17726. helper.onLimitExceeded();
  17727. }
  17728. }
  17729. return ret;
  17730. }
  17731. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  17732. {
  17733. ActivityTimer t(totalCycles, timeActivities);
  17734. const void * ret = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  17735. if (ret)
  17736. {
  17737. if (wasCompleteMatch)
  17738. processed++;
  17739. if (processed > rowLimit)
  17740. {
  17741. ReleaseRoxieRow(ret);
  17742. if (traceLevel > 4)
  17743. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  17744. helper.onLimitExceeded();
  17745. }
  17746. }
  17747. return ret;
  17748. }
  17749. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  17750. {
  17751. return input->gatherConjunctions(collector);
  17752. }
  17753. virtual void resetEOF()
  17754. {
  17755. //Do not reset the rowLimit
  17756. inputStream->resetEOF();
  17757. }
  17758. IInputSteppingMeta * querySteppingMeta()
  17759. {
  17760. return input->querySteppingMeta();
  17761. }
  17762. };
  17763. class CRoxieServerLimitActivityFactory : public CRoxieServerActivityFactory
  17764. {
  17765. public:
  17766. CRoxieServerLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17767. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  17768. {
  17769. }
  17770. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  17771. {
  17772. return new CRoxieServerLimitActivity(_ctx, this, _probeManager);
  17773. }
  17774. };
  17775. IRoxieServerActivityFactory *createRoxieServerLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17776. {
  17777. return new CRoxieServerLimitActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  17778. }
  17779. //=====================================================================================================
  17780. class CRoxieServerSkipLimitActivity : public CRoxieServerLimitActivity
  17781. {
  17782. ConstPointerArray buff;
  17783. bool started = false;
  17784. unsigned index = 0;
  17785. bool isFail = false;
  17786. public:
  17787. CRoxieServerSkipLimitActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _onFail)
  17788. : CRoxieServerLimitActivity(_ctx, _factory, _probeManager)
  17789. {
  17790. started = false;
  17791. index = 0;
  17792. isFail = _onFail;
  17793. }
  17794. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17795. {
  17796. started = false;
  17797. index = 0;
  17798. CRoxieServerLimitActivity::start(parentExtractSize, parentExtract, paused);
  17799. }
  17800. virtual void reset()
  17801. {
  17802. roxiemem::ReleaseRoxieRowRange(buff.getArray(), index, buff.ordinality());
  17803. buff.kill();
  17804. index = 0;
  17805. started = false;
  17806. CRoxieServerLimitActivity::reset();
  17807. }
  17808. virtual const void *nextRow()
  17809. {
  17810. ActivityTimer t(totalCycles, timeActivities);
  17811. if (!started)
  17812. pullInput();
  17813. if (buff.isItem(index))
  17814. {
  17815. const void * next = buff.item(index++);
  17816. if(next)
  17817. processed++;
  17818. return next;
  17819. }
  17820. return NULL;
  17821. }
  17822. protected:
  17823. void pullInput()
  17824. {
  17825. unsigned count = 0;
  17826. for (;;)
  17827. {
  17828. const void * next = inputStream->nextRow();
  17829. if (next == NULL)
  17830. {
  17831. next = inputStream->nextRow();
  17832. if(next == NULL)
  17833. break;
  17834. buff.append(NULL);
  17835. }
  17836. count++;
  17837. if (count > rowLimit)
  17838. {
  17839. ReleaseRoxieRow(next);
  17840. ReleaseRoxieRows(buff);
  17841. if (ctx->queryDebugContext())
  17842. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  17843. if (isFail)
  17844. {
  17845. ensureRowAllocator();
  17846. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17847. size32_t outSize = helper.transformOnLimitExceeded(rowBuilder);
  17848. if (outSize)
  17849. buff.append(rowBuilder.finalizeRowClear(outSize));
  17850. }
  17851. break;
  17852. }
  17853. buff.append(next);
  17854. }
  17855. started = true;
  17856. }
  17857. };
  17858. class CRoxieServerSkipLimitActivityFactory : public CRoxieServerActivityFactory
  17859. {
  17860. public:
  17861. CRoxieServerSkipLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17862. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  17863. {
  17864. }
  17865. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  17866. {
  17867. return new CRoxieServerSkipLimitActivity(_ctx, this, _probeManager, kind==TAKcreaterowlimit);
  17868. }
  17869. };
  17870. IRoxieServerActivityFactory *createRoxieServerSkipLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17871. {
  17872. return new CRoxieServerSkipLimitActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  17873. }
  17874. //=================================================================================
  17875. class CRoxieServerCatchActivity : public CRoxieServerActivity
  17876. {
  17877. IHThorCatchArg &helper;
  17878. public:
  17879. CRoxieServerCatchActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17880. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorCatchArg &)basehelper)
  17881. {
  17882. }
  17883. virtual const void *nextRow()
  17884. {
  17885. ActivityTimer t(totalCycles, timeActivities);
  17886. try
  17887. {
  17888. const void *ret = inputStream->nextRow();
  17889. if (ret)
  17890. processed++;
  17891. return ret;
  17892. }
  17893. catch (IException *E)
  17894. {
  17895. E->Release();
  17896. helper.onExceptionCaught();
  17897. }
  17898. catch (...)
  17899. {
  17900. helper.onExceptionCaught();
  17901. }
  17902. throwUnexpected(); // onExceptionCaught should have thrown something
  17903. }
  17904. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  17905. {
  17906. try
  17907. {
  17908. ActivityTimer t(totalCycles, timeActivities);
  17909. const void * ret = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  17910. if (ret && wasCompleteMatch)
  17911. processed++;
  17912. return ret;
  17913. }
  17914. catch (IException *E)
  17915. {
  17916. E->Release();
  17917. helper.onExceptionCaught();
  17918. }
  17919. catch (...)
  17920. {
  17921. helper.onExceptionCaught();
  17922. }
  17923. throwUnexpected(); // onExceptionCaught should have thrown something
  17924. }
  17925. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  17926. {
  17927. return input->gatherConjunctions(collector);
  17928. }
  17929. virtual void resetEOF()
  17930. {
  17931. inputStream->resetEOF(); // MORE - why not in base class?
  17932. }
  17933. IInputSteppingMeta * querySteppingMeta()
  17934. {
  17935. return input->querySteppingMeta();
  17936. }
  17937. };
  17938. class CRoxieServerSkipCatchActivity : public CRoxieServerActivity
  17939. {
  17940. ConstPointerArray buff;
  17941. bool started;
  17942. unsigned index;
  17943. IHThorCatchArg &helper;
  17944. bool createRow;
  17945. public:
  17946. CRoxieServerSkipCatchActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _createRow)
  17947. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorCatchArg &)basehelper), createRow(_createRow)
  17948. {
  17949. started = false;
  17950. index = 0;
  17951. }
  17952. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17953. {
  17954. started = false;
  17955. index = 0;
  17956. try
  17957. {
  17958. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  17959. }
  17960. catch (IException *E)
  17961. {
  17962. onException(E);
  17963. started = true;
  17964. }
  17965. catch (...)
  17966. {
  17967. onException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught"));
  17968. started = true;
  17969. }
  17970. }
  17971. virtual void reset()
  17972. {
  17973. roxiemem::ReleaseRoxieRowRange(buff.getArray(), index, buff.ordinality());
  17974. buff.kill();
  17975. index = 0;
  17976. started = false;
  17977. CRoxieServerActivity::reset();
  17978. }
  17979. virtual const void *nextRow()
  17980. {
  17981. ActivityTimer t(totalCycles, timeActivities);
  17982. if (!started)
  17983. pullInput();
  17984. if (buff.isItem(index))
  17985. {
  17986. const void * next = buff.item(index++);
  17987. if(next)
  17988. processed++;
  17989. return next;
  17990. }
  17991. return NULL;
  17992. }
  17993. protected:
  17994. void onException(IException *E)
  17995. {
  17996. inputStream->stop();
  17997. ReleaseRoxieRows(buff);
  17998. if (createRow)
  17999. {
  18000. ensureRowAllocator();
  18001. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  18002. size32_t outSize = helper.transformOnExceptionCaught(rowBuilder, E);
  18003. if (outSize)
  18004. buff.append(rowBuilder.finalizeRowClear(outSize));
  18005. }
  18006. E->Release();
  18007. }
  18008. void pullInput()
  18009. {
  18010. try
  18011. {
  18012. bool EOGseen = false;
  18013. for (;;)
  18014. {
  18015. const void * next = inputStream->nextRow();
  18016. buff.append(next);
  18017. if (next == NULL)
  18018. {
  18019. if (EOGseen)
  18020. break;
  18021. EOGseen = true;
  18022. }
  18023. else
  18024. EOGseen = false;
  18025. }
  18026. }
  18027. catch (IException *E)
  18028. {
  18029. onException(E);
  18030. }
  18031. catch (...)
  18032. {
  18033. onException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught"));
  18034. }
  18035. started = true;
  18036. }
  18037. };
  18038. class CRoxieServerCatchActivityFactory : public CRoxieServerActivityFactory
  18039. {
  18040. public:
  18041. CRoxieServerCatchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  18042. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  18043. {
  18044. }
  18045. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18046. {
  18047. switch (kind)
  18048. {
  18049. case TAKcatch:
  18050. return new CRoxieServerCatchActivity(_ctx, this, _probeManager);
  18051. case TAKskipcatch:
  18052. return new CRoxieServerSkipCatchActivity(_ctx, this, _probeManager, false);
  18053. case TAKcreaterowcatch:
  18054. return new CRoxieServerSkipCatchActivity(_ctx, this, _probeManager, true);
  18055. default:
  18056. throwUnexpected();
  18057. }
  18058. }
  18059. };
  18060. IRoxieServerActivityFactory *createRoxieServerCatchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  18061. {
  18062. return new CRoxieServerCatchActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  18063. }
  18064. //=================================================================================
  18065. class CRoxieServerPullActivity : public CRoxieServerActivity
  18066. {
  18067. ConstPointerArray buff;
  18068. bool started;
  18069. unsigned index;
  18070. public:
  18071. CRoxieServerPullActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18072. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  18073. {
  18074. started = false;
  18075. index = 0;
  18076. }
  18077. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18078. {
  18079. started = false;
  18080. index = 0;
  18081. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  18082. }
  18083. virtual void reset()
  18084. {
  18085. while (buff.isItem(index))
  18086. ReleaseRoxieRow(buff.item(index++));
  18087. buff.kill();
  18088. started = false;
  18089. index = 0;
  18090. CRoxieServerActivity::reset();
  18091. }
  18092. virtual const void *nextRow()
  18093. {
  18094. ActivityTimer t(totalCycles, timeActivities);
  18095. if (!started)
  18096. pullInput();
  18097. if (buff.isItem(index))
  18098. {
  18099. const void * next = buff.item(index++);
  18100. if (next)
  18101. processed++;
  18102. return next;
  18103. }
  18104. return NULL;
  18105. }
  18106. protected:
  18107. void pullInput()
  18108. {
  18109. bool EOGseen = false;
  18110. for (;;)
  18111. {
  18112. const void * next = inputStream->nextRow();
  18113. buff.append(next);
  18114. if (next == NULL)
  18115. {
  18116. if (EOGseen)
  18117. break;
  18118. EOGseen = true;
  18119. }
  18120. else
  18121. EOGseen = false;
  18122. }
  18123. started = true;
  18124. }
  18125. };
  18126. class CRoxieServerPullActivityFactory : public CRoxieServerActivityFactory
  18127. {
  18128. public:
  18129. CRoxieServerPullActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  18130. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  18131. {
  18132. }
  18133. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18134. {
  18135. return new CRoxieServerPullActivity(_ctx, this, _probeManager);
  18136. }
  18137. };
  18138. IRoxieServerActivityFactory *createRoxieServerPullActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  18139. {
  18140. return new CRoxieServerPullActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  18141. }
  18142. //=================================================================================
  18143. class CRoxieServerTraceActivity : public CRoxieServerActivity
  18144. {
  18145. public:
  18146. CRoxieServerTraceActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18147. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorTraceArg &) basehelper),
  18148. keepLimit(0), skip(0), sample(0)
  18149. {
  18150. assertex(meta.hasXML());
  18151. traceEnabled = defaultTraceEnabled && !isBlind();
  18152. }
  18153. virtual void onCreate(IHThorArg *_colocalParent)
  18154. {
  18155. CRoxieServerActivity::onCreate(_colocalParent);
  18156. if (ctx)
  18157. traceEnabled = ctx->queryOptions().traceEnabled && !isBlind();
  18158. }
  18159. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18160. {
  18161. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  18162. if (traceEnabled && helper.canMatchAny())
  18163. {
  18164. keepLimit = helper.getKeepLimit();
  18165. if (keepLimit==(unsigned) -1)
  18166. keepLimit = ctx->queryOptions().traceLimit;
  18167. skip = helper.getSkip();
  18168. sample = helper.getSample();
  18169. if (sample)
  18170. sample--;
  18171. name.setown(helper.getName());
  18172. if (!name)
  18173. name.set("Row");
  18174. }
  18175. else
  18176. keepLimit = 0;
  18177. }
  18178. virtual void stop()
  18179. {
  18180. name.clear();
  18181. CRoxieServerActivity::stop();
  18182. }
  18183. virtual bool isPassThrough()
  18184. {
  18185. return true;
  18186. }
  18187. virtual const void *nextRow()
  18188. {
  18189. ActivityTimer t(totalCycles, timeActivities);
  18190. const void *row = inputStream->nextRow();
  18191. if (row)
  18192. {
  18193. onTrace(row);
  18194. processed++;
  18195. }
  18196. return row;
  18197. }
  18198. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  18199. {
  18200. // MORE - will need rethinking once we rethink the nextRowGE interface for global smart-stepping.
  18201. ActivityTimer t(totalCycles, timeActivities);
  18202. const void * row = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  18203. if (row)
  18204. {
  18205. onTrace(row);
  18206. processed++;
  18207. }
  18208. return row;
  18209. }
  18210. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  18211. {
  18212. return input->gatherConjunctions(collector);
  18213. }
  18214. virtual void resetEOF()
  18215. {
  18216. inputStream->resetEOF();
  18217. }
  18218. IInputSteppingMeta * querySteppingMeta()
  18219. {
  18220. return input->querySteppingMeta();
  18221. }
  18222. protected:
  18223. void onTrace(const void *row)
  18224. {
  18225. if (keepLimit && helper.isValid(row))
  18226. {
  18227. if (skip)
  18228. skip--;
  18229. else if (sample)
  18230. sample--;
  18231. else
  18232. {
  18233. CommonXmlWriter xmlwrite(XWFnoindent);
  18234. meta.toXML((const byte *) row, xmlwrite);
  18235. CTXLOG("TRACE: <%s>%s<%s>", name.get(), xmlwrite.str(), name.get());
  18236. keepLimit--;
  18237. sample = helper.getSample();
  18238. if (sample)
  18239. sample--;
  18240. }
  18241. }
  18242. }
  18243. OwnedRoxieString name;
  18244. IHThorTraceArg &helper;
  18245. unsigned keepLimit;
  18246. unsigned skip;
  18247. unsigned sample;
  18248. bool traceEnabled;
  18249. };
  18250. class CRoxieServerTraceActivityFactory : public CRoxieServerActivityFactory
  18251. {
  18252. public:
  18253. CRoxieServerTraceActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  18254. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  18255. {
  18256. }
  18257. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18258. {
  18259. return new CRoxieServerTraceActivity(_ctx, this, _probeManager);
  18260. }
  18261. };
  18262. IRoxieServerActivityFactory *createRoxieServerTraceActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  18263. {
  18264. return new CRoxieServerTraceActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  18265. }
  18266. //=================================================================================
  18267. class CRoxieServerCaseActivity : public CRoxieServerMultiInputBaseActivity
  18268. {
  18269. IHThorCaseArg &helper;
  18270. unsigned cond;
  18271. bool unusedStopped;
  18272. IEngineRowStream *active;
  18273. public:
  18274. CRoxieServerCaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  18275. : CRoxieServerMultiInputBaseActivity(_ctx, _factory, _probeManager, _numInputs), helper((IHThorCaseArg &)basehelper)
  18276. {
  18277. unusedStopped = false;
  18278. cond = 0;
  18279. active = NULL;
  18280. }
  18281. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18282. {
  18283. CRoxieServerMultiInputBaseActivity::start(parentExtractSize, parentExtract, paused);
  18284. cond = helper.getBranch();
  18285. //CHOOSE defaults to the last argument if out of range.
  18286. if (cond >= numInputs)
  18287. cond = numInputs - 1;
  18288. inputArray[cond]->start(parentExtractSize, parentExtract, paused);
  18289. startJunction(junctionArray[cond]);
  18290. assertex(numInputs==numStreams);
  18291. for (unsigned idx = 0; idx < numStreams; idx++)
  18292. {
  18293. if (idx!=cond)
  18294. streamArray[idx]->stop(); // Note: stopping unused branches early helps us avoid buffering splits too long.
  18295. }
  18296. active = streamArray[cond];
  18297. unusedStopped = true;
  18298. }
  18299. virtual void stop()
  18300. {
  18301. for (unsigned idx = 0; idx < numStreams; idx++)
  18302. {
  18303. if (idx==cond || !unusedStopped)
  18304. streamArray[idx]->stop();
  18305. }
  18306. CRoxieServerMultiInputBaseActivity::stop();
  18307. }
  18308. virtual void reset()
  18309. {
  18310. unusedStopped = false;
  18311. active = NULL;
  18312. CRoxieServerMultiInputBaseActivity::reset();
  18313. }
  18314. virtual const void *nextRow()
  18315. {
  18316. ActivityTimer t(totalCycles, timeActivities);
  18317. if (active)
  18318. {
  18319. const void *ret = active->nextRow();
  18320. if (ret)
  18321. processed++;
  18322. return ret;
  18323. }
  18324. return NULL;
  18325. }
  18326. };
  18327. class CRoxieServerCaseActivityFactory : public CRoxieServerMultiInputFactory
  18328. {
  18329. bool graphInvariant;
  18330. public:
  18331. CRoxieServerCaseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _graphInvariant)
  18332. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  18333. {
  18334. graphInvariant = _graphInvariant;
  18335. }
  18336. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18337. {
  18338. return new CRoxieServerCaseActivity(_ctx, this, _probeManager, numInputs());
  18339. }
  18340. virtual bool isGraphInvariant() const
  18341. {
  18342. return graphInvariant;
  18343. }
  18344. };
  18345. IRoxieServerActivityFactory *createRoxieServerCaseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _graphInvariant)
  18346. {
  18347. return new CRoxieServerCaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _graphInvariant);
  18348. }
  18349. //=================================================================================
  18350. class CRoxieServerIfActivity : public CRoxieServerActivity
  18351. {
  18352. IHThorIfArg &helper;
  18353. IFinalRoxieInput *inputTrue;
  18354. IFinalRoxieInput *inputFalse;
  18355. IEngineRowStream *streamTrue;
  18356. IEngineRowStream *streamFalse;
  18357. unsigned sourceIdxFalse = 0;
  18358. unsigned sourceIdxTrue = 0;
  18359. Owned<IStrandJunction> junctionTrue;
  18360. Owned<IStrandJunction> junctionFalse;
  18361. bool cond;
  18362. bool unusedStopped;
  18363. public:
  18364. CRoxieServerIfActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18365. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorIfArg &)basehelper)
  18366. {
  18367. inputFalse = NULL;
  18368. inputTrue = NULL;
  18369. streamTrue = NULL;
  18370. streamFalse = NULL;
  18371. unusedStopped = false;
  18372. cond = false;
  18373. }
  18374. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18375. {
  18376. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  18377. cond = helper.getCondition();
  18378. if (cond)
  18379. {
  18380. inputTrue->start(parentExtractSize, parentExtract, paused);
  18381. startJunction(junctionTrue);
  18382. if (streamFalse)
  18383. streamFalse->stop(); // Note: stopping unused branches early helps us avoid buffering splits too long.
  18384. }
  18385. else
  18386. {
  18387. if (inputFalse)
  18388. {
  18389. inputFalse->start(parentExtractSize, parentExtract, paused);
  18390. startJunction(junctionFalse);
  18391. }
  18392. streamTrue->stop();
  18393. }
  18394. unusedStopped = true;
  18395. }
  18396. virtual void stop()
  18397. {
  18398. if (!unusedStopped || cond)
  18399. streamTrue->stop();
  18400. if (streamFalse && (!unusedStopped || !cond))
  18401. streamFalse->stop();
  18402. CRoxieServerActivity::stop();
  18403. }
  18404. virtual unsigned __int64 queryLocalCycles() const
  18405. {
  18406. __int64 localCycles = totalCycles.totalCycles;
  18407. localCycles -= inputTrue->queryTotalCycles();
  18408. if (inputFalse)
  18409. localCycles -= inputFalse->queryTotalCycles();
  18410. if (localCycles < 0)
  18411. localCycles = 0;
  18412. return localCycles;
  18413. }
  18414. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  18415. {
  18416. switch (idx)
  18417. {
  18418. case 0:
  18419. return inputTrue;
  18420. case 1:
  18421. return inputFalse;
  18422. default:
  18423. return NULL;
  18424. }
  18425. }
  18426. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { return this; }
  18427. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { return nullptr; }
  18428. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  18429. {
  18430. IFinalRoxieInput *in = cond ? inputTrue : inputFalse;
  18431. if (in)
  18432. return in->queryIndexReadActivity();
  18433. return NULL;
  18434. }
  18435. virtual void reset()
  18436. {
  18437. CRoxieServerActivity::reset();
  18438. inputTrue->reset();
  18439. if (inputFalse)
  18440. inputFalse->reset();
  18441. resetJunction(junctionTrue);
  18442. resetJunction(junctionFalse);
  18443. unusedStopped = false;
  18444. }
  18445. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  18446. {
  18447. if (idx==1)
  18448. {
  18449. inputFalse = _in;
  18450. sourceIdxFalse = _sourceIdx;
  18451. }
  18452. else
  18453. {
  18454. assertex(!idx);
  18455. inputTrue = _in;
  18456. sourceIdxTrue = _sourceIdx;
  18457. }
  18458. }
  18459. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  18460. {
  18461. //It should be possible to stream IF(), but the number of strands would need to match on the two branches.
  18462. streamTrue = connectSingleStream(ctx, inputTrue, sourceIdxTrue, junctionTrue, consumerOrdered);
  18463. streamFalse = connectSingleStream(ctx, inputFalse, sourceIdxFalse, junctionFalse, consumerOrdered);
  18464. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, nullptr, consumerOrdered, nullptr);
  18465. }
  18466. virtual const void *nextRow()
  18467. {
  18468. ActivityTimer t(totalCycles, timeActivities);
  18469. IEngineRowStream *in = cond ? streamTrue : streamFalse;
  18470. if (in)
  18471. {
  18472. const void * ret;
  18473. if ((ret = in->nextRow()) != NULL)
  18474. processed++;
  18475. return ret;
  18476. }
  18477. return NULL;
  18478. }
  18479. };
  18480. class CRoxieServerIfActivityFactory : public CRoxieServerActivityFactory
  18481. {
  18482. unsigned input2;
  18483. unsigned input2idx;
  18484. bool graphInvariant;
  18485. public:
  18486. CRoxieServerIfActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _graphInvariant)
  18487. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  18488. {
  18489. graphInvariant = _graphInvariant;
  18490. input2 = (unsigned)-1;
  18491. input2idx = (unsigned)-1;
  18492. }
  18493. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18494. {
  18495. return new CRoxieServerIfActivity(_ctx, this, _probeManager);
  18496. }
  18497. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  18498. {
  18499. if (idx==1)
  18500. {
  18501. input2 = source;
  18502. input2idx = sourceidx;
  18503. }
  18504. else
  18505. CRoxieServerActivityFactory::setInput(idx, source, sourceidx);
  18506. }
  18507. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  18508. {
  18509. switch (idx)
  18510. {
  18511. case 1:
  18512. sourceidx = input2idx;
  18513. return input2;
  18514. case 0:
  18515. return CRoxieServerActivityFactory::getInput(idx, sourceidx);
  18516. default:
  18517. return (unsigned) -1;
  18518. }
  18519. }
  18520. virtual unsigned numInputs() const { return (input2 == (unsigned)-1) ? 1 : 2; }
  18521. virtual bool isGraphInvariant() const
  18522. {
  18523. return graphInvariant;
  18524. }
  18525. };
  18526. IRoxieServerActivityFactory *createRoxieServerIfActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _graphInvariant)
  18527. {
  18528. return new CRoxieServerIfActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _graphInvariant);
  18529. }
  18530. //=================================================================================
  18531. class CRoxieServerActionBaseActivity : public CRoxieServerActivity
  18532. {
  18533. CriticalSection ecrit;
  18534. Owned<IException> exception;
  18535. bool executed;
  18536. public:
  18537. CRoxieServerActionBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18538. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  18539. {
  18540. executed = false;
  18541. }
  18542. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract) = 0;
  18543. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  18544. {
  18545. CriticalBlock b(ecrit);
  18546. if (exception)
  18547. throw(exception.getLink());
  18548. if (!executed)
  18549. {
  18550. try
  18551. {
  18552. executed = true;
  18553. start(parentExtractSize, parentExtract, false);
  18554. doExecuteAction(parentExtractSize, parentExtract);
  18555. stop();
  18556. }
  18557. catch (IException * E)
  18558. {
  18559. ctx->notifyAbort(E);
  18560. abort();
  18561. exception.set(E);
  18562. throw;
  18563. }
  18564. }
  18565. }
  18566. virtual void reset()
  18567. {
  18568. executed = false;
  18569. exception.clear();
  18570. CRoxieServerActivity::reset();
  18571. }
  18572. virtual const void *nextRow()
  18573. {
  18574. throwUnexpected(); // I am nobody's input
  18575. }
  18576. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  18577. {
  18578. return NULL;
  18579. }
  18580. };
  18581. class CRoxieServerIfActionActivity : public CRoxieServerActionBaseActivity
  18582. {
  18583. IHThorIfArg &helper;
  18584. public:
  18585. CRoxieServerIfActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18586. : CRoxieServerActionBaseActivity(_ctx, _factory, _probeManager), helper((IHThorIfArg &)basehelper)
  18587. {
  18588. }
  18589. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  18590. {
  18591. bool cond;
  18592. {
  18593. ActivityTimer t(totalCycles, timeActivities);
  18594. cond = helper.getCondition();
  18595. }
  18596. stopDependencies(parentExtractSize, parentExtract, cond ? 2 : 1);
  18597. executeDependencies(parentExtractSize, parentExtract, cond ? 1 : 2);
  18598. }
  18599. };
  18600. class CRoxieServerIfActionActivityFactory : public CRoxieServerActivityFactory
  18601. {
  18602. bool isRoot;
  18603. public:
  18604. CRoxieServerIfActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18605. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  18606. {
  18607. }
  18608. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18609. {
  18610. return new CRoxieServerIfActionActivity(_ctx, this, _probeManager);
  18611. }
  18612. virtual bool isSink() const
  18613. {
  18614. return isRoot;
  18615. }
  18616. };
  18617. IRoxieServerActivityFactory *createRoxieServerIfActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18618. {
  18619. return new CRoxieServerIfActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  18620. }
  18621. //=================================================================================
  18622. class CRoxieServerParallelActionActivity : public CRoxieServerActionBaseActivity
  18623. {
  18624. public:
  18625. CRoxieServerParallelActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18626. : CRoxieServerActionBaseActivity(_ctx, _factory, _probeManager)
  18627. {
  18628. }
  18629. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  18630. {
  18631. #ifdef PARALLEL_EXECUTE
  18632. CParallelActivityExecutor afor(dependencies, parentExtractSize, parentExtract);
  18633. afor.For(dependencies.ordinality(), dependencies.ordinality(), true);
  18634. #else
  18635. ForEachItemIn(idx, dependencies)
  18636. {
  18637. dependencies.item(idx).execute(parentExtractSize, parentExtract);
  18638. }
  18639. #endif
  18640. }
  18641. };
  18642. class CRoxieServerParallelActionActivityFactory : public CRoxieServerActivityFactory
  18643. {
  18644. bool isRoot;
  18645. public:
  18646. CRoxieServerParallelActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18647. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  18648. {
  18649. assertex(!isRoot); // non-internal should be expanded out..
  18650. }
  18651. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18652. {
  18653. return new CRoxieServerParallelActionActivity(_ctx, this, _probeManager);
  18654. }
  18655. virtual bool isSink() const
  18656. {
  18657. return isRoot;
  18658. }
  18659. };
  18660. IRoxieServerActivityFactory *createRoxieServerParallelActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18661. {
  18662. return new CRoxieServerParallelActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  18663. }
  18664. //=================================================================================
  18665. class CRoxieServerSequentialActionActivity : public CRoxieServerActionBaseActivity
  18666. {
  18667. IHThorSequentialArg &helper;
  18668. public:
  18669. CRoxieServerSequentialActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18670. : CRoxieServerActionBaseActivity(_ctx, _factory, _probeManager), helper((IHThorSequentialArg &)basehelper)
  18671. {
  18672. }
  18673. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  18674. {
  18675. unsigned numBranches = helper.numBranches();
  18676. for (unsigned branch=1; branch <= numBranches; branch++)
  18677. executeDependencies(parentExtractSize, parentExtract, branch);
  18678. }
  18679. };
  18680. class CRoxieServerSequentialActionActivityFactory : public CRoxieServerActivityFactory
  18681. {
  18682. bool isRoot;
  18683. public:
  18684. CRoxieServerSequentialActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18685. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  18686. {
  18687. }
  18688. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18689. {
  18690. return new CRoxieServerSequentialActionActivity(_ctx, this, _probeManager);
  18691. }
  18692. virtual bool isSink() const
  18693. {
  18694. return isRoot;
  18695. }
  18696. };
  18697. IRoxieServerActivityFactory *createRoxieServerSequentialActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18698. {
  18699. return new CRoxieServerSequentialActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  18700. }
  18701. //=================================================================================
  18702. class CRoxieServerWhenActivity : public CRoxieServerActivity
  18703. {
  18704. public:
  18705. CRoxieServerWhenActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18706. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  18707. {
  18708. savedExtractSize = 0;
  18709. savedExtract = NULL;
  18710. eofseen = false;
  18711. eogseen = false;
  18712. }
  18713. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18714. {
  18715. savedExtractSize = parentExtractSize;
  18716. savedExtract = parentExtract;
  18717. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  18718. executeDependencies(parentExtractSize, parentExtract, WhenBeforeId);
  18719. executeDependencies(parentExtractSize, parentExtract, WhenParallelId); // MORE: This should probably be done in parallel!
  18720. eofseen = false;
  18721. eogseen = false;
  18722. }
  18723. virtual void stop()
  18724. {
  18725. if (state == STATEreset || (!aborted && !eofseen)) // If someone else aborted, then WHEN clauses don't trigger, whatever
  18726. {
  18727. stopDependencies(savedExtractSize, savedExtract, WhenSuccessId);
  18728. stopDependencies(savedExtractSize, savedExtract, WhenFailureId);
  18729. }
  18730. else if (state != STATEstopped)
  18731. {
  18732. stopDependencies(savedExtractSize, savedExtract, aborted ? WhenSuccessId : WhenFailureId); // These ones don't get executed
  18733. executeDependencies(savedExtractSize, savedExtract, aborted ? WhenFailureId : WhenSuccessId); // These ones do
  18734. }
  18735. CRoxieServerActivity::stop();
  18736. }
  18737. virtual const void *nextRow()
  18738. {
  18739. try
  18740. {
  18741. ActivityTimer t(totalCycles, timeActivities); // bit of a waste of time....
  18742. const void *ret = inputStream->nextRow();
  18743. if (!ret)
  18744. {
  18745. if (eogseen)
  18746. eofseen = true;
  18747. else
  18748. eogseen = true;
  18749. }
  18750. else
  18751. eogseen = false;
  18752. return ret;
  18753. }
  18754. catch (...)
  18755. {
  18756. aborted = true;
  18757. throw;
  18758. }
  18759. }
  18760. protected:
  18761. const byte *savedExtract;
  18762. unsigned savedExtractSize;
  18763. bool eofseen;
  18764. bool eogseen;
  18765. };
  18766. class CRoxieServerWhenActivityFactory : public CRoxieServerActivityFactory
  18767. {
  18768. public:
  18769. CRoxieServerWhenActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  18770. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  18771. {
  18772. }
  18773. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18774. {
  18775. return new CRoxieServerWhenActivity(_ctx, this, _probeManager);
  18776. }
  18777. };
  18778. extern IRoxieServerActivityFactory *createRoxieServerWhenActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  18779. {
  18780. return new CRoxieServerWhenActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  18781. }
  18782. //=================================================================================
  18783. class CRoxieServerWhenActionActivity : public CRoxieServerActionBaseActivity
  18784. {
  18785. public:
  18786. CRoxieServerWhenActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18787. : CRoxieServerActionBaseActivity(_ctx, _factory, _probeManager)
  18788. {
  18789. savedExtractSize = 0;
  18790. savedExtract = NULL;
  18791. }
  18792. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18793. {
  18794. savedExtractSize = parentExtractSize;
  18795. savedExtract = parentExtract;
  18796. CRoxieServerActionBaseActivity::start(parentExtractSize, parentExtract, paused);
  18797. executeDependencies(parentExtractSize, parentExtract, WhenBeforeId);
  18798. executeDependencies(parentExtractSize, parentExtract, WhenParallelId); // MORE: This should probably be done in parallel!
  18799. }
  18800. virtual void stop()
  18801. {
  18802. if (state != STATEstopped)
  18803. {
  18804. stopDependencies(savedExtractSize, savedExtract, aborted ? WhenSuccessId : WhenFailureId); // these are NOT going to execute
  18805. executeDependencies(savedExtractSize, savedExtract, aborted ? WhenFailureId : WhenSuccessId);
  18806. }
  18807. CRoxieServerActionBaseActivity::stop();
  18808. }
  18809. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  18810. {
  18811. executeDependencies(parentExtractSize, parentExtract, 1);
  18812. }
  18813. protected:
  18814. unsigned savedExtractSize;
  18815. const byte *savedExtract;
  18816. };
  18817. class CRoxieServerWhenActionActivityFactory : public CRoxieServerActivityFactory
  18818. {
  18819. public:
  18820. CRoxieServerWhenActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18821. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  18822. {
  18823. }
  18824. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18825. {
  18826. return new CRoxieServerWhenActionActivity(_ctx, this, _probeManager);
  18827. }
  18828. virtual bool isSink() const
  18829. {
  18830. return isRoot;
  18831. }
  18832. private:
  18833. bool isRoot;
  18834. };
  18835. extern IRoxieServerActivityFactory *createRoxieServerWhenActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18836. {
  18837. return new CRoxieServerWhenActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  18838. }
  18839. //=================================================================================
  18840. class CRoxieServerStrandedParseActivity : public CRoxieServerStrandedActivity
  18841. {
  18842. INlpParseAlgorithm * algorithm;
  18843. class ParseProcessor : public StrandProcessor, implements IMatchedAction
  18844. {
  18845. protected:
  18846. IHThorParseArg &helper;
  18847. INlpParser * parser;
  18848. INlpResultIterator * rowIter;
  18849. const void * in;
  18850. char * curSearchText;
  18851. size32_t curSearchTextLen;
  18852. bool processRecord(const void * inRec)
  18853. {
  18854. if (helper.searchTextNeedsFree())
  18855. rtlFree(curSearchText);
  18856. curSearchTextLen = 0;
  18857. curSearchText = NULL;
  18858. helper.getSearchText(curSearchTextLen, curSearchText, inRec);
  18859. return parser->performMatch(*this, in, curSearchTextLen, curSearchText);
  18860. }
  18861. public:
  18862. ParseProcessor(CRoxieServerActivity &_parent, IEngineRowStream *_inputStream, IHThorParseArg &_helper, INlpParseAlgorithm * _algorithm)
  18863. : StrandProcessor(_parent, _inputStream, false), helper(_helper)
  18864. {
  18865. parser = _algorithm->createParser(parent.queryCodeContext(), parent.queryId(), helper.queryHelper(), &helper);
  18866. rowIter = parser->queryResultIter();
  18867. in = NULL;
  18868. curSearchText = NULL;
  18869. curSearchTextLen = 0;
  18870. }
  18871. ~ParseProcessor()
  18872. {
  18873. ::Release(parser);
  18874. }
  18875. virtual void start()
  18876. {
  18877. StrandProcessor::start();
  18878. numProcessedLastGroup = 0;
  18879. curSearchTextLen = 0;
  18880. curSearchText = NULL;
  18881. in = NULL;
  18882. parser->reset();
  18883. }
  18884. virtual void reset()
  18885. {
  18886. if (helper.searchTextNeedsFree())
  18887. rtlFree(curSearchText);
  18888. curSearchText = NULL;
  18889. ReleaseClearRoxieRow(in);
  18890. StrandProcessor::reset();
  18891. }
  18892. virtual const void * nextRow()
  18893. {
  18894. ActivityTimer t(totalCycles, timeActivities);
  18895. for (;;)
  18896. {
  18897. if (rowIter->isValid())
  18898. {
  18899. OwnedConstRoxieRow out = rowIter->getRow();
  18900. rowIter->next();
  18901. processed++;
  18902. return out.getClear();
  18903. }
  18904. ReleaseClearRoxieRow(in);
  18905. in = inputStream->nextRow();
  18906. if (!in)
  18907. {
  18908. if (processed == numProcessedLastGroup)
  18909. in = inputStream->nextRow();
  18910. if (!in)
  18911. {
  18912. processed = numProcessedLastGroup;
  18913. return NULL;
  18914. }
  18915. in = inputStream->nextRow();
  18916. if (!in)
  18917. return NULL;
  18918. }
  18919. processRecord(in);
  18920. rowIter->first();
  18921. }
  18922. }
  18923. virtual unsigned onMatch(ARowBuilder & self, const void * curRecord, IMatchedResults * results, IMatchWalker * walker)
  18924. {
  18925. try
  18926. {
  18927. return helper.transform(self, curRecord, results, walker);
  18928. }
  18929. catch (IException *E)
  18930. {
  18931. throw parent.makeWrappedException(E);
  18932. }
  18933. }
  18934. };
  18935. public:
  18936. CRoxieServerStrandedParseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, INlpParseAlgorithm * _algorithm, const StrandOptions &_strandOptions)
  18937. : CRoxieServerStrandedActivity(_ctx, _factory, _probeManager, _strandOptions), algorithm(_algorithm)
  18938. {
  18939. }
  18940. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18941. {
  18942. CRoxieServerStrandedActivity::start(parentExtractSize, parentExtract, paused);
  18943. onStartStrands();
  18944. }
  18945. virtual StrandProcessor *createStrandProcessor(IEngineRowStream *instream)
  18946. {
  18947. return new ParseProcessor(*this, instream, (IHThorParseArg &) basehelper, algorithm);
  18948. }
  18949. virtual StrandProcessor *createStrandSourceProcessor(bool inputOrdered) { throwUnexpected(); }
  18950. };
  18951. class CRoxieServerParseActivityFactory : public CRoxieServerActivityFactory
  18952. {
  18953. Owned<INlpParseAlgorithm> algorithm;
  18954. Owned<IHThorParseArg> helper;
  18955. StrandOptions strandOptions;
  18956. public:
  18957. CRoxieServerParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, IResourceContext *rc)
  18958. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), strandOptions(_graphNode)
  18959. {
  18960. helper.setown((IHThorParseArg *) helperFactory());
  18961. algorithm.setown(createThorParser(rc, *helper));
  18962. optStableInput = false;
  18963. }
  18964. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18965. {
  18966. return new CRoxieServerStrandedParseActivity(_ctx, this, _probeManager, algorithm, strandOptions);
  18967. }
  18968. };
  18969. IRoxieServerActivityFactory *createRoxieServerParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, IResourceContext *rc)
  18970. {
  18971. return new CRoxieServerParseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, rc);
  18972. }
  18973. //=====================================================================================================
  18974. class CRoxieServerWorkUnitWriteActivity : public CRoxieServerInternalSinkActivity
  18975. {
  18976. IHThorWorkUnitWriteArg &helper;
  18977. bool isReread;
  18978. bool grouped;
  18979. IRoxieServerContext *serverContext;
  18980. public:
  18981. CRoxieServerWorkUnitWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _isReread, unsigned _numOutputs)
  18982. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _numOutputs), helper((IHThorWorkUnitWriteArg &)basehelper), isReread(_isReread)
  18983. {
  18984. grouped = (helper.getFlags() & POFgrouped) != 0;
  18985. serverContext = NULL;
  18986. }
  18987. virtual void onCreate(IHThorArg *_colocalParent)
  18988. {
  18989. CRoxieServerInternalSinkActivity::onCreate(_colocalParent);
  18990. serverContext = ctx->queryServerContext();
  18991. if (!serverContext)
  18992. {
  18993. throw MakeStringException(ROXIE_PIPE_ERROR, "Pipe output activity cannot be executed in slave context");
  18994. }
  18995. }
  18996. virtual bool needsAllocator() const { return true; }
  18997. virtual void onExecute()
  18998. {
  18999. int sequence = helper.getSequence();
  19000. const char *storedName = helper.queryName();
  19001. if (!storedName)
  19002. storedName = "Dataset";
  19003. MemoryBuffer result;
  19004. bool saveInContext = (int) sequence < 0 || isReread;
  19005. if (!meta.queryOriginal()) // this is a bit of a hack - don't know why no meta on an output....
  19006. meta.set(input->queryOutputMeta());
  19007. Owned<IOutputRowSerializer> rowSerializer;
  19008. Owned<IXmlWriter> xmlwriter;
  19009. bool appendRaw = false;
  19010. IHpccProtocolResultsWriter *results = NULL;
  19011. IHpccNativeProtocolResultsWriter *nativeResults = NULL;
  19012. IHpccProtocolResponse *protocol = serverContext->queryProtocol();
  19013. unsigned protocolFlags = (protocol) ? protocol->getFlags() : 0;
  19014. if ((int) sequence >= 0)
  19015. {
  19016. results = (protocol) ? protocol->queryHpccResultsSection() : NULL;
  19017. if (results)
  19018. {
  19019. nativeResults = dynamic_cast<IHpccNativeProtocolResultsWriter*>(results);
  19020. xmlwriter.setown(results->addDataset(helper.queryName(), sequence, "Dataset", appendRaw, serverContext->getXmlFlags(), (helper.getFlags() & POFextend) != 0, serverContext->queryXmlns(sequence))); //xmlwriter only returned if needed
  19021. }
  19022. }
  19023. size32_t outputLimitBytes = 0;
  19024. IConstWorkUnit *workunit = serverContext->queryWorkUnit();
  19025. if (workunit)
  19026. {
  19027. size32_t outputLimit;
  19028. if (helper.getFlags() & POFmaxsize)
  19029. outputLimit = helper.getMaxSize();
  19030. else
  19031. {
  19032. // In absense of OPT_OUTPUTLIMIT check pre 5.2 legacy name OPT_OUTPUTLIMIT_LEGACY
  19033. outputLimit = workunit->getDebugValueInt(OPT_OUTPUTLIMIT, workunit->getDebugValueInt(OPT_OUTPUTLIMIT_LEGACY, defaultDaliResultLimit));
  19034. }
  19035. if (outputLimit>defaultDaliResultOutputMax)
  19036. 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);
  19037. assertex(outputLimit<=0x1000); // 32bit limit because MemoryBuffer/CMessageBuffers involved etc.
  19038. outputLimitBytes = outputLimit * 0x100000;
  19039. }
  19040. if (workunit != NULL || (results && (protocol->getFlags() & HPCC_PROTOCOL_NATIVE_RAW)))
  19041. {
  19042. ensureRowAllocator();
  19043. rowSerializer.setown(rowAllocator->createDiskSerializer(ctx->queryCodeContext()));
  19044. }
  19045. __int64 initialProcessed = processed;
  19046. RtlLinkedDatasetBuilder builder(rowAllocator);
  19047. for (;;)
  19048. {
  19049. const void *row = inputStream->nextRow();
  19050. if (saveInContext)
  19051. {
  19052. if (row || grouped)
  19053. builder.append(row);
  19054. }
  19055. if (grouped && (processed != initialProcessed))
  19056. {
  19057. if (workunit)
  19058. result.append(row == NULL);
  19059. if (results)
  19060. {
  19061. if ((protocolFlags & HPCC_PROTOCOL_NATIVE_RAW) && nativeResults)
  19062. {
  19063. char val = (char)(row == NULL);
  19064. nativeResults->appendRaw(sequence, 1, &val);
  19065. }
  19066. else if (xmlwriter)
  19067. {
  19068. xmlwriter->outputBeginNested("Row", false);
  19069. xmlwriter->outputCString("1", "@__GroupBreak__");
  19070. xmlwriter->outputEndNested("Row");
  19071. }
  19072. }
  19073. }
  19074. if (!row)
  19075. {
  19076. row = inputStream->nextRow();
  19077. if (!row)
  19078. break;
  19079. if (saveInContext)
  19080. builder.append(row);
  19081. }
  19082. processed++;
  19083. if (workunit)
  19084. {
  19085. CThorDemoRowSerializer serializerTarget(result);
  19086. rowSerializer->serialize(serializerTarget, (const byte *) row);
  19087. }
  19088. if ((int) sequence >= 0)
  19089. {
  19090. if (appendRaw && nativeResults)
  19091. {
  19092. // MORE - should be able to serialize straight to the response...
  19093. MemoryBuffer rowbuff;
  19094. CThorDemoRowSerializer serializerTarget(rowbuff);
  19095. rowSerializer->serialize(serializerTarget, (const byte *) row);
  19096. nativeResults->appendRawRow(sequence, rowbuff.length(), rowbuff.toByteArray());
  19097. }
  19098. else if (xmlwriter)
  19099. {
  19100. xmlwriter->outputBeginNested(DEFAULTXMLROWTAG, false);
  19101. helper.serializeXml((byte *) row, *xmlwriter);
  19102. xmlwriter->outputEndNested(DEFAULTXMLROWTAG);
  19103. results->finalizeXmlRow(sequence);
  19104. }
  19105. else if (nativeResults)
  19106. {
  19107. SimpleOutputWriter x;
  19108. helper.serializeXml((byte *) row, x);
  19109. x.newline();
  19110. nativeResults->appendSimpleRow(sequence, x.str());
  19111. }
  19112. }
  19113. ReleaseRoxieRow(row);
  19114. if (outputLimitBytes && result.length() > outputLimitBytes)
  19115. {
  19116. StringBuffer errMsg("Dataset too large to output to workunit (limit ");
  19117. errMsg.append(outputLimitBytes/0x100000).append(" megabytes), in result (");
  19118. const char *name = helper.queryName();
  19119. if (name)
  19120. errMsg.append("name=").append(name);
  19121. else
  19122. errMsg.append("sequence=").append(helper.getSequence());
  19123. errMsg.append(")");
  19124. throw MakeStringExceptionDirect(0, errMsg.str());
  19125. }
  19126. }
  19127. if (xmlwriter)
  19128. xmlwriter->outputEndArray(DEFAULTXMLROWTAG);
  19129. if (saveInContext)
  19130. serverContext->appendResultDeserialized(storedName, sequence, builder.getcount(), builder.linkrows(), (helper.getFlags() & POFextend) != 0, LINK(meta.queryOriginal()));
  19131. if (workunit)
  19132. serverContext->appendResultRawContext(storedName, sequence, result.length(), result.toByteArray(), processed, (helper.getFlags() & POFextend) != 0, false); // MORE - shame to do extra copy...
  19133. }
  19134. };
  19135. class CRoxieServerWorkUnitWriteActivityFactory : public CRoxieServerInternalSinkFactory
  19136. {
  19137. bool isReread;
  19138. public:
  19139. CRoxieServerWorkUnitWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  19140. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot)
  19141. {
  19142. isReread = usageCount > 0;
  19143. Owned<IHThorWorkUnitWriteArg> helper = (IHThorWorkUnitWriteArg *) helperFactory();
  19144. isInternal = (helper->getSequence()==ResultSequenceInternal);
  19145. }
  19146. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  19147. {
  19148. return new CRoxieServerWorkUnitWriteActivity(_ctx, this, _probeManager, isReread, usageCount);
  19149. }
  19150. };
  19151. IRoxieServerActivityFactory *createRoxieServerWorkUnitWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  19152. {
  19153. return new CRoxieServerWorkUnitWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot);
  19154. }
  19155. //=====================================================================================================
  19156. class CRoxieServerWorkUnitWriteDictActivity : public CRoxieServerInternalSinkActivity
  19157. {
  19158. IHThorDictionaryWorkUnitWriteArg &helper;
  19159. IRoxieServerContext *serverContext;
  19160. public:
  19161. CRoxieServerWorkUnitWriteDictActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _usageCount)
  19162. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _usageCount), helper((IHThorDictionaryWorkUnitWriteArg &)basehelper)
  19163. {
  19164. serverContext = NULL;
  19165. }
  19166. virtual void onCreate(IHThorArg *_colocalParent)
  19167. {
  19168. CRoxieServerInternalSinkActivity::onCreate(_colocalParent);
  19169. serverContext = ctx->queryServerContext();
  19170. if (!serverContext)
  19171. {
  19172. throw MakeStringException(ROXIE_PIPE_ERROR, "Write Dictionary activity cannot be executed in slave context");
  19173. }
  19174. }
  19175. virtual bool needsAllocator() const { return true; }
  19176. virtual void onExecute()
  19177. {
  19178. int sequence = helper.getSequence();
  19179. const char *storedName = helper.queryName();
  19180. assertex(storedName && *storedName);
  19181. assertex(sequence < 0);
  19182. RtlLinkedDictionaryBuilder builder(rowAllocator, helper.queryHashLookupInfo());
  19183. for (;;)
  19184. {
  19185. const void *row = inputStream->ungroupedNextRow();
  19186. if (!row)
  19187. break;
  19188. builder.appendOwn(row);
  19189. processed++;
  19190. }
  19191. serverContext->appendResultDeserialized(storedName, sequence, builder.getcount(), builder.linkrows(), (helper.getFlags() & POFextend) != 0, LINK(meta.queryOriginal()));
  19192. }
  19193. };
  19194. class CRoxieServerWorkUnitWriteDictActivityFactory : public CRoxieServerInternalSinkFactory
  19195. {
  19196. public:
  19197. CRoxieServerWorkUnitWriteDictActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  19198. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot)
  19199. {
  19200. Owned<IHThorDictionaryWorkUnitWriteArg> helper = (IHThorDictionaryWorkUnitWriteArg *) helperFactory();
  19201. isInternal = (helper->getSequence()==ResultSequenceInternal);
  19202. }
  19203. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  19204. {
  19205. return new CRoxieServerWorkUnitWriteDictActivity(_ctx, this, _probeManager, usageCount);
  19206. }
  19207. };
  19208. IRoxieServerActivityFactory *createRoxieServerWorkUnitWriteDictActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  19209. {
  19210. return new CRoxieServerWorkUnitWriteDictActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot);
  19211. }
  19212. //=================================================================================
  19213. class CRoxieServerRemoteResultActivity : public CRoxieServerInternalSinkActivity
  19214. {
  19215. IHThorRemoteResultArg &helper;
  19216. public:
  19217. CRoxieServerRemoteResultActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  19218. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _numOutputs), helper((IHThorRemoteResultArg &)basehelper)
  19219. {
  19220. }
  19221. virtual void onExecute()
  19222. {
  19223. OwnedConstRoxieRow row = inputStream->nextRow();
  19224. helper.sendResult(row); // should be only one row or something has gone wrong!
  19225. }
  19226. };
  19227. class CRoxieServerRemoteResultActivityFactory : public CRoxieServerInternalSinkFactory
  19228. {
  19229. public:
  19230. CRoxieServerRemoteResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  19231. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot)
  19232. {
  19233. Owned<IHThorRemoteResultArg> helper = (IHThorRemoteResultArg *) helperFactory();
  19234. isInternal = (helper->getSequence()==ResultSequenceInternal);
  19235. }
  19236. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  19237. {
  19238. return new CRoxieServerRemoteResultActivity(_ctx, this, _probeManager, usageCount);
  19239. }
  19240. };
  19241. IRoxieServerActivityFactory *createRoxieServerRemoteResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  19242. {
  19243. return new CRoxieServerRemoteResultActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot);
  19244. }
  19245. //=================================================================================
  19246. class CRoxieServerXmlParseActivity : public CRoxieServerActivity, implements IXMLSelect
  19247. {
  19248. IHThorXmlParseArg &helper;
  19249. Owned<IXMLParse> xmlParser;
  19250. const void * in;
  19251. char * srchStr;
  19252. unsigned numProcessedLastGroup;
  19253. bool srchStrNeedsFree;
  19254. Owned<IColumnProvider> lastMatch;
  19255. public:
  19256. IMPLEMENT_IINTERFACE_USING(CRoxieServerActivity)
  19257. CRoxieServerXmlParseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  19258. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  19259. helper((IHThorXmlParseArg &)basehelper)
  19260. {
  19261. srchStrNeedsFree = helper.searchTextNeedsFree();
  19262. numProcessedLastGroup = 0;
  19263. srchStr = NULL;
  19264. in = NULL;
  19265. }
  19266. ~CRoxieServerXmlParseActivity()
  19267. {
  19268. }
  19269. virtual bool needsAllocator() const { return true; }
  19270. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19271. {
  19272. numProcessedLastGroup = 0;
  19273. srchStr = NULL;
  19274. in = NULL;
  19275. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  19276. }
  19277. virtual void reset()
  19278. {
  19279. if (helper.searchTextNeedsFree())
  19280. rtlFree(srchStr);
  19281. srchStr = NULL;
  19282. ReleaseClearRoxieRow(in);
  19283. xmlParser.clear();
  19284. CRoxieServerActivity::reset();
  19285. }
  19286. virtual void match(IColumnProvider &entry, offset_t startOffset, offset_t endOffset)
  19287. {
  19288. lastMatch.set(&entry);
  19289. }
  19290. virtual const void *nextRow()
  19291. {
  19292. ActivityTimer t(totalCycles, timeActivities);
  19293. for (;;)
  19294. {
  19295. if(xmlParser)
  19296. {
  19297. for (;;)
  19298. {
  19299. if(!xmlParser->next())
  19300. {
  19301. if (srchStrNeedsFree)
  19302. {
  19303. rtlFree(srchStr);
  19304. srchStr = NULL;
  19305. }
  19306. xmlParser.clear();
  19307. break;
  19308. }
  19309. if(lastMatch)
  19310. {
  19311. try
  19312. {
  19313. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  19314. size32_t outSize = helper.transform(rowBuilder, in, lastMatch);
  19315. lastMatch.clear();
  19316. if (outSize)
  19317. {
  19318. processed++;
  19319. return rowBuilder.finalizeRowClear(outSize);
  19320. }
  19321. }
  19322. catch (IException *E)
  19323. {
  19324. throw makeWrappedException(E);
  19325. }
  19326. }
  19327. }
  19328. }
  19329. ReleaseClearRoxieRow(in);
  19330. in = inputStream->nextRow();
  19331. if(!in)
  19332. {
  19333. if(numProcessedLastGroup == processed)
  19334. in = inputStream->nextRow();
  19335. if(!in)
  19336. {
  19337. numProcessedLastGroup = processed;
  19338. return NULL;
  19339. }
  19340. }
  19341. size32_t srchLen;
  19342. helper.getSearchText(srchLen, srchStr, in);
  19343. OwnedRoxieString xmlIteratorPath(helper.getXmlIteratorPath());
  19344. xmlParser.setown(createXMLParse(srchStr, srchLen, xmlIteratorPath, *this));
  19345. }
  19346. }
  19347. };
  19348. class CRoxieServerXmlParseActivityFactory : public CRoxieServerActivityFactory
  19349. {
  19350. public:
  19351. CRoxieServerXmlParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  19352. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  19353. {
  19354. }
  19355. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  19356. {
  19357. return new CRoxieServerXmlParseActivity(_ctx, this, _probeManager);
  19358. }
  19359. };
  19360. IRoxieServerActivityFactory *createRoxieServerXmlParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  19361. {
  19362. return new CRoxieServerXmlParseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  19363. }
  19364. //=====================================================================================================
  19365. class CRoxieServerDiskReadBaseActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler, implements IIndexReadContext
  19366. {
  19367. protected:
  19368. IHThorDiskReadBaseArg &helper;
  19369. IHThorSourceLimitTransformExtra * limitTransformExtra = nullptr;
  19370. IHThorCompoundExtra * compoundHelper;
  19371. RemoteActivityId remoteId; // Note we copy it rather than reference
  19372. Owned<CSkippableRemoteResultAdaptor> remote;
  19373. unsigned numParts;
  19374. unsigned __int64 rowLimit;
  19375. unsigned __int64 stopAfter;
  19376. Linked<IInMemoryIndexManager> manager;
  19377. Linked<ITranslatorSet> translators;
  19378. ScoredRowFilter postFilter;
  19379. Owned<IDirectReader> reader;
  19380. bool eof;
  19381. bool variableFileName;
  19382. bool isOpt;
  19383. bool sorted;
  19384. bool maySkip;
  19385. bool isLocal;
  19386. bool forceRemote;
  19387. bool isGrouped = false;
  19388. CachedOutputMetaData diskSize;
  19389. Owned<const IResolvedFile> varFileInfo;
  19390. inline bool useRemote()
  19391. {
  19392. return remote != NULL && (forceRemote || numParts > 1);
  19393. }
  19394. public:
  19395. IMPLEMENT_IINTERFACE_USING(CRoxieServerActivity)
  19396. CRoxieServerDiskReadBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  19397. unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager, ITranslatorSet *_translators)
  19398. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  19399. helper((IHThorDiskReadBaseArg &)basehelper),
  19400. numParts(_numParts),
  19401. remoteId(_remoteId),
  19402. manager(_manager),
  19403. translators(_translators),
  19404. isLocal(_isLocal),
  19405. sorted(_sorted),
  19406. maySkip(_maySkip)
  19407. {
  19408. forceRemote = factory->queryQueryFactory().queryOptions().disableLocalOptimizations;
  19409. if ((forceRemote || numParts != 1) && !isLocal) // NOTE : when numParts == 0 (variable case) we create, even though we may not use
  19410. remote.setown(new CSkippableRemoteResultAdaptor(_ctx, this, remoteId, meta.queryOriginal(), helper, *this, sorted, false, _maySkip));
  19411. compoundHelper = NULL;
  19412. eof = false;
  19413. rowLimit = (unsigned __int64) -1;
  19414. stopAfter = I64C(0x7FFFFFFFFFFFFFFF);
  19415. diskSize.set(helper.queryDiskRecordSize()->querySerializedDiskMeta());
  19416. isGrouped = diskSize.isGrouped();
  19417. variableFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getFlags() & (TDXvarfilename|TDXdynamicfilename)) != 0);
  19418. isOpt = (helper.getFlags() & TDRoptional) != 0;
  19419. }
  19420. virtual const IResolvedFile *queryVarFileInfo() const
  19421. {
  19422. return varFileInfo;
  19423. }
  19424. virtual void onCreate(IHThorArg *_colocalParent)
  19425. {
  19426. CRoxieServerActivity::onCreate(_colocalParent);
  19427. if (remote)
  19428. remote->onCreate(_colocalParent);
  19429. }
  19430. virtual bool needsAllocator() const { return true; }
  19431. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19432. {
  19433. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  19434. if (compoundHelper)
  19435. {
  19436. rowLimit = compoundHelper->getRowLimit();
  19437. stopAfter = compoundHelper->getChooseNLimit();
  19438. }
  19439. if (!helper.canMatchAny())
  19440. eof = true;
  19441. else
  19442. {
  19443. if (variableFileName)
  19444. {
  19445. OwnedRoxieString fileName(helper.getFileName());
  19446. varFileInfo.setown(resolveLFNFlat(fileName, isOpt));
  19447. numParts = 0;
  19448. if (varFileInfo)
  19449. numParts = varFileInfo->getNumParts();
  19450. }
  19451. if (!numParts)
  19452. {
  19453. eof = true;
  19454. }
  19455. else if (useRemote())
  19456. {
  19457. remote->onStart(parentExtractSize, parentExtract);
  19458. remote->setLimits(rowLimit, (unsigned __int64) -1, stopAfter);
  19459. unsigned fileNo = 0;
  19460. // Translation into a message per channel done elsewhere....
  19461. remote->getMem(0, fileNo, 0);
  19462. remote->flush();
  19463. remote->senddone();
  19464. }
  19465. else
  19466. {
  19467. if (variableFileName)
  19468. {
  19469. unsigned channel = isLocal ? factory->queryQueryFactory().queryChannel() : 0;
  19470. unsigned expectedFormatCrc = helper.getDiskFormatCrc();
  19471. unsigned projectedFormatCrc = helper.getProjectedFormatCrc();
  19472. translators.setown(varFileInfo->getTranslators(projectedFormatCrc, helper.queryProjectedDiskRecordSize(), expectedFormatCrc, helper.queryDiskRecordSize(), skipFileFormatCrcCheck(), getEnableFieldTranslation(), false));
  19473. manager.setown(varFileInfo->getIndexManager(isOpt, channel, translators->queryActualLayout(0), false));
  19474. }
  19475. assertex(manager != NULL);
  19476. postFilter.clear();
  19477. helper.createSegmentMonitors(this);
  19478. const IKeyTranslator *keyTranslator = translators->queryKeyTranslator(0); // any part would do - in-memory requires all actuals to have same layout
  19479. if (keyTranslator)
  19480. keyTranslator->translate(postFilter);
  19481. reader.setown(manager->selectKey(postFilter, translators, *this));
  19482. if (!reader)
  19483. reader.setown(manager->createReader(postFilter, isGrouped, 0, 0, 1, translators));
  19484. assertex(reader);
  19485. helper.setCallback(reader);
  19486. }
  19487. }
  19488. }
  19489. virtual void append(IKeySegmentMonitor *segment)
  19490. {
  19491. segment->Release();
  19492. throwUnexpected();
  19493. }
  19494. virtual void append(FFoption option, const IFieldFilter * filter)
  19495. {
  19496. if (filter->isWild())
  19497. filter->Release();
  19498. else
  19499. postFilter.addFilter(*filter);
  19500. }
  19501. virtual void stop()
  19502. {
  19503. if (useRemote())
  19504. remote->onStop();
  19505. CRoxieServerActivity::stop();
  19506. }
  19507. virtual void reset()
  19508. {
  19509. if (useRemote())
  19510. {
  19511. processed = remote->processed;
  19512. remote->processed = 0;
  19513. remote->onReset();
  19514. }
  19515. varFileInfo.clear();
  19516. eof = false;
  19517. reader.clear();
  19518. CRoxieServerActivity::reset();
  19519. }
  19520. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  19521. {
  19522. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  19523. }
  19524. virtual void onLimitExceeded(bool isKeyed)
  19525. {
  19526. if (traceLevel > 4)
  19527. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  19528. assertex(compoundHelper);
  19529. if (isKeyed) // MORE does this exist for diskread? should it?
  19530. {
  19531. if (helper.getFlags() & (TDRkeyedlimitskips|TDRkeyedlimitcreates))
  19532. {
  19533. if (ctx->queryDebugContext())
  19534. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  19535. throw makeLimitSkipException(true);
  19536. }
  19537. else
  19538. {
  19539. UNIMPLEMENTED;
  19540. //compoundHelper->onKeyedLimitExceeded(); Doesn't exist - though the flags do... interesting...
  19541. }
  19542. }
  19543. else
  19544. {
  19545. if (helper.getFlags() & (TDRlimitskips|TDRlimitcreates))
  19546. {
  19547. if (ctx->queryDebugContext())
  19548. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  19549. throw makeLimitSkipException(false);
  19550. }
  19551. else
  19552. compoundHelper->onLimitExceeded();
  19553. }
  19554. }
  19555. virtual const void * createLimitFailRow(bool isKeyed)
  19556. {
  19557. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  19558. assertex(limitTransformExtra);
  19559. size32_t outSize = isKeyed ? limitTransformExtra->transformOnKeyedLimitExceeded(rowBuilder) : limitTransformExtra->transformOnLimitExceeded(rowBuilder);
  19560. if (outSize)
  19561. return rowBuilder.finalizeRowClear(outSize);
  19562. return NULL;
  19563. }
  19564. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  19565. {
  19566. CRoxieServerActivity::gatherStats(merged);
  19567. if (remote)
  19568. remote->gatherStats(merged);
  19569. }
  19570. };
  19571. class CRoxieServerDiskReadActivity : public CRoxieServerDiskReadBaseActivity
  19572. {
  19573. IHThorDiskReadArg * readHelper;
  19574. ConstPointerArray readrows;
  19575. bool readAheadDone;
  19576. unsigned readIndex;
  19577. unsigned lastGroupProcessed;
  19578. bool someInGroup = false;
  19579. public:
  19580. CRoxieServerDiskReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager, ITranslatorSet *_translators)
  19581. : CRoxieServerDiskReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, _maySkip, _manager, _translators)
  19582. {
  19583. compoundHelper = (IHThorDiskReadArg *)&helper;
  19584. readHelper = (IHThorDiskReadArg *)&helper;
  19585. limitTransformExtra = readHelper;
  19586. readAheadDone = false;
  19587. readIndex = 0;
  19588. lastGroupProcessed = processed;
  19589. }
  19590. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19591. {
  19592. rowLimit = compoundHelper->getRowLimit();
  19593. stopAfter = compoundHelper->getChooseNLimit();
  19594. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  19595. readAheadDone = false;
  19596. readIndex = 0;
  19597. lastGroupProcessed = processed;
  19598. someInGroup = false;
  19599. }
  19600. virtual void reset()
  19601. {
  19602. roxiemem::ReleaseRoxieRowRange(readrows.getArray(), readIndex, readrows.ordinality());
  19603. readrows.kill();
  19604. readAheadDone = false;
  19605. readIndex = 0;
  19606. lastGroupProcessed = processed;
  19607. someInGroup = false;
  19608. CRoxieServerDiskReadBaseActivity::reset();
  19609. }
  19610. virtual const void *nextRow()
  19611. {
  19612. ActivityTimer t(totalCycles, timeActivities);
  19613. if (eof)
  19614. return NULL;
  19615. else if (useRemote())
  19616. return remote->nextRow();
  19617. else if (maySkip)
  19618. {
  19619. if (!readAheadDone)
  19620. {
  19621. unsigned preprocessed = 0;
  19622. while (!eof)
  19623. {
  19624. const void *row = _nextRow();
  19625. if (row)
  19626. preprocessed++;
  19627. if (preprocessed > rowLimit)
  19628. {
  19629. ReleaseRoxieRow(row);
  19630. roxiemem::ReleaseRoxieRowRange(readrows.getArray(), readIndex, readrows.ordinality());
  19631. readrows.kill();
  19632. readIndex = 0;
  19633. eof = true;
  19634. if (ctx->queryDebugContext())
  19635. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  19636. if (helper.getFlags() & TDRlimitskips)
  19637. return NULL;
  19638. else if (helper.getFlags() & TDRlimitcreates)
  19639. return createLimitFailRow(false);
  19640. else
  19641. throwUnexpected();
  19642. }
  19643. if (preprocessed > stopAfter) // MORE - bit of a strange place to check
  19644. {
  19645. eof = true;
  19646. ReleaseRoxieRow(row);
  19647. break;
  19648. }
  19649. readrows.append(row);
  19650. }
  19651. readAheadDone = true;
  19652. }
  19653. if (readrows.isItem(readIndex))
  19654. {
  19655. const void *ret = readrows.item(readIndex++);
  19656. if (ret)
  19657. processed++;
  19658. return ret;
  19659. }
  19660. else
  19661. {
  19662. eof = true;
  19663. return NULL;
  19664. }
  19665. }
  19666. else
  19667. {
  19668. const void *ret = _nextRow();
  19669. if (ret)
  19670. {
  19671. processed++;
  19672. if (processed > rowLimit)
  19673. {
  19674. if (traceLevel > 4)
  19675. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  19676. ReleaseRoxieRow(ret);
  19677. compoundHelper->onLimitExceeded();
  19678. throwUnexpected(); // onLimitExceeded is not supposed to return
  19679. }
  19680. if (processed > stopAfter) // MORE - bit of a strange place to check
  19681. {
  19682. eof = true;
  19683. ReleaseRoxieRow(ret);
  19684. return NULL;
  19685. }
  19686. }
  19687. return ret;
  19688. }
  19689. }
  19690. const void *_nextRow()
  19691. {
  19692. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  19693. unsigned transformedSize = 0;
  19694. for (;;)
  19695. {
  19696. const byte *nextRec = reader->nextRow();
  19697. if (nextRec)
  19698. {
  19699. someInGroup = true;
  19700. if (likely(readHelper->canMatch(nextRec)))
  19701. {
  19702. transformedSize = readHelper->transform(rowBuilder, nextRec);
  19703. reader->finishedRow();
  19704. if (transformedSize)
  19705. break;
  19706. }
  19707. else
  19708. reader->finishedRow();
  19709. }
  19710. else if (isGrouped)
  19711. {
  19712. if (lastGroupProcessed != processed)
  19713. {
  19714. someInGroup = false;
  19715. lastGroupProcessed = processed;
  19716. return nullptr;
  19717. }
  19718. else if (!someInGroup)
  19719. {
  19720. eof = true;
  19721. return nullptr;
  19722. }
  19723. }
  19724. else
  19725. {
  19726. eof = true;
  19727. return nullptr;
  19728. }
  19729. }
  19730. return rowBuilder.finalizeRowClear(transformedSize);
  19731. }
  19732. };
  19733. class CRoxieServerXmlReadActivity : public CRoxieServerDiskReadBaseActivity, implements IXMLSelect, implements IThorDiskCallback
  19734. {
  19735. IHThorXmlReadArg * readHelper;
  19736. Owned<IXmlToRowTransformer> rowTransformer;
  19737. Owned<IXMLParse> xmlParser;
  19738. Owned<IColumnProvider> lastMatch;
  19739. unsigned __int64 fileoffset;
  19740. IDirectStreamReader *streamReader = nullptr;
  19741. public:
  19742. IMPLEMENT_IINTERFACE_USING(CRoxieServerDiskReadBaseActivity)
  19743. CRoxieServerXmlReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  19744. unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager, ITranslatorSet *_translators)
  19745. : CRoxieServerDiskReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, _maySkip, _manager, _translators)
  19746. {
  19747. compoundHelper = NULL;
  19748. readHelper = (IHThorXmlReadArg *)&helper;
  19749. fileoffset = 0;
  19750. }
  19751. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19752. {
  19753. rowLimit = readHelper->getRowLimit();
  19754. stopAfter = readHelper->getChooseNLimit();
  19755. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  19756. if (!useRemote())
  19757. {
  19758. rowTransformer.set(readHelper->queryTransformer());
  19759. assertex(reader != NULL);
  19760. streamReader = reader->queryDirectStreamReader();
  19761. assertex(streamReader != NULL);
  19762. OwnedRoxieString xmlIterator(readHelper->getXmlIteratorPath());
  19763. if (factory->getKind()==TAKjsonread)
  19764. xmlParser.setown(createJSONParse(*streamReader, xmlIterator, *this, (0 != (TDRxmlnoroot & readHelper->getFlags()))?ptr_noRoot:ptr_none, (readHelper->getFlags() & TDRusexmlcontents) != 0));
  19765. else
  19766. xmlParser.setown(createXMLParse(*streamReader, xmlIterator, *this, (0 != (TDRxmlnoroot & readHelper->getFlags()))?ptr_noRoot:ptr_none, (readHelper->getFlags() & TDRusexmlcontents) != 0));
  19767. }
  19768. }
  19769. virtual void reset()
  19770. {
  19771. CRoxieServerDiskReadBaseActivity::reset();
  19772. rowTransformer.clear();
  19773. xmlParser.clear();
  19774. }
  19775. virtual void match(IColumnProvider &entry, offset_t startOffset, offset_t endOffset)
  19776. {
  19777. fileoffset = startOffset;
  19778. lastMatch.set(&entry);
  19779. }
  19780. //interface IThorDiskCallback
  19781. virtual unsigned __int64 getFilePosition(const void * row)
  19782. {
  19783. return fileoffset;
  19784. }
  19785. virtual unsigned __int64 getLocalFilePosition(const void * row)
  19786. {
  19787. return streamReader->makeFilePositionLocal(fileoffset);
  19788. }
  19789. virtual const char * queryLogicalFilename(const void * row)
  19790. {
  19791. return reader->queryLogicalFilename(row);
  19792. }
  19793. virtual const void *nextRow()
  19794. {
  19795. ActivityTimer t(totalCycles, timeActivities);
  19796. if (eof)
  19797. return NULL;
  19798. else if (useRemote())
  19799. return remote->nextRow();
  19800. assertex(xmlParser != NULL);
  19801. try
  19802. {
  19803. while (!eof)
  19804. {
  19805. //call to next() will callback on the IXmlSelect interface
  19806. bool gotNext = false;
  19807. gotNext = xmlParser->next();
  19808. if(!gotNext)
  19809. eof = true;
  19810. else if (lastMatch)
  19811. {
  19812. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  19813. unsigned sizeGot = rowTransformer->transform(rowBuilder, lastMatch, this);
  19814. lastMatch.clear();
  19815. fileoffset = 0;
  19816. if (sizeGot)
  19817. {
  19818. OwnedConstRoxieRow ret = rowBuilder.finalizeRowClear(sizeGot);
  19819. if (processed > rowLimit)
  19820. {
  19821. if (traceLevel > 4)
  19822. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  19823. readHelper->onLimitExceeded();
  19824. throwUnexpected(); // onLimitExceeded is not supposed to return
  19825. }
  19826. processed++;
  19827. if (processed > stopAfter) // MORE - bit of a strange place to check
  19828. {
  19829. eof = true;
  19830. return NULL;
  19831. }
  19832. return ret.getClear();
  19833. }
  19834. }
  19835. }
  19836. return NULL;
  19837. }
  19838. catch(IException *E)
  19839. {
  19840. throw makeWrappedException(E);
  19841. }
  19842. }
  19843. };
  19844. class CRoxieServerCsvReadActivity : public CRoxieServerDiskReadBaseActivity
  19845. {
  19846. IHThorCsvReadArg *readHelper;
  19847. ICsvParameters * csvInfo;
  19848. unsigned headerLines;
  19849. unsigned maxDiskSize;
  19850. CSVSplitter csvSplitter;
  19851. unsigned __int64 localOffset;
  19852. IDirectStreamReader *streamReader = nullptr;
  19853. const char *quotes;
  19854. const char *separators;
  19855. const char *terminators;
  19856. const char *escapes;
  19857. size32_t maxRowSize;
  19858. public:
  19859. CRoxieServerCsvReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  19860. unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager, ITranslatorSet *_translators,
  19861. const char *_quotes, const char *_separators, const char *_terminators, const char *_escapes, size32_t _maxRowSize)
  19862. : CRoxieServerDiskReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, _maySkip, _manager, _translators),
  19863. quotes(_quotes), separators(_separators), terminators(_terminators), escapes(_escapes), maxRowSize(_maxRowSize)
  19864. {
  19865. compoundHelper = NULL;
  19866. readHelper = (IHThorCsvReadArg *)&helper;
  19867. rowLimit = readHelper->getRowLimit();
  19868. stopAfter = readHelper->getChooseNLimit();
  19869. csvInfo = readHelper->queryCsvParameters();
  19870. maxDiskSize = csvInfo->queryMaxSize();
  19871. localOffset = 0;
  19872. headerLines = 0;
  19873. }
  19874. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19875. {
  19876. rowLimit = readHelper->getRowLimit();
  19877. stopAfter = readHelper->getChooseNLimit();
  19878. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  19879. if (!useRemote())
  19880. {
  19881. if (!eof)
  19882. {
  19883. assertex(reader != nullptr);
  19884. streamReader = reader->queryDirectStreamReader();
  19885. assertex(streamReader != nullptr);
  19886. headerLines = csvInfo->queryHeaderLen();
  19887. if (headerLines && isLocal && streamReader->queryFilePart() != 1)
  19888. 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...
  19889. if (varFileInfo)
  19890. {
  19891. const IPropertyTree *options = varFileInfo->queryProperties();
  19892. if (options)
  19893. {
  19894. quotes = options->queryProp("@csvQuote");
  19895. separators = options->queryProp("@csvSeparate");
  19896. terminators = options->queryProp("@csvTerminate");
  19897. escapes = options->queryProp("@csvEscape");
  19898. }
  19899. }
  19900. csvSplitter.init(readHelper->getMaxColumns(), csvInfo, quotes, separators, terminators, escapes);
  19901. }
  19902. }
  19903. }
  19904. virtual const void *nextRow()
  19905. {
  19906. ActivityTimer t(totalCycles, timeActivities);
  19907. if (eof)
  19908. return NULL;
  19909. else if (useRemote())
  19910. return remote->nextRow();
  19911. try
  19912. {
  19913. while (!eof)
  19914. {
  19915. size32_t thisLineLength = csvSplitter.splitLine(streamReader, maxRowSize);
  19916. if (!thisLineLength)
  19917. break;
  19918. if (headerLines)
  19919. {
  19920. headerLines--;
  19921. streamReader->skip(thisLineLength);
  19922. }
  19923. else
  19924. {
  19925. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  19926. unsigned transformedSize = readHelper->transform(rowBuilder, csvSplitter.queryLengths(), (const char * *)csvSplitter.queryData());
  19927. streamReader->skip(thisLineLength);
  19928. if (transformedSize)
  19929. {
  19930. OwnedConstRoxieRow ret = rowBuilder.finalizeRowClear(transformedSize);
  19931. if (processed > rowLimit)
  19932. {
  19933. readHelper->onLimitExceeded();
  19934. throwUnexpected(); // onLimitExceeded is not supposed to return
  19935. }
  19936. processed++;
  19937. if (processed > stopAfter) // MORE - bit of a strange place to check
  19938. {
  19939. eof = true;
  19940. return NULL;
  19941. }
  19942. return ret.getClear();
  19943. }
  19944. }
  19945. }
  19946. return NULL;
  19947. }
  19948. catch(IException *E)
  19949. {
  19950. throw makeWrappedException(E);
  19951. }
  19952. }
  19953. virtual void reset()
  19954. {
  19955. CRoxieServerDiskReadBaseActivity::reset();
  19956. csvSplitter.reset();
  19957. localOffset = 0;
  19958. }
  19959. virtual unsigned __int64 getFilePosition(const void * row)
  19960. {
  19961. UNIMPLEMENTED; // we know offset in the reader but not sure it helps us much
  19962. }
  19963. virtual unsigned __int64 getLocalFilePosition(const void * row)
  19964. {
  19965. UNIMPLEMENTED;
  19966. }
  19967. };
  19968. class CRoxieServerDiskNormalizeActivity : public CRoxieServerDiskReadBaseActivity
  19969. {
  19970. IHThorDiskNormalizeArg *normalizeHelper;
  19971. bool firstPending;
  19972. public:
  19973. CRoxieServerDiskNormalizeActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, IInMemoryIndexManager *_manager, ITranslatorSet *_translators)
  19974. : CRoxieServerDiskReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, false, _manager, _translators)
  19975. {
  19976. compoundHelper = (IHThorDiskNormalizeArg *)&helper;
  19977. normalizeHelper = (IHThorDiskNormalizeArg *)&helper;
  19978. limitTransformExtra = normalizeHelper;
  19979. firstPending = true;
  19980. }
  19981. virtual void reset()
  19982. {
  19983. firstPending = true;
  19984. CRoxieServerDiskReadBaseActivity::reset();
  19985. }
  19986. virtual const void *nextRow()
  19987. {
  19988. ActivityTimer t(totalCycles, timeActivities);
  19989. if (eof)
  19990. return NULL;
  19991. else if (useRemote())
  19992. return remote->nextRow();
  19993. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  19994. unsigned transformedSize = 0;
  19995. for (;;)
  19996. {
  19997. while (firstPending)
  19998. {
  19999. const byte *nextRec = reader->nextRow();
  20000. if (!nextRec)
  20001. {
  20002. eof = true;
  20003. return NULL;
  20004. }
  20005. if (normalizeHelper->first(nextRec))
  20006. firstPending = false;
  20007. reader->finishedRow();
  20008. }
  20009. transformedSize = normalizeHelper->transform(rowBuilder);
  20010. firstPending = !normalizeHelper->next();
  20011. if (transformedSize)
  20012. break;
  20013. }
  20014. OwnedConstRoxieRow recBuffer = rowBuilder.finalizeRowClear(transformedSize);
  20015. processed++;
  20016. if (processed > rowLimit)
  20017. {
  20018. compoundHelper->onLimitExceeded();
  20019. throwUnexpected(); // onLimitExceeded is not supposed to return
  20020. }
  20021. if (processed > stopAfter) // MORE - bit of a strange place to check
  20022. {
  20023. eof = true;
  20024. return NULL;
  20025. }
  20026. return recBuffer.getClear();
  20027. }
  20028. };
  20029. class CRoxieServerDiskAggregateBaseActivity : public CRoxieServerDiskReadBaseActivity
  20030. {
  20031. protected:
  20032. bool done;
  20033. public:
  20034. CRoxieServerDiskAggregateBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager, ITranslatorSet *_translators)
  20035. : CRoxieServerDiskReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, false, false, _manager, _translators),
  20036. done(false)
  20037. {
  20038. }
  20039. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20040. {
  20041. done = false;
  20042. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  20043. }
  20044. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  20045. {
  20046. if (idx==(unsigned)-1)
  20047. idx = 0;
  20048. return idx ? NULL: this;
  20049. }
  20050. };
  20051. class CRoxieServerDiskCountActivity : public CRoxieServerDiskAggregateBaseActivity
  20052. {
  20053. IHThorDiskCountArg & countHelper;
  20054. unsigned __int64 choosenLimit;
  20055. unsigned __int64 getSkippedCount()
  20056. {
  20057. unsigned flags = countHelper.getFlags();
  20058. if (flags & TDRlimitskips)
  20059. return 0;
  20060. else if (flags & TDRlimitcreates)
  20061. return 1;
  20062. else
  20063. {
  20064. countHelper.onLimitExceeded();
  20065. throwUnexpected(); // onLimitExceeded should always throw exception
  20066. }
  20067. }
  20068. public:
  20069. CRoxieServerDiskCountActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager, ITranslatorSet *_translators)
  20070. : CRoxieServerDiskAggregateBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _manager, _translators),
  20071. countHelper((IHThorDiskCountArg &)basehelper)
  20072. {
  20073. choosenLimit = 0;
  20074. }
  20075. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20076. {
  20077. choosenLimit = countHelper.getChooseNLimit();
  20078. rowLimit = countHelper.getRowLimit();
  20079. // keyedLimit = countHelper->getKeyedLimit(); // more - should there be one?
  20080. CRoxieServerDiskAggregateBaseActivity::start(parentExtractSize, parentExtract, paused);
  20081. }
  20082. virtual const void *nextRow()
  20083. {
  20084. ActivityTimer t(totalCycles, timeActivities);
  20085. if (done) return NULL;
  20086. done = true;
  20087. unsigned __int64 totalCount = 0;
  20088. if (helper.canMatchAny() && !eof)
  20089. {
  20090. if (useRemote())
  20091. {
  20092. for (;;)
  20093. {
  20094. const void * next = remote->nextRow();
  20095. if (!next)
  20096. break;
  20097. if (meta.getFixedSize() == 1)
  20098. totalCount += *(byte *)next;
  20099. else
  20100. totalCount += *(unsigned __int64 *)next;
  20101. ReleaseRoxieRow(next);
  20102. if (totalCount > rowLimit)
  20103. {
  20104. totalCount = getSkippedCount();
  20105. break;
  20106. }
  20107. else if (totalCount >= choosenLimit)
  20108. {
  20109. totalCount = choosenLimit;
  20110. break;
  20111. }
  20112. }
  20113. }
  20114. else
  20115. {
  20116. for (;;)
  20117. {
  20118. const byte *nextRec = reader->nextRow();
  20119. if (!nextRec)
  20120. break;
  20121. totalCount += countHelper.numValid(nextRec);
  20122. reader->finishedRow();
  20123. if (totalCount > rowLimit)
  20124. {
  20125. totalCount = getSkippedCount();
  20126. break;
  20127. }
  20128. else if (totalCount >= choosenLimit)
  20129. {
  20130. totalCount = choosenLimit;
  20131. break;
  20132. }
  20133. }
  20134. }
  20135. }
  20136. size32_t rowSize = meta.getFixedSize();
  20137. void * result = rowAllocator->createRow();
  20138. if (rowSize == 1)
  20139. *(byte *)result = (byte)totalCount;
  20140. else
  20141. {
  20142. assertex(rowSize == sizeof(unsigned __int64));
  20143. *(unsigned __int64 *)result = totalCount;
  20144. }
  20145. return rowAllocator->finalizeRow(rowSize, result, rowSize);
  20146. }
  20147. };
  20148. class CRoxieServerDiskAggregateActivity : public CRoxieServerDiskAggregateBaseActivity
  20149. {
  20150. IHThorCompoundAggregateExtra & aggregateHelper;
  20151. public:
  20152. CRoxieServerDiskAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  20153. unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager, ITranslatorSet *_translators)
  20154. : CRoxieServerDiskAggregateBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _manager, _translators),
  20155. aggregateHelper((IHThorDiskAggregateArg &)basehelper)
  20156. {
  20157. }
  20158. const void * gatherMerged()
  20159. {
  20160. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  20161. size32_t finalSize = 0;
  20162. if (useRemote())
  20163. {
  20164. const void * firstRow = remote->nextRow();
  20165. if (!firstRow)
  20166. {
  20167. rowBuilder.ensureRow();
  20168. finalSize = aggregateHelper.clearAggregate(rowBuilder);
  20169. }
  20170. else
  20171. {
  20172. // NOTE need to clone this because going to modify below, could special case 1 row only
  20173. finalSize = cloneRow(rowBuilder, firstRow, meta);
  20174. ReleaseRoxieRow(firstRow);
  20175. }
  20176. for (;;)
  20177. {
  20178. const void * next = remote->nextRow();
  20179. if (!next)
  20180. break;
  20181. finalSize = aggregateHelper.mergeAggregate(rowBuilder, next);
  20182. ReleaseRoxieRow(next);
  20183. }
  20184. }
  20185. else
  20186. {
  20187. aggregateHelper.clearAggregate(rowBuilder);
  20188. if (helper.canMatchAny() && !eof)
  20189. {
  20190. for (;;)
  20191. {
  20192. const byte *nextRec = reader->nextRow();
  20193. if (!nextRec)
  20194. break;
  20195. aggregateHelper.processRow(rowBuilder, nextRec);
  20196. reader->finishedRow();
  20197. }
  20198. }
  20199. finalSize = meta.getRecordSize(rowBuilder.getSelf());
  20200. }
  20201. return rowBuilder.finalizeRowClear(finalSize);
  20202. }
  20203. virtual const void *nextRow()
  20204. {
  20205. ActivityTimer t(totalCycles, timeActivities);
  20206. if (done) return NULL;
  20207. const void * ret = gatherMerged();
  20208. done = true;
  20209. return ret;
  20210. }
  20211. };
  20212. class CRoxieServerDiskGroupAggregateActivity : public CRoxieServerDiskAggregateBaseActivity
  20213. {
  20214. IHThorDiskGroupAggregateArg & aggregateHelper;
  20215. RowAggregator resultAggregator;
  20216. bool gathered;
  20217. public:
  20218. CRoxieServerDiskGroupAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager, ITranslatorSet *_translators)
  20219. : CRoxieServerDiskAggregateBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _manager, _translators),
  20220. aggregateHelper((IHThorDiskGroupAggregateArg &)basehelper),
  20221. resultAggregator(aggregateHelper, aggregateHelper),
  20222. gathered(false)
  20223. {
  20224. }
  20225. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20226. {
  20227. gathered= false;
  20228. CRoxieServerDiskAggregateBaseActivity::start(parentExtractSize, parentExtract, paused);
  20229. resultAggregator.start(rowAllocator, ctx->queryCodeContext(), activityId);
  20230. }
  20231. virtual void reset()
  20232. {
  20233. resultAggregator.reset();
  20234. CRoxieServerDiskAggregateBaseActivity::reset();
  20235. }
  20236. void gatherMerged()
  20237. {
  20238. if (useRemote())
  20239. {
  20240. for (;;)
  20241. {
  20242. const void * next = remote->nextRow();
  20243. if (!next)
  20244. break;
  20245. resultAggregator.mergeElement(next);
  20246. ReleaseRoxieRow(next);
  20247. }
  20248. }
  20249. else
  20250. {
  20251. if (helper.canMatchAny() && !eof)
  20252. {
  20253. Owned<IInMemoryFileProcessor> processor = createGroupAggregateRecordProcessor(resultAggregator, aggregateHelper, reader);
  20254. processor->doQuery(NULL, 0, 0, 0);
  20255. }
  20256. }
  20257. gathered = true;
  20258. }
  20259. virtual const void *nextRow()
  20260. {
  20261. ActivityTimer t(totalCycles, timeActivities);
  20262. if (done)
  20263. return NULL;
  20264. if (!gathered)
  20265. gatherMerged();
  20266. Owned<AggregateRowBuilder> next = resultAggregator.nextResult();
  20267. if (next)
  20268. {
  20269. processed++;
  20270. return next->finalizeRowClear();
  20271. }
  20272. done = true;
  20273. return NULL;
  20274. }
  20275. };
  20276. class CRoxieServerDiskReadActivityFactory : public CRoxieServerActivityFactory
  20277. {
  20278. public:
  20279. RemoteActivityId remoteId;
  20280. bool isLocal;
  20281. bool sorted;
  20282. bool maySkip;
  20283. bool variableFileName;
  20284. Owned<ITranslatorSet> translators;
  20285. Owned<IInMemoryIndexManager> manager;
  20286. Owned<const IResolvedFile> datafile;
  20287. const char *quotes;
  20288. const char *separators;
  20289. const char *terminators;
  20290. const char *escapes;
  20291. size32_t maxCsvRowSize;
  20292. CRoxieServerDiskReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  20293. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), remoteId(_remoteId)
  20294. {
  20295. isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  20296. Owned<IHThorDiskReadBaseArg> helper = (IHThorDiskReadBaseArg *) helperFactory();
  20297. sorted = (helper->getFlags() & TDRunsorted) == 0;
  20298. variableFileName = allFilesDynamic || _queryFactory.isDynamic() || ((helper->getFlags() & (TDXvarfilename|TDXdynamicfilename)) != 0);
  20299. maySkip = (helper->getFlags() & (TDRkeyedlimitskips|TDRkeyedlimitcreates|TDRlimitskips|TDRlimitcreates)) != 0;
  20300. quotes = separators = terminators = escapes = NULL;
  20301. if (!variableFileName)
  20302. {
  20303. bool isOpt = (helper->getFlags() & TDRoptional) != 0;
  20304. OwnedRoxieString fileName(helper->getFileName());
  20305. datafile.setown(_queryFactory.queryPackage().lookupFileName(fileName, isOpt, true, true, _queryFactory.queryWorkUnit(), true));
  20306. bool isSimple = (datafile && datafile->getNumParts()==1 && !_queryFactory.queryOptions().disableLocalOptimizations);
  20307. if (isLocal || isSimple)
  20308. {
  20309. if (datafile)
  20310. {
  20311. unsigned channel = isLocal ? queryFactory.queryChannel() : 0;
  20312. unsigned expectedFormatCrc = helper->getDiskFormatCrc();
  20313. unsigned projectedFormatCrc = helper->getProjectedFormatCrc();
  20314. translators.setown(datafile->getTranslators(projectedFormatCrc, helper->queryProjectedDiskRecordSize(), expectedFormatCrc, helper->queryDiskRecordSize(), skipFileFormatCrcCheck(), getEnableFieldTranslation(), false));
  20315. manager.setown(datafile->getIndexManager(isOpt, channel, translators->queryActualLayout(0), _graphNode.getPropBool("att[@name=\"preload\"]/@value", false)));
  20316. const IPropertyTree *options = datafile->queryProperties();
  20317. if (options)
  20318. {
  20319. quotes = options->queryProp("@csvQuote");
  20320. separators = options->queryProp("@csvSeparate");
  20321. terminators = options->queryProp("@csvTerminate");
  20322. escapes = options->queryProp("@csvEscape");
  20323. }
  20324. }
  20325. else
  20326. manager.setown(createInMemoryIndexManager(helper->queryProjectedDiskRecordSize()->queryRecordAccessor(true), true, nullptr));
  20327. }
  20328. }
  20329. switch (kind)
  20330. {
  20331. case TAKcsvread:
  20332. {
  20333. maxCsvRowSize = defaultMaxCsvRowSize * 1024 * 1024;
  20334. IConstWorkUnit *workunit = _queryFactory.queryWorkUnit();
  20335. if (workunit)
  20336. maxCsvRowSize = workunit->getDebugValueInt(OPT_MAXCSVROWSIZE, defaultMaxCsvRowSize) * 1024 * 1024;
  20337. break;
  20338. }
  20339. default:
  20340. maxCsvRowSize = 0; // unused
  20341. }
  20342. }
  20343. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  20344. {
  20345. unsigned numParts = datafile ? datafile->getNumParts() : 0;
  20346. switch (kind)
  20347. {
  20348. case TAKcsvread:
  20349. return new CRoxieServerCsvReadActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, sorted, maySkip, manager, translators,
  20350. quotes, separators, terminators, escapes, maxCsvRowSize);
  20351. case TAKxmlread:
  20352. case TAKjsonread:
  20353. return new CRoxieServerXmlReadActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, sorted, maySkip, manager, translators);
  20354. case TAKdiskread:
  20355. case TAKspillread:
  20356. return new CRoxieServerDiskReadActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, sorted, maySkip, manager, translators);
  20357. case TAKdisknormalize:
  20358. return new CRoxieServerDiskNormalizeActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, sorted, manager, translators);
  20359. case TAKdiskcount:
  20360. return new CRoxieServerDiskCountActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, manager, translators);
  20361. case TAKdiskaggregate:
  20362. return new CRoxieServerDiskAggregateActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, manager, translators);
  20363. case TAKdiskgroupaggregate:
  20364. return new CRoxieServerDiskGroupAggregateActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, manager, translators);
  20365. }
  20366. throwUnexpected();
  20367. }
  20368. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  20369. {
  20370. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  20371. }
  20372. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  20373. {
  20374. if (datafile)
  20375. addXrefFileInfo(reply, datafile);
  20376. else
  20377. {
  20378. // Temporarily resolve the file
  20379. Owned<IHThorDiskReadBaseArg> helper = (IHThorDiskReadBaseArg *) helperFactory();
  20380. if ((helper->getFlags() & (TDXvarfilename|TDXdynamicfilename)) == 0)
  20381. {
  20382. OwnedRoxieString fileName(helper->getFileName());
  20383. Owned<const IResolvedFile> temp = queryFactory.queryPackage().lookupFileName(fileName, true, true, false, queryFactory.queryWorkUnit(), true);
  20384. if (temp)
  20385. addXrefFileInfo(reply, temp);
  20386. }
  20387. }
  20388. }
  20389. virtual const StatisticsMapping &queryStatsMapping() const
  20390. {
  20391. return diskStatistics;
  20392. }
  20393. };
  20394. IRoxieServerActivityFactory *createRoxieServerDiskReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  20395. {
  20396. return new CRoxieServerDiskReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  20397. }
  20398. //=================================================================================
  20399. class CRoxieServerBaseIndexActivityFactory : public CRoxieServerActivityFactory
  20400. {
  20401. public:
  20402. Owned<IKeyArray> keySet;
  20403. Owned<ITranslatorSet> translators;
  20404. RemoteActivityId remoteId;
  20405. bool isSimple;
  20406. bool isLocal;
  20407. bool maySkip;
  20408. bool sorted;
  20409. bool variableFileName;
  20410. unsigned maxSeekLookahead;
  20411. Owned<const IResolvedFile> indexfile;
  20412. CRoxieServerSideCache *cache;
  20413. CRoxieServerBaseIndexActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  20414. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), remoteId(_remoteId)
  20415. {
  20416. Owned<IHThorIndexReadBaseArg> indexHelper = (IHThorIndexReadBaseArg *) helperFactory();
  20417. unsigned flags = indexHelper->getFlags();
  20418. sorted = (flags & TIRunordered) == 0;
  20419. isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  20420. variableFileName = allFilesDynamic || _queryFactory.isDynamic() || ((flags & (TIRvarfilename|TIRdynamicfilename)) != 0);
  20421. if (!variableFileName)
  20422. {
  20423. bool isOpt = (flags & TIRoptional) != 0;
  20424. OwnedRoxieString indexName(indexHelper->getFileName());
  20425. indexfile.setown(queryFactory.queryPackage().lookupFileName(indexName, isOpt, true, true, queryFactory.queryWorkUnit(), true));
  20426. if (indexfile)
  20427. {
  20428. unsigned projectedCrc = indexHelper->getProjectedFormatCrc();
  20429. unsigned expectedCrc = indexHelper->getDiskFormatCrc();
  20430. IOutputMetaData *projectedMeta = indexHelper->queryProjectedDiskRecordSize();
  20431. IOutputMetaData *expectedMeta = indexHelper->queryDiskRecordSize();
  20432. translators.setown(indexfile->getTranslators(projectedCrc, projectedMeta, expectedCrc, expectedMeta, skipFileFormatCrcCheck(), getEnableFieldTranslation(), true));
  20433. keySet.setown(indexfile->getKeyArray(isOpt, isLocal ? queryFactory.queryChannel() : 0));
  20434. }
  20435. }
  20436. isSimple = isLocal;
  20437. maySkip = (flags & (TIRkeyedlimitskips|TIRlimitskips|TIRlimitcreates|TIRkeyedlimitcreates)) != 0;
  20438. if (keySet && keySet->length()==1 && !isLocal && (flags & (TIRlimitskips|TIRlimitcreates|TIRkeyedlimitskips|TIRkeyedlimitcreates))==0)
  20439. {
  20440. IKeyIndexBase *thisBase = keySet->queryKeyPart(0);
  20441. if (thisBase->numParts()==1 && !thisBase->queryPart(0)->isTopLevelKey() && !_queryFactory.queryOptions().disableLocalOptimizations)
  20442. isSimple = true;
  20443. }
  20444. int cacheSize = _graphNode.getPropInt("hint[@name='cachehits']/@value", serverSideCacheSize);
  20445. cache = cacheSize ? new CRoxieServerSideCache(cacheSize) : NULL;
  20446. maxSeekLookahead = _graphNode.getPropInt("hint[@name='maxseeklookahead']/@value", 0);
  20447. }
  20448. ~CRoxieServerBaseIndexActivityFactory()
  20449. {
  20450. delete cache;
  20451. }
  20452. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  20453. {
  20454. if (indexfile)
  20455. addXrefFileInfo(reply, indexfile);
  20456. else
  20457. {
  20458. Owned<IHThorIndexReadBaseArg> indexHelper = (IHThorIndexReadBaseArg *) helperFactory();
  20459. if ((indexHelper->getFlags() & (TIRvarfilename|TIRdynamicfilename)) == 0)
  20460. {
  20461. OwnedRoxieString indexName(indexHelper->getFileName());
  20462. Owned<const IResolvedFile> temp = queryFactory.queryPackage().lookupFileName(indexName, true, true, false, queryFactory.queryWorkUnit(), true);
  20463. if (temp)
  20464. addXrefFileInfo(reply, temp);
  20465. }
  20466. }
  20467. }
  20468. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  20469. {
  20470. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for indexread activity");
  20471. }
  20472. virtual IRoxieServerSideCache *queryServerSideCache() const
  20473. {
  20474. return cache;
  20475. }
  20476. virtual const StatisticsMapping &queryStatsMapping() const
  20477. {
  20478. return indexStatistics;
  20479. }
  20480. };
  20481. class CRoxieServerIndexActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler
  20482. {
  20483. protected:
  20484. IHThorIndexReadBaseArg &indexHelper;
  20485. IHThorSteppedSourceExtra *steppedExtra;
  20486. Linked<IKeyArray> keySet;
  20487. Linked<ITranslatorSet> translators;
  20488. CSkippableRemoteResultAdaptor remote;
  20489. CIndexTransformCallback callback;
  20490. bool sorted;
  20491. bool variableFileName;
  20492. bool variableInfoPending;
  20493. bool isOpt;
  20494. bool isLocal;
  20495. unsigned __int64 rowLimit;
  20496. unsigned __int64 keyedLimit;
  20497. unsigned __int64 choosenLimit;
  20498. unsigned accepted;
  20499. unsigned rejected;
  20500. unsigned seekGEOffset;
  20501. Owned<IKeyManager> tlk;
  20502. Owned<const IResolvedFile> varFileInfo;
  20503. const RemoteActivityId &remoteId;
  20504. void setVariableFileInfo()
  20505. {
  20506. OwnedRoxieString indexName(indexHelper.getFileName());
  20507. varFileInfo.setown(resolveLFNIndex(indexName, isOpt));
  20508. if (varFileInfo)
  20509. {
  20510. unsigned projectedCrc = indexHelper.getProjectedFormatCrc();
  20511. unsigned expectedCrc = indexHelper.getDiskFormatCrc();
  20512. IOutputMetaData *projectedMeta = indexHelper.queryProjectedDiskRecordSize();
  20513. IOutputMetaData *expectedMeta = indexHelper.queryDiskRecordSize();
  20514. translators.setown(varFileInfo->getTranslators(projectedCrc, projectedMeta, expectedCrc, expectedMeta, skipFileFormatCrcCheck(), getEnableFieldTranslation(), true));
  20515. keySet.setown(varFileInfo->getKeyArray(isOpt, isLocal ? factory->queryQueryFactory().queryChannel() : 0));
  20516. }
  20517. variableInfoPending = false;
  20518. }
  20519. public:
  20520. CRoxieServerIndexActivity(IRoxieSlaveContext *_ctx, const CRoxieServerBaseIndexActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  20521. bool _sorted, bool _isLocal, bool _maySkip)
  20522. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  20523. keySet(_factory->keySet),
  20524. translators(_factory->translators),
  20525. indexHelper((IHThorIndexReadBaseArg &)basehelper),
  20526. remote(_ctx, this, _remoteId, meta.queryOriginal(), indexHelper, *this, _sorted, false, _maySkip),
  20527. remoteId(_remoteId),
  20528. sorted(_sorted),
  20529. isLocal(_isLocal)
  20530. {
  20531. indexHelper.setCallback(&callback);
  20532. steppedExtra = indexHelper.querySteppingExtra();
  20533. variableFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((indexHelper.getFlags() & (TIRvarfilename|TIRdynamicfilename)) != 0);
  20534. variableInfoPending = false;
  20535. isOpt = (indexHelper.getFlags() & TIRoptional) != 0;
  20536. seekGEOffset = 0;
  20537. // started = false;
  20538. rejected = accepted = 0;
  20539. rowLimit = choosenLimit = keyedLimit = 0;
  20540. }
  20541. virtual const IResolvedFile *queryVarFileInfo() const
  20542. {
  20543. return varFileInfo;
  20544. }
  20545. virtual void onCreate(IHThorArg *_colocalParent)
  20546. {
  20547. CRoxieServerActivity::onCreate(_colocalParent);
  20548. remote.onCreate(_colocalParent);
  20549. }
  20550. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20551. {
  20552. accepted = 0;
  20553. rejected = 0;
  20554. rowLimit = (unsigned __int64) -1;
  20555. keyedLimit = (unsigned __int64 ) -1;
  20556. choosenLimit = I64C(0x7fffffffffffffff);
  20557. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  20558. remote.onStart(parentExtractSize, parentExtract);
  20559. variableInfoPending = variableFileName;
  20560. }
  20561. void processAllKeys()
  20562. {
  20563. try
  20564. {
  20565. if (indexHelper.canMatchAny())
  20566. {
  20567. if (variableInfoPending)
  20568. setVariableFileInfo();
  20569. remote.setLimits(rowLimit, keyedLimit, choosenLimit);
  20570. if (keySet)
  20571. {
  20572. // MORE - this recreates the segmonitors per part but not per fileno (which is a little backwards).
  20573. // 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
  20574. // However order is probably better to iterate fileno's inside partnos
  20575. // MORE - also not properly supporting STEPPED I fear.
  20576. // A superkey that mixes single and multipart or tlk and roroot keys might be hard
  20577. for (unsigned partNo = 0; partNo < keySet->length(); partNo++)
  20578. {
  20579. IKeyIndexBase *thisBase = keySet->queryKeyPart(partNo);
  20580. if (thisBase)
  20581. {
  20582. unsigned fileNo = 0;
  20583. IKeyIndex *thisKey = thisBase->queryPart(fileNo);
  20584. if (!thisKey->isTopLevelKey())
  20585. {
  20586. if (keyedLimit != (unsigned __int64) -1)
  20587. {
  20588. if ((indexHelper.getFlags() & TIRcountkeyedlimit) != 0)
  20589. {
  20590. Owned<IKeyManager> countKey;
  20591. countKey.setown(createLocalKeyManager(indexHelper.queryDiskRecordSize()->queryRecordAccessor(true), thisKey, this, indexHelper.hasNewSegmentMonitors()));
  20592. countKey->setLayoutTranslator(translators->queryTranslator(fileNo));
  20593. createSegmentMonitors(countKey);
  20594. unsigned __int64 count = countKey->checkCount(keyedLimit);
  20595. if (count > keyedLimit)
  20596. {
  20597. if (traceLevel > 4)
  20598. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  20599. onLimitExceeded(true);
  20600. }
  20601. }
  20602. }
  20603. }
  20604. if (seekGEOffset && !thisKey->isTopLevelKey())
  20605. {
  20606. tlk.setown(createSingleKeyMerger(indexHelper.queryDiskRecordSize()->queryRecordAccessor(true), thisKey, seekGEOffset, this, indexHelper.hasNewSegmentMonitors()));
  20607. }
  20608. else
  20609. {
  20610. tlk.setown(createLocalKeyManager(indexHelper.queryDiskRecordSize()->queryRecordAccessor(true), thisKey, this, indexHelper.hasNewSegmentMonitors()));
  20611. if (!thisKey->isTopLevelKey())
  20612. tlk->setLayoutTranslator(translators->queryTranslator(fileNo));
  20613. else
  20614. tlk->setLayoutTranslator(nullptr);
  20615. }
  20616. createSegmentMonitors(tlk);
  20617. if (queryTraceLevel() > 3 || ctx->queryProbeManager())
  20618. {
  20619. StringBuffer out;
  20620. tlk->describeFilter(out);
  20621. CTXLOG("Using filter %s", out.str());
  20622. if (ctx->queryProbeManager())
  20623. ctx->queryProbeManager()->setNodeProperty(this, "filter", out.str());
  20624. }
  20625. tlk->reset();
  20626. for (;;) // for each file part
  20627. {
  20628. //block for TransformCallbackAssociation
  20629. {
  20630. TransformCallbackAssociation associate(callback, tlk);
  20631. if (thisKey->isTopLevelKey())
  20632. {
  20633. if (thisKey->isFullySorted())
  20634. {
  20635. while (tlk->lookup(false))
  20636. {
  20637. unsigned slavePart = (unsigned)extractFpos(tlk);
  20638. if (slavePart)
  20639. {
  20640. accepted++;
  20641. remote.getMem(slavePart, fileNo, 0); // the cached context is all we need to send
  20642. if (sorted && numChannels>1)
  20643. remote.flush(); // don't combine parts if we need result sorted, except on a 1-way
  20644. }
  20645. }
  20646. }
  20647. else
  20648. {
  20649. unsigned slavePart = tlk->getPartition(); // Returns 0 if no partition info, or filter cannot be partitioned
  20650. remote.getMem(slavePart, fileNo, 0);
  20651. }
  20652. }
  20653. else
  20654. {
  20655. if (processSingleKey(thisKey, translators->queryTranslator(fileNo)))
  20656. break;
  20657. }
  20658. }
  20659. if (++fileNo < thisBase->numParts())
  20660. {
  20661. thisKey = thisBase->queryPart(fileNo);
  20662. tlk->setKey(thisKey);
  20663. if (!thisKey->isTopLevelKey())
  20664. tlk->setLayoutTranslator(translators->queryTranslator(fileNo));
  20665. else
  20666. tlk->setLayoutTranslator(nullptr);
  20667. tlk->reset();
  20668. }
  20669. else
  20670. break;
  20671. }
  20672. tlk->releaseSegmentMonitors();
  20673. tlk->setKey(NULL);
  20674. }
  20675. }
  20676. }
  20677. }
  20678. remote.flush();
  20679. remote.senddone();
  20680. }
  20681. catch (IException *E)
  20682. {
  20683. remote.setException(E);
  20684. }
  20685. }
  20686. virtual void createSegmentMonitors(IKeyManager *key)
  20687. {
  20688. indexHelper.createSegmentMonitors(key);
  20689. key->finishSegmentMonitors();
  20690. }
  20691. virtual bool processSingleKey(IKeyIndex *key, const IDynamicTransform * trans) = 0;
  20692. virtual void reset()
  20693. {
  20694. if (accepted)
  20695. noteStatistic(StNumIndexAccepted, accepted);
  20696. if (rejected)
  20697. noteStatistic(StNumIndexRejected, rejected);
  20698. remote.onReset();
  20699. CRoxieServerActivity::reset();
  20700. if (varFileInfo)
  20701. {
  20702. keySet.clear();
  20703. varFileInfo.clear();
  20704. }
  20705. variableInfoPending = false;
  20706. }
  20707. virtual void stop()
  20708. {
  20709. remote.onStop();
  20710. CRoxieServerActivity::stop();
  20711. }
  20712. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  20713. {
  20714. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  20715. }
  20716. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  20717. {
  20718. CRoxieServerActivity::gatherStats(merged);
  20719. remote.gatherStats(merged);
  20720. }
  20721. };
  20722. class CRoxieServerIndexReadBaseActivity : public CRoxieServerIndexActivity
  20723. {
  20724. protected:
  20725. IHThorSourceLimitTransformExtra * limitTransformExtra = nullptr;
  20726. public:
  20727. CRoxieServerIndexReadBaseActivity(IRoxieSlaveContext *_ctx, const CRoxieServerBaseIndexActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  20728. bool _sorted, bool _isLocal, bool _maySkip)
  20729. : CRoxieServerIndexActivity(_ctx, _factory, _probeManager, _remoteId, _sorted, _isLocal, _maySkip)
  20730. {
  20731. }
  20732. virtual void reset()
  20733. {
  20734. remote.onReset();
  20735. CRoxieServerIndexActivity::reset();
  20736. }
  20737. virtual const void *nextRow()
  20738. {
  20739. ActivityTimer t(totalCycles, timeActivities);
  20740. try
  20741. {
  20742. const void *ret = remote.nextRow();
  20743. if (ret)
  20744. processed++;
  20745. return ret;
  20746. }
  20747. catch (IException *E)
  20748. {
  20749. throw makeWrappedException(E);
  20750. }
  20751. }
  20752. protected:
  20753. virtual const void * createLimitFailRow(bool isKeyed)
  20754. {
  20755. ensureRowAllocator();
  20756. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  20757. assertex(limitTransformExtra);
  20758. size32_t outSize = isKeyed ? limitTransformExtra->transformOnKeyedLimitExceeded(rowBuilder) : limitTransformExtra->transformOnLimitExceeded(rowBuilder);
  20759. if (outSize)
  20760. return rowBuilder.finalizeRowClear(outSize);
  20761. return NULL;
  20762. }
  20763. };
  20764. class CRoxieServerIndexReadActivity : public CRoxieServerIndexReadBaseActivity, implements IIndexReadActivityInfo
  20765. {
  20766. protected:
  20767. IHThorIndexReadArg & readHelper;
  20768. ISteppingMeta *rawMeta = nullptr;
  20769. CSteppingMeta steppingMeta;
  20770. unsigned * seekSizes = nullptr;
  20771. bool optimizeSteppedPostFilter;
  20772. ISteppingMeta * projectedMeta = nullptr;
  20773. unsigned maxSeekLookahead;
  20774. public:
  20775. CRoxieServerIndexReadActivity(IRoxieSlaveContext *_ctx, const CRoxieServerBaseIndexActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  20776. bool _sorted, bool _isLocal, bool _maySkip, unsigned _maxSeekLookahead)
  20777. : CRoxieServerIndexReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _sorted, _isLocal, _maySkip),
  20778. readHelper((IHThorIndexReadArg &)basehelper)
  20779. {
  20780. limitTransformExtra = &readHelper;
  20781. rawMeta = readHelper.queryRawSteppingMeta();
  20782. unsigned flags = indexHelper.getFlags();
  20783. optimizeSteppedPostFilter = (flags & TIRunfilteredtransform) != 0;
  20784. seekSizes = NULL;
  20785. maxSeekLookahead = _maxSeekLookahead;
  20786. if (rawMeta)
  20787. {
  20788. const CFieldOffsetSize * fields = rawMeta->queryFields();
  20789. unsigned maxFields = rawMeta->getNumFields();
  20790. seekGEOffset = fields[0].offset;
  20791. seekSizes = new unsigned[maxFields];
  20792. seekSizes[0] = fields[0].size;
  20793. for (unsigned i=1; i < maxFields; i++)
  20794. seekSizes[i] = seekSizes[i-1] + fields[i].size;
  20795. projectedMeta = readHelper.queryProjectedSteppingMeta();
  20796. ISteppingMeta *useMeta = projectedMeta ? projectedMeta : rawMeta;
  20797. remote.setMergeInfo(useMeta); // also need to consider superfile case where there is a mix of multiway and singleparts.. ?
  20798. bool hasPostFilter = readHelper.transformMayFilter() && optimizeSteppedPostFilter;
  20799. steppingMeta.init(useMeta, hasPostFilter);
  20800. }
  20801. }
  20802. ~CRoxieServerIndexReadActivity()
  20803. {
  20804. delete [] seekSizes;
  20805. }
  20806. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20807. {
  20808. CRoxieServerIndexReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  20809. steppingMeta.setDistributed();
  20810. if (steppedExtra)
  20811. steppingMeta.setExtra(steppedExtra);
  20812. rowLimit = readHelper.getRowLimit();
  20813. keyedLimit = readHelper.getKeyedLimit();
  20814. choosenLimit = readHelper.getChooseNLimit();
  20815. if (!paused)
  20816. processAllKeys();
  20817. }
  20818. class LazyLocalKeyReader : implements IMessageUnpackCursor, implements IMessageResult, public CInterface
  20819. {
  20820. public:
  20821. IMPLEMENT_IINTERFACE;
  20822. virtual IMessageUnpackCursor *getCursor(roxiemem::IRowManager *rowMgr) const
  20823. {
  20824. Link();
  20825. return const_cast<LazyLocalKeyReader*> (this);
  20826. }
  20827. virtual const void *getMessageHeader(unsigned &length) const
  20828. {
  20829. length = 0;
  20830. return NULL;
  20831. }
  20832. virtual const void *getMessageMetadata(unsigned &length) const
  20833. {
  20834. length = 0;
  20835. return NULL;
  20836. }
  20837. virtual void discard() const
  20838. {
  20839. // nothing to do.
  20840. }
  20841. unsigned keyedCount;
  20842. unsigned matched;
  20843. bool EOFseen;
  20844. Owned<IKeyIndexSet> keySet;
  20845. Owned<IKeyManager> tlk;
  20846. CRoxieServerIndexReadActivity &owner;
  20847. LazyLocalKeyReader(CRoxieServerIndexReadActivity &_owner, IKeyIndex *key, const IDynamicTransform * trans)
  20848. : owner(_owner)
  20849. {
  20850. keyedCount = 0;
  20851. matched = 0;
  20852. EOFseen = false;
  20853. keySet.setown(createKeyIndexSet());
  20854. keySet->addIndex(LINK(key));
  20855. if (owner.seekGEOffset)
  20856. tlk.setown(createKeyMerger(owner.indexHelper.queryDiskRecordSize()->queryRecordAccessor(true), keySet, owner.seekGEOffset, &owner, owner.indexHelper.hasNewSegmentMonitors()));
  20857. else
  20858. tlk.setown(createLocalKeyManager(owner.indexHelper.queryDiskRecordSize()->queryRecordAccessor(true), keySet->queryPart(0), &owner, owner.indexHelper.hasNewSegmentMonitors()));
  20859. if (!key->isTopLevelKey())
  20860. tlk->setLayoutTranslator(trans);
  20861. owner.indexHelper.createSegmentMonitors(tlk);
  20862. tlk->finishSegmentMonitors();
  20863. tlk->reset();
  20864. }
  20865. virtual const void *getNext(int length)
  20866. {
  20867. TransformCallbackAssociation associate(owner.callback, tlk);
  20868. while (tlk->lookup(true))
  20869. {
  20870. keyedCount++;
  20871. if (keyedCount > owner.keyedLimit)
  20872. {
  20873. owner.onLimitExceeded(true); // Should throw exception
  20874. throwUnexpected();
  20875. }
  20876. size32_t transformedSize;
  20877. RtlDynamicRowBuilder rowBuilder(owner.rowAllocator);
  20878. byte const * keyRow = tlk->queryKeyBuffer();
  20879. if (likely(owner.readHelper.canMatch(keyRow)))
  20880. {
  20881. try
  20882. {
  20883. transformedSize = owner.readHelper.transform(rowBuilder, keyRow);
  20884. owner.callback.finishedRow();
  20885. }
  20886. catch (IException *E)
  20887. {
  20888. throw owner.makeWrappedException(E);
  20889. }
  20890. if (transformedSize)
  20891. {
  20892. OwnedConstRoxieRow result = rowBuilder.finalizeRowClear(transformedSize);
  20893. matched++;
  20894. if (matched > owner.rowLimit)
  20895. {
  20896. owner.onLimitExceeded(false); // Should throw exception
  20897. throwUnexpected();
  20898. }
  20899. if (matched > owner.choosenLimit) // MORE - bit of a strange place to check
  20900. {
  20901. break;
  20902. }
  20903. owner.accepted++;
  20904. return result.getClear();
  20905. }
  20906. else
  20907. owner.rejected++;
  20908. }
  20909. else
  20910. {
  20911. owner.callback.finishedRow(); // since filter might have accessed a blob
  20912. owner.rejected++;
  20913. }
  20914. }
  20915. EOFseen = true;
  20916. return NULL;
  20917. }
  20918. virtual bool atEOF() const
  20919. {
  20920. return EOFseen;
  20921. }
  20922. virtual bool isSerialized() const
  20923. {
  20924. return false;
  20925. }
  20926. };
  20927. virtual bool processSingleKey(IKeyIndex *key, const IDynamicTransform * trans) override
  20928. {
  20929. ensureRowAllocator();
  20930. remote.injectResult(new LazyLocalKeyReader(*this, key, trans));
  20931. return false;
  20932. }
  20933. virtual void onLimitExceeded(bool isKeyed)
  20934. {
  20935. if (traceLevel > 4)
  20936. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  20937. if (isKeyed)
  20938. {
  20939. if (indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates))
  20940. {
  20941. if (ctx->queryDebugContext())
  20942. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  20943. throw makeLimitSkipException(true);
  20944. }
  20945. else
  20946. readHelper.onKeyedLimitExceeded();
  20947. }
  20948. else
  20949. {
  20950. if (indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates))
  20951. {
  20952. if (ctx->queryDebugContext())
  20953. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  20954. throw makeLimitSkipException(false);
  20955. }
  20956. else
  20957. readHelper.onLimitExceeded();
  20958. }
  20959. }
  20960. virtual void serializeSkipInfo(MemoryBuffer &out, unsigned seekLen, const void *rawSeek, unsigned numFields, const void * seek, const SmartStepExtra &stepExtra) const
  20961. {
  20962. out.append((unsigned short) numFields);
  20963. out.append((unsigned short) seekLen);
  20964. out.append((unsigned short) stepExtra.queryFlags());
  20965. IMultipleStepSeekInfo *seeks = stepExtra.queryExtraSeeks();
  20966. if (seeks)
  20967. {
  20968. unsigned lookahead = 40000/seekLen;
  20969. if (maxSeekLookahead && (lookahead > maxSeekLookahead))
  20970. lookahead = maxSeekLookahead;
  20971. seeks->ensureFilled(seek, numFields, lookahead);
  20972. out.append(lookahead != seeks->ordinality()); // seeksAreEof flag
  20973. unsigned serialized = 1; // rawseek is always serialized...
  20974. unsigned patchLength = out.length();
  20975. out.append(serialized); // NOTE - we come back and patch with the actual value...
  20976. out.append(seekLen, rawSeek);
  20977. if (seeks->ordinality())
  20978. {
  20979. const void *lastSeek = rawSeek;
  20980. byte *nextSeek = NULL;
  20981. if (projectedMeta)
  20982. nextSeek = (byte *) alloca(seekLen);
  20983. for (unsigned i = 0; i < seeks->ordinality(); i++)
  20984. {
  20985. if (projectedMeta)
  20986. {
  20987. RtlStaticRowBuilder rowBuilder(nextSeek-seekGEOffset, seekGEOffset+seekLen);
  20988. readHelper.mapOutputToInput(rowBuilder, seeks->querySeek(i), numFields); // NOTE - weird interface to mapOutputToInput means that it STARTS writing at seekGEOffset...
  20989. }
  20990. else
  20991. nextSeek = (byte *) seeks->querySeek(i)+seekGEOffset;
  20992. int diff = memcmp(nextSeek, lastSeek, seekLen);
  20993. if (diff > 0)
  20994. {
  20995. serialized++;
  20996. out.append(seekLen, nextSeek);
  20997. lastSeek = (const byte *) out.reserve(0) - seekLen;
  20998. }
  20999. }
  21000. unsigned length = out.length();
  21001. out.setWritePos(patchLength);
  21002. out.append(serialized);
  21003. out.setWritePos(length);
  21004. }
  21005. }
  21006. else
  21007. {
  21008. out.append(false);
  21009. out.append(1);
  21010. out.append(seekLen, rawSeek);
  21011. }
  21012. }
  21013. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  21014. {
  21015. ActivityTimer t(totalCycles, timeActivities);
  21016. try
  21017. {
  21018. unsigned seeklen = 0;
  21019. const void *rawSeek = NULL;
  21020. if (seek && numFields)
  21021. {
  21022. seeklen = seekSizes[numFields-1];
  21023. rawSeek = (const byte *)seek + seekGEOffset;
  21024. if (projectedMeta)
  21025. {
  21026. byte * temp = (byte *) alloca(seeklen);
  21027. RtlStaticRowBuilder rawBuilder(temp-seekGEOffset, seekGEOffset+seeklen);
  21028. readHelper.mapOutputToInput(rawBuilder, seek, numFields); // NOTE - weird interface to mapOutputToInput means that it STARTS writing at seekGEOffset...
  21029. rawSeek = (byte *)temp;
  21030. }
  21031. }
  21032. const void *ret = remote.nextRowGE(seek, rawSeek, numFields, seeklen, wasCompleteMatch, stepExtra);
  21033. if (ret && wasCompleteMatch) // GH pleas confirm the wasCompleteMatch I just added here is right
  21034. processed++;
  21035. return ret;
  21036. }
  21037. catch (IException *E)
  21038. {
  21039. throw makeWrappedException(E);
  21040. }
  21041. }
  21042. virtual IInputSteppingMeta * querySteppingMeta()
  21043. {
  21044. if (rawMeta && steppingEnabled && ((indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates|TIRkeyedlimitskips|TIRkeyedlimitcreates)) == 0))
  21045. return &steppingMeta;
  21046. return NULL;
  21047. }
  21048. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  21049. {
  21050. if (variableInfoPending)
  21051. setVariableFileInfo();
  21052. return this;
  21053. }
  21054. virtual IKeyArray *getKeySet() const
  21055. {
  21056. return keySet.getLink();
  21057. }
  21058. virtual const IResolvedFile *getVarFileInfo() const
  21059. {
  21060. return varFileInfo.getLink();
  21061. }
  21062. virtual ITranslatorSet *getTranslators() const override
  21063. {
  21064. return translators.getLink();
  21065. }
  21066. virtual void mergeSegmentMonitors(IIndexReadContext *irc) const
  21067. {
  21068. indexHelper.createSegmentMonitors(irc); // NOTE: they will merge
  21069. }
  21070. virtual IRoxieServerActivity *queryActivity() { return this; }
  21071. virtual const RemoteActivityId& queryRemoteId() const
  21072. {
  21073. return remoteId;
  21074. }
  21075. };
  21076. class CRoxieServerSimpleIndexReadActivity : public CRoxieServerActivity, implements IIndexReadActivityInfo
  21077. {
  21078. IHThorIndexReadArg & indexHelper;
  21079. IHThorSteppedSourceExtra * steppedExtra;
  21080. bool eof;
  21081. Linked<IKeyArray>keySet;
  21082. Owned<IKeyIndexSet>keyIndexSet;
  21083. Owned<IKeyManager> tlk;
  21084. Linked<ITranslatorSet> translators;
  21085. CIndexTransformCallback callback;
  21086. unsigned __int64 keyedLimit;
  21087. unsigned rowLimit;
  21088. unsigned chooseNLimit;
  21089. unsigned accepted;
  21090. unsigned rejected;
  21091. unsigned keyedCount;
  21092. ISteppingMeta * rawMeta;
  21093. ISteppingMeta * projectedMeta;
  21094. size32_t seekGEOffset;
  21095. unsigned * seekSizes;
  21096. CSteppingMeta steppingMeta;
  21097. Owned<const IResolvedFile> varFileInfo;
  21098. const RemoteActivityId &remoteId;
  21099. bool firstRead;
  21100. bool variableFileName;
  21101. bool variableInfoPending;
  21102. bool isOpt;
  21103. bool isLocal;
  21104. bool optimizeSteppedPostFilter;
  21105. // MORE there may be enough in common between this and CRoxieServerIndexActivity to warrant some refactoring
  21106. void initKeySet()
  21107. {
  21108. if ((keySet->length() > 1 || rawMeta != NULL) && translators->isTranslating())
  21109. {
  21110. throw MakeStringException(ROXIE_UNIMPLEMENTED_ERROR, "Layout translation is not available when merging key parts or smart-stepping, as it may change record order");
  21111. }
  21112. keyIndexSet.setown(createKeyIndexSet());
  21113. for (unsigned part = 0; part < keySet->length(); part++)
  21114. {
  21115. IKeyIndexBase *kib = keySet->queryKeyPart(part);
  21116. if (kib)
  21117. {
  21118. for (unsigned subpart = 0; subpart < kib->numParts(); subpart++)
  21119. {
  21120. IKeyIndex *k = kib->queryPart(subpart);
  21121. if (k)
  21122. {
  21123. assertex(!k->isTopLevelKey());
  21124. keyIndexSet->addIndex(LINK(k));
  21125. }
  21126. }
  21127. }
  21128. }
  21129. }
  21130. void setVariableFileInfo()
  21131. {
  21132. OwnedRoxieString indexName(indexHelper.getFileName());
  21133. varFileInfo.setown(resolveLFNIndex(indexName, isOpt));
  21134. unsigned projectedCrc = indexHelper.getProjectedFormatCrc();
  21135. unsigned expectedCrc = indexHelper.getDiskFormatCrc();
  21136. IOutputMetaData *projectedMeta = indexHelper.queryProjectedDiskRecordSize();
  21137. IOutputMetaData *expectedMeta = indexHelper.queryDiskRecordSize();
  21138. translators.setown(varFileInfo->getTranslators(projectedCrc, projectedMeta, expectedCrc, expectedMeta, skipFileFormatCrcCheck(), getEnableFieldTranslation(), true));
  21139. keySet.setown(varFileInfo->getKeyArray(isOpt, isLocal ? factory->queryQueryFactory().queryChannel() : 0));
  21140. initKeySet();
  21141. variableInfoPending = false;
  21142. }
  21143. void onEOF()
  21144. {
  21145. callback.setManager(NULL);
  21146. eof = true;
  21147. tlk.clear();
  21148. }
  21149. public:
  21150. CRoxieServerSimpleIndexReadActivity(IRoxieSlaveContext *_ctx, const CRoxieServerBaseIndexActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, bool _isLocal)
  21151. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  21152. indexHelper((IHThorIndexReadArg &)basehelper),
  21153. translators(_factory->translators),
  21154. keySet(_factory->keySet),
  21155. isLocal(_isLocal),
  21156. remoteId(_remoteId)
  21157. {
  21158. rowLimit = 0;
  21159. keyedLimit = 0;
  21160. chooseNLimit = 0;
  21161. indexHelper.setCallback(&callback);
  21162. steppedExtra = indexHelper.querySteppingExtra();
  21163. unsigned flags = indexHelper.getFlags();
  21164. variableFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((flags & (TIRvarfilename|TIRdynamicfilename)) != 0);
  21165. variableInfoPending = false;
  21166. isOpt = (flags & TIRoptional) != 0;
  21167. optimizeSteppedPostFilter = (flags & TIRunfilteredtransform) != 0;
  21168. firstRead = true;
  21169. accepted = 0;
  21170. rejected = 0;
  21171. keyedCount = 0;
  21172. eof = false;
  21173. rawMeta = indexHelper.queryRawSteppingMeta();
  21174. projectedMeta = indexHelper.queryProjectedSteppingMeta();
  21175. seekGEOffset = 0;
  21176. seekSizes = NULL;
  21177. if (rawMeta)
  21178. {
  21179. // MORE - should check all keys in maxFields list can actually be keyed.
  21180. const CFieldOffsetSize * fields = rawMeta->queryFields();
  21181. unsigned maxFields = rawMeta->getNumFields();
  21182. seekGEOffset = fields[0].offset;
  21183. seekSizes = new unsigned[maxFields];
  21184. seekSizes[0] = fields[0].size;
  21185. for (unsigned i=1; i < maxFields; i++)
  21186. seekSizes[i] = seekSizes[i-1] + fields[i].size;
  21187. bool hasPostFilter = indexHelper.transformMayFilter() && optimizeSteppedPostFilter;
  21188. if (projectedMeta)
  21189. steppingMeta.init(projectedMeta, hasPostFilter);
  21190. else
  21191. steppingMeta.init(rawMeta, hasPostFilter);
  21192. }
  21193. }
  21194. virtual const IResolvedFile *queryVarFileInfo() const
  21195. {
  21196. return varFileInfo;
  21197. }
  21198. ~CRoxieServerSimpleIndexReadActivity()
  21199. {
  21200. delete [] seekSizes;
  21201. }
  21202. virtual bool needsAllocator() const { return true; }
  21203. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21204. {
  21205. firstRead = true;
  21206. accepted = 0;
  21207. rejected = 0;
  21208. keyedCount = 0;
  21209. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  21210. if (steppedExtra)
  21211. steppingMeta.setExtra(steppedExtra);
  21212. eof = !indexHelper.canMatchAny();
  21213. if (variableFileName)
  21214. variableInfoPending = true;
  21215. else
  21216. {
  21217. variableInfoPending = false;
  21218. if (!keyIndexSet)
  21219. initKeySet();
  21220. }
  21221. }
  21222. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  21223. {
  21224. if (variableInfoPending)
  21225. setVariableFileInfo();
  21226. return this;
  21227. }
  21228. virtual IKeyArray *getKeySet() const
  21229. {
  21230. return keySet.getLink();
  21231. }
  21232. virtual const IResolvedFile *getVarFileInfo() const
  21233. {
  21234. return varFileInfo.getLink();
  21235. }
  21236. virtual ITranslatorSet *getTranslators() const override
  21237. {
  21238. return translators.getLink();
  21239. }
  21240. virtual void mergeSegmentMonitors(IIndexReadContext *irc) const
  21241. {
  21242. indexHelper.createSegmentMonitors(irc); // NOTE: they will merge
  21243. }
  21244. virtual IRoxieServerActivity *queryActivity() { return this; }
  21245. virtual const RemoteActivityId& queryRemoteId() const
  21246. {
  21247. return remoteId;
  21248. }
  21249. const void *nextRow()
  21250. {
  21251. bool matched = true;
  21252. return nextRowGE(NULL, 0, matched, dummySmartStepExtra);
  21253. }
  21254. unsigned __int64 checkCount(unsigned __int64 limit)
  21255. {
  21256. unsigned numParts = keyIndexSet->numParts();
  21257. unsigned __int64 result = 0;
  21258. for (unsigned i = 0; i < numParts; i++)
  21259. {
  21260. Owned<IKeyManager> countTlk = createLocalKeyManager(indexHelper.queryDiskRecordSize()->queryRecordAccessor(true), keyIndexSet->queryPart(i), this, indexHelper.hasNewSegmentMonitors());
  21261. countTlk->setLayoutTranslator(translators->queryTranslator(i));
  21262. indexHelper.createSegmentMonitors(countTlk);
  21263. countTlk->finishSegmentMonitors();
  21264. result += countTlk->checkCount(limit-result);
  21265. if (result > limit)
  21266. break;
  21267. }
  21268. return result;
  21269. }
  21270. virtual const void *nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  21271. {
  21272. ActivityTimer t(totalCycles, timeActivities);
  21273. if (eof)
  21274. return NULL;
  21275. if (firstRead)
  21276. {
  21277. if (variableInfoPending)
  21278. setVariableFileInfo();
  21279. rowLimit = (unsigned) indexHelper.getRowLimit();
  21280. chooseNLimit = (unsigned) indexHelper.getChooseNLimit();
  21281. unsigned numParts = keyIndexSet->numParts();
  21282. if (!numParts)
  21283. {
  21284. onEOF();
  21285. return NULL;
  21286. }
  21287. if (numParts > 1 || seekGEOffset)
  21288. {
  21289. tlk.setown(createKeyMerger(indexHelper.queryDiskRecordSize()->queryRecordAccessor(true), keyIndexSet, seekGEOffset, this, indexHelper.hasNewSegmentMonitors()));
  21290. // note that we don't set up translator because we don't support it. If that ever changes...
  21291. }
  21292. else
  21293. {
  21294. tlk.setown(createLocalKeyManager(indexHelper.queryDiskRecordSize()->queryRecordAccessor(true), keyIndexSet->queryPart(0), this, indexHelper.hasNewSegmentMonitors()));
  21295. tlk->setLayoutTranslator(translators->queryTranslator(0));
  21296. }
  21297. indexHelper.createSegmentMonitors(tlk);
  21298. tlk->finishSegmentMonitors();
  21299. if (queryTraceLevel() > 3 || ctx->queryProbeManager())
  21300. {
  21301. StringBuffer out;
  21302. tlk->describeFilter(out);
  21303. CTXLOG("Using filter %s", out.str());
  21304. if (ctx->queryProbeManager())
  21305. ctx->queryProbeManager()->setNodeProperty(this, "filter", out.str());
  21306. }
  21307. tlk->reset();
  21308. callback.setManager(tlk);
  21309. keyedLimit = indexHelper.getKeyedLimit();
  21310. if (keyedLimit != (unsigned __int64) -1)
  21311. {
  21312. if ((indexHelper.getFlags() & TIRcountkeyedlimit) != 0)
  21313. {
  21314. unsigned __int64 count = checkCount(keyedLimit);
  21315. if (count > keyedLimit)
  21316. {
  21317. if ((indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates)) == 0)
  21318. indexHelper.onKeyedLimitExceeded();
  21319. const void * ret = NULL;
  21320. if (indexHelper.getFlags() & TIRkeyedlimitcreates)
  21321. ret = createKeyedLimitOnFailRow();
  21322. onEOF();
  21323. return ret;
  21324. }
  21325. keyedLimit = (unsigned __int64) -1;
  21326. }
  21327. }
  21328. firstRead = false;
  21329. }
  21330. if (accepted == chooseNLimit)
  21331. {
  21332. onEOF();
  21333. return NULL;
  21334. }
  21335. const byte * rawSeek = NULL;
  21336. unsigned seekSize = 0;
  21337. if (seek)
  21338. {
  21339. seekSize = seekSizes[numFields-1];
  21340. rawSeek = (const byte *)seek + seekGEOffset;
  21341. if (projectedMeta)
  21342. {
  21343. byte *temp = (byte *) alloca(seekSize);
  21344. RtlStaticRowBuilder rawBuilder(temp-seekGEOffset, seekGEOffset+seekSize);
  21345. indexHelper.mapOutputToInput(rawBuilder, seek, numFields);// NOTE - weird interface to mapOutputToInput means that it STARTS writing at seekGEOffset...
  21346. rawSeek = (byte *)temp;
  21347. }
  21348. #ifdef _DEBUG
  21349. // StringBuffer seekStr;
  21350. // for (unsigned i = 0; i < seekSize; i++)
  21351. // {
  21352. // seekStr.appendf("%02x ", ((unsigned char *) rawSeek)[i]);
  21353. // }
  21354. // DBGLOG("nextRowGE can skip offset %d size %d value %s", seekGEOffset, seekSize, seekStr.str());
  21355. #endif
  21356. }
  21357. const byte * originalRawSeek = rawSeek;
  21358. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  21359. while (rawSeek ? tlk->lookupSkip(rawSeek, seekGEOffset, seekSize) : tlk->lookup(true))
  21360. {
  21361. checkAbort();
  21362. keyedCount++;
  21363. if (keyedCount > keyedLimit)
  21364. {
  21365. indexHelper.onKeyedLimitExceeded();
  21366. break;
  21367. }
  21368. byte const * keyRow = tlk->queryKeyBuffer();
  21369. if (likely(indexHelper.canMatch(keyRow)))
  21370. {
  21371. #ifdef _DEBUG
  21372. // StringBuffer recstr;
  21373. // unsigned size = (tlk->queryRecordSize()<80) ? tlk->queryRecordSize() : 80;
  21374. // for (unsigned i = 0; i < size; i++)
  21375. // {
  21376. // recstr.appendf("%02x ", ((unsigned char *) keyRow)[i]);
  21377. // }
  21378. // DBGLOG("nextRowGE Got %s", recstr.str());
  21379. if (originalRawSeek && memcmp(keyRow + seekGEOffset, originalRawSeek, seekSize) < 0)
  21380. assertex(!"smart seek failure");
  21381. #endif
  21382. size32_t transformedSize;
  21383. rowBuilder.ensureRow();
  21384. try
  21385. {
  21386. transformedSize =indexHelper.transform(rowBuilder, keyRow);
  21387. //if the post filter causes a mismatch, and the stepping condition no longer matches
  21388. //then return a mismatch record - so the join code can start seeking on the other input.
  21389. if (transformedSize == 0 && optimizeSteppedPostFilter && stepExtra.returnMismatches())
  21390. {
  21391. if (memcmp(keyRow + seekGEOffset, originalRawSeek, seekSize) != 0)
  21392. {
  21393. transformedSize = indexHelper.unfilteredTransform(rowBuilder, keyRow);
  21394. if (transformedSize != 0)
  21395. wasCompleteMatch = false;
  21396. }
  21397. }
  21398. callback.finishedRow();
  21399. }
  21400. catch (IException *E)
  21401. {
  21402. throw makeWrappedException(E);
  21403. }
  21404. if (transformedSize)
  21405. {
  21406. accepted++;
  21407. if (accepted > rowLimit)
  21408. {
  21409. if ((indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates)) != 0)
  21410. {
  21411. throwUnexpected(); // should not have used simple variant if maySkip set...
  21412. }
  21413. if (traceLevel > 4)
  21414. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  21415. indexHelper.onLimitExceeded();
  21416. break;
  21417. }
  21418. processed++;
  21419. #ifdef _DEBUG
  21420. // const byte *ret = (const byte *) out.get();
  21421. // CommonXmlWriter xmlwrite(XWFnoindent|XWFtrim|XWFopt);
  21422. // queryOutputMeta()->toXML(ret, xmlwrite);
  21423. // DBGLOG("ROW: {%p} %s", ret, xmlwrite.str());
  21424. #endif
  21425. return rowBuilder.finalizeRowClear(transformedSize);
  21426. }
  21427. else
  21428. rejected++;
  21429. }
  21430. else
  21431. {
  21432. callback.finishedRow(); // since filter might have accessed a blob
  21433. rejected++;
  21434. }
  21435. rawSeek = NULL;
  21436. }
  21437. onEOF();
  21438. return NULL;
  21439. }
  21440. virtual void reset()
  21441. {
  21442. onEOF();
  21443. if (accepted)
  21444. noteStatistic(StNumIndexAccepted, accepted);
  21445. if (rejected)
  21446. noteStatistic(StNumIndexRejected, rejected);
  21447. if (variableFileName)
  21448. {
  21449. varFileInfo.clear();
  21450. translators.clear();
  21451. }
  21452. variableInfoPending = false;
  21453. CRoxieServerActivity::reset();
  21454. }
  21455. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  21456. {
  21457. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  21458. }
  21459. virtual IInputSteppingMeta * querySteppingMeta()
  21460. {
  21461. if (rawMeta && steppingEnabled && ((indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates|TIRkeyedlimitskips|TIRkeyedlimitcreates)) == 0))
  21462. return &steppingMeta;
  21463. return NULL;
  21464. }
  21465. protected:
  21466. const void * createKeyedLimitOnFailRow()
  21467. {
  21468. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  21469. size32_t outSize = indexHelper.transformOnKeyedLimitExceeded(rowBuilder);
  21470. if (outSize)
  21471. return rowBuilder.finalizeRowClear(outSize);
  21472. return NULL;
  21473. }
  21474. };
  21475. class CRoxieServerIndexReadActivityFactory : public CRoxieServerBaseIndexActivityFactory
  21476. {
  21477. public:
  21478. CRoxieServerIndexReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21479. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId)
  21480. {
  21481. }
  21482. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  21483. {
  21484. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  21485. return new CRoxieServerNullActivity(_ctx, this, _probeManager);
  21486. else if (isSimple && !maySkip)
  21487. return new CRoxieServerSimpleIndexReadActivity(_ctx, this, _probeManager, remoteId, isLocal);
  21488. else
  21489. return new CRoxieServerIndexReadActivity(_ctx, this, _probeManager, remoteId, sorted, isLocal, maySkip, maxSeekLookahead);
  21490. }
  21491. };
  21492. IRoxieServerActivityFactory *createRoxieServerIndexReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21493. {
  21494. return new CRoxieServerIndexReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  21495. }
  21496. //--------------------------------------------------------------------------------------------------------------------------
  21497. class CRoxieServerNullCountActivity : public CRoxieServerActivity
  21498. {
  21499. bool done;
  21500. public:
  21501. CRoxieServerNullCountActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  21502. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  21503. {
  21504. done = false;
  21505. }
  21506. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21507. {
  21508. done = false;
  21509. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  21510. }
  21511. virtual bool needsAllocator() const { return true; }
  21512. virtual const void *nextRow()
  21513. {
  21514. ActivityTimer t(totalCycles, timeActivities);
  21515. if (done) return NULL;
  21516. done = true;
  21517. size32_t rowSize = meta.getFixedSize();
  21518. void * nullRow = rowAllocator->createRow();
  21519. if (rowSize == 1)
  21520. *(byte *)nullRow = 0;
  21521. else
  21522. {
  21523. assertex(rowSize == sizeof(unsigned __int64));
  21524. *(unsigned __int64 *)nullRow = 0;
  21525. }
  21526. return rowAllocator->finalizeRow(rowSize, nullRow, rowSize);
  21527. }
  21528. };
  21529. class CRoxieServerIndexCountActivity : public CRoxieServerIndexActivity
  21530. {
  21531. IHThorIndexCountArg & countHelper;
  21532. bool done;
  21533. public:
  21534. CRoxieServerIndexCountActivity(IRoxieSlaveContext *_ctx, const CRoxieServerBaseIndexActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, bool _isLocal)
  21535. : CRoxieServerIndexActivity(_ctx, _factory, _probeManager, _remoteId, false, _isLocal, false),
  21536. countHelper((IHThorIndexCountArg &)basehelper),
  21537. done(false)
  21538. {
  21539. }
  21540. virtual bool needsAllocator() const { return true; }
  21541. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21542. {
  21543. done = false;
  21544. CRoxieServerIndexActivity::start(parentExtractSize, parentExtract, paused);
  21545. choosenLimit = countHelper.getChooseNLimit();
  21546. rowLimit = countHelper.getRowLimit();
  21547. keyedLimit = countHelper.getKeyedLimit();
  21548. if (!paused)
  21549. processAllKeys();
  21550. }
  21551. virtual bool processSingleKey(IKeyIndex *key, const IDynamicTransform * trans) override
  21552. {
  21553. unsigned __int64 count = 0;
  21554. if (countHelper.hasFilter())
  21555. {
  21556. while (tlk->lookup(true))
  21557. {
  21558. try
  21559. {
  21560. count += countHelper.numValid(tlk->queryKeyBuffer());
  21561. callback.finishedRow();
  21562. }
  21563. catch (IException *E)
  21564. {
  21565. throw makeWrappedException(E);
  21566. }
  21567. accepted++;
  21568. if (count >= choosenLimit) // MORE - what about limit?
  21569. break;
  21570. }
  21571. }
  21572. else
  21573. count = tlk->getCount(); //MORE: GH->RKC There should be value in providing a max limit to getCount()
  21574. if (count)
  21575. {
  21576. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), false);
  21577. if (count > choosenLimit)
  21578. count = choosenLimit;
  21579. void * recBuffer = rowAllocator->createRow();
  21580. if (meta.getFixedSize() == 1)
  21581. *(byte *)recBuffer = (byte)count;
  21582. else
  21583. {
  21584. assertex(meta.getFixedSize() == sizeof(unsigned __int64));
  21585. *(unsigned __int64 *)recBuffer = count;
  21586. }
  21587. recBuffer = rowAllocator->finalizeRow(meta.getFixedSize(), recBuffer, meta.getFixedSize());
  21588. result->append(recBuffer);
  21589. remote.injectResult(result.getClear());
  21590. //GH->RKC for count(,choosen)/exists passing in the previous count would short-circuit this much earlier
  21591. if (count >= choosenLimit)
  21592. return true;
  21593. }
  21594. return false;
  21595. }
  21596. virtual void onLimitExceeded(bool isKeyed)
  21597. {
  21598. if (traceLevel > 4)
  21599. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  21600. if (isKeyed)
  21601. {
  21602. if (indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates))
  21603. {
  21604. if (ctx->queryDebugContext())
  21605. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  21606. throw makeLimitSkipException(true);
  21607. }
  21608. else
  21609. {
  21610. countHelper.onKeyedLimitExceeded();
  21611. }
  21612. }
  21613. else
  21614. {
  21615. if (indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates))
  21616. {
  21617. if (ctx->queryDebugContext())
  21618. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  21619. throw makeLimitSkipException(false);
  21620. }
  21621. else
  21622. {
  21623. countHelper.onLimitExceeded();
  21624. }
  21625. }
  21626. }
  21627. virtual const void *createLimitFailRow(bool isKeyed)
  21628. {
  21629. throwUnexpected();
  21630. }
  21631. virtual const void *nextRow()
  21632. {
  21633. ActivityTimer t(totalCycles, timeActivities);
  21634. if (done) return NULL;
  21635. done = true;
  21636. unsigned __int64 totalCount = 0;
  21637. bool hasLimit = rowLimit != (unsigned __int64) -1;
  21638. try
  21639. {
  21640. for (;;)
  21641. {
  21642. const void * next = remote.nextRow();
  21643. if (!next)
  21644. break;
  21645. if (meta.getFixedSize() == 1)
  21646. totalCount += *(byte *)next;
  21647. else
  21648. totalCount += *(unsigned __int64 *) next;
  21649. ReleaseRoxieRow(next);
  21650. if (totalCount > rowLimit || (totalCount > choosenLimit && !hasLimit)) // can't break out early if there is a possibility of later slave throwing limit exception
  21651. break;
  21652. }
  21653. if (totalCount > rowLimit)
  21654. {
  21655. unsigned flags = indexHelper.getFlags();
  21656. if (flags & TIRlimitskips)
  21657. totalCount = 0;
  21658. else if (flags & TIRlimitcreates)
  21659. totalCount = 1;
  21660. else
  21661. countHelper.onLimitExceeded();
  21662. }
  21663. else if (totalCount > choosenLimit)
  21664. totalCount = choosenLimit;
  21665. }
  21666. catch (IException *E)
  21667. {
  21668. if (QUERYINTERFACE(E, LimitSkipException))
  21669. {
  21670. totalCount = 0;
  21671. unsigned flags = indexHelper.getFlags();
  21672. if (E->errorCode() == KeyedLimitSkipErrorCode)
  21673. {
  21674. if (flags & TIRkeyedlimitcreates)
  21675. totalCount++;
  21676. }
  21677. else
  21678. {
  21679. if (flags & TIRlimitcreates)
  21680. totalCount++;
  21681. }
  21682. if (totalCount > choosenLimit)
  21683. totalCount = choosenLimit; // would have to be weird code (and escape the optimizer...)
  21684. E->Release();
  21685. }
  21686. else
  21687. throw ;
  21688. }
  21689. void * result = rowAllocator->createRow();
  21690. if (meta.getFixedSize() == 1)
  21691. *(byte *)result = (byte)totalCount;
  21692. else
  21693. {
  21694. assertex(meta.getFixedSize() == sizeof(unsigned __int64));
  21695. *(unsigned __int64 *)result = totalCount;
  21696. }
  21697. return rowAllocator->finalizeRow(meta.getFixedSize(), result, meta.getFixedSize());
  21698. }
  21699. };
  21700. class CRoxieServerIndexCountActivityFactory : public CRoxieServerBaseIndexActivityFactory
  21701. {
  21702. public:
  21703. CRoxieServerIndexCountActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21704. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId)
  21705. {
  21706. }
  21707. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  21708. {
  21709. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  21710. return new CRoxieServerNullCountActivity(_ctx, this, _probeManager);
  21711. // else if (isSimple)
  21712. // return new CRoxieServerSimpleIndexCountActivity(this, keySet->queryKeyPart(0)->queryPart(0));
  21713. else
  21714. return new CRoxieServerIndexCountActivity(_ctx, this, _probeManager, remoteId, isLocal);
  21715. }
  21716. };
  21717. IRoxieServerActivityFactory *createRoxieServerIndexCountActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21718. {
  21719. return new CRoxieServerIndexCountActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  21720. }
  21721. //--------------------------------------------------------------------------------------------------------------------------
  21722. class CRoxieServerNullIndexAggregateActivity : public CRoxieServerActivity
  21723. {
  21724. IHThorIndexAggregateArg &aggregateHelper;
  21725. bool done;
  21726. public:
  21727. CRoxieServerNullIndexAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  21728. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  21729. aggregateHelper((IHThorIndexAggregateArg &)basehelper)
  21730. {
  21731. done = false;
  21732. }
  21733. virtual bool needsAllocator() const { return true; }
  21734. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21735. {
  21736. done = false;
  21737. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  21738. }
  21739. virtual const void *nextRow()
  21740. {
  21741. ActivityTimer t(totalCycles, timeActivities);
  21742. if (done) return NULL;
  21743. done = true;
  21744. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  21745. size32_t thisSize = aggregateHelper.clearAggregate(rowBuilder);
  21746. return rowBuilder.finalizeRowClear(thisSize);
  21747. }
  21748. };
  21749. class CRoxieServerIndexAggregateActivity : public CRoxieServerIndexActivity
  21750. {
  21751. IHThorCompoundAggregateExtra & aggregateHelper;
  21752. bool done;
  21753. public:
  21754. CRoxieServerIndexAggregateActivity(IRoxieSlaveContext *_ctx, const CRoxieServerBaseIndexActivityFactory *_factory, IProbeManager *_probeManager,
  21755. const RemoteActivityId &_remoteId, bool _isLocal)
  21756. : CRoxieServerIndexActivity(_ctx, _factory, _probeManager, _remoteId, false, _isLocal, false),
  21757. aggregateHelper((IHThorIndexAggregateArg &)basehelper),
  21758. done(false)
  21759. {
  21760. }
  21761. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21762. {
  21763. done = false;
  21764. CRoxieServerIndexActivity::start(parentExtractSize, parentExtract, paused);
  21765. if (!paused)
  21766. processAllKeys();
  21767. }
  21768. virtual bool needsAllocator() const { return true; }
  21769. virtual bool processSingleKey(IKeyIndex *key, const IDynamicTransform * trans) override
  21770. {
  21771. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  21772. while (tlk->lookup(true))
  21773. {
  21774. if (!rowBuilder.exists())
  21775. {
  21776. rowBuilder.ensureRow();
  21777. aggregateHelper.clearAggregate(rowBuilder);
  21778. }
  21779. try
  21780. {
  21781. aggregateHelper.processRow(rowBuilder, tlk->queryKeyBuffer());
  21782. callback.finishedRow();
  21783. }
  21784. catch (IException *E)
  21785. {
  21786. throw makeWrappedException(E);
  21787. }
  21788. accepted++;
  21789. }
  21790. if (aggregateHelper.processedAnyRows())
  21791. {
  21792. size32_t size = meta.getRecordSize(rowBuilder.getSelf());
  21793. const void * recBuffer = rowBuilder.finalizeRowClear(size);
  21794. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), meta.isVariableSize());
  21795. result->append(recBuffer);
  21796. remote.injectResult(result.getClear());
  21797. }
  21798. return false;
  21799. }
  21800. virtual void onLimitExceeded(bool isKeyed)
  21801. {
  21802. if (traceLevel > 4)
  21803. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  21804. throwUnexpected();
  21805. }
  21806. virtual const void *createLimitFailRow(bool isKeyed)
  21807. {
  21808. throwUnexpected();
  21809. }
  21810. const void * gatherMerged()
  21811. {
  21812. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  21813. const void * firstRow = remote.nextRow();
  21814. size32_t finalSize = 0;
  21815. if (!firstRow)
  21816. {
  21817. rowBuilder.ensureRow();
  21818. finalSize = aggregateHelper.clearAggregate(rowBuilder);
  21819. }
  21820. else
  21821. {
  21822. // NOTE need to clone this because going to modify below, could special case 1 row only
  21823. finalSize = cloneRow(rowBuilder, firstRow, meta);
  21824. ReleaseRoxieRow(firstRow);
  21825. }
  21826. for (;;)
  21827. {
  21828. const void * next = remote.nextRow();
  21829. if (!next)
  21830. break;
  21831. finalSize = aggregateHelper.mergeAggregate(rowBuilder, next);
  21832. ReleaseRoxieRow(next);
  21833. }
  21834. return rowBuilder.finalizeRowClear(finalSize);
  21835. }
  21836. virtual const void *nextRow()
  21837. {
  21838. ActivityTimer t(totalCycles, timeActivities);
  21839. if (done) return NULL;
  21840. const void * ret = gatherMerged();
  21841. done = true;
  21842. return ret;
  21843. }
  21844. };
  21845. class CRoxieServerIndexAggregateActivityFactory : public CRoxieServerBaseIndexActivityFactory
  21846. {
  21847. public:
  21848. CRoxieServerIndexAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21849. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId)
  21850. {
  21851. }
  21852. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  21853. {
  21854. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  21855. return new CRoxieServerNullIndexAggregateActivity(_ctx, this, _probeManager);
  21856. // else if (isSimple)
  21857. // return new CRoxieServerSimpleIndexAggregateActivity(this, keySet->queryKeyPart(0)->queryPart(0));
  21858. else
  21859. return new CRoxieServerIndexAggregateActivity(_ctx, this, _probeManager, remoteId, isLocal);
  21860. }
  21861. };
  21862. IRoxieServerActivityFactory *createRoxieServerIndexAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21863. {
  21864. return new CRoxieServerIndexAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  21865. }
  21866. //--------------------------------------------------------------------------------------------------------------------------
  21867. class CRoxieServerIndexGroupAggregateActivity : public CRoxieServerIndexActivity, implements IHThorGroupAggregateCallback
  21868. {
  21869. IHThorCompoundGroupAggregateExtra & aggregateHelper;
  21870. RowAggregator singleAggregator;
  21871. RowAggregator resultAggregator;
  21872. unsigned groupSegCount;
  21873. bool gathered;
  21874. bool eof;
  21875. public:
  21876. CRoxieServerIndexGroupAggregateActivity(IRoxieSlaveContext *_ctx, const CRoxieServerBaseIndexActivityFactory *_factory, IProbeManager *_probeManager,
  21877. const RemoteActivityId &_remoteId, bool _isLocal)
  21878. : CRoxieServerIndexActivity(_ctx, _factory, _probeManager, _remoteId, false, _isLocal, false),
  21879. aggregateHelper((IHThorIndexGroupAggregateArg &)basehelper),
  21880. singleAggregator(aggregateHelper, aggregateHelper),
  21881. resultAggregator(aggregateHelper, aggregateHelper),
  21882. gathered(false), eof(true)
  21883. {
  21884. groupSegCount = 0;
  21885. }
  21886. IMPLEMENT_IINTERFACE_USING(CRoxieServerIndexActivity)
  21887. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21888. {
  21889. eof = false;
  21890. gathered= false;
  21891. CRoxieServerIndexActivity::start(parentExtractSize, parentExtract, paused);
  21892. groupSegCount = 0;
  21893. if (!paused)
  21894. processAllKeys();
  21895. resultAggregator.start(rowAllocator, ctx->queryCodeContext(), activityId);
  21896. }
  21897. virtual bool needsAllocator() const { return true; }
  21898. virtual void reset()
  21899. {
  21900. resultAggregator.reset();
  21901. CRoxieServerIndexActivity::reset();
  21902. }
  21903. virtual void processRow(const void * next)
  21904. {
  21905. singleAggregator.addRow(next);
  21906. }
  21907. virtual void createSegmentMonitors(IKeyManager *key)
  21908. {
  21909. ThorActivityKind kind = factory->getKind();
  21910. CRoxieServerIndexActivity::createSegmentMonitors(key);
  21911. if ((kind==TAKindexgroupcount || kind==TAKindexgroupexists))
  21912. groupSegCount = aggregateHelper.getGroupingMaxField();
  21913. else
  21914. groupSegCount = 0;
  21915. }
  21916. virtual bool processSingleKey(IKeyIndex *key, const IDynamicTransform * trans) override
  21917. {
  21918. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), meta.isVariableSize());
  21919. singleAggregator.start(rowAllocator, ctx->queryCodeContext(), activityId);
  21920. ThorActivityKind kind = factory->getKind();
  21921. while (tlk->lookup(true))
  21922. {
  21923. try
  21924. {
  21925. if (groupSegCount && !trans)
  21926. {
  21927. AggregateRowBuilder &rowBuilder = singleAggregator.addRow(tlk->queryKeyBuffer());
  21928. callback.finishedRow();
  21929. if (kind==TAKindexgroupcount)
  21930. {
  21931. unsigned __int64 count = tlk->getCurrentRangeCount(groupSegCount);
  21932. aggregateHelper.processCountGrouping(rowBuilder, count-1);
  21933. }
  21934. if (!tlk->nextRange(groupSegCount))
  21935. break;
  21936. }
  21937. else
  21938. {
  21939. aggregateHelper.processRow(tlk->queryKeyBuffer(), this);
  21940. callback.finishedRow();
  21941. }
  21942. }
  21943. catch (IException *E)
  21944. {
  21945. throw makeWrappedException(E);
  21946. }
  21947. accepted++;
  21948. }
  21949. for (;;)
  21950. {
  21951. Owned<AggregateRowBuilder> next = singleAggregator.nextResult();
  21952. if (!next)
  21953. break;
  21954. size32_t size = next->querySize();
  21955. result->append(next->finalizeRowClear());
  21956. }
  21957. remote.injectResult(result.getClear());
  21958. singleAggregator.reset();
  21959. return false;
  21960. }
  21961. virtual void onLimitExceeded(bool isKeyed)
  21962. {
  21963. if (traceLevel > 4)
  21964. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  21965. throwUnexpected();
  21966. }
  21967. virtual const void *createLimitFailRow(bool isKeyed)
  21968. {
  21969. throwUnexpected();
  21970. }
  21971. void gatherMerged()
  21972. {
  21973. gathered = true;
  21974. for (;;)
  21975. {
  21976. const void * next = remote.nextRow();
  21977. if (!next)
  21978. break;
  21979. resultAggregator.mergeElement(next);
  21980. ReleaseRoxieRow(next);
  21981. }
  21982. }
  21983. virtual const void *nextRow()
  21984. {
  21985. ActivityTimer t(totalCycles, timeActivities);
  21986. if (eof)
  21987. return NULL;
  21988. if (!gathered)
  21989. gatherMerged();
  21990. Owned<AggregateRowBuilder> next = resultAggregator.nextResult();
  21991. if (next)
  21992. {
  21993. processed++;
  21994. return next->finalizeRowClear();
  21995. }
  21996. eof = true;
  21997. return NULL;
  21998. }
  21999. };
  22000. class CRoxieServerIndexGroupAggregateActivityFactory : public CRoxieServerBaseIndexActivityFactory
  22001. {
  22002. public:
  22003. CRoxieServerIndexGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  22004. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId)
  22005. {
  22006. }
  22007. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  22008. {
  22009. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  22010. return new CRoxieServerNullActivity(_ctx, this, _probeManager);
  22011. // else if (isSimple)
  22012. // return new CRoxieServerSimpleIndexGroupAggregateActivity(this, keySet->queryKeyPart(0)->queryPart(0));
  22013. else
  22014. return new CRoxieServerIndexGroupAggregateActivity(_ctx, this, _probeManager, remoteId, isLocal);
  22015. }
  22016. };
  22017. IRoxieServerActivityFactory *createRoxieServerIndexGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  22018. {
  22019. return new CRoxieServerIndexGroupAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  22020. }
  22021. //--------------------------------------------------------------------------------------------------------------------------
  22022. class CRoxieServerIndexNormalizeActivity : public CRoxieServerIndexReadBaseActivity
  22023. {
  22024. IHThorIndexNormalizeArg & readHelper;
  22025. public:
  22026. CRoxieServerIndexNormalizeActivity(IRoxieSlaveContext *_ctx, const CRoxieServerBaseIndexActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  22027. bool _sorted, bool _isLocal)
  22028. : CRoxieServerIndexReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _sorted, _isLocal, false),
  22029. readHelper((IHThorIndexNormalizeArg &)basehelper)
  22030. {
  22031. limitTransformExtra = &readHelper;
  22032. }
  22033. virtual bool needsAllocator() const { return true; }
  22034. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  22035. {
  22036. CRoxieServerIndexReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  22037. rowLimit = readHelper.getRowLimit();
  22038. keyedLimit = readHelper.getKeyedLimit();
  22039. choosenLimit = readHelper.getChooseNLimit();
  22040. if (!paused)
  22041. processAllKeys();
  22042. }
  22043. virtual bool processSingleKey(IKeyIndex *key, const IDynamicTransform * trans) override
  22044. {
  22045. unsigned keyedCount = 0;
  22046. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  22047. while (tlk->lookup(true))
  22048. {
  22049. keyedCount++;
  22050. if (keyedCount > keyedLimit)
  22051. {
  22052. if (traceLevel > 4)
  22053. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  22054. onLimitExceeded(true);
  22055. break;
  22056. }
  22057. size32_t transformedSize;
  22058. if (readHelper.first(tlk->queryKeyBuffer()))
  22059. {
  22060. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), meta.isVariableSize());
  22061. do
  22062. {
  22063. if (accepted>=choosenLimit)
  22064. break;
  22065. rowBuilder.ensureRow();
  22066. try
  22067. {
  22068. transformedSize = readHelper.transform(rowBuilder);
  22069. }
  22070. catch (IException *E)
  22071. {
  22072. throw makeWrappedException(E);
  22073. }
  22074. if (transformedSize)
  22075. {
  22076. // MORE - would be a good idea to stop these asap if rowlimit exceeded
  22077. result->append(rowBuilder.finalizeRowClear(transformedSize));
  22078. accepted++;
  22079. }
  22080. else
  22081. rejected++;
  22082. } while (readHelper.next());
  22083. remote.injectResult(result.getClear());
  22084. callback.finishedRow();
  22085. if (accepted>=choosenLimit)
  22086. return true;
  22087. }
  22088. }
  22089. return false;
  22090. }
  22091. virtual void onLimitExceeded(bool isKeyed)
  22092. {
  22093. if (traceLevel > 4)
  22094. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  22095. if (isKeyed)
  22096. {
  22097. if (indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates))
  22098. {
  22099. if (ctx->queryDebugContext())
  22100. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  22101. throw makeLimitSkipException(true);
  22102. }
  22103. else
  22104. readHelper.onKeyedLimitExceeded();
  22105. }
  22106. else
  22107. {
  22108. if (indexHelper.getFlags() & (TIRlimitskips||TIRlimitcreates))
  22109. {
  22110. if (ctx->queryDebugContext())
  22111. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  22112. throw makeLimitSkipException(false);
  22113. }
  22114. else
  22115. readHelper.onLimitExceeded();
  22116. }
  22117. }
  22118. virtual const void *createLimitFailRow(bool isKeyed)
  22119. {
  22120. UNIMPLEMENTED;
  22121. }
  22122. };
  22123. class CRoxieServerIndexNormalizeActivityFactory : public CRoxieServerBaseIndexActivityFactory
  22124. {
  22125. public:
  22126. CRoxieServerIndexNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  22127. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId)
  22128. {
  22129. }
  22130. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  22131. {
  22132. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  22133. return new CRoxieServerNullActivity(_ctx, this, _probeManager);
  22134. else
  22135. return new CRoxieServerIndexNormalizeActivity(_ctx, this, _probeManager, remoteId, sorted, isLocal);
  22136. }
  22137. };
  22138. IRoxieServerActivityFactory *createRoxieServerIndexNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  22139. {
  22140. return new CRoxieServerIndexNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  22141. }
  22142. //=================================================================================
  22143. class CRoxieServerFetchActivity : public CRoxieServerActivity, implements IRecordPullerCallback, implements IRoxieServerErrorHandler
  22144. {
  22145. IHThorFetchBaseArg &helper;
  22146. Linked<IFilePartMap> map;
  22147. CRemoteResultAdaptor remote;
  22148. RecordPullerThread puller;
  22149. bool needsRHS;
  22150. bool variableFileName;
  22151. bool isOpt;
  22152. Owned<const IResolvedFile> varFileInfo;
  22153. Owned<IEngineRowAllocator> extractAllocator;
  22154. public:
  22155. CRoxieServerFetchActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IFilePartMap *_map)
  22156. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorFetchBaseArg &)basehelper), map(_map), remote(_ctx, this, _remoteId, meta.queryOriginal(), helper, *this, true, true), puller(false)
  22157. {
  22158. needsRHS = helper.transformNeedsRhs();
  22159. if (needsRHS)
  22160. extractAllocator.setown(createRowAllocator(helper.queryExtractedSize()));
  22161. variableFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  22162. isOpt = (helper.getFetchFlags() & FFdatafileoptional) != 0;
  22163. }
  22164. virtual const IResolvedFile *queryVarFileInfo() const
  22165. {
  22166. return varFileInfo;
  22167. }
  22168. virtual void onCreate(IHThorArg *_colocalParent)
  22169. {
  22170. CRoxieServerActivity::onCreate(_colocalParent);
  22171. remote.onCreate(_colocalParent);
  22172. }
  22173. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  22174. {
  22175. if (idx)
  22176. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
  22177. puller.setInput(this, _sourceIdx, _in);
  22178. }
  22179. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  22180. {
  22181. puller.connectInputStreams(ctx, consumerOrdered);
  22182. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
  22183. }
  22184. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  22185. {
  22186. if (idx==0)
  22187. return puller.queryInput();
  22188. else
  22189. return NULL;
  22190. }
  22191. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  22192. {
  22193. CRoxieServerActivity::gatherStats(merged);
  22194. remote.gatherStats(merged);
  22195. }
  22196. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  22197. {
  22198. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  22199. remote.onStart(parentExtractSize, parentExtract);
  22200. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  22201. if (variableFileName)
  22202. {
  22203. OwnedRoxieString fname(helper.getFileName());
  22204. varFileInfo.setown(resolveLFNFlat(fname, isOpt));
  22205. if (varFileInfo)
  22206. map.setown(varFileInfo->getFileMap());
  22207. }
  22208. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().fetchPreload, false, ctx);
  22209. }
  22210. virtual void stop()
  22211. {
  22212. // Called from remote, so no need to call back to it....
  22213. puller.stop();
  22214. CRoxieServerActivity::stop();
  22215. }
  22216. virtual void reset()
  22217. {
  22218. processed = remote.processed;
  22219. remote.processed = 0;
  22220. puller.reset();
  22221. if (variableFileName)
  22222. {
  22223. varFileInfo.clear();
  22224. map.clear();
  22225. }
  22226. CRoxieServerActivity::reset();
  22227. }
  22228. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  22229. {
  22230. if (idx==(unsigned)-1)
  22231. idx = 0;
  22232. return idx ? NULL : &remote;
  22233. }
  22234. virtual void processRow(const void *row)
  22235. {
  22236. // called from puller thread
  22237. offset_t rp = helper.extractPosition(row);
  22238. unsigned partNo;
  22239. if (isLocalFpos(rp))
  22240. partNo = getLocalFposPart(rp) + 1;
  22241. else
  22242. partNo = map->mapOffset(rp);
  22243. if (needsRHS)
  22244. {
  22245. RtlDynamicRowBuilder rb(extractAllocator, true);
  22246. unsigned rhsSize = helper.extractJoinFields(rb, row);
  22247. char * block = (char *) remote.getMem(partNo, 0, sizeof(rp) + sizeof(rhsSize) + rhsSize); // MORE - superfiles
  22248. *(offset_t *) block = rp;
  22249. block += sizeof(rp);
  22250. *(unsigned *) block = rhsSize;
  22251. block += sizeof(rhsSize);
  22252. memcpy(block, rb.row(), rhsSize);
  22253. }
  22254. else
  22255. *(offset_t *) remote.getMem(partNo, 0, sizeof(rp)) = rp; // MORE - superfiles
  22256. ReleaseRoxieRow(row);
  22257. }
  22258. void processEOG()
  22259. {
  22260. #ifdef FETCH_PRESERVES_GROUPING
  22261. UNIMPLEMENTED;
  22262. #endif
  22263. // else discard is correct
  22264. }
  22265. void processGroup(const ConstPointerArray &)
  22266. {
  22267. throwUnexpected();
  22268. }
  22269. void processDone()
  22270. {
  22271. // called from puller thread
  22272. remote.flush();
  22273. remote.senddone();
  22274. }
  22275. virtual bool fireException(IException *e)
  22276. {
  22277. return remote.fireException(e);
  22278. }
  22279. virtual void onLimitExceeded(bool isKeyed)
  22280. {
  22281. if (traceLevel > 4)
  22282. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  22283. if (isKeyed)
  22284. throwUnexpected();
  22285. helper.onLimitExceeded();
  22286. }
  22287. virtual const void *createLimitFailRow(bool isKeyed)
  22288. {
  22289. UNIMPLEMENTED;
  22290. }
  22291. virtual const void *nextRow()
  22292. {
  22293. throwUnexpected(); // I am nobody's input
  22294. }
  22295. };
  22296. class CRoxieServerFetchActivityFactory : public CRoxieServerActivityFactory
  22297. {
  22298. RemoteActivityId remoteId;
  22299. Owned<IFilePartMap> map;
  22300. bool variableFileName;
  22301. Owned<const IResolvedFile> datafile;
  22302. public:
  22303. CRoxieServerFetchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  22304. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), remoteId(_remoteId)
  22305. {
  22306. Owned<IHThorFetchBaseArg> helper = (IHThorFetchBaseArg *) helperFactory();
  22307. variableFileName = allFilesDynamic || _queryFactory.isDynamic() || ((helper->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  22308. if (!variableFileName)
  22309. {
  22310. OwnedRoxieString fname(helper->getFileName());
  22311. datafile.setown(_queryFactory.queryPackage().lookupFileName(fname,
  22312. (helper->getFetchFlags() & FFdatafileoptional) != 0,
  22313. true, true,
  22314. _queryFactory.queryWorkUnit(), true));
  22315. if (datafile)
  22316. map.setown(datafile->getFileMap());
  22317. }
  22318. }
  22319. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  22320. {
  22321. return new CRoxieServerFetchActivity(_ctx, this, _probeManager, remoteId, map);
  22322. }
  22323. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  22324. {
  22325. if (datafile)
  22326. addXrefFileInfo(reply, datafile);
  22327. else
  22328. {
  22329. // Temporarily resolve the file
  22330. Owned<IHThorFetchBaseArg> helper = (IHThorFetchBaseArg *) helperFactory();
  22331. if ((helper->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) == 0)
  22332. {
  22333. OwnedRoxieString fileName(helper->getFileName());
  22334. Owned<const IResolvedFile> temp = queryFactory.queryPackage().lookupFileName(fileName, true, true, false, queryFactory.queryWorkUnit(), true);
  22335. if (temp)
  22336. addXrefFileInfo(reply, temp);
  22337. }
  22338. }
  22339. }
  22340. virtual const StatisticsMapping &queryStatsMapping() const
  22341. {
  22342. return diskStatistics;
  22343. }
  22344. };
  22345. IRoxieServerActivityFactory *createRoxieServerFetchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  22346. {
  22347. return new CRoxieServerFetchActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  22348. }
  22349. // MORE - is there any point keeping this now?
  22350. class CRoxieServerDummyActivityFactory : public CRoxieServerActivityFactory // not a real activity - just used to properly link files
  22351. {
  22352. public:
  22353. Owned<const IResolvedFile> indexfile;
  22354. Owned<const IResolvedFile> datafile;
  22355. StringAttr fileName;
  22356. StringAttr indexName;
  22357. Owned<IKeyArray> keySet;
  22358. Owned<IFileIOArray> files;
  22359. CRoxieServerDummyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool isLoadDataOnly)
  22360. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  22361. {
  22362. try // does not want any missing file errors to be fatal, or throw traps - just log it
  22363. {
  22364. if (_graphNode.getPropBool("att[@name='_isSpill']/@value", false) || _graphNode.getPropBool("att[@name='_isSpillGlobal']/@value", false))
  22365. return; // ignore 'spills'
  22366. bool isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  22367. ThorActivityKind kind = getActivityKind(_graphNode);
  22368. if (kind != TAKdiskwrite && kind != TAKspillwrite && kind != TAKindexwrite && kind != TAKpiperead && kind != TAKpipewrite)
  22369. {
  22370. fileName.set(queryNodeFileName(_graphNode, kind));
  22371. indexName.set(queryNodeIndexName(_graphNode, kind));
  22372. if (indexName && !allFilesDynamic && !queryFactory.isDynamic())
  22373. {
  22374. bool isOpt = pretendAllOpt || _graphNode.getPropBool("att[@name='_isIndexOpt']/@value");
  22375. indexfile.setown(queryFactory.queryPackage().lookupFileName(indexName, isOpt, true, true, queryFactory.queryWorkUnit(), true));
  22376. if (indexfile)
  22377. keySet.setown(indexfile->getKeyArray(isOpt, isLocal ? queryFactory.queryChannel() : 0));
  22378. }
  22379. if (fileName && !allFilesDynamic && !queryFactory.isDynamic())
  22380. {
  22381. bool isOpt = pretendAllOpt || _graphNode.getPropBool("att[@name='_isOpt']/@value");
  22382. datafile.setown(_queryFactory.queryPackage().lookupFileName(fileName, isOpt, true, true, queryFactory.queryWorkUnit(), true));
  22383. if (datafile)
  22384. {
  22385. if (isLocal)
  22386. files.setown(datafile->getIFileIOArray(isOpt, queryFactory.queryChannel()));
  22387. }
  22388. }
  22389. }
  22390. }
  22391. catch(IException *E)
  22392. {
  22393. StringBuffer errors;
  22394. E->errorMessage(errors);
  22395. DBGLOG("%s File error = %s", (isLoadDataOnly) ? "LOADDATAONLY" : "SUSPENDED QUERY", errors.str());
  22396. E->Release();
  22397. }
  22398. }
  22399. 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__); }
  22400. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  22401. {
  22402. if (!allFilesDynamic)
  22403. {
  22404. if (datafile)
  22405. addXrefFileInfo(reply, datafile);
  22406. if (indexfile)
  22407. addXrefFileInfo(reply, indexfile);
  22408. }
  22409. else
  22410. {
  22411. Owned<const IResolvedFile> temp;
  22412. if (fileName.length())
  22413. {
  22414. temp.setown(queryFactory.queryPackage().lookupFileName(fileName, true, true, false, queryFactory.queryWorkUnit(), true));
  22415. if (temp)
  22416. addXrefFileInfo(reply, temp);
  22417. }
  22418. if (indexName.length())
  22419. {
  22420. temp.setown(queryFactory.queryPackage().lookupFileName(indexName, true, true, false, queryFactory.queryWorkUnit(), true));
  22421. if (temp)
  22422. addXrefFileInfo(reply, temp);
  22423. }
  22424. }
  22425. }
  22426. };
  22427. IRoxieServerActivityFactory *createRoxieServerDummyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool isLoadDataOnly)
  22428. {
  22429. return new CRoxieServerDummyActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, isLoadDataOnly);
  22430. }
  22431. //=====================================================================================================
  22432. // Keyed joins...
  22433. //
  22434. // Input records are pulled by a puller thread, which checks each LHS record to determine which (if any) channels it
  22435. // may have RHS matches on, and sends the relevant fields to the relevant slaves.
  22436. // 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
  22437. // the transform and returns rows that are created.
  22438. // 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)
  22439. //
  22440. //=====================================================================================================
  22441. class CJoinGroup;
  22442. interface IJoinProcessor
  22443. {
  22444. virtual void processEOG() = 0;
  22445. virtual CJoinGroup *createJoinGroup(const void *row) = 0;
  22446. virtual void noteEndReceived(CJoinGroup *jg, unsigned candidateCount) = 0;
  22447. virtual bool fireException(IException *E) = 0;
  22448. virtual void processCompletedGroups() = 0;
  22449. };
  22450. //------------------------------------------------------------------------------------------------------
  22451. // Class CJoinGroup has a record per LHS row, plus (if preserving grouping) a 'head of group' record
  22452. // It gathers all the corresponding RHS rows, keeping track of how may slave transactions are pending in endMarkersPending
  22453. // If preserving groups, the 'head of group' record keeps track of how many LHS records in the group are still incomplete.
  22454. // CJoinGroup records are allocated out of the Roxie row memory manager by overloading operator new, so that they are included in the
  22455. // per-query limits etc (Note that the pointer array block is not though).
  22456. // Because of that, the exact size is significant - especially whether fit just under or just over a chunking threshold...
  22457. //
  22458. // There are two phases to the life of a JoinGroup - it is created by the puller thread that is also firing off slave requests
  22459. // notePending will be called once for every slave request. Puller thread calls noteEndReceived(0) once when done - this corresponds to the
  22460. // initial count when created.
  22461. // Slave replies and are noted by the consumer thread calling addRightMatch() and noteEndReceived(n).
  22462. // Once endMarkersPending reaches 0, JoinGroup is complete. Last thread to call noteEndReceived will process the rows and destroy the group.
  22463. // There is no need for a critsec because although multiple threads will access at different times, only the consumer thread will
  22464. // access any modifiable member variables while endMarkersPending != 0 (i.e. complete() is false). Once complete returns true there is a single
  22465. // remaining reference and the JoinGroup will be processed and destroyed.
  22466. //
  22467. //------------------------------------------------------------------------------------------------------
  22468. class CJoinGroup : public CInterface
  22469. {
  22470. protected:
  22471. const void *left; // LHS row
  22472. PointerArrayOf<KeyedJoinHeader> rows; // matching RHS rows
  22473. atomic_t endMarkersPending; // How many slave responses still waiting for
  22474. CJoinGroup *groupStart; // Head of group, or NULL if not grouping
  22475. unsigned lastPartNo;
  22476. unsigned pos;
  22477. unsigned candidates; // Number of RHS keyed candidates - note this may not be the same as rows.ordinality()
  22478. public:
  22479. void *operator new(size_t size, IRowManager *a, unsigned activityId)
  22480. {
  22481. return a->allocate(size, activityId);
  22482. }
  22483. void operator delete(void *ptr, IRowManager *a, unsigned activityId)
  22484. {
  22485. ReleaseRoxieRow(ptr);
  22486. }
  22487. void operator delete(void *ptr)
  22488. {
  22489. ReleaseRoxieRow(ptr);
  22490. }
  22491. public:
  22492. CJoinGroup(const void *_left, CJoinGroup *_groupStart)
  22493. {
  22494. #ifdef TRACE_JOINGROUPS
  22495. DBGLOG("Creating joinGroup %p, groupstart %p", this, _groupStart);
  22496. #endif
  22497. candidates = 0;
  22498. lastPartNo = 0;
  22499. pos = 0;
  22500. left = _left;
  22501. groupStart = _groupStart;
  22502. if (_groupStart)
  22503. {
  22504. atomic_inc(&_groupStart->endMarkersPending);
  22505. }
  22506. atomic_set(&endMarkersPending, 1);
  22507. }
  22508. ~CJoinGroup()
  22509. {
  22510. #ifdef TRACE_JOINGROUPS
  22511. DBGLOG("Destroying joinGroup %p", this);
  22512. #endif
  22513. if (left)
  22514. {
  22515. ReleaseRoxieRow(left);
  22516. roxiemem::ReleaseRoxieRowArray(rows.ordinality(), (const void * *)rows.getArray());
  22517. rows.kill();
  22518. }
  22519. }
  22520. inline bool isHeadRecord() const
  22521. {
  22522. return left==NULL;
  22523. }
  22524. inline bool complete() const
  22525. {
  22526. return atomic_read(&endMarkersPending) == 0;
  22527. }
  22528. #ifdef TRACE_JOINGROUPS
  22529. inline void notePending(unsigned lineNo)
  22530. #else
  22531. inline void notePending()
  22532. #endif
  22533. {
  22534. assert(!complete());
  22535. atomic_inc(&endMarkersPending);
  22536. #ifdef TRACE_JOINGROUPS
  22537. DBGLOG("CJoinGroup::notePending %p from %d, count became %d group count %d", this, lineNo, atomic_read(&endMarkersPending), groupStart ? atomic_read(&groupStart->endMarkersPending) : 0);
  22538. #endif
  22539. }
  22540. inline bool inGroup(CJoinGroup *leader) const
  22541. {
  22542. return groupStart==leader;
  22543. }
  22544. inline const KeyedJoinHeader *queryRow(unsigned idx) const
  22545. {
  22546. // Single threaded by now
  22547. assert(complete());
  22548. return rows.item(idx);
  22549. }
  22550. #ifdef TRACE_JOINGROUPS
  22551. bool noteEndReceived(unsigned candidateCount, unsigned lineNo)
  22552. #else
  22553. bool noteEndReceived(unsigned candidateCount)
  22554. #endif
  22555. {
  22556. assert(!complete());
  22557. if (candidateCount)
  22558. {
  22559. candidates += candidateCount;
  22560. }
  22561. #ifdef TRACE_JOINGROUPS
  22562. 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);
  22563. #endif
  22564. // NOTE - as soon as endMarkersPending and groupStart->endMarkersPending are decremented to zero this object may get released asynchronously by other threads
  22565. // There must therefore be nothing in this method after them that acceses member variables. Think of it as a delete this...
  22566. // In particular, we can't safely reference groupStart after the dec_and_test of endMarkersPending, hence copy local first
  22567. CJoinGroup *localGroupStart = groupStart;
  22568. if (atomic_dec_and_test(&endMarkersPending))
  22569. {
  22570. if (localGroupStart)
  22571. return atomic_dec_and_test(&localGroupStart->endMarkersPending);
  22572. else
  22573. return true;
  22574. }
  22575. else
  22576. return false;
  22577. }
  22578. inline const void *queryLeft() const
  22579. {
  22580. return left;
  22581. }
  22582. void addRightMatch(KeyedJoinHeader *right)
  22583. {
  22584. assert(!complete());
  22585. unsigned short partNo = right->partNo;
  22586. if (partNo != lastPartNo)
  22587. {
  22588. // MORE - should we binchop? If we did we would need to be careful to find LAST match
  22589. if (partNo > lastPartNo)
  22590. pos = rows.length();
  22591. while (pos>0)
  22592. {
  22593. if (rows.item(pos-1)->partNo <= partNo)
  22594. break;
  22595. pos--;
  22596. }
  22597. lastPartNo = partNo;
  22598. }
  22599. rows.add(right, pos);
  22600. pos++;
  22601. }
  22602. inline unsigned rowsSeen() const
  22603. {
  22604. assert(complete());
  22605. return rows.length();
  22606. }
  22607. inline unsigned candidateCount() const
  22608. {
  22609. assert(complete());
  22610. return candidates;
  22611. }
  22612. };
  22613. #ifdef TRACE_JOINGROUPS
  22614. #define notePending() notePending(__LINE__)
  22615. #define noteEndReceived(a) noteEndReceived(a, __LINE__)
  22616. #endif
  22617. class KeyedJoinRemoteAdaptor : public CRemoteResultAdaptor // MORE - not sure it should be derived from this - makes processed all wrong, for example
  22618. {
  22619. private:
  22620. SafeQueueOf<const void, true> ready;
  22621. public:
  22622. IHThorKeyedJoinArg &helper;
  22623. unsigned joinProcessed;
  22624. bool isFullKey;
  22625. bool eof;
  22626. bool isSimple;
  22627. bool allPulled;
  22628. ActivityTimeAccumulator totalCycles;
  22629. unsigned activityId;
  22630. RecordPullerThread &puller;
  22631. SafeQueueOf<const void, true> injected; // Used in isSimple mode
  22632. Owned<IEngineRowAllocator> ccdRecordAllocator;
  22633. IJoinProcessor &processor;
  22634. KeyedJoinRemoteAdaptor(IRoxieSlaveContext *_ctx, IRoxieServerErrorHandler *_errorHandler, const RemoteActivityId &_remoteId, IHThorKeyedJoinArg &_helper,
  22635. IRoxieServerActivity &_activity, bool _isFullKey, bool _isSimple,
  22636. RecordPullerThread &_puller, IJoinProcessor &_processor)
  22637. : helper(_helper),
  22638. CRemoteResultAdaptor(_ctx, _errorHandler, _remoteId, 0, _helper, _activity, true, true),
  22639. isFullKey(_isFullKey),
  22640. isSimple(_isSimple),
  22641. puller(_puller),
  22642. processor(_processor),
  22643. activityId(_activity.queryId())
  22644. {
  22645. joinProcessed = 0;
  22646. allPulled = false;
  22647. eof = false;
  22648. }
  22649. virtual void onCreate(IHThorArg *_colocalArg)
  22650. {
  22651. CRemoteResultAdaptor::onCreate(_colocalArg);
  22652. ccdRecordAllocator.setown(activity.createRowAllocator(helper.queryJoinFieldsRecordSize()));
  22653. }
  22654. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  22655. {
  22656. eof = false;
  22657. joinProcessed = 0;
  22658. totalCycles.totalCycles = 0;
  22659. allPulled = false;
  22660. assertex(ready.ordinality()==0);
  22661. CRemoteResultAdaptor::start(parentExtractSize, parentExtract, paused);
  22662. }
  22663. virtual void reset()
  22664. {
  22665. CRemoteResultAdaptor::reset();
  22666. while (ready.ordinality())
  22667. {
  22668. const void *goer = ready.dequeue();
  22669. if (goer)
  22670. ReleaseRoxieRow(goer);
  22671. }
  22672. while (injected.ordinality())
  22673. {
  22674. const void *goer = injected.dequeue();
  22675. if (goer)
  22676. ReleaseRoxieRow(goer);
  22677. }
  22678. }
  22679. inline void addResult(const void *row)
  22680. {
  22681. ready.enqueue(row);
  22682. }
  22683. virtual unsigned __int64 queryTotalCycles() const
  22684. {
  22685. return totalCycles.totalCycles;
  22686. }
  22687. virtual const void *nextRow()
  22688. {
  22689. ActivityTimer t(totalCycles, timeActivities);
  22690. for (;;)
  22691. {
  22692. if (eof)
  22693. return NULL;
  22694. processSlaveResults();
  22695. if (ready.ordinality())
  22696. {
  22697. const void *result = ready.dequeue();
  22698. if (result)
  22699. joinProcessed++;
  22700. return result;
  22701. }
  22702. else
  22703. eof = true;
  22704. }
  22705. }
  22706. void gatherStats(CRuntimeStatisticCollection & merged) const
  22707. {
  22708. CRemoteResultAdaptor::gatherStats(merged);
  22709. if (ccdRecordAllocator)
  22710. ccdRecordAllocator->gatherStats(merged);
  22711. }
  22712. private:
  22713. void processSlaveResults()
  22714. {
  22715. while (!ready.ordinality())
  22716. {
  22717. KeyedJoinHeader *fetchedData;
  22718. if (isSimple)
  22719. {
  22720. while (!allPulled && !injected.ordinality())
  22721. {
  22722. if (!puller.pullRecords(1))
  22723. {
  22724. puller.done();
  22725. allPulled = true;
  22726. }
  22727. }
  22728. fetchedData = (KeyedJoinHeader *) injected.dequeue();
  22729. }
  22730. else
  22731. fetchedData = (KeyedJoinHeader *) CRemoteResultAdaptor::nextRow();
  22732. if (fetchedData)
  22733. {
  22734. CJoinGroup *thisGroup = fetchedData->thisGroup;
  22735. if (fetchedData->partNo == (unsigned short) -1)
  22736. {
  22737. #ifdef TRACE_JOINGROUPS
  22738. CTXLOG("Got end for group %p", thisGroup);
  22739. #endif
  22740. unsigned candidateCount = (unsigned) fetchedData->fpos;
  22741. ReleaseRoxieRow(fetchedData);
  22742. processor.noteEndReceived(thisGroup, candidateCount); // note - this can throw exception. So release fetchdata before calling
  22743. }
  22744. else
  22745. {
  22746. #ifdef TRACE_JOINGROUPS
  22747. CTXLOG("Reading another %d bytes for group %p data", ccdRecordSize, thisGroup);
  22748. #endif
  22749. thisGroup->addRightMatch(fetchedData);
  22750. if (isFullKey)
  22751. {
  22752. #ifdef TRACE_JOINGROUPS
  22753. CTXLOG("Calling noteEndReceived for record returned from FETCH of full keyed join");
  22754. #endif
  22755. processor.noteEndReceived(thisGroup, 0); // note - this can throw exception. So release fetchdata before calling
  22756. }
  22757. }
  22758. }
  22759. else
  22760. break;
  22761. }
  22762. }
  22763. };
  22764. class CRoxieServerFullKeyedJoinHead: public CRoxieServerActivity, implements IRecordPullerCallback, implements IRoxieServerErrorHandler
  22765. {
  22766. IHThorKeyedJoinArg &helper;
  22767. Owned<IKeyManager> tlk;
  22768. Linked<IKeyArray> keySet;
  22769. Linked<ITranslatorSet> translators;
  22770. CRemoteResultAdaptor remote;
  22771. RecordPullerThread puller;
  22772. IOutputMetaData *indexReadMeta;
  22773. IJoinProcessor *joinHandler;
  22774. bool variableIndexFileName;
  22775. bool indexReadInputRecordVariable;
  22776. bool isLocal;
  22777. Owned<IEngineRowAllocator> indexReadAllocator;
  22778. Owned<const IResolvedFile> varFileInfo;
  22779. IFinalRoxieInput *indexReadInput;
  22780. unsigned indexReadIdx = 0;
  22781. IIndexReadActivityInfo *rootIndex;
  22782. public:
  22783. CRoxieServerFullKeyedJoinHead(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IKeyArray * _keySet, ITranslatorSet *_translators, IOutputMetaData *_indexReadMeta, IJoinProcessor *_joinHandler, bool _isLocal)
  22784. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  22785. helper((IHThorKeyedJoinArg &)basehelper),
  22786. tlk(createLocalKeyManager(helper.queryIndexRecordSize()->queryRecordAccessor(true), NULL, this, helper.hasNewSegmentMonitors())),
  22787. translators(_translators),
  22788. keySet(_keySet),
  22789. remote(_ctx, this, _remoteId, 0, helper, *this, true, true),
  22790. indexReadMeta(_indexReadMeta),
  22791. joinHandler(_joinHandler),
  22792. puller(false),
  22793. isLocal(_isLocal)
  22794. {
  22795. variableIndexFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getJoinFlags() & (JFvarindexfilename|JFdynamicindexfilename|JFindexfromactivity)) != 0);
  22796. indexReadInputRecordVariable = indexReadMeta->isVariableSize();
  22797. indexReadInput = NULL;
  22798. rootIndex = NULL;
  22799. }
  22800. virtual const IResolvedFile *queryVarFileInfo() const
  22801. {
  22802. return varFileInfo;
  22803. }
  22804. virtual void onCreate(IHThorArg *_colocalParent)
  22805. {
  22806. CRoxieServerActivity::onCreate(_colocalParent);
  22807. remote.onCreate(_colocalParent);
  22808. indexReadAllocator.setown(createRowAllocator(indexReadMeta));
  22809. }
  22810. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  22811. {
  22812. if (!idx)
  22813. puller.setInput(this, _sourceIdx, _in);
  22814. else if (idx==1)
  22815. {
  22816. indexReadInput = _in;
  22817. indexReadIdx = _sourceIdx;
  22818. }
  22819. else
  22820. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
  22821. }
  22822. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  22823. {
  22824. puller.connectInputStreams(ctx, consumerOrdered);
  22825. //No rows are read from indexReadInput, so no need to extract the streams
  22826. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
  22827. }
  22828. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  22829. {
  22830. switch (idx)
  22831. {
  22832. case 0:
  22833. return puller.queryInput();
  22834. case 1:
  22835. return indexReadInput;
  22836. default:
  22837. return NULL;
  22838. }
  22839. }
  22840. virtual void serializeExtra(MemoryBuffer &out)
  22841. {
  22842. if (helper.getJoinFlags() & JFindexfromactivity)
  22843. {
  22844. assertex(rootIndex);
  22845. const RemoteActivityId& indexId = rootIndex->queryRemoteId();
  22846. indexId.serialize(out);
  22847. // could mess about reserving space for length then patching it again, to avoid copy, but probably not worth it
  22848. MemoryBuffer tmp;
  22849. rootIndex->queryActivity()->serializeCreateStartContext(tmp);
  22850. if (rootIndex->queryActivity()->queryVarFileInfo())
  22851. {
  22852. rootIndex->queryActivity()->queryVarFileInfo()->queryTimeStamp().serialize(tmp);
  22853. tmp.append(rootIndex->queryActivity()->queryVarFileInfo()->queryCheckSum());
  22854. }
  22855. unsigned ctxlen = tmp.length();
  22856. out.append(ctxlen).append(tmp);
  22857. }
  22858. }
  22859. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  22860. {
  22861. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  22862. if (indexReadInput)
  22863. {
  22864. indexReadInput->start(parentExtractSize, parentExtract, true); // paused=true because we don't want to actually run the index read
  22865. rootIndex = indexReadInput->queryIndexReadActivity();
  22866. if (!rootIndex)
  22867. throw MakeStringException(ROXIE_INTERNAL_ERROR,"Index in keyed join %d could not be resolved", queryId());
  22868. }
  22869. remote.onStart(parentExtractSize, parentExtract);
  22870. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  22871. if (rootIndex)
  22872. {
  22873. varFileInfo.setown(rootIndex->getVarFileInfo());
  22874. translators.setown(rootIndex->getTranslators());
  22875. keySet.setown(rootIndex->getKeySet());
  22876. }
  22877. else if (variableIndexFileName)
  22878. {
  22879. OwnedRoxieString indexFileName(helper.getIndexFileName());
  22880. varFileInfo.setown(resolveLFNIndex(indexFileName, (helper.getJoinFlags() & JFindexoptional) != 0));
  22881. if (varFileInfo)
  22882. {
  22883. unsigned expectedCrc = helper.getIndexFormatCrc();
  22884. unsigned projectedCrc = helper.getProjectedIndexFormatCrc();
  22885. translators.setown(varFileInfo->getTranslators(projectedCrc, helper.queryProjectedIndexRecordSize(), expectedCrc, helper.queryIndexRecordSize(), skipFileFormatCrcCheck(), getEnableFieldTranslation(), true));
  22886. keySet.setown(varFileInfo->getKeyArray(false, isLocal ? factory->queryQueryFactory().queryChannel() : 0));
  22887. }
  22888. }
  22889. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().fullKeyedJoinPreload, false, ctx);
  22890. }
  22891. virtual void stop()
  22892. {
  22893. puller.stop();
  22894. CRoxieServerActivity::stop();
  22895. }
  22896. virtual void reset()
  22897. {
  22898. CRoxieServerActivity::reset();
  22899. puller.reset();
  22900. if (varFileInfo)
  22901. {
  22902. keySet.clear();
  22903. varFileInfo.clear();
  22904. }
  22905. }
  22906. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  22907. {
  22908. if (idx==(unsigned)-1)
  22909. idx = 0;
  22910. return idx ? NULL : &remote;
  22911. }
  22912. virtual void processRow(const void *row)
  22913. {
  22914. // MORE - this code seems to be pretty much duplicated below in half-keyed....
  22915. // called from front puller thread
  22916. // buffer up an IndexRead request
  22917. if (keySet && helper.leftCanMatch(row))
  22918. {
  22919. RtlDynamicRowBuilder extractedBuilder(indexReadAllocator);
  22920. unsigned indexReadSize = helper.extractIndexReadFields(extractedBuilder, row);
  22921. OwnedConstRoxieRow extracted;
  22922. if (indexReadSize)
  22923. extracted.setown(extractedBuilder.finalizeRowClear(indexReadSize));
  22924. CJoinGroup *jg = joinHandler->createJoinGroup(row);
  22925. for (unsigned partNo = 0; partNo < keySet->length(); partNo++)
  22926. {
  22927. IKeyIndexBase *thisBase = keySet->queryKeyPart(partNo);
  22928. if (thisBase)
  22929. {
  22930. unsigned fileNo = 0;
  22931. IKeyIndex *thisKey = thisBase->queryPart(fileNo);
  22932. try
  22933. {
  22934. tlk->setKey(thisKey);
  22935. if (!thisKey->isTopLevelKey())
  22936. tlk->setLayoutTranslator(translators->queryTranslator(fileNo));
  22937. else
  22938. tlk->setLayoutTranslator(nullptr);
  22939. helper.createSegmentMonitors(tlk, extracted);
  22940. if (rootIndex)
  22941. rootIndex->mergeSegmentMonitors(tlk);
  22942. tlk->finishSegmentMonitors();
  22943. tlk->reset();
  22944. for (;;)
  22945. {
  22946. typedef const void * cvp;
  22947. if (thisKey->isTopLevelKey())
  22948. {
  22949. bool locallySorted = !thisKey->isFullySorted();
  22950. while (locallySorted || tlk->lookup(false))
  22951. {
  22952. unsigned slavePart = locallySorted ? tlk->getPartition() : (unsigned)extractFpos(tlk);
  22953. if (locallySorted || slavePart)
  22954. {
  22955. cvp *outputBuffer = (cvp *) remote.getMem(slavePart, fileNo, indexReadSize + sizeof(cvp) + (indexReadInputRecordVariable ? sizeof(unsigned) : 0));
  22956. *outputBuffer++ = jg;
  22957. if (indexReadInputRecordVariable)
  22958. {
  22959. *(unsigned *) outputBuffer = indexReadSize;
  22960. outputBuffer = (cvp*) (((unsigned *) outputBuffer) + 1);
  22961. }
  22962. jg->notePending();
  22963. memcpy(outputBuffer, extracted, indexReadSize);
  22964. if (!slavePart)
  22965. {
  22966. for (unsigned i = 1; i < numChannels; i++)
  22967. jg->notePending();
  22968. }
  22969. if (locallySorted)
  22970. break;
  22971. }
  22972. }
  22973. }
  22974. else
  22975. {
  22976. // MORE - this code seems to be duplicated in half keyed
  22977. unsigned accepted = 0;
  22978. unsigned rejected = 0;
  22979. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), true);
  22980. jg->notePending();
  22981. unsigned candidateCount = 0;
  22982. ScopedAtomic<unsigned> indexRecordsRead(::indexRecordsRead);
  22983. ScopedAtomic<unsigned> postFiltered(::postFiltered);
  22984. while (tlk->lookup(true))
  22985. {
  22986. candidateCount++;
  22987. indexRecordsRead++;
  22988. KLBlobProviderAdapter adapter(tlk);
  22989. const byte *indexRow = tlk->queryKeyBuffer();
  22990. size_t fposOffset = tlk->queryRowSize() - sizeof(offset_t);
  22991. offset_t fpos = rtlReadBigUInt8(indexRow + fposOffset);
  22992. if (helper.indexReadMatch(extracted, indexRow, &adapter))
  22993. {
  22994. KeyedJoinHeader *rhs = (KeyedJoinHeader *) ctx->queryRowManager().allocate(KEYEDJOIN_RECORD_SIZE(0), activityId);
  22995. rhs->fpos = fpos;
  22996. rhs->thisGroup = jg;
  22997. rhs->partNo = partNo;
  22998. result->append(rhs);
  22999. }
  23000. else
  23001. {
  23002. rejected++;
  23003. postFiltered++;
  23004. }
  23005. }
  23006. // output an end marker for the matches to this group
  23007. KeyedJoinHeader *endMarker = (KeyedJoinHeader *) ctx->queryRowManager().allocate(KEYEDJOIN_RECORD_SIZE(0), activityId);
  23008. endMarker->fpos = (offset_t) candidateCount;
  23009. endMarker->thisGroup = jg;
  23010. endMarker->partNo = (unsigned short) -1;
  23011. result->append(endMarker);
  23012. remote.injectResult(result.getClear());
  23013. if (accepted)
  23014. noteStatistic(StNumIndexAccepted, accepted);
  23015. if (rejected)
  23016. noteStatistic(StNumIndexRejected, rejected);
  23017. }
  23018. if (++fileNo < thisBase->numParts())
  23019. {
  23020. thisKey = thisBase->queryPart(fileNo);
  23021. tlk->setKey(thisKey);
  23022. if (!thisKey->isTopLevelKey())
  23023. tlk->setLayoutTranslator(translators->queryTranslator(fileNo));
  23024. else
  23025. tlk->setLayoutTranslator(nullptr);
  23026. tlk->reset();
  23027. }
  23028. else
  23029. break;
  23030. }
  23031. tlk->releaseSegmentMonitors();
  23032. tlk->setKey(NULL);
  23033. }
  23034. catch (...)
  23035. {
  23036. tlk->releaseSegmentMonitors();
  23037. tlk->setKey(NULL);
  23038. throw;
  23039. }
  23040. }
  23041. }
  23042. joinHandler->noteEndReceived(jg, 0);
  23043. }
  23044. else
  23045. {
  23046. joinHandler->noteEndReceived(joinHandler->createJoinGroup(row), 0);
  23047. }
  23048. }
  23049. void processGroup(const ConstPointerArray &)
  23050. {
  23051. throwUnexpected();
  23052. }
  23053. virtual void processEOG()
  23054. {
  23055. joinHandler->processEOG();
  23056. }
  23057. virtual void processDone()
  23058. {
  23059. // called from puller thread
  23060. remote.flush();
  23061. remote.senddone();
  23062. }
  23063. virtual void onLimitExceeded(bool isKeyed)
  23064. {
  23065. if (traceLevel > 4)
  23066. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  23067. if (isKeyed)
  23068. throwUnexpected();
  23069. helper.onLimitExceeded();
  23070. }
  23071. virtual const void *createLimitFailRow(bool isKeyed)
  23072. {
  23073. throwUnexpected();
  23074. }
  23075. virtual bool fireException(IException *e)
  23076. {
  23077. // called from puller thread on failure
  23078. remote.fireException(LINK(e));
  23079. return joinHandler->fireException(e);
  23080. }
  23081. virtual const void *nextRow()
  23082. {
  23083. throwUnexpected(); // I am nobody's input
  23084. }
  23085. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  23086. {
  23087. CRoxieServerActivity::gatherStats(merged);
  23088. remote.gatherStats(merged);
  23089. if (indexReadAllocator)
  23090. indexReadAllocator->gatherStats(merged);
  23091. }
  23092. };
  23093. class CRoxieServerKeyedJoinBase : public CRoxieServerActivity, implements IRecordPullerCallback, implements IRoxieServerErrorHandler, implements IJoinProcessor
  23094. {
  23095. protected:
  23096. IHThorKeyedJoinArg &helper;
  23097. KeyedJoinRemoteAdaptor remote;
  23098. RecordPullerThread puller;
  23099. OwnedConstRoxieRow defaultRight;
  23100. Owned<IEngineRowAllocator> defaultRightAllocator;
  23101. unsigned joinFlags;
  23102. unsigned atMost;
  23103. unsigned atmostsTriggered;
  23104. unsigned abortLimit;
  23105. unsigned keepLimit;
  23106. bool limitFail;
  23107. bool limitOnFail;
  23108. bool preserveGroups;
  23109. bool cloneLeft;
  23110. bool isSimple;
  23111. bool isLocal;
  23112. ThorActivityKind activityKind;
  23113. CJoinGroup *groupStart;
  23114. CriticalSection groupsCrit;
  23115. QueueOf<CJoinGroup, false> groups;
  23116. IFinalRoxieInput *indexReadInput;
  23117. unsigned indexReadIdx = 0;
  23118. Owned<IStrandJunction> indexReadJunction;
  23119. IEngineRowStream *indexReadStream = NULL; // Never actually pulled
  23120. IIndexReadActivityInfo *rootIndex;
  23121. void createDefaultRight()
  23122. {
  23123. if (!defaultRight)
  23124. {
  23125. if (!defaultRightAllocator)
  23126. defaultRightAllocator.setown(createRowAllocator(helper.queryJoinFieldsRecordSize()));
  23127. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  23128. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  23129. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  23130. }
  23131. }
  23132. public:
  23133. CRoxieServerKeyedJoinBase(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _joinFlags
  23134. , bool isFull, bool _isSimple, bool _isLocal)
  23135. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  23136. helper((IHThorKeyedJoinArg &)basehelper),
  23137. remote(_ctx, this, _remoteId, helper, *this, isFull, _isSimple, puller, *this),
  23138. joinFlags(_joinFlags),
  23139. preserveGroups(meta.isGrouped()),
  23140. puller(false),
  23141. isSimple(_isSimple),
  23142. isLocal(_isLocal),
  23143. abortLimit(0),
  23144. keepLimit(0),
  23145. atMost(0),
  23146. limitFail(false),
  23147. limitOnFail(false),
  23148. cloneLeft(false)
  23149. {
  23150. groupStart = NULL;
  23151. activityKind = _factory->getKind();
  23152. indexReadInput = NULL;
  23153. rootIndex = NULL;
  23154. atmostsTriggered = 0;
  23155. // MORE - code would be easier to read if I got more values from helper rather than passing from factory
  23156. }
  23157. virtual void onCreate(IHThorArg *_colocalParent)
  23158. {
  23159. CRoxieServerActivity::onCreate(_colocalParent);
  23160. remote.onCreate(_colocalParent);
  23161. }
  23162. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  23163. {
  23164. if (!idx)
  23165. puller.setInput(this, _sourceIdx, _in);
  23166. else if (idx==1)
  23167. {
  23168. indexReadInput = _in;
  23169. indexReadIdx = _sourceIdx;
  23170. }
  23171. else
  23172. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
  23173. }
  23174. virtual void connectInputStreams(bool consumerOrdered)
  23175. {
  23176. CRoxieServerActivity::connectInputStreams(consumerOrdered);
  23177. puller.connectInputStreams(ctx, consumerOrdered);
  23178. if (indexReadInput)
  23179. indexReadStream = connectSingleStream(ctx, indexReadInput, indexReadIdx, indexReadJunction, consumerOrdered); // We never actually pull the stream
  23180. }
  23181. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  23182. {
  23183. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  23184. if (indexReadInput)
  23185. {
  23186. indexReadInput->start(parentExtractSize, parentExtract, true); // paused=true because we don't want to actually run the index read
  23187. rootIndex = indexReadInput->queryIndexReadActivity();
  23188. if (!rootIndex)
  23189. throw MakeStringException(ROXIE_INTERNAL_ERROR,"Index in keyed join %d could not be resolved", queryId());
  23190. }
  23191. remote.onStart(parentExtractSize, parentExtract);
  23192. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  23193. atmostsTriggered = 0;
  23194. atMost = helper.getJoinLimit();
  23195. if (atMost == 0) atMost = (unsigned)-1;
  23196. abortLimit = helper.getMatchAbortLimit();
  23197. if (abortLimit == 0 || atMost != (unsigned) -1) abortLimit = (unsigned)-1;
  23198. keepLimit = helper.getKeepLimit();
  23199. if (keepLimit == 0) keepLimit = (unsigned)-1;
  23200. getLimitType(joinFlags, limitFail, limitOnFail);
  23201. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  23202. if ((joinFlags & JFleftouter) || limitOnFail)
  23203. createDefaultRight();
  23204. }
  23205. virtual void stop()
  23206. {
  23207. puller.stop();
  23208. if (indexReadStream)
  23209. indexReadStream->stop(); // Could probably do this as soon as re have fetched rootIndex?
  23210. CRoxieServerActivity::stop();
  23211. }
  23212. virtual unsigned __int64 queryLocalCycles() const
  23213. {
  23214. __int64 localCycles = remote.totalCycles.totalCycles;
  23215. localCycles -= puller.queryTotalCycles(); // MORE - debatable... but probably fair.
  23216. if (localCycles < 0)
  23217. localCycles = 0;
  23218. return localCycles;
  23219. }
  23220. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  23221. {
  23222. CRoxieServerActivity::gatherStats(merged);
  23223. remote.gatherStats(merged);
  23224. }
  23225. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  23226. {
  23227. if (idx==0)
  23228. return puller.queryInput();
  23229. else if (idx==1)
  23230. return indexReadInput;
  23231. else
  23232. return NULL;
  23233. }
  23234. virtual void reset()
  23235. {
  23236. totalCycles.totalCycles = remote.totalCycles.totalCycles;
  23237. remote.totalCycles.totalCycles = 0;
  23238. processed = remote.joinProcessed;
  23239. remote.joinProcessed = 0;
  23240. defaultRight.clear();
  23241. if (indexReadInput)
  23242. indexReadInput->reset();
  23243. if (atmostsTriggered)
  23244. noteStatistic(StNumAtmostTriggered, atmostsTriggered);
  23245. CRoxieServerActivity::reset();
  23246. puller.reset();
  23247. while (groups.ordinality())
  23248. {
  23249. ::Release(groups.dequeue());
  23250. }
  23251. }
  23252. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  23253. {
  23254. if (idx==(unsigned)-1)
  23255. idx = 0;
  23256. return idx ? NULL : &remote;
  23257. }
  23258. virtual CJoinGroup *createJoinGroup(const void *row)
  23259. {
  23260. // NOTE - we need to protect access to queue, since it's also modified by consumer thread. Groupstart is only modified by puller thread.
  23261. CriticalBlock c(groupsCrit);
  23262. if (preserveGroups && !groupStart)
  23263. {
  23264. groupStart = new (&ctx->queryRowManager(), activityId) CJoinGroup(NULL, NULL);
  23265. groups.enqueue(groupStart);
  23266. }
  23267. CJoinGroup *jg = new (&ctx->queryRowManager(), activityId) CJoinGroup(row, groupStart);
  23268. groups.enqueue(jg);
  23269. return jg;
  23270. }
  23271. void endGroup()
  23272. {
  23273. CriticalBlock c(groupsCrit);
  23274. if (groupStart)
  23275. noteEndReceived(groupStart, 0);
  23276. groupStart = NULL;
  23277. }
  23278. virtual void noteEndReceived(CJoinGroup *jg, unsigned candidateCount)
  23279. {
  23280. if (jg->noteEndReceived(candidateCount))
  23281. processCompletedGroups();
  23282. }
  23283. void processCompletedGroups()
  23284. {
  23285. CriticalBlock c(groupsCrit);
  23286. while (groups.ordinality())
  23287. {
  23288. if (!groups.head()->complete())
  23289. break;
  23290. Owned<CJoinGroup> head = groups.dequeue();
  23291. if (preserveGroups)
  23292. {
  23293. assert(head->isHeadRecord());
  23294. assert(groups.head()->inGroup(head));
  23295. unsigned joinGroupSize = 0;
  23296. while (groups.ordinality() && groups.head()->inGroup(head))
  23297. {
  23298. Owned<CJoinGroup> finger = groups.dequeue();
  23299. joinGroupSize += doJoinGroup(finger);
  23300. }
  23301. if (joinGroupSize)
  23302. remote.addResult(NULL);
  23303. }
  23304. else
  23305. doJoinGroup(head);
  23306. }
  23307. }
  23308. void failLimit(const void * left)
  23309. {
  23310. helper.onMatchAbortLimitExceeded();
  23311. CommonXmlWriter xmlwrite(0);
  23312. if (input && input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  23313. {
  23314. input->queryOutputMeta()->toXML((byte *) left, xmlwrite);
  23315. }
  23316. throw MakeStringException(ROXIE_JOIN_ERROR, "More than %d match candidates in keyed join %d for row %s", abortLimit, queryId(), xmlwrite.str());
  23317. }
  23318. virtual bool needsAllocator() const { return true; }
  23319. unsigned doTransform(const void *left, const void *right, offset_t fpos_or_count, IException *except, const void **group, unsigned counter)
  23320. {
  23321. if (cloneLeft && !except)
  23322. {
  23323. LinkRoxieRow(left);
  23324. remote.addResult((void *) left);
  23325. return 1;
  23326. }
  23327. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  23328. unsigned outSize;
  23329. try
  23330. {
  23331. outSize = except ? helper.onFailTransform(rowBuilder, left, right, fpos_or_count, except) :
  23332. (activityKind == TAKkeyeddenormalizegroup) ? helper.transform(rowBuilder, left, right, (unsigned)fpos_or_count, group) :
  23333. helper.transform(rowBuilder, left, right, fpos_or_count, counter);
  23334. }
  23335. catch (IException *E)
  23336. {
  23337. throw makeWrappedException(E);
  23338. }
  23339. if (outSize)
  23340. {
  23341. const void *shrunk = rowBuilder.finalizeRowClear(outSize);
  23342. remote.addResult(shrunk);
  23343. return 1;
  23344. }
  23345. else
  23346. return 0;
  23347. }
  23348. unsigned doJoinGroup(CJoinGroup *jg)
  23349. {
  23350. unsigned matched = jg->rowsSeen();
  23351. unsigned added = 0;
  23352. const void *left = jg->queryLeft();
  23353. if (jg->candidateCount() > abortLimit)
  23354. {
  23355. if (limitFail)
  23356. failLimit(left);
  23357. if (ctx->queryDebugContext())
  23358. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  23359. if (limitOnFail)
  23360. {
  23361. Owned<IException> except;
  23362. try
  23363. {
  23364. failLimit(left);
  23365. }
  23366. catch(IException * e)
  23367. {
  23368. except.setown(e);
  23369. }
  23370. added = doTransform(left, defaultRight, 0, except, NULL, 0);
  23371. }
  23372. }
  23373. else if (!matched || jg->candidateCount() > atMost)
  23374. {
  23375. if (jg->candidateCount() > atMost)
  23376. atmostsTriggered++;
  23377. switch (joinFlags & JFtypemask)
  23378. {
  23379. case JFleftouter:
  23380. case JFleftonly:
  23381. switch (activityKind)
  23382. {
  23383. case TAKkeyedjoin:
  23384. case TAKkeyeddenormalizegroup:
  23385. added = doTransform(left, defaultRight, 0, NULL, NULL, 0);
  23386. break;
  23387. case TAKkeyeddenormalize:
  23388. LinkRoxieRow(left);
  23389. remote.addResult((void *) left);
  23390. added++;
  23391. break;
  23392. }
  23393. break;
  23394. }
  23395. }
  23396. else if (!(joinFlags & JFexclude))
  23397. {
  23398. unsigned idx = 0;
  23399. switch (activityKind)
  23400. {
  23401. case TAKkeyedjoin:
  23402. while (idx < matched)
  23403. {
  23404. const KeyedJoinHeader *rhs = jg->queryRow(idx);
  23405. added += doTransform(left, &rhs->rhsdata, 0, NULL, NULL, idx+1);
  23406. if (added==keepLimit)
  23407. break;
  23408. idx++;
  23409. }
  23410. break;
  23411. case TAKkeyeddenormalize:
  23412. {
  23413. OwnedConstRoxieRow newLeft;
  23414. newLeft.set(left);
  23415. unsigned rowSize = 0;
  23416. unsigned rightAdded = 0;
  23417. while (idx < matched)
  23418. {
  23419. const KeyedJoinHeader *rhs = jg->queryRow(idx);
  23420. try
  23421. {
  23422. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  23423. size32_t transformedSize = helper.transform(rowBuilder, newLeft, &rhs->rhsdata, rhs->fpos, idx+1);
  23424. if (transformedSize)
  23425. {
  23426. rowSize = transformedSize;
  23427. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  23428. rightAdded++;
  23429. if (rightAdded==keepLimit)
  23430. break;
  23431. }
  23432. idx++;
  23433. }
  23434. catch (IException *E)
  23435. {
  23436. throw makeWrappedException(E);
  23437. }
  23438. }
  23439. if (rowSize)
  23440. {
  23441. remote.addResult(newLeft.getClear());
  23442. added++;
  23443. }
  23444. }
  23445. break;
  23446. case TAKkeyeddenormalizegroup:
  23447. {
  23448. ConstPointerArray extractedRows;
  23449. while (idx < matched && idx < keepLimit)
  23450. {
  23451. const KeyedJoinHeader *rhs = jg->queryRow(idx);
  23452. extractedRows.append((void *) &rhs->rhsdata);
  23453. idx++;
  23454. }
  23455. added += doTransform(left, extractedRows.item(0), extractedRows.ordinality(), NULL, (const void * *)extractedRows.getArray(), 0);
  23456. }
  23457. break;
  23458. }
  23459. }
  23460. return added;
  23461. }
  23462. virtual void processDone()
  23463. {
  23464. // called from puller thread
  23465. remote.flush();
  23466. remote.senddone();
  23467. }
  23468. virtual void onLimitExceeded(bool isKeyed)
  23469. {
  23470. if (traceLevel > 4)
  23471. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  23472. if (isKeyed)
  23473. throwUnexpected();
  23474. helper.onLimitExceeded();
  23475. }
  23476. virtual const void *createLimitFailRow(bool isKeyed)
  23477. {
  23478. throwUnexpected();
  23479. }
  23480. virtual bool fireException(IException *e)
  23481. {
  23482. // called from puller thread on failure
  23483. return remote.fireException(e);
  23484. }
  23485. virtual const void *nextRow()
  23486. {
  23487. throwUnexpected(); // I am nobody's input
  23488. }
  23489. };
  23490. #ifdef _MSC_VER
  23491. #pragma warning ( push )
  23492. #pragma warning ( disable: 4355 )
  23493. #endif
  23494. class CRoxieServerKeyedJoinActivity : public CRoxieServerKeyedJoinBase
  23495. {
  23496. CRoxieServerFullKeyedJoinHead head;
  23497. Owned<IEngineRowAllocator> fetchInputAllocator;
  23498. Linked<IFilePartMap> map;
  23499. bool variableFetchFileName;
  23500. Owned<const IResolvedFile> varFetchFileInfo;
  23501. CachedOutputMetaData fetchInputFields;
  23502. public:
  23503. CRoxieServerKeyedJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_headId, IKeyArray * _key, ITranslatorSet *_keyTranslators, IOutputMetaData *_indexReadMeta,
  23504. const RemoteActivityId &_tailId, IFilePartMap *_map, unsigned _joinFlags, bool _isLocal)
  23505. : CRoxieServerKeyedJoinBase(_ctx, _factory, _probeManager, _tailId, _joinFlags, true, false, _isLocal),
  23506. head(_ctx, _factory, _probeManager, _headId, _key, _keyTranslators, _indexReadMeta, this, _isLocal),
  23507. map(_map)
  23508. {
  23509. CRoxieServerKeyedJoinBase::setInput(0, 0, head.queryOutput(0));
  23510. variableFetchFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  23511. }
  23512. virtual const IResolvedFile *queryVarFileInfo() const
  23513. {
  23514. return varFetchFileInfo;
  23515. }
  23516. virtual void onCreate(IHThorArg *_colocalParent)
  23517. {
  23518. CRoxieServerKeyedJoinBase::onCreate(_colocalParent);
  23519. head.onCreate(_colocalParent);
  23520. fetchInputFields.set(helper.queryFetchInputRecordSize());
  23521. fetchInputAllocator.setown(createRowAllocator(helper.queryFetchInputRecordSize()));
  23522. }
  23523. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  23524. {
  23525. CRoxieServerKeyedJoinBase::start(parentExtractSize, parentExtract, paused);
  23526. if (variableFetchFileName)
  23527. {
  23528. bool isFetchOpt = (helper.getFetchFlags() & FFdatafileoptional) != 0;
  23529. OwnedRoxieString fname(helper.getFileName());
  23530. varFetchFileInfo.setown(resolveLFNFlat(fname, isFetchOpt));
  23531. if (varFetchFileInfo)
  23532. {
  23533. // Note - we don't need to do any translation on the disk part of full-keyed joins
  23534. map.setown(varFetchFileInfo->getFileMap());
  23535. }
  23536. }
  23537. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().keyedJoinPreload, false, ctx);
  23538. }
  23539. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  23540. {
  23541. head.setInput(idx, _sourceIdx, _in);
  23542. }
  23543. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  23544. {
  23545. connectInputStreams(consumerOrdered);
  23546. return head.getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
  23547. }
  23548. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  23549. {
  23550. return head.queryInput(idx);
  23551. }
  23552. virtual void processRow(const void *_rhs)
  23553. {
  23554. // called from puller thread
  23555. KeyedJoinHeader *rhs = (KeyedJoinHeader *) _rhs;
  23556. CJoinGroup *jg = rhs->thisGroup;
  23557. if (rhs->partNo != (unsigned short) -1)
  23558. {
  23559. unsigned partNo = map->mapOffset(rhs->fpos);
  23560. RtlDynamicRowBuilder fetchBuilder(fetchInputAllocator, true);
  23561. size32_t fisize = helper.extractFetchFields(fetchBuilder, jg->queryLeft());
  23562. if (fetchInputFields.isVariableSize())
  23563. {
  23564. KeyedJoinHeader *outRow = (KeyedJoinHeader *) remote.getMem(partNo, 0, KEYEDJOIN_RECORD_SIZE(fisize + sizeof(fisize)));
  23565. memcpy(outRow, rhs, KEYEDJOIN_RECORD_SIZE(0)); // MORE - copy constructor might be more appropriate....
  23566. ReleaseRoxieRow(rhs);
  23567. jg->notePending();
  23568. memcpy(&outRow->rhsdata, &fisize, sizeof(fisize));
  23569. memcpy((&outRow->rhsdata)+sizeof(fisize), fetchBuilder.row(), fisize);
  23570. }
  23571. else
  23572. {
  23573. KeyedJoinHeader *outRow = (KeyedJoinHeader *) remote.getMem(partNo, 0, KEYEDJOIN_RECORD_SIZE(fisize));
  23574. memcpy(outRow, rhs, KEYEDJOIN_RECORD_SIZE(0)); // MORE - copy constructor might be more appropriate....
  23575. ReleaseRoxieRow(rhs);
  23576. jg->notePending();
  23577. memcpy(&outRow->rhsdata, fetchBuilder.row(), fisize);
  23578. }
  23579. }
  23580. else
  23581. {
  23582. unsigned candidateCount = (unsigned) rhs->fpos;
  23583. // CTXLOG("Full keyed join - all results back from index");
  23584. ReleaseRoxieRow(rhs);
  23585. noteEndReceived(jg, candidateCount); // may throw exception - so release row before calling
  23586. }
  23587. }
  23588. virtual void processEOG()
  23589. {
  23590. // called from front puller thread
  23591. if (preserveGroups)
  23592. endGroup();
  23593. }
  23594. void processGroup(const ConstPointerArray &)
  23595. {
  23596. throwUnexpected();
  23597. }
  23598. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  23599. {
  23600. CRoxieServerKeyedJoinBase::gatherStats(merged);
  23601. if (fetchInputAllocator)
  23602. fetchInputAllocator->gatherStats(merged);
  23603. }
  23604. };
  23605. #ifdef _MSC_VER
  23606. #pragma warning ( pop )
  23607. #endif
  23608. class CRoxieServerHalfKeyedJoinActivity : public CRoxieServerKeyedJoinBase
  23609. {
  23610. IOutputMetaData *indexReadMeta;
  23611. Owned<IEngineRowAllocator> indexReadAllocator;
  23612. Owned<IKeyManager> tlk;
  23613. bool variableIndexFileName;
  23614. bool indexReadInputRecordVariable;
  23615. Owned<const IResolvedFile> varFileInfo;
  23616. Linked<ITranslatorSet> translators;
  23617. Linked<IKeyArray> keySet;
  23618. Owned<IOutputMetaData> joinPrefixedMeta;
  23619. Owned<IEngineRowAllocator> joinFieldsAllocator;
  23620. public:
  23621. CRoxieServerHalfKeyedJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IKeyArray * _keySet, ITranslatorSet *_translators,
  23622. IOutputMetaData *_indexReadMeta, unsigned _joinFlags, bool _isSimple, bool _isLocal)
  23623. : CRoxieServerKeyedJoinBase(_ctx, _factory, _probeManager, _remoteId, _joinFlags, false, _isSimple, _isLocal),
  23624. indexReadMeta(_indexReadMeta),
  23625. tlk(createLocalKeyManager(helper.queryIndexRecordSize()->queryRecordAccessor(true), NULL, this, helper.hasNewSegmentMonitors())),
  23626. keySet(_keySet),
  23627. translators(_translators)
  23628. {
  23629. variableIndexFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getJoinFlags() & (JFvarindexfilename|JFdynamicindexfilename|JFindexfromactivity)) != 0);
  23630. indexReadInputRecordVariable = indexReadMeta->isVariableSize();
  23631. }
  23632. virtual void serializeExtra(MemoryBuffer &out)
  23633. {
  23634. if (helper.getJoinFlags() & JFindexfromactivity)
  23635. {
  23636. assertex(rootIndex);
  23637. const RemoteActivityId& indexId = rootIndex->queryRemoteId();
  23638. indexId.serialize(out);
  23639. // could mess about reserving space for length then patching it again, to avoid copy, but probably not worth it
  23640. MemoryBuffer tmp;
  23641. rootIndex->queryActivity()->serializeCreateStartContext(tmp);
  23642. if (rootIndex->queryActivity()->queryVarFileInfo())
  23643. {
  23644. rootIndex->queryActivity()->queryVarFileInfo()->queryTimeStamp().serialize(tmp);
  23645. tmp.append(rootIndex->queryActivity()->queryVarFileInfo()->queryCheckSum());
  23646. }
  23647. unsigned ctxlen = tmp.length();
  23648. out.append(ctxlen).append(tmp);
  23649. }
  23650. }
  23651. virtual void onCreate(IHThorArg *_colocalParent)
  23652. {
  23653. CRoxieServerKeyedJoinBase::onCreate(_colocalParent);
  23654. indexReadAllocator.setown(createRowAllocator(indexReadMeta));
  23655. IOutputMetaData *joinFieldsMeta = helper.queryJoinFieldsRecordSize();
  23656. joinPrefixedMeta.setown(new CPrefixedOutputMeta(KEYEDJOIN_RECORD_SIZE(0), joinFieldsMeta)); // MORE - not sure if we really need this
  23657. joinFieldsAllocator.setown(createRowAllocator(joinPrefixedMeta));
  23658. }
  23659. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  23660. {
  23661. CRoxieServerKeyedJoinBase::start(parentExtractSize, parentExtract, paused);
  23662. if (rootIndex)
  23663. {
  23664. varFileInfo.setown(rootIndex->getVarFileInfo());
  23665. translators.setown(rootIndex->getTranslators());
  23666. keySet.setown(rootIndex->getKeySet());
  23667. }
  23668. else if (variableIndexFileName)
  23669. {
  23670. OwnedRoxieString indexFileName(helper.getIndexFileName());
  23671. varFileInfo.setown(resolveLFNIndex(indexFileName, (helper.getJoinFlags() & JFindexoptional) != 0));
  23672. if (varFileInfo)
  23673. {
  23674. unsigned expectedCrc = helper.getIndexFormatCrc();
  23675. unsigned projectedCrc = helper.getProjectedIndexFormatCrc();
  23676. translators.setown(varFileInfo->getTranslators(projectedCrc, helper.queryProjectedIndexRecordSize(), expectedCrc, helper.queryIndexRecordSize(), skipFileFormatCrcCheck(), getEnableFieldTranslation(), true));
  23677. keySet.setown(varFileInfo->getKeyArray(false, isLocal ? factory->queryQueryFactory().queryChannel() : 0));
  23678. }
  23679. }
  23680. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().keyedJoinPreload, isSimple, ctx);
  23681. }
  23682. virtual const IResolvedFile *queryVarFileInfo() const
  23683. {
  23684. return varFileInfo;
  23685. }
  23686. virtual void reset()
  23687. {
  23688. CRoxieServerKeyedJoinBase::reset();
  23689. if (varFileInfo)
  23690. {
  23691. keySet.clear();
  23692. varFileInfo.clear();
  23693. }
  23694. }
  23695. virtual void processRow(const void *row)
  23696. {
  23697. // called from front puller thread
  23698. // buffer up an IndexRead request
  23699. if (keySet && helper.leftCanMatch(row))
  23700. {
  23701. RtlDynamicRowBuilder extractBuilder(indexReadAllocator);
  23702. unsigned indexReadRecordSize = helper.extractIndexReadFields(extractBuilder, row);
  23703. OwnedConstRoxieRow extracted;
  23704. if (indexReadRecordSize)
  23705. extracted.setown(extractBuilder.finalizeRowClear(indexReadRecordSize));
  23706. CJoinGroup *jg = createJoinGroup(row);
  23707. for (unsigned partNo = 0; partNo < keySet->length(); partNo++)
  23708. {
  23709. IKeyIndexBase *thisBase = keySet->queryKeyPart(partNo);
  23710. if (thisBase)
  23711. {
  23712. unsigned fileNo = 0;
  23713. IKeyIndex *thisKey = thisBase->queryPart(fileNo);
  23714. tlk->setKey(thisKey);
  23715. if (thisKey && !thisKey->isTopLevelKey())
  23716. tlk->setLayoutTranslator(translators->queryTranslator(fileNo));
  23717. else
  23718. tlk->setLayoutTranslator(nullptr);
  23719. helper.createSegmentMonitors(tlk, extracted);
  23720. if (rootIndex)
  23721. rootIndex->mergeSegmentMonitors(tlk);
  23722. tlk->finishSegmentMonitors();
  23723. try
  23724. {
  23725. tlk->reset();
  23726. for (;;)
  23727. {
  23728. typedef const void * cvp;
  23729. if (thisKey && thisKey->isTopLevelKey())
  23730. {
  23731. bool locallySorted = (!thisKey->isFullySorted());
  23732. while (locallySorted || tlk->lookup(false))
  23733. {
  23734. unsigned slavePart = locallySorted ? tlk->getPartition() : (unsigned)extractFpos(tlk);
  23735. if (locallySorted || slavePart)
  23736. {
  23737. cvp *outputBuffer = (cvp *) remote.getMem(slavePart, fileNo, indexReadRecordSize + sizeof(cvp) + (indexReadInputRecordVariable ? sizeof(unsigned) : 0));
  23738. *outputBuffer++ = jg;
  23739. if (indexReadInputRecordVariable)
  23740. {
  23741. *(unsigned *) outputBuffer = indexReadRecordSize;
  23742. outputBuffer = (cvp *) (((unsigned *) outputBuffer) + 1);
  23743. }
  23744. jg->notePending();
  23745. memcpy(outputBuffer, extracted, indexReadRecordSize);
  23746. if (!slavePart)
  23747. {
  23748. for (unsigned i = 1; i < numChannels; i++)
  23749. jg->notePending();
  23750. }
  23751. if (locallySorted)
  23752. break;
  23753. }
  23754. }
  23755. }
  23756. else
  23757. {
  23758. unsigned accepted = 0;
  23759. unsigned rejected = 0;
  23760. Owned<CRowArrayMessageResult> result;
  23761. if (!isSimple)
  23762. result.setown(new CRowArrayMessageResult(ctx->queryRowManager(), true));
  23763. // MORE - This code seems to be duplicated in keyedJoinHead
  23764. jg->notePending();
  23765. unsigned candidateCount = 0;
  23766. ScopedAtomic<unsigned> indexRecordsRead(::indexRecordsRead);
  23767. ScopedAtomic<unsigned> postFiltered(::postFiltered);
  23768. while (tlk->lookup(true))
  23769. {
  23770. candidateCount++;
  23771. indexRecordsRead++;
  23772. KLBlobProviderAdapter adapter(tlk);
  23773. const byte *indexRow = tlk->queryKeyBuffer();
  23774. size_t fposOffset = tlk->queryRowSize() - sizeof(offset_t);
  23775. offset_t fpos = rtlReadBigUInt8(indexRow + fposOffset);
  23776. if (helper.indexReadMatch(extracted, indexRow, &adapter))
  23777. {
  23778. RtlDynamicRowBuilder rb(joinFieldsAllocator, true);
  23779. CPrefixedRowBuilder pb(KEYEDJOIN_RECORD_SIZE(0), rb);
  23780. accepted++;
  23781. KLBlobProviderAdapter adapter(tlk);
  23782. size32_t joinFieldsSize = helper.extractJoinFields(pb, indexRow, &adapter);
  23783. KeyedJoinHeader *rec = (KeyedJoinHeader *) rb.getUnfinalizedClear(); // lack of finalize ok as unserialized data here.
  23784. rec->fpos = fpos;
  23785. rec->thisGroup = jg;
  23786. rec->partNo = partNo;
  23787. if (isSimple)
  23788. remote.injected.enqueue(rec);
  23789. else
  23790. result->append(rec);
  23791. }
  23792. else
  23793. {
  23794. rejected++;
  23795. postFiltered++;
  23796. }
  23797. }
  23798. // output an end marker for the matches to this group
  23799. KeyedJoinHeader *rec = (KeyedJoinHeader *) ctx->queryRowManager().allocate(KEYEDJOIN_RECORD_SIZE(0), activityId);
  23800. rec->fpos = (offset_t) candidateCount;
  23801. rec->thisGroup = jg;
  23802. rec->partNo = (unsigned short) -1;
  23803. if (isSimple)
  23804. remote.injected.enqueue(rec);
  23805. else
  23806. {
  23807. result->append(rec);
  23808. remote.injectResult(result.getClear());
  23809. }
  23810. if (accepted)
  23811. noteStatistic(StNumIndexAccepted, accepted);
  23812. if (rejected)
  23813. noteStatistic(StNumIndexRejected, rejected);
  23814. }
  23815. if (++fileNo < thisBase->numParts())
  23816. {
  23817. thisKey = thisBase->queryPart(fileNo);
  23818. tlk->setKey(thisKey);
  23819. if (thisKey && !thisKey->isTopLevelKey())
  23820. tlk->setLayoutTranslator(translators->queryTranslator(fileNo));
  23821. else
  23822. tlk->setLayoutTranslator(nullptr);
  23823. tlk->reset();
  23824. }
  23825. else
  23826. break;
  23827. }
  23828. tlk->releaseSegmentMonitors();
  23829. tlk->setKey(NULL);
  23830. }
  23831. catch (...)
  23832. {
  23833. tlk->releaseSegmentMonitors();
  23834. tlk->setKey(NULL);
  23835. throw;
  23836. }
  23837. }
  23838. }
  23839. noteEndReceived(jg, 0);
  23840. }
  23841. else
  23842. {
  23843. noteEndReceived(createJoinGroup(row), 0);
  23844. }
  23845. }
  23846. virtual void processEOG()
  23847. {
  23848. // called from front puller thread
  23849. if (preserveGroups)
  23850. endGroup();
  23851. }
  23852. void processGroup(const ConstPointerArray &)
  23853. {
  23854. throwUnexpected();
  23855. }
  23856. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  23857. {
  23858. CRoxieServerKeyedJoinBase::gatherStats(merged);
  23859. if (indexReadAllocator)
  23860. indexReadAllocator->gatherStats(merged);
  23861. if (joinFieldsAllocator)
  23862. joinFieldsAllocator->gatherStats(merged);
  23863. }
  23864. };
  23865. class CRoxieServerKeyedJoinActivityFactory : public CRoxieServerMultiInputFactory
  23866. {
  23867. Owned<const IResolvedFile> indexfile;
  23868. Owned<const IResolvedFile> datafile;
  23869. Owned<IKeyArray> keySet;
  23870. Owned<ITranslatorSet> keyTranslators; // For the indexes
  23871. RemoteActivityId headId;
  23872. RemoteActivityId tailId;
  23873. IOutputMetaData *indexReadMeta;
  23874. Owned<IFilePartMap> map;
  23875. Owned<ITranslatorSet> translators; // for the disk files on local full keyed joins
  23876. Owned<IFileIOArray> files;
  23877. unsigned joinFlags;
  23878. bool isHalfKeyed;
  23879. bool isLocal;
  23880. bool variableFetchFileName;
  23881. bool variableIndexFileName;
  23882. bool isSimple;
  23883. public:
  23884. CRoxieServerKeyedJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_headId, const RemoteActivityId &_tailId)
  23885. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), headId(_headId), tailId(_tailId)
  23886. {
  23887. Owned<IHThorKeyedJoinArg> helper = (IHThorKeyedJoinArg *) helperFactory();
  23888. isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  23889. isSimple = isLocal;
  23890. rtlDataAttr indexLayoutMeta;
  23891. size32_t indexLayoutSize = 0;
  23892. if(!helper->getIndexLayout(indexLayoutSize, indexLayoutMeta.refdata()))
  23893. assertex(indexLayoutSize== 0);
  23894. joinFlags = helper->getJoinFlags();
  23895. variableIndexFileName = allFilesDynamic || _queryFactory.isDynamic() || ((joinFlags & (JFvarindexfilename|JFdynamicindexfilename|JFindexfromactivity)) != 0);
  23896. variableFetchFileName = allFilesDynamic || _queryFactory.isDynamic() || ((helper->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  23897. if (!variableIndexFileName)
  23898. {
  23899. bool isOpt = (joinFlags & JFindexoptional) != 0;
  23900. OwnedRoxieString indexFileName(helper->getIndexFileName());
  23901. indexfile.setown(queryFactory.queryPackage().lookupFileName(indexFileName, isOpt, true, true, queryFactory.queryWorkUnit(), true));
  23902. if (indexfile)
  23903. {
  23904. unsigned expectedCrc = helper->getIndexFormatCrc();
  23905. unsigned projectedCrc = helper->getProjectedIndexFormatCrc();
  23906. keyTranslators.setown(indexfile->getTranslators(projectedCrc, helper->queryProjectedIndexRecordSize(), expectedCrc, helper->queryIndexRecordSize(), skipFileFormatCrcCheck(), getEnableFieldTranslation(), true));
  23907. keySet.setown(indexfile->getKeyArray(isOpt, isLocal ? queryFactory.queryChannel() : 0));
  23908. }
  23909. }
  23910. if (keySet && keySet->length()==1 && !isSimple)
  23911. {
  23912. IKeyIndexBase *thisBase = keySet->queryKeyPart(0);
  23913. if (thisBase->numParts()==1 && !thisBase->queryPart(0)->isTopLevelKey() && !_queryFactory.queryOptions().disableLocalOptimizations)
  23914. isSimple = true;
  23915. // MORE - if it's a variable filename then it MAY be simple, we don't know. Tough.
  23916. }
  23917. if (!simpleLocalKeyedJoins)
  23918. isSimple = false;
  23919. isHalfKeyed = !helper->diskAccessRequired();
  23920. indexReadMeta = QUERYINTERFACE(helper->queryIndexReadInputRecordSize(), IOutputMetaData);
  23921. if (!isHalfKeyed && !variableFetchFileName)
  23922. {
  23923. bool isFetchOpt = (helper->getFetchFlags() & FFdatafileoptional) != 0;
  23924. datafile.setown(_queryFactory.queryPackage().lookupFileName(queryNodeFileName(_graphNode, _kind), isFetchOpt, true, true, _queryFactory.queryWorkUnit(), true));
  23925. if (datafile)
  23926. {
  23927. if (isLocal) // Not sure this works
  23928. {
  23929. unsigned expectedCrc = helper->getDiskFormatCrc();
  23930. unsigned projectedCrc = helper->getProjectedFormatCrc();
  23931. translators.setown(datafile->getTranslators(expectedCrc, helper->queryProjectedDiskRecordSize(), projectedCrc, helper->queryDiskRecordSize(), skipFileFormatCrcCheck(), getEnableFieldTranslation(), false));
  23932. files.setown(datafile->getIFileIOArray(isFetchOpt, queryFactory.queryChannel()));
  23933. }
  23934. else
  23935. map.setown(datafile->getFileMap());
  23936. }
  23937. }
  23938. }
  23939. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  23940. {
  23941. if (isHalfKeyed)
  23942. return new CRoxieServerHalfKeyedJoinActivity(_ctx, this, _probeManager,
  23943. headId, keySet, keyTranslators, indexReadMeta, joinFlags, isSimple, isLocal);
  23944. else
  23945. return new CRoxieServerKeyedJoinActivity(_ctx, this, _probeManager,
  23946. headId, keySet, keyTranslators, indexReadMeta,
  23947. tailId, map, joinFlags, isLocal); // MORE - not sure local variant actually works - should be using files not map, for example?
  23948. }
  23949. virtual const StatisticsMapping &queryStatsMapping() const
  23950. {
  23951. return keyedJoinStatistics;
  23952. }
  23953. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  23954. {
  23955. if (datafile)
  23956. addXrefFileInfo(reply, datafile);
  23957. if (indexfile)
  23958. addXrefFileInfo(reply, indexfile);
  23959. }
  23960. };
  23961. IRoxieServerActivityFactory *createRoxieServerKeyedJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId, const RemoteActivityId &_remoteId2)
  23962. {
  23963. return new CRoxieServerKeyedJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId, _remoteId2);
  23964. }
  23965. //=================================================================================
  23966. class CRoxieServerSoapActivityBase : public CRoxieServerActivity, implements ISoapCallRowProvider, implements IRoxieAbortMonitor
  23967. {
  23968. protected:
  23969. Owned<ISoapCallHelper> soaphelper;
  23970. IHThorSoapActionArg & helper;
  23971. StringBuffer authToken;
  23972. bool eof;
  23973. CriticalSection crit;
  23974. ClientCertificate *pClientCert;
  23975. public:
  23976. IMPLEMENT_IINTERFACE_USING(CRoxieServerActivity)
  23977. CRoxieServerSoapActivityBase(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  23978. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorSoapActionArg &)basehelper)
  23979. {
  23980. eof = false;
  23981. if (clientCert.certificate.length() > 0 && clientCert.privateKey.length() > 0 && clientCert.passphrase.length() > 0)
  23982. pClientCert = &clientCert;
  23983. else
  23984. pClientCert = NULL;
  23985. }
  23986. // ISoapCallRowProvider
  23987. virtual IHThorSoapActionArg * queryActionHelper() { return &helper; };
  23988. virtual IHThorSoapCallArg * queryCallHelper() { return NULL; };
  23989. virtual const void * getNextRow() { return NULL; };
  23990. virtual void releaseRow(const void * r) { ReleaseRoxieRow(r); };
  23991. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  23992. {
  23993. eof = false;
  23994. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  23995. authToken.append(ctx->queryAuthToken());
  23996. }
  23997. virtual void reset()
  23998. {
  23999. // MORE - Shouldn't we make sure thread is stopped etc???
  24000. soaphelper.clear();
  24001. CRoxieServerActivity::reset();
  24002. }
  24003. // IRoxieAbortMonitor
  24004. virtual void checkForAbort() { checkAbort(); }
  24005. };
  24006. //---------------------------------------------------------------------------
  24007. class CRoxieServerSoapRowCallActivity : public CRoxieServerSoapActivityBase
  24008. {
  24009. IHThorSoapCallArg & callHelper;
  24010. public:
  24011. CRoxieServerSoapRowCallActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  24012. : CRoxieServerSoapActivityBase(_ctx, _factory, _probeManager), callHelper((IHThorSoapCallArg &)basehelper)
  24013. {
  24014. }
  24015. virtual IHThorSoapCallArg * queryCallHelper()
  24016. {
  24017. return &callHelper;
  24018. }
  24019. virtual bool needsAllocator() const { return true; }
  24020. virtual const void *nextRow()
  24021. {
  24022. ActivityTimer t(totalCycles, timeActivities);
  24023. if(eof) return NULL;
  24024. if (soaphelper == NULL)
  24025. {
  24026. if (factory->getKind()==TAKhttp_rowdataset)
  24027. soaphelper.setown(createHttpCallHelper(this, rowAllocator, authToken.str(), SCrow, pClientCert, *this, this));
  24028. else
  24029. soaphelper.setown(createSoapCallHelper(this, rowAllocator, authToken.str(), SCrow, pClientCert, *this, this));
  24030. soaphelper->start();
  24031. }
  24032. OwnedConstRoxieRow ret = soaphelper->getRow();
  24033. if (!ret)
  24034. {
  24035. eof = true;
  24036. return NULL;
  24037. }
  24038. ++processed;
  24039. return ret.getClear();
  24040. }
  24041. };
  24042. class CRoxieServerSoapRowCallActivityFactory : public CRoxieServerActivityFactory
  24043. {
  24044. public:
  24045. CRoxieServerSoapRowCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  24046. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  24047. {
  24048. }
  24049. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  24050. {
  24051. return new CRoxieServerSoapRowCallActivity(_ctx, this, _probeManager);
  24052. }
  24053. virtual const StatisticsMapping &queryStatsMapping() const
  24054. {
  24055. return soapStatistics;
  24056. }
  24057. };
  24058. IRoxieServerActivityFactory *createRoxieServerSoapRowCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  24059. {
  24060. return new CRoxieServerSoapRowCallActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  24061. }
  24062. //---------------------------------------------------------------------------
  24063. class CRoxieServerSoapRowActionActivity : public CRoxieServerSoapActivityBase
  24064. {
  24065. public:
  24066. CRoxieServerSoapRowActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  24067. : CRoxieServerSoapActivityBase(_ctx, _factory, _probeManager)
  24068. {}
  24069. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  24070. {
  24071. //MORE: parentExtract not passed to start - although shouldn't be a problem.
  24072. soaphelper.setown(createSoapCallHelper(this, NULL, ctx->queryAuthToken(), SCrow, pClientCert, *this, this));
  24073. soaphelper->start();
  24074. soaphelper->waitUntilDone();
  24075. IException *e = soaphelper->getError();
  24076. soaphelper.clear();
  24077. if (e)
  24078. throw e;
  24079. }
  24080. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  24081. {
  24082. return NULL;
  24083. }
  24084. virtual const void *nextRow()
  24085. {
  24086. throwUnexpected(); // I am nobody's input
  24087. }
  24088. };
  24089. class CRoxieServerSoapRowActionActivityFactory : public CRoxieServerActivityFactory
  24090. {
  24091. bool isRoot;
  24092. public:
  24093. CRoxieServerSoapRowActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  24094. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  24095. {
  24096. }
  24097. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  24098. {
  24099. return new CRoxieServerSoapRowActionActivity(_ctx, this, _probeManager);
  24100. }
  24101. virtual bool isSink() const
  24102. {
  24103. return isRoot;
  24104. }
  24105. virtual const StatisticsMapping &queryStatsMapping() const
  24106. {
  24107. return soapStatistics;
  24108. }
  24109. };
  24110. IRoxieServerActivityFactory *createRoxieServerSoapRowActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  24111. {
  24112. return new CRoxieServerSoapRowActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  24113. }
  24114. //---------------------------------------------------------------------------
  24115. class CRoxieServerSoapDatasetCallActivity : public CRoxieServerSoapActivityBase
  24116. {
  24117. IHThorSoapCallArg & callHelper;
  24118. public:
  24119. CRoxieServerSoapDatasetCallActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  24120. : CRoxieServerSoapActivityBase(_ctx, _factory, _probeManager), callHelper((IHThorSoapCallArg &)basehelper)
  24121. {
  24122. }
  24123. virtual IHThorSoapCallArg * queryCallHelper()
  24124. {
  24125. return &callHelper;
  24126. }
  24127. virtual const void *getNextRow()
  24128. {
  24129. CriticalBlock b(crit); // MORE - why ?
  24130. return inputStream->ungroupedNextRow();
  24131. }
  24132. virtual bool needsAllocator() const { return true; }
  24133. virtual const void *nextRow()
  24134. {
  24135. ActivityTimer t(totalCycles, timeActivities);
  24136. if(eof) return NULL;
  24137. if (soaphelper == NULL)
  24138. {
  24139. soaphelper.setown(createSoapCallHelper(this, rowAllocator, authToken.str(), SCdataset, pClientCert, *this, this));
  24140. soaphelper->start();
  24141. }
  24142. OwnedConstRoxieRow ret = soaphelper->getRow();
  24143. if (!ret)
  24144. {
  24145. eof = true;
  24146. return NULL;
  24147. }
  24148. ++processed;
  24149. return ret.getClear();
  24150. }
  24151. };
  24152. class CRoxieServerSoapDatasetCallActivityFactory : public CRoxieServerActivityFactory
  24153. {
  24154. public:
  24155. CRoxieServerSoapDatasetCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  24156. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  24157. {
  24158. }
  24159. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  24160. {
  24161. return new CRoxieServerSoapDatasetCallActivity(_ctx, this, _probeManager);
  24162. }
  24163. virtual const StatisticsMapping &queryStatsMapping() const
  24164. {
  24165. return soapStatistics;
  24166. }
  24167. };
  24168. IRoxieServerActivityFactory *createRoxieServerSoapDatasetCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  24169. {
  24170. return new CRoxieServerSoapDatasetCallActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  24171. }
  24172. //---------------------------------------------------------------------------
  24173. class CRoxieServerSoapDatasetActionActivity : public CRoxieServerSoapActivityBase
  24174. {
  24175. public:
  24176. CRoxieServerSoapDatasetActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  24177. : CRoxieServerSoapActivityBase(_ctx, _factory, _probeManager)
  24178. {}
  24179. virtual const void *getNextRow()
  24180. {
  24181. CriticalBlock b(crit); // MORE - Why?
  24182. const void *nextrec = inputStream->ungroupedNextRow();
  24183. if (nextrec)
  24184. processed++;
  24185. return nextrec;
  24186. }
  24187. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  24188. {
  24189. try
  24190. {
  24191. start(parentExtractSize, parentExtract, false);
  24192. soaphelper.setown(createSoapCallHelper(this, NULL, ctx->queryAuthToken(), SCdataset, pClientCert, *this, this));
  24193. soaphelper->start();
  24194. soaphelper->waitUntilDone();
  24195. IException *e = soaphelper->getError();
  24196. soaphelper.clear();
  24197. if (e)
  24198. throw e;
  24199. stop();
  24200. }
  24201. catch (IException *E)
  24202. {
  24203. ctx->notifyAbort(E);
  24204. abort();
  24205. throw;
  24206. }
  24207. catch(...)
  24208. {
  24209. Owned<IException> E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught at %s:%d", sanitizeSourceFile(__FILE__), __LINE__);
  24210. ctx->notifyAbort(E);
  24211. abort();
  24212. throw;
  24213. }
  24214. }
  24215. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  24216. {
  24217. return NULL;
  24218. }
  24219. virtual const void *nextRow()
  24220. {
  24221. throwUnexpected(); // I am nobody's input
  24222. }
  24223. };
  24224. class CRoxieServerSoapDatasetActionActivityFactory : public CRoxieServerActivityFactory
  24225. {
  24226. bool isRoot;
  24227. public:
  24228. CRoxieServerSoapDatasetActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  24229. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  24230. {
  24231. }
  24232. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  24233. {
  24234. return new CRoxieServerSoapDatasetActionActivity(_ctx, this, _probeManager);
  24235. }
  24236. virtual bool isSink() const
  24237. {
  24238. return isRoot;
  24239. }
  24240. virtual const StatisticsMapping &queryStatsMapping() const
  24241. {
  24242. return soapStatistics;
  24243. }
  24244. };
  24245. IRoxieServerActivityFactory *createRoxieServerSoapDatasetActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  24246. {
  24247. return new CRoxieServerSoapDatasetActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  24248. }
  24249. //=====================================================================================================
  24250. class CGraphResults : implements IRoxieGraphResults, public CInterface
  24251. {
  24252. IArrayOf<IGraphResult> results;
  24253. CriticalSection cs;
  24254. IGraphResult & select(unsigned idx)
  24255. {
  24256. CriticalBlock procedure(cs);
  24257. if (idx >= results.ordinality())
  24258. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Error reading graph result %d before it is calculated", idx);
  24259. return results.item(idx);
  24260. }
  24261. public:
  24262. IMPLEMENT_IINTERFACE
  24263. void clear()
  24264. {
  24265. CriticalBlock procedure(cs);
  24266. results.kill();
  24267. }
  24268. virtual IEngineRowStream * createIterator(unsigned id)
  24269. {
  24270. return select(id).createIterator();
  24271. }
  24272. virtual void getLinkedResult(unsigned & count, const byte * * & ret, unsigned id) override
  24273. {
  24274. select(id).getLinkedResult(count, ret);
  24275. }
  24276. virtual void getDictionaryResult(unsigned & count, const byte * * & ret, unsigned id) override
  24277. {
  24278. select(id).getLinkedResult(count, ret);
  24279. }
  24280. virtual const void * getLinkedRowResult(unsigned id)
  24281. {
  24282. return select(id).getLinkedRowResult();
  24283. }
  24284. void setResult(unsigned id, IGraphResult * result)
  24285. {
  24286. CriticalBlock procedure(cs);
  24287. if (results.ordinality() <= id)
  24288. {
  24289. while (results.ordinality() < id)
  24290. results.append(*new CGraphResult);
  24291. results.append(*LINK(result));
  24292. }
  24293. else
  24294. results.replace(*LINK(result), id);
  24295. }
  24296. void appendResult(IGraphResult * result)
  24297. {
  24298. CriticalBlock procedure(cs);
  24299. results.append(*LINK(result));
  24300. }
  24301. };
  24302. //===================================================================================================================
  24303. class CPseudoArg : implements CThorSinkArgOf<IHThorArg>
  24304. {
  24305. };
  24306. class CPseudoActivity : public CRoxieServerActivity
  24307. {
  24308. public:
  24309. CPseudoActivity(IRoxieSlaveContext *_ctx, IHThorArg & _helper) : CRoxieServerActivity(_ctx, _helper) {}
  24310. virtual const void *nextRow()
  24311. {
  24312. throwUnexpected(); // I am nobody's input
  24313. }
  24314. };
  24315. class CActivityGraph : implements IActivityGraph, implements IThorChildGraph, implements ILocalGraphEx, implements IRoxieServerChildGraph, public CInterface
  24316. {
  24317. protected:
  24318. class ActivityGraphSlaveContext : public IndirectSlaveContext
  24319. {
  24320. SpinLock abortLock;
  24321. bool aborted;
  24322. Owned<IException> exception;
  24323. public:
  24324. ActivityGraphSlaveContext(IRoxieSlaveContext *_ctx, const IRoxieContextLogger &_logctx) : IndirectSlaveContext(_ctx), logctx(_logctx), loopCounter(0), codeContext(NULL)
  24325. {
  24326. aborted = false;
  24327. }
  24328. // Note - we must track exceptions at the child level in case there is a CATCH in parent
  24329. virtual void notifyAbort(IException *E)
  24330. {
  24331. SpinBlock b(abortLock);
  24332. if (!aborted && QUERYINTERFACE(E, InterruptedSemaphoreException) == NULL)
  24333. {
  24334. aborted = true;
  24335. exception.set(E);
  24336. }
  24337. }
  24338. virtual void checkAbort()
  24339. {
  24340. if (aborted) // NOTE - don't bother getting lock before reading this (for speed) - a false read is very unlikely and not a problem
  24341. {
  24342. SpinBlock b(abortLock);
  24343. if (!exception)
  24344. exception.setown(MakeStringException(ROXIE_INTERNAL_ERROR, "Query was aborted"));
  24345. throw exception.getLink();
  24346. }
  24347. IndirectSlaveContext::checkAbort();
  24348. }
  24349. virtual ICodeContext *queryCodeContext()
  24350. {
  24351. return codeContext;
  24352. }
  24353. void setCodeContext(ICodeContext * _codeContext)
  24354. {
  24355. codeContext = _codeContext;
  24356. }
  24357. void setLoopCounter(unsigned _loopCounter)
  24358. {
  24359. loopCounter = _loopCounter;
  24360. }
  24361. virtual void noteChildGraph(unsigned id, IActivityGraph *childGraph)
  24362. {
  24363. childGraphs.setValue(id, childGraph);
  24364. }
  24365. virtual IActivityGraph * queryChildGraph(unsigned id)
  24366. {
  24367. if (queryTraceLevel() > 10)
  24368. CTXLOG("resolveChildGraph %d", id);
  24369. IActivityGraph *childGraph = childGraphs.getValue(id);
  24370. assertex(childGraph);
  24371. return childGraph;
  24372. }
  24373. // 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
  24374. virtual StringBuffer &getLogPrefix(StringBuffer &ret) const
  24375. {
  24376. logctx.getLogPrefix(ret);
  24377. if (loopCounter)
  24378. ret.appendf("{%u}", loopCounter);
  24379. return ret;
  24380. }
  24381. protected:
  24382. const IRoxieContextLogger &logctx;
  24383. unsigned loopCounter;
  24384. ICodeContext * codeContext;
  24385. MapXToMyClass<unsigned, unsigned, IActivityGraph> childGraphs;
  24386. } graphSlaveContext;
  24387. class ActivityGraphCodeContext : public IndirectCodeContext
  24388. {
  24389. public:
  24390. virtual IEclGraphResults * resolveLocalQuery(__int64 activityId)
  24391. {
  24392. if ((unsigned) activityId == container->queryId())
  24393. return container;
  24394. IActivityGraph * match = slaveContext->queryChildGraph((unsigned) activityId);
  24395. if (match)
  24396. return match->queryLocalGraph();
  24397. return IndirectCodeContext::resolveLocalQuery(activityId);
  24398. }
  24399. virtual IThorChildGraph * resolveChildQuery(__int64 activityId, IHThorArg * colocal)
  24400. {
  24401. IActivityGraph * match = slaveContext->queryChildGraph((unsigned) activityId);
  24402. return LINK(match->queryChildGraph());
  24403. }
  24404. virtual unsigned getGraphLoopCounter() const
  24405. {
  24406. return container->queryLoopCounter(); // only called if value is valid
  24407. }
  24408. void setContainer(IRoxieSlaveContext * _slaveContext, CActivityGraph * _container)
  24409. {
  24410. slaveContext = _slaveContext;
  24411. container = _container;
  24412. }
  24413. protected:
  24414. IRoxieSlaveContext * slaveContext;
  24415. CActivityGraph * container;
  24416. } graphCodeContext;
  24417. // NOTE - destructor order is significant - need to destroy graphCodeContext and graphSlaveContext last
  24418. IArrayOf<IRoxieServerActivity> activities;
  24419. IArrayOf<IRoxieProbe> probes;
  24420. IRoxieServerActivityCopyArray sinks;
  24421. StringAttr graphName;
  24422. Owned<CGraphResults> results;
  24423. CGraphResults graphLoopResults;
  24424. const ActivityArray & graphDefinition;
  24425. CriticalSection evaluateCrit;
  24426. IProbeManager *probeManager;
  24427. unsigned id;
  24428. unsigned loopCounter;
  24429. public:
  24430. IMPLEMENT_IINTERFACE;
  24431. CActivityGraph(IRoxieSlaveContext *_ctx, const char *_graphName, unsigned _id, const ActivityArray &x, IProbeManager *_probeManager, const IRoxieContextLogger &_logctx)
  24432. : probeManager(_probeManager), graphDefinition(x), graphName(_graphName), graphSlaveContext(_ctx, _logctx)
  24433. {
  24434. id = x.getLibraryGraphId();
  24435. if (!id)
  24436. id = _id;
  24437. loopCounter = 0;
  24438. graphSlaveContext.setCodeContext(&graphCodeContext);
  24439. graphCodeContext.setContainer(&graphSlaveContext, this);
  24440. }
  24441. ~CActivityGraph()
  24442. {
  24443. if (probeManager)
  24444. probeManager->deleteGraph((IArrayOf<IActivityBase>*)&activities, (IArrayOf<IInputBase>*)&probes);
  24445. }
  24446. virtual const char *queryName() const
  24447. {
  24448. return graphName.get();
  24449. }
  24450. void createGraph(IRoxieSlaveContext *_ctx)
  24451. {
  24452. if (graphDefinition.isMultiInstance())
  24453. {
  24454. graphCodeContext.set(_ctx->queryCodeContext());
  24455. _ctx = &graphSlaveContext;
  24456. }
  24457. ForEachItemIn(idx, graphDefinition)
  24458. {
  24459. IRoxieServerActivityFactory &donor = graphDefinition.serverItem(idx);
  24460. IRoxieServerActivity &activity = *donor.createActivity(_ctx, probeManager);
  24461. activities.append(activity);
  24462. if (donor.isSink())
  24463. {
  24464. sinks.append(activity);
  24465. if (probeManager)
  24466. probeManager->noteSink(&activity);
  24467. }
  24468. }
  24469. ForEachItemIn(idx1, graphDefinition)
  24470. {
  24471. IRoxieServerActivityFactory &donor = graphDefinition.serverItem(idx1);
  24472. IRoxieServerActivity &activity = activities.item(idx1);
  24473. unsigned inputidx = 0;
  24474. for (;;)
  24475. {
  24476. unsigned outputidx;
  24477. unsigned source = donor.getInput(inputidx, outputidx);
  24478. if (source==(unsigned) -1)
  24479. break;
  24480. connectInput(idx1, inputidx, source, outputidx, 0);
  24481. inputidx++;
  24482. }
  24483. IntArray &dependencies = donor.queryDependencies();
  24484. IntArray &dependencyIndexes = donor.queryDependencyIndexes();
  24485. IntArray &dependencyControlIds = donor.queryDependencyControlIds();
  24486. StringArray &dependencyEdgeIds = donor.queryDependencyEdgeIds();
  24487. ForEachItemIn(idx2, dependencies)
  24488. {
  24489. IRoxieServerActivity &dependencySourceActivity = activities.item(dependencies.item(idx2));
  24490. unsigned dependencySourceIndex = dependencyIndexes.item(idx2);
  24491. unsigned dependencyControlId = dependencyControlIds.item(idx2);
  24492. activity.addDependency(dependencySourceActivity, dependencySourceIndex, dependencyControlId);
  24493. if (probeManager)
  24494. probeManager->noteDependency( &dependencySourceActivity, dependencySourceIndex, dependencyControlId, dependencyEdgeIds.item(idx2), &activity);
  24495. }
  24496. }
  24497. ForEachItemIn(idx2, sinks)
  24498. {
  24499. IRoxieServerActivity &sink = sinks.item(idx2);
  24500. sink.connectInputStreams(true);
  24501. }
  24502. }
  24503. void connectInput(unsigned target, unsigned targetIdx, unsigned source, unsigned sourceIdx, unsigned iteration)
  24504. {
  24505. IRoxieServerActivity &targetActivity = activities.item(target);
  24506. IRoxieServerActivity &sourceActivity = activities.item(source);
  24507. IFinalRoxieInput * output = sourceActivity.queryOutput(sourceIdx);
  24508. if (probeManager)
  24509. {
  24510. IRoxieProbe * inputProbe = probeManager->createProbe(static_cast<IInputBase*>(output), &sourceActivity, &targetActivity, sourceIdx, targetIdx, iteration);
  24511. probes.append(*LINK(inputProbe));
  24512. output = &dynamic_cast<IFinalRoxieInput &>(inputProbe->queryInput());
  24513. }
  24514. targetActivity.setInput(targetIdx, sourceIdx, output);
  24515. }
  24516. virtual void onCreate(IHThorArg *_colocalParent)
  24517. {
  24518. ForEachItemIn(idx, activities)
  24519. {
  24520. IRoxieServerActivity *activity = &activities.item(idx);
  24521. if (activity)
  24522. activity->onCreate(_colocalParent);
  24523. }
  24524. }
  24525. virtual void abort()
  24526. {
  24527. ForEachItemIn(idx, sinks)
  24528. {
  24529. IRoxieServerActivity &sink = sinks.item(idx);
  24530. sink.abort();
  24531. }
  24532. }
  24533. virtual void reset()
  24534. {
  24535. ForEachItemIn(idx, sinks)
  24536. {
  24537. IRoxieServerActivity &sink = sinks.item(idx);
  24538. sink.reset();
  24539. }
  24540. }
  24541. Linked<IException> exception;
  24542. CriticalSection eCrit;
  24543. virtual void noteException(IException *E)
  24544. {
  24545. CriticalBlock b(eCrit);
  24546. if (!exception)
  24547. {
  24548. if (graphSlaveContext.queryDebugContext())
  24549. {
  24550. graphSlaveContext.queryDebugContext()->checkBreakpoint(DebugStateException, NULL, exception);
  24551. }
  24552. exception.set(E);
  24553. }
  24554. }
  24555. virtual void checkAbort()
  24556. {
  24557. CriticalBlock b(eCrit);
  24558. if (exception)
  24559. throw exception.getLink();
  24560. }
  24561. virtual void execute()
  24562. {
  24563. results.setown(new CGraphResults);
  24564. doExecute(0, NULL);
  24565. }
  24566. //New child query code...
  24567. virtual IThorChildGraph * queryChildGraph()
  24568. {
  24569. return this;
  24570. }
  24571. virtual IEclGraphResults * queryLocalGraph()
  24572. {
  24573. return this;
  24574. }
  24575. virtual IRoxieServerChildGraph * queryLoopGraph()
  24576. {
  24577. return this;
  24578. }
  24579. inline unsigned queryId() const
  24580. {
  24581. return id;
  24582. }
  24583. inline unsigned queryLoopCounter() const
  24584. {
  24585. return loopCounter;
  24586. }
  24587. void doExecute(unsigned parentExtractSize, const byte * parentExtract)
  24588. {
  24589. if (sinks.ordinality()==1)
  24590. sinks.item(0).execute(parentExtractSize, parentExtract);
  24591. #ifdef PARALLEL_EXECUTE
  24592. else if (!probeManager && !graphDefinition.isSequential())
  24593. {
  24594. class casyncfor: public CAsyncFor
  24595. {
  24596. public:
  24597. IActivityGraph &parent;
  24598. unsigned parentExtractSize;
  24599. const byte * parentExtract;
  24600. casyncfor(IRoxieServerActivityCopyArray &_sinks, IActivityGraph &_parent, unsigned _parentExtractSize, const byte * _parentExtract) :
  24601. sinks(_sinks), parent(_parent), parentExtractSize(_parentExtractSize), parentExtract(_parentExtract) { }
  24602. void Do(unsigned i)
  24603. {
  24604. try
  24605. {
  24606. sinks.item(i).execute(parentExtractSize, parentExtract);
  24607. }
  24608. catch (IException *E)
  24609. {
  24610. parent.noteException(E);
  24611. throw;
  24612. }
  24613. }
  24614. private:
  24615. IRoxieServerActivityCopyArray &sinks;
  24616. } afor(sinks, *this, parentExtractSize, parentExtract);
  24617. afor.For(sinks.ordinality(), sinks.ordinality());
  24618. }
  24619. #endif
  24620. else
  24621. {
  24622. ForEachItemIn(idx, sinks)
  24623. {
  24624. IRoxieServerActivity &sink = sinks.item(idx);
  24625. sink.execute(parentExtractSize, parentExtract);
  24626. }
  24627. }
  24628. }
  24629. virtual IEclGraphResults *evaluate(unsigned parentExtractSize, const byte * parentExtract)
  24630. {
  24631. CriticalBlock block(evaluateCrit);
  24632. results.setown(new CGraphResults);
  24633. try
  24634. {
  24635. doExecute(parentExtractSize, parentExtract);
  24636. }
  24637. catch (...)
  24638. {
  24639. DBGLOG("Exception thrown in child query - cleaning up");
  24640. reset();
  24641. throw;
  24642. }
  24643. reset();
  24644. return results.getClear();
  24645. }
  24646. virtual void updateFactoryStatistics() const override
  24647. {
  24648. ForEachItemIn(i, activities)
  24649. activities.item(i).updateFactoryStatistics();
  24650. }
  24651. //interface IRoxieServerChildGraph
  24652. virtual void beforeExecute()
  24653. {
  24654. results.setown(new CGraphResults);
  24655. }
  24656. virtual IFinalRoxieInput * startOutput(unsigned id, unsigned parentExtractSize, const byte *parentExtract, bool paused)
  24657. {
  24658. IFinalRoxieInput * ret = selectOutput(id);
  24659. ret->start(parentExtractSize, parentExtract, paused);
  24660. return ret;
  24661. }
  24662. virtual IFinalRoxieInput * selectOutput(unsigned id)
  24663. {
  24664. ForEachItemIn(i, sinks)
  24665. {
  24666. IFinalRoxieInput * ret = sinks.item(i).querySelectOutput(id);
  24667. if (ret)
  24668. return ret;
  24669. }
  24670. throwUnexpected();
  24671. return NULL;
  24672. }
  24673. virtual void setInputResult(unsigned id, IGraphResult * result)
  24674. {
  24675. results->setResult(id, result);
  24676. }
  24677. virtual bool querySetInputResult(unsigned id, unsigned _sourceIdx, IFinalRoxieInput * input)
  24678. {
  24679. ForEachItemIn(i, activities)
  24680. {
  24681. if (activities.item(i).querySetStreamInput(id, _sourceIdx, input))
  24682. return true;
  24683. }
  24684. return false;
  24685. }
  24686. virtual void stopUnusedOutputs()
  24687. {
  24688. //Hmm not sure how to do this...
  24689. }
  24690. virtual void afterExecute()
  24691. {
  24692. ForEachItemIn(i, sinks)
  24693. {
  24694. sinks.item(i).stop();
  24695. }
  24696. if (graphSlaveContext.queryDebugContext())
  24697. {
  24698. graphSlaveContext.queryDebugContext()->checkBreakpoint(DebugStateGraphFinished, NULL, NULL);
  24699. }
  24700. reset();
  24701. }
  24702. virtual IRoxieGraphResults * execute(size32_t parentExtractSize, const byte *parentExtract)
  24703. {
  24704. doExecute(parentExtractSize, parentExtract);
  24705. return LINK(results);
  24706. }
  24707. virtual void getLinkedResult(unsigned & count, const byte * * & ret, unsigned id) override
  24708. {
  24709. results->getLinkedResult(count, ret, id);
  24710. }
  24711. virtual void getDictionaryResult(unsigned & count, const byte * * & ret, unsigned id) override
  24712. {
  24713. results->getLinkedResult(count, ret, id);
  24714. }
  24715. virtual const void * getLinkedRowResult(unsigned id)
  24716. {
  24717. return results->getLinkedRowResult(id);
  24718. }
  24719. virtual void setResult(unsigned id, IGraphResult * result)
  24720. {
  24721. results->setResult(id, result);
  24722. }
  24723. virtual IEngineRowStream * createResultIterator(unsigned id)
  24724. {
  24725. return results->createIterator(id);
  24726. }
  24727. virtual void setGraphLoopResult(IGraphResult * result)
  24728. {
  24729. graphLoopResults.appendResult(result);
  24730. }
  24731. virtual IEngineRowStream * createGraphLoopResultIterator(unsigned id)
  24732. {
  24733. try
  24734. {
  24735. return graphLoopResults.createIterator(id);
  24736. }
  24737. catch (IException * e)
  24738. {
  24739. e->Release();
  24740. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Error reading graph result %d before it is calculated", id);
  24741. }
  24742. }
  24743. virtual void clearGraphLoopResults()
  24744. {
  24745. graphLoopResults.clear();
  24746. }
  24747. virtual void executeGraphLoop(size32_t parentExtractSize, const byte *parentExtract)
  24748. {
  24749. doExecute(parentExtractSize, parentExtract);
  24750. }
  24751. virtual void setGraphLoopResult(unsigned id, IGraphResult * result)
  24752. {
  24753. graphLoopResults.setResult(id, result);
  24754. }
  24755. virtual IEngineRowStream * getGraphLoopResult(unsigned id)
  24756. {
  24757. return graphLoopResults.createIterator(id);
  24758. }
  24759. virtual void getProbeResponse(IPropertyTree *query)
  24760. {
  24761. if (probeManager)
  24762. probeManager->getProbeResponse(query);
  24763. }
  24764. virtual IRoxieServerChildGraph * createGraphLoopInstance(IRoxieSlaveContext *ctx, unsigned loopCounter, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &logctx)
  24765. {
  24766. throwUnexpected();
  24767. }
  24768. virtual CGraphIterationInfo *selectGraphLoopOutput()
  24769. {
  24770. return NULL;
  24771. }
  24772. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor)
  24773. {
  24774. throwUnexpected();
  24775. }
  24776. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor)
  24777. {
  24778. throwUnexpected();
  24779. }
  24780. };
  24781. class CProxyActivityGraph : implements IActivityGraph, implements IThorChildGraph, public CInterface
  24782. {
  24783. public:
  24784. IMPLEMENT_IINTERFACE;
  24785. CProxyActivityGraph(IRoxieSlaveContext *_ctx, const char *_graphName, unsigned _id, ActivityArray &_graphDefinition, const IRoxieContextLogger &_logctx, unsigned _numParallel)
  24786. : ctx(_ctx), graphName(_graphName), id(_id), graphDefinition(_graphDefinition), logctx(_logctx), numParallel(_numParallel)
  24787. {
  24788. }
  24789. virtual void abort() override { throwUnexpected(); }
  24790. virtual void reset() override { throwUnexpected(); }
  24791. virtual void execute() override { throwUnexpected(); }
  24792. virtual void getProbeResponse(IPropertyTree *query) override { throwUnexpected(); }
  24793. virtual void onCreate(IHThorArg *_colocalArg) override
  24794. {
  24795. colocalArg = _colocalArg;
  24796. }
  24797. virtual void noteException(IException *E) override { throwUnexpected(); }
  24798. virtual void checkAbort() override { throwUnexpected(); }
  24799. virtual IThorChildGraph * queryChildGraph() override { return this; }
  24800. virtual IEclGraphResults * queryLocalGraph() override { throwUnexpected(); }
  24801. virtual IRoxieServerChildGraph * queryLoopGraph() override { throwUnexpected(); }
  24802. virtual IRoxieServerChildGraph * createGraphLoopInstance(IRoxieSlaveContext *ctx, unsigned loopCounter, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &logctx) override { throwUnexpected(); }
  24803. virtual const char *queryName() const override { throwUnexpected(); }
  24804. virtual void updateFactoryStatistics() const override
  24805. {
  24806. CriticalBlock b(graphCrit);
  24807. ForEachItemIn(i, stack)
  24808. stack.item(i).updateFactoryStatistics();
  24809. }
  24810. virtual IEclGraphResults * evaluate(unsigned parentExtractSize, const byte * parentExtract) override
  24811. {
  24812. Owned<CActivityGraph> realGraph;
  24813. {
  24814. CriticalBlock b(graphCrit);
  24815. if (stack.length())
  24816. realGraph.setown(&stack.popGet());
  24817. }
  24818. if (!realGraph)
  24819. {
  24820. realGraph.setown(new CActivityGraph(ctx, graphName, id, graphDefinition, NULL, logctx));
  24821. realGraph->createGraph(ctx);
  24822. realGraph->onCreate(colocalArg);
  24823. }
  24824. Owned<IEclGraphResults> results = realGraph->evaluate(parentExtractSize, parentExtract);
  24825. {
  24826. CriticalBlock b(graphCrit);
  24827. stack.append(*realGraph.getClear());
  24828. }
  24829. return results.getClear();
  24830. }
  24831. protected:
  24832. IRoxieSlaveContext *ctx;
  24833. StringAttr graphName;
  24834. unsigned id;
  24835. ActivityArray &graphDefinition;
  24836. const IRoxieContextLogger &logctx;
  24837. unsigned numParallel;
  24838. IHThorArg *colocalArg = nullptr;
  24839. mutable CriticalSection graphCrit;
  24840. CIArrayOf<CActivityGraph> stack;
  24841. };
  24842. class CIterationActivityGraph : public CActivityGraph
  24843. {
  24844. IHThorArg * colocalParent;
  24845. unsigned fixedParentExtractSize;
  24846. const byte * fixedParentExtract;
  24847. unsigned graphOutputActivityIndex;
  24848. public:
  24849. CIterationActivityGraph(const char *_graphName, unsigned _id, ActivityArray &x, IProbeManager *_probeManager,
  24850. unsigned _loopCounter, IRoxieSlaveContext *_ctx, IHThorArg * _colocalParent, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &_logctx)
  24851. : CActivityGraph(_ctx, _graphName, _id, x, _probeManager, _logctx)
  24852. {
  24853. graphOutputActivityIndex = 0;
  24854. loopCounter = _loopCounter;
  24855. colocalParent = _colocalParent;
  24856. graphSlaveContext.setLoopCounter(loopCounter);
  24857. graphCodeContext.set(_ctx->queryCodeContext());
  24858. fixedParentExtractSize = parentExtractSize;
  24859. fixedParentExtract = parentExtract;
  24860. }
  24861. void createIterationGraph(IRoxieSlaveContext *_ctx)
  24862. {
  24863. Owned<IRoxieServerActivity> pseudoActivity = new CPseudoActivity(_ctx, *new CPseudoArg);
  24864. ForEachItemIn(idx1, graphDefinition)
  24865. activities.append(*LINK(pseudoActivity));
  24866. graphOutputActivityIndex = queryGraphOutputIndex();
  24867. recursiveCreateGraph(_ctx, graphOutputActivityIndex);
  24868. }
  24869. unsigned queryGraphOutputIndex() const
  24870. {
  24871. ForEachItemIn(i, graphDefinition)
  24872. if (graphDefinition.serverItem(i).getKind() == TAKgraphloopresultwrite)
  24873. return i;
  24874. throwUnexpected();
  24875. }
  24876. void recursiveCreateGraph(IRoxieSlaveContext *_ctx, unsigned whichActivity)
  24877. {
  24878. //Check to see if already created
  24879. IRoxieServerActivity & prevActivity = activities.item(whichActivity);
  24880. if (prevActivity.queryId() != 0)
  24881. {
  24882. prevActivity.noteOutputUsed(); //We need to patch up the number of outputs for splitters.
  24883. return;
  24884. }
  24885. IRoxieServerActivityFactory &donor = graphDefinition.serverItem(whichActivity);
  24886. IRoxieServerActivity * activity = NULL;
  24887. if (donor.isGraphInvariant())
  24888. {
  24889. ThorActivityKind kind = donor.getKind();
  24890. switch (kind)
  24891. {
  24892. case TAKif:
  24893. case TAKchildif:
  24894. case TAKcase:
  24895. case TAKchildcase: // MORE RKC->GH - what about FILTER with a graph-invariant condition and other latestart activities?
  24896. {
  24897. Owned<IHThorArg> helper = &donor.getHelper();
  24898. helper->onCreate(&graphCodeContext, colocalParent, NULL);
  24899. helper->onStart(fixedParentExtract, NULL);
  24900. unsigned branch;
  24901. switch (kind)
  24902. {
  24903. case TAKif: case TAKchildif:
  24904. branch = static_cast<IHThorIfArg *>(helper.get())->getCondition() ? 0 : 1;
  24905. break;
  24906. case TAKcase: case TAKchildcase:
  24907. branch = static_cast<IHThorCaseArg *>(helper.get())->getBranch();
  24908. if (branch >= donor.numInputs())
  24909. branch = donor.numInputs() - 1;
  24910. break;
  24911. default:
  24912. throwUnexpected();
  24913. }
  24914. helper.clear();
  24915. unsigned outputidx;
  24916. unsigned source = donor.getInput(branch, outputidx);
  24917. if (source ==(unsigned) -1)
  24918. activity = createRoxieServerNullActivity(&graphSlaveContext, &donor, probeManager);
  24919. else
  24920. activity = createRoxieServerPassThroughActivity(&graphSlaveContext, &donor, probeManager);
  24921. activities.replace(*activity, whichActivity);
  24922. activity->onCreate(colocalParent);
  24923. if (source ==(unsigned) -1)
  24924. return;
  24925. recursiveCreateGraph(_ctx, source);
  24926. connectInput(whichActivity, 0, source, outputidx, loopCounter);
  24927. break;
  24928. }
  24929. }
  24930. }
  24931. if (!activity)
  24932. {
  24933. activity = donor.createActivity(&graphSlaveContext, probeManager);
  24934. activities.replace(*activity, whichActivity);
  24935. activity->onCreate(colocalParent);
  24936. activity->resetOutputsUsed();
  24937. unsigned inputidx = 0;
  24938. for (;;)
  24939. {
  24940. unsigned outputidx;
  24941. unsigned source = donor.getInput(inputidx, outputidx);
  24942. if (source==(unsigned) -1)
  24943. break;
  24944. recursiveCreateGraph(_ctx, source);
  24945. connectInput(whichActivity, inputidx, source, outputidx, loopCounter);
  24946. inputidx++;
  24947. }
  24948. }
  24949. IntArray &dependencies = donor.queryDependencies();
  24950. IntArray &dependencyIndexes = donor.queryDependencyIndexes();
  24951. IntArray &dependencyControlIds = donor.queryDependencyControlIds();
  24952. ForEachItemIn(idx2, dependencies)
  24953. {
  24954. unsigned input = dependencies.item(idx2);
  24955. recursiveCreateGraph(_ctx, input);
  24956. activity->addDependency(activities.item(input),dependencyIndexes.item(idx2),dependencyControlIds.item(idx2));
  24957. }
  24958. }
  24959. virtual CGraphIterationInfo *selectGraphLoopOutput()
  24960. {
  24961. IRoxieServerActivity &sourceActivity = activities.item(graphOutputActivityIndex);
  24962. IFinalRoxieInput *sourceInput = sourceActivity.queryOutput(0);
  24963. return new CGraphIterationInfo(&sourceActivity, sourceInput, 0, loopCounter);
  24964. }
  24965. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor)
  24966. {
  24967. ForEachItemIn(i, activities)
  24968. activities.item(i).gatherIterationUsage(processor, fixedParentExtractSize, fixedParentExtract);
  24969. }
  24970. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor)
  24971. {
  24972. ForEachItemIn(i, activities)
  24973. activities.item(i).associateIterationOutputs(processor, fixedParentExtractSize, fixedParentExtract, probeManager, probes);
  24974. }
  24975. };
  24976. class CDelayedActivityGraph : implements IActivityGraph, public CInterface
  24977. {
  24978. StringAttr graphName;
  24979. ActivityArray & graphDefinition;
  24980. IProbeManager *probeManager;
  24981. unsigned id;
  24982. IRoxieSlaveContext * ctx;
  24983. IHThorArg * colocalParent;
  24984. public:
  24985. IMPLEMENT_IINTERFACE;
  24986. CDelayedActivityGraph(const char *_graphName, unsigned _id, ActivityArray &x, IProbeManager *_probeManager)
  24987. : probeManager(_probeManager), graphDefinition(x)
  24988. {
  24989. graphName.set(_graphName);
  24990. id = _id;
  24991. ctx = NULL;
  24992. colocalParent = NULL;
  24993. }
  24994. virtual const char *queryName() const override { return graphName.get(); }
  24995. virtual void abort() override { throwUnexpected(); }
  24996. virtual void reset() override { }
  24997. virtual void execute() override { throwUnexpected(); }
  24998. virtual void getProbeResponse(IPropertyTree *query) override { throwUnexpected(); }
  24999. virtual void noteException(IException *E) override { throwUnexpected(); }
  25000. virtual void checkAbort() override { throwUnexpected(); }
  25001. virtual IThorChildGraph * queryChildGraph() override { throwUnexpected(); }
  25002. virtual IEclGraphResults * queryLocalGraph() override { throwUnexpected(); }
  25003. virtual IRoxieServerChildGraph * queryLoopGraph() override { throwUnexpected(); }
  25004. virtual void updateFactoryStatistics() const override { }
  25005. virtual void onCreate(IHThorArg *_colocalParent) override
  25006. {
  25007. colocalParent = _colocalParent;
  25008. }
  25009. virtual IRoxieServerChildGraph * createGraphLoopInstance(IRoxieSlaveContext *ctx, unsigned loopCounter, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &logctx) override
  25010. {
  25011. Owned<CIterationActivityGraph> ret = new CIterationActivityGraph(graphName, id, graphDefinition, probeManager, loopCounter, ctx, colocalParent, parentExtractSize, parentExtract, logctx);
  25012. ret->createIterationGraph(ctx);
  25013. return ret.getClear();
  25014. }
  25015. };
  25016. IActivityGraph *createActivityGraph(IRoxieSlaveContext *ctx, const char *_graphName, unsigned id, ActivityArray &childFactories, IRoxieServerActivity *parentActivity, IProbeManager *_probeManager, const IRoxieContextLogger &_logctx, unsigned numParallel)
  25017. {
  25018. if (childFactories.isDelayed())
  25019. {
  25020. assertex(numParallel==1);
  25021. return new CDelayedActivityGraph(_graphName, id, childFactories, _probeManager);
  25022. }
  25023. else
  25024. {
  25025. if (numParallel==1 || _probeManager != nullptr)
  25026. {
  25027. Owned<IProbeManager> childProbe;
  25028. if (_probeManager)
  25029. childProbe.setown(_probeManager->startChildGraph(id, parentActivity));
  25030. Owned<CActivityGraph> ret = new CActivityGraph(ctx, _graphName, id, childFactories, childProbe, _logctx);
  25031. ret->createGraph(ctx);
  25032. if (_probeManager)
  25033. _probeManager->endChildGraph(childProbe, parentActivity);
  25034. return ret.getClear();
  25035. }
  25036. else
  25037. return new CProxyActivityGraph(ctx, _graphName, id, childFactories, _logctx, numParallel);
  25038. }
  25039. }
  25040. //================================================================================================================
  25041. #ifdef _USE_CPPUNIT
  25042. #include "unittests.hpp"
  25043. // 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...
  25044. #if _MSC_VER==1200
  25045. #undef protected
  25046. #endif
  25047. static const char *sortAlgorithm;
  25048. class TestMetaData : public CInterface, implements IOutputMetaData
  25049. {
  25050. public:
  25051. IMPLEMENT_IINTERFACE;
  25052. virtual size32_t getRecordSize(const void *) { return 10; }
  25053. virtual size32_t getMinRecordSize() const { return 10; }
  25054. virtual size32_t getFixedSize() const { return 10; }
  25055. virtual void toXML(const byte * self, IXmlWriter & out) {}
  25056. virtual unsigned getVersion() const { return OUTPUTMETADATA_VERSION; }
  25057. virtual unsigned getMetaFlags() { return 0; }
  25058. virtual void destruct(byte * self) {}
  25059. virtual IOutputRowSerializer * createDiskSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  25060. virtual IOutputRowDeserializer * createDiskDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  25061. virtual ISourceRowPrefetcher * createDiskPrefetcher() { return NULL; }
  25062. virtual IOutputMetaData * querySerializedDiskMeta() { return NULL; }
  25063. virtual IOutputRowSerializer * createInternalSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  25064. virtual IOutputRowDeserializer * createInternalDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  25065. virtual void walkIndirectMembers(const byte * self, IIndirectMemberVisitor & visitor) {}
  25066. virtual IOutputMetaData * queryChildMeta(unsigned i) { return NULL; }
  25067. virtual const RtlRecord &queryRecordAccessor(bool expand) const { throwUnexpected(); }
  25068. } testMeta;
  25069. class TestInput : public CInterface, implements IFinalRoxieInput, implements IEngineRowStream
  25070. {
  25071. char const * const *input;
  25072. IRoxieSlaveContext *ctx;
  25073. unsigned endSeen;
  25074. bool eof;
  25075. unsigned count;
  25076. ActivityTimeAccumulator totalCycles;
  25077. size32_t recordSize;
  25078. unsigned activityId;
  25079. public:
  25080. enum { STATEreset, STATEstarted, STATEstopped } state;
  25081. bool allRead;
  25082. unsigned repeat;
  25083. IMPLEMENT_IINTERFACE;
  25084. TestInput(IRoxieSlaveContext *_ctx, char const * const *_input)
  25085. {
  25086. ctx = _ctx;
  25087. input = _input;
  25088. count = 0;
  25089. eof = false;
  25090. allRead = false;
  25091. endSeen = 0;
  25092. recordSize = testMeta.getFixedSize();
  25093. state = STATEreset;
  25094. activityId = 1;
  25095. repeat = 0;
  25096. }
  25097. virtual IOutputMetaData * queryOutputMeta() const { return &testMeta; }
  25098. virtual void prestart(unsigned parentExtractSize, const byte *parentExtract)
  25099. {
  25100. ASSERT(state == STATEreset);
  25101. }
  25102. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  25103. {
  25104. ASSERT(state == STATEreset);
  25105. state = STATEstarted;
  25106. }
  25107. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  25108. {
  25109. streams.append(this);
  25110. return NULL;
  25111. }
  25112. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { assertex(whichInput==0); return this; }
  25113. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { assertex(idx==0); return nullptr; }
  25114. virtual IRoxieServerActivity *queryActivity()
  25115. {
  25116. throwUnexpected();
  25117. }
  25118. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  25119. {
  25120. throwUnexpected();
  25121. }
  25122. virtual void stop()
  25123. {
  25124. state = STATEstopped;
  25125. }
  25126. virtual void reset()
  25127. {
  25128. ASSERT(state == STATEstopped);
  25129. eof = false; count = 0; endSeen = 0; allRead = false; state = STATEreset;
  25130. }
  25131. virtual void resetEOF()
  25132. {
  25133. throwUnexpected();
  25134. }
  25135. virtual void checkAbort() {}
  25136. virtual unsigned queryId() const { return activityId; };
  25137. virtual const void *nextRow()
  25138. {
  25139. ActivityTimer t(totalCycles, ctx->queryOptions().timeActivities);
  25140. ASSERT(state == STATEstarted);
  25141. ASSERT(allRead || !eof);
  25142. if (eof)
  25143. return NULL;
  25144. again:
  25145. const char *nextSource = input[count++];
  25146. if (nextSource)
  25147. {
  25148. endSeen = 0;
  25149. void *ret = ctx->queryRowManager().ALLOCATE(recordSize);
  25150. memset(ret, 0, recordSize);
  25151. strncpy((char *) ret, nextSource, recordSize);
  25152. return ret;
  25153. }
  25154. else if (repeat)
  25155. {
  25156. repeat--;
  25157. count = 0;
  25158. goto again;
  25159. }
  25160. else
  25161. {
  25162. endSeen++;
  25163. if (endSeen==2)
  25164. eof = true;
  25165. return NULL;
  25166. }
  25167. }
  25168. virtual bool nextGroup(ConstPointerArray & group)
  25169. {
  25170. const void * next;
  25171. while ((next = nextRow()) != NULL)
  25172. group.append(next);
  25173. if (group.ordinality())
  25174. return true;
  25175. return false;
  25176. }
  25177. virtual unsigned __int64 queryTotalCycles() const { return totalCycles.totalCycles; }
  25178. virtual unsigned __int64 queryLocalCycles() const { return totalCycles.totalCycles; }
  25179. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  25180. {
  25181. return NULL;
  25182. }
  25183. };
  25184. struct SortActivityTest : public CThorSortArg {
  25185. public:
  25186. struct CompareClass : public ICompare {
  25187. virtual int docompare(const void * _left, const void * _right) const {
  25188. return memcmp(_left, _right, 5);
  25189. }
  25190. } compare;
  25191. virtual ICompare * queryCompare() { return &compare; }
  25192. virtual IOutputMetaData * queryOutputMeta()
  25193. {
  25194. return &testMeta;
  25195. }
  25196. virtual unsigned getAlgorithmFlags() { return TAFunstable; }
  25197. virtual const char * getAlgorithm() { return sortAlgorithm; }
  25198. };
  25199. extern "C" IHThorArg * sortActivityTestFactory() { return new SortActivityTest; }
  25200. struct MergeActivityTest : public CThorMergeArg {
  25201. static bool isDedup;
  25202. public:
  25203. struct CompareClass : public ICompare {
  25204. virtual int docompare(const void * _left, const void * _right) const {
  25205. return memcmp(_left, _right, 5);
  25206. }
  25207. } compare;
  25208. virtual ICompare * queryCompare() { return &compare; }
  25209. virtual IOutputMetaData * queryOutputMeta()
  25210. {
  25211. return &testMeta;
  25212. }
  25213. virtual bool dedup() { return isDedup; }
  25214. };
  25215. bool MergeActivityTest::isDedup = false;
  25216. extern "C" IHThorArg * mergeActivityTestFactory() { return new MergeActivityTest; }
  25217. struct SplitActivityTest : public CThorSplitArg {
  25218. public:
  25219. virtual unsigned numBranches() { return 2; }
  25220. virtual IOutputMetaData * queryOutputMeta()
  25221. {
  25222. return &testMeta;
  25223. }
  25224. };
  25225. extern "C" IHThorArg * splitActivityTestFactory() { return new SplitActivityTest; }
  25226. class CcdServerTest : public CppUnit::TestFixture
  25227. {
  25228. CPPUNIT_TEST_SUITE(CcdServerTest);
  25229. CPPUNIT_TEST(testSetup);
  25230. CPPUNIT_TEST(testHeapSort);
  25231. CPPUNIT_TEST(testQuickSort);
  25232. CPPUNIT_TEST(testMerge);
  25233. CPPUNIT_TEST(testMergeDedup);
  25234. CPPUNIT_TEST(testMiscellaneous);
  25235. CPPUNIT_TEST(testSplitter);
  25236. CPPUNIT_TEST(testCleanup);
  25237. CPPUNIT_TEST_SUITE_END();
  25238. protected:
  25239. SlaveContextLogger logctx;
  25240. Owned<const IQueryDll> queryDll;
  25241. Owned<IRoxiePackage> package;
  25242. Owned<IPropertyTree> stateInfo;
  25243. Owned<IQueryFactory> queryFactory;
  25244. Owned<IRoxieSlaveContext> ctx;
  25245. void testSetup()
  25246. {
  25247. selfTestMode = true;
  25248. roxiemem::setTotalMemoryLimit(false, true, false, 100 * 1024 * 1024, 0, NULL, NULL);
  25249. }
  25250. void testCleanup()
  25251. {
  25252. roxiemem::releaseRoxieHeap();
  25253. }
  25254. void init()
  25255. {
  25256. package.setown(createRoxiePackage(NULL, NULL));
  25257. queryDll.setown(createExeQueryDll("roxie"));
  25258. stateInfo.setown(createPTreeFromXMLString("<test memoryLimit='50000000'/>"));
  25259. queryFactory.setown(createServerQueryFactory("test", queryDll.getLink(), *package, stateInfo, false, false));
  25260. ctx.setown(createSlaveContext(queryFactory, logctx, NULL, false));
  25261. queryActiveTimer()->reset();
  25262. }
  25263. void testActivity(IRoxieServerActivity *activity, char const * const *input, char const * const *output)
  25264. {
  25265. testActivity(activity, input, NULL, output);
  25266. }
  25267. void testActivity(IRoxieServerActivity *activity, char const * const *input, char const * const *input2, char const * const *output, unsigned outputIdx = 0)
  25268. {
  25269. TestInput in(ctx, input);
  25270. TestInput in2(ctx, input2);
  25271. activity->setInput(0, 0, &in);
  25272. if (input2)
  25273. activity->setInput(1, 0, &in2);
  25274. IFinalRoxieInput *out = activity->queryOutput(outputIdx);
  25275. IEngineRowStream *outStream = connectSingleStream(ctx, out, outputIdx, true);
  25276. IOutputMetaData *meta = out->queryOutputMeta();
  25277. void *buf = alloca(meta->getFixedSize());
  25278. for (unsigned iteration = 0; iteration < 8; iteration++)
  25279. {
  25280. // 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)
  25281. // This should be true whether we read all, some, or none of the data.
  25282. // Should not matter if an activity is not started
  25283. if (iteration % 4 == 0)
  25284. activity->onCreate(NULL);
  25285. unsigned count = 0;
  25286. if (iteration % 4 != 3)
  25287. {
  25288. activity->start(0, NULL, false);
  25289. ASSERT(in.state == TestInput::STATEstarted);
  25290. ASSERT(!input2 || in2.state == TestInput::STATEstarted);
  25291. for (;;)
  25292. {
  25293. const void *next = outStream->nextRow();
  25294. if (!next)
  25295. {
  25296. ASSERT(output[count++] == NULL);
  25297. next = outStream->nextRow();
  25298. if (!next)
  25299. {
  25300. ASSERT(output[count++] == NULL);
  25301. break;
  25302. }
  25303. }
  25304. ASSERT(output[count] != NULL);
  25305. unsigned outsize = meta->getRecordSize(next);
  25306. memset(buf, 0, outsize);
  25307. strncpy((char *) buf, output[count++], outsize);
  25308. ASSERT(memcmp(next, buf, outsize) == 0);
  25309. ReleaseRoxieRow(next);
  25310. if (iteration % 4 == 2)
  25311. break;
  25312. }
  25313. if (iteration % 4 != 2)
  25314. {
  25315. // Check that reading after end is harmless
  25316. in.allRead = true;
  25317. const void *next = outStream->nextRow();
  25318. ASSERT(next == NULL);
  25319. }
  25320. }
  25321. activity->stop();
  25322. ASSERT(in.state == TestInput::STATEstopped);
  25323. ASSERT(!input2 || in2.state == TestInput::STATEstopped);
  25324. activity->reset();
  25325. ASSERT(in.state == TestInput::STATEreset);
  25326. ASSERT(!input2 || in2.state == TestInput::STATEreset);
  25327. ctx->queryRowManager().reportLeaks();
  25328. ASSERT(ctx->queryRowManager().numPagesAfterCleanup(true) == 0);
  25329. }
  25330. }
  25331. void testSplitActivity(IRoxieServerActivityFactory *factory, char const * const *input, char const * const *output, unsigned numOutputs, unsigned repeat)
  25332. {
  25333. Owned <IRoxieServerActivity> activity = factory->createActivity(ctx, NULL);
  25334. TestInput in(ctx, input);
  25335. in.repeat = repeat;
  25336. activity->setInput(0, 0, &in);
  25337. ArrayOf<IFinalRoxieInput *> out;
  25338. for (unsigned i = 0; i < numOutputs; i++)
  25339. {
  25340. out.append(activity->queryOutput(i));
  25341. }
  25342. activity->onCreate(NULL);
  25343. class casyncfor: public CAsyncFor
  25344. {
  25345. public:
  25346. casyncfor(CcdServerTest *_parent, IRoxieServerActivity *_activity, ArrayOf<IFinalRoxieInput *> &_outputs, char const * const *_input, char const * const *_output, unsigned _repeat)
  25347. : parent(_parent), activity(_activity), outputs(_outputs), input(_input), output(_output), repeat(_repeat)
  25348. {}
  25349. void Do(unsigned i)
  25350. {
  25351. IFinalRoxieInput *out = outputs.item(i);
  25352. IEngineRowStream *outStream = connectSingleStream(NULL, out, 0, true);
  25353. out->start(0, NULL, false);
  25354. IOutputMetaData *meta = out->queryOutputMeta();
  25355. void *buf = alloca(meta->getFixedSize());
  25356. unsigned count = 0;
  25357. unsigned repeats = repeat;
  25358. for (;;)
  25359. {
  25360. const void *next = outStream->nextRow();
  25361. if (!next)
  25362. {
  25363. ASSERT(repeats==0);
  25364. ASSERT(output[count] == NULL);
  25365. count++;
  25366. next = outStream->nextRow();
  25367. if (!next)
  25368. {
  25369. ASSERT(output[count] == NULL);
  25370. count++;
  25371. break;
  25372. }
  25373. }
  25374. if (output[count] == NULL && repeats)
  25375. {
  25376. repeats--;
  25377. count = 0;
  25378. }
  25379. ASSERT(output[count] != NULL);
  25380. unsigned outsize = meta->getRecordSize(next);
  25381. memset(buf, 0, outsize);
  25382. strncpy((char *) buf, output[count++], outsize);
  25383. ASSERT(memcmp(next, buf, outsize) == 0);
  25384. ReleaseRoxieRow(next);
  25385. }
  25386. outStream->stop();
  25387. }
  25388. private:
  25389. IRoxieServerActivity *activity;
  25390. ArrayOf<IFinalRoxieInput *> &outputs;
  25391. char const * const *input;
  25392. char const * const *output;
  25393. unsigned repeat;
  25394. CcdServerTest *parent;
  25395. } afor(this, activity, out, input, output, repeat);
  25396. afor.For(numOutputs, numOutputs);
  25397. ASSERT(in.state == TestInput::STATEstopped);
  25398. for (unsigned i2 = 0; i2 < numOutputs; i2++)
  25399. {
  25400. out.item(i2)->reset();
  25401. }
  25402. ASSERT(in.state == TestInput::STATEreset);
  25403. ctx->queryRowManager().reportLeaks();
  25404. ASSERT(ctx->queryRowManager().numPagesAfterCleanup(true) == 0);
  25405. }
  25406. static int compareFunc(const void *l, const void *r)
  25407. {
  25408. return strcmp(*(char **) l, *(char **) r);
  25409. }
  25410. void testSort(unsigned type)
  25411. {
  25412. init();
  25413. sortAlgorithm = NULL;
  25414. if (type==2)
  25415. sortAlgorithm = "heapSort";
  25416. else
  25417. sortAlgorithm = "quickSort";
  25418. DBGLOG("Testing %s activity", sortAlgorithm);
  25419. Owned<IPropertyTree> dummyNode = createPTree("node");
  25420. Owned <IRoxieServerActivityFactory> factory = createRoxieServerSortActivityFactory(1, 1, *queryFactory, sortActivityTestFactory, TAKsort, *dummyNode);
  25421. Owned <IRoxieServerActivity> activity = factory->createActivity(ctx, NULL);
  25422. const char * test[] = { NULL, NULL };
  25423. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  25424. const char * test54321[] = { "5", "4", "3", "2", "1", NULL, NULL };
  25425. const char * test11111[] = { "1", "1", "1", "1", "1", NULL, NULL };
  25426. const char * test11111_12345[] = { "1", "1", "1", "1", "1", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  25427. const char * test11111_54321[] = { "1", "1", "1", "1", "1", NULL, "5", "4", "3", "2", "1", NULL, NULL };
  25428. const char * test54321_54321[] = { "5", "4", "3", "2", "1", NULL, "5", "4", "3", "2", "1", NULL, NULL };
  25429. const char * test12345_12345[] = { "1", "2", "3", "4", "5", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  25430. testActivity(activity, test, test);
  25431. testActivity(activity, test12345, test12345);
  25432. testActivity(activity, test54321, test12345);
  25433. testActivity(activity, test11111, test11111);
  25434. testActivity(activity, test11111_12345, test11111_12345);
  25435. testActivity(activity, test11111_54321, test11111_12345);
  25436. testActivity(activity, test54321_54321, test12345_12345);
  25437. // A few larger tests
  25438. char *input[2002];
  25439. char *output[2002];
  25440. input[2000] = input[2001] = output[2000] = output[2001] = NULL;
  25441. unsigned i;
  25442. // identical
  25443. for (i=0; i<2000; i++)
  25444. {
  25445. input[i] = new char[11];
  25446. output[i] = new char[11];
  25447. sprintf(input[i], "1");
  25448. sprintf(output[i], "1");
  25449. }
  25450. testActivity(activity, input, output);
  25451. // Ascending
  25452. for (i=0; i<2000; i++)
  25453. {
  25454. sprintf(input[i], "%04d", i);
  25455. sprintf(output[i], "%04d", i);
  25456. }
  25457. testActivity(activity, input, output);
  25458. // Almost sorted
  25459. for (i=0; i<20; i++)
  25460. {
  25461. unsigned h = i*100;
  25462. sprintf(input[h], "%04d", 1900-h);
  25463. }
  25464. testActivity(activity, input, output);
  25465. // Descending
  25466. for (i=0; i<2000; i++)
  25467. {
  25468. sprintf(input[i], "%04d", 1999-i);
  25469. sprintf(output[i], "%04d", i);
  25470. }
  25471. testActivity(activity, input, output);
  25472. // Random
  25473. for (i=0; i<2000; i++)
  25474. {
  25475. unsigned r = fastRand() % 1500;
  25476. sprintf(input[i], "%04d", r);
  25477. sprintf(output[i], "%04d", r);
  25478. }
  25479. qsort(output, 2000, sizeof(output[0]), compareFunc);
  25480. testActivity(activity, input, output);
  25481. unsigned __int64 us = factory->queryLocalTimeNs();
  25482. DBGLOG("Simple %s sorts: activity time %u.%u ms", type==2?"Heap" : (type==1 ? "Insertion" : "Quick"), (int)(us/1000), (int)(us%1000));
  25483. factory->resetNodeProgressInfo();
  25484. if (type)
  25485. {
  25486. // Other than quicksort, it's supposed to be stable. Let's check that it is
  25487. // All sort identical
  25488. for (i=0; i<2000; i++)
  25489. {
  25490. sprintf(input[i], "1 %d", i);
  25491. sprintf(output[i], "1 %d", i);
  25492. }
  25493. testActivity(activity, input, output);
  25494. // Already sorted
  25495. for (i=0; i<2000; i++)
  25496. {
  25497. sprintf(input[i], "%04d %d", i / 10, i);
  25498. sprintf(output[i], "%04d %d", i / 10, i);
  25499. }
  25500. testActivity(activity, input, output);
  25501. // Reverse order
  25502. for (i=0; i<2000; i++)
  25503. {
  25504. sprintf(input[i], "%04d %d", 199 - (i / 10), i%10);
  25505. sprintf(output[i], "%04d %d", i / 10, i%10);
  25506. }
  25507. testActivity(activity, input, output);
  25508. }
  25509. for (i=0; i<2000; i++)
  25510. {
  25511. delete [] input[i];
  25512. delete [] output[i];
  25513. }
  25514. DBGLOG("Finished testing %s sort", type==2?"Heap" : (type==1 ? "Insertion" : "Quick"));
  25515. }
  25516. void testQuickSort()
  25517. {
  25518. testSort(0);
  25519. }
  25520. void testHeapSort()
  25521. {
  25522. testSort(2);
  25523. }
  25524. void testMerge()
  25525. {
  25526. DBGLOG("testMerge");
  25527. init();
  25528. Owned<IPropertyTree> splitterNode = createPTree();
  25529. Owned <IRoxieServerActivityFactory> factory = createRoxieServerMergeActivityFactory(1, 1, *queryFactory, mergeActivityTestFactory, TAKmerge, *splitterNode);
  25530. factory->setInput(0,0,0);
  25531. factory->setInput(1,0,0);
  25532. Owned <IRoxieServerActivity> activity = factory->createActivity(ctx, NULL);
  25533. const char * test[] = { NULL, NULL };
  25534. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  25535. const char * test1122334455[] = { "1", "1", "2", "2", "3", "3", "4", "4", "5", "5", NULL, NULL };
  25536. const char * test11111[] = { "1", "1", "1", "1", "1", NULL, NULL };
  25537. const char * test1111111111[] = { "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", NULL, NULL };
  25538. const char * test11111_12345[] = { "1", "1", "1", "1", "1", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  25539. const char * test1111112345[] = { "1", "1", "1", "1", "1", "1", "2", "3", "4", "5", NULL, NULL };
  25540. 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 };
  25541. testActivity(activity, test, test, test);
  25542. testActivity(activity, test12345, test, test12345);
  25543. testActivity(activity, test, test12345, test12345);
  25544. testActivity(activity, test12345, test12345, test1122334455);
  25545. testActivity(activity, test11111, test, test11111);
  25546. testActivity(activity, test, test11111, test11111);
  25547. testActivity(activity, test11111, test11111, test1111111111);
  25548. testActivity(activity, test11111_12345, test, test1111112345);
  25549. testActivity(activity, test11111_12345, test11111_12345, test11111111111122334455);
  25550. // Should really test WHICH side gets kept...
  25551. // Should test with more than 2 inputs...
  25552. DBGLOG("testMerge done");
  25553. }
  25554. void testMergeDedup()
  25555. {
  25556. DBGLOG("testMergeDedup");
  25557. init();
  25558. MergeActivityTest::isDedup = true;
  25559. Owned<IPropertyTree> splitterNode = createPTree();
  25560. Owned <IRoxieServerActivityFactory> factory = createRoxieServerMergeActivityFactory(1, 1, *queryFactory, mergeActivityTestFactory, TAKmerge, *splitterNode);
  25561. factory->setInput(0,0,0);
  25562. factory->setInput(1,0,0);
  25563. Owned <IRoxieServerActivity> activity = factory->createActivity(ctx, NULL);
  25564. const char * test[] = { NULL, NULL };
  25565. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  25566. const char * test11111[] = { "1", "1", "1", "1", "1", NULL, NULL };
  25567. const char * test11111_12345[] = { "1", "1", "1", "1", "1", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  25568. const char * test1111112345[] = { "1", "1", "1", "1", "1", "1", "2", "3", "4", "5", NULL, NULL };
  25569. testActivity(activity, test11111, test, test11111); // No dedup within a stream
  25570. testActivity(activity, test11111, test11111, test11111); // No dedup within a stream
  25571. testActivity(activity, test, test11111, test11111);
  25572. testActivity(activity, test, test, test);
  25573. testActivity(activity, test12345, test, test12345);
  25574. testActivity(activity, test, test12345, test12345);
  25575. testActivity(activity, test12345, test12345, test12345);
  25576. testActivity(activity, test11111_12345, test, test1111112345);
  25577. testActivity(activity, test11111_12345, test11111_12345, test1111112345);
  25578. // Should really test WHICH side gets kept...
  25579. // Should test with more than 2 inputs...
  25580. DBGLOG("testMergeDedup done");
  25581. }
  25582. void doTestSplitter(unsigned numOutputs)
  25583. {
  25584. DBGLOG("testSplit %d", numOutputs);
  25585. init();
  25586. Owned<IPropertyTree> splitterNode = createPTree();
  25587. Owned <IRoxieServerActivityFactory> factory = createRoxieServerThroughSpillActivityFactory(*queryFactory, splitActivityTestFactory, numOutputs, *splitterNode);
  25588. factory->setInput(0,0,0);
  25589. Owned <IRoxieServerActivity> activity = factory->createActivity(ctx, NULL);
  25590. const char * test[] = { NULL, NULL };
  25591. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  25592. unsigned start = msTick();
  25593. testSplitActivity(factory, test, test, numOutputs, 0);
  25594. testSplitActivity(factory, test12345, test12345, numOutputs, 0);
  25595. testSplitActivity(factory, test12345, test12345, numOutputs, 100);
  25596. unsigned elapsed = msTick() - start;
  25597. DBGLOG("testSplit %d done in %dms", numOutputs, elapsed);
  25598. }
  25599. void testSplitter()
  25600. {
  25601. doTestSplitter(1);
  25602. doTestSplitter(2);
  25603. doTestSplitter(3);
  25604. doTestSplitter(10);
  25605. }
  25606. void testMiscellaneous()
  25607. {
  25608. DBGLOG("sizeof(CriticalSection)=%u", (unsigned) sizeof(CriticalSection));
  25609. DBGLOG("sizeof(SpinLock)=%u", (unsigned) sizeof(SpinLock));
  25610. DBGLOG("sizeof(CJoinGroup)=%u", (unsigned) sizeof(CJoinGroup));
  25611. ASSERT(sizeof(CJoinGroup) <= 120);
  25612. }
  25613. };
  25614. CPPUNIT_TEST_SUITE_REGISTRATION( CcdServerTest );
  25615. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( CcdServerTest, "CcdServerTest" );
  25616. #endif