ccdserver.cpp 988 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236
  1. /*##############################################################################
  2. HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems®.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. ############################################################################## */
  13. #include "jmisc.hpp"
  14. #include "jdebug.hpp"
  15. #include "jptree.hpp"
  16. #include "rtlkey.hpp"
  17. #include "jsort.hpp"
  18. #include "jhtree.hpp"
  19. #include "jqueue.tpp"
  20. #include "jisem.hpp"
  21. #include "thorxmlread.hpp"
  22. #include "thorrparse.ipp"
  23. #include "thorxmlwrite.hpp"
  24. #include "thorsoapcall.hpp"
  25. #include "thorcommon.ipp"
  26. #include "thorsort.hpp"
  27. #include "thorstats.hpp"
  28. #include "jlzw.hpp"
  29. #include "javahash.hpp"
  30. #include "javahash.tpp"
  31. #include "thorstep.ipp"
  32. #include "thorpipe.hpp"
  33. #include "thorfile.hpp"
  34. #include "eclhelper.hpp"
  35. #include "eclrtl_imp.hpp"
  36. #include "rtlfield_imp.hpp"
  37. #include "rtlds_imp.hpp"
  38. #include "rtlread_imp.hpp"
  39. #include <algorithm>
  40. #include "dafdesc.hpp"
  41. #include "dautils.hpp"
  42. #include "ftbase.ipp"
  43. namespace ccdserver_hqlhelper
  44. {
  45. #include "eclhelper_base.hpp"
  46. }
  47. #include "ccd.hpp"
  48. #include "ccdserver.hpp"
  49. #include "ccdcontext.hpp"
  50. #include "ccdactivities.hpp"
  51. #include "ccdquery.hpp"
  52. #include "ccdstate.hpp"
  53. #include "ccdqueue.ipp"
  54. #include "ccdsnmp.hpp"
  55. #include "ccddali.hpp"
  56. #include "jsmartsock.hpp"
  57. #include "dllserver.hpp"
  58. #include "workflow.hpp"
  59. #include "roxiemem.hpp"
  60. #include "roxierowbuff.hpp"
  61. #include "roxiehelper.hpp"
  62. #include "roxielmj.hpp"
  63. #include "roxierow.hpp"
  64. #include "thorplugin.hpp"
  65. #include "keybuild.hpp"
  66. #include "thorstrand.hpp"
  67. #define MAX_HTTP_HEADERSIZE 8000
  68. #define MIN_PAYLOAD_SIZE 800
  69. #pragma warning(disable : 4355)
  70. #define DEFAULT_PARALLEL_LOOP_THREADS 1
  71. #define PROBE
  72. #ifdef _DEBUG
  73. //#define FAKE_EXCEPTIONS
  74. //#define TRACE_JOINGROUPS
  75. //#define TRACE_SPLIT
  76. //#define _CHECK_HEAPSORT
  77. //#undef PARALLEL_EXECUTE
  78. //#define TRACE_SEEK_REQUESTS
  79. #endif
  80. using roxiemem::OwnedRoxieRow;
  81. using roxiemem::OwnedRoxieString;
  82. using roxiemem::OwnedConstRoxieRow;
  83. using roxiemem::IRowManager;
  84. using roxiemem::ReleaseRoxieRows;
  85. // There is a bug in VC6 implemetation of protected which prevents nested classes from accessing owner's data. It can be tricky to work around - hence...
  86. #if _MSC_VER==1200
  87. #define protected public
  88. #endif
  89. #define TRACE_STARTSTOP // This determines if it is available - it is enabled/disabled by a configuration option
  90. #define TRACE_STRANDS
  91. #define MAX_SENSIBLE_STRANDS 1024 // Architecture dependent...
  92. static const SmartStepExtra dummySmartStepExtra(SSEFreadAhead, NULL);
  93. //=================================================================================
  94. class RestartableThread : public CInterface
  95. {
  96. class MyThread : public Thread
  97. {
  98. Linked<RestartableThread> owner;
  99. public:
  100. MyThread(RestartableThread *_owner, const char *name) : Thread(name), owner(_owner)
  101. {
  102. }
  103. virtual int run()
  104. {
  105. owner->started.signal();
  106. return owner->run();
  107. }
  108. };
  109. friend class MyThread;
  110. Semaphore started;
  111. Owned<MyThread> thread;
  112. CriticalSection crit;
  113. StringAttr name;
  114. public:
  115. RestartableThread(const char *_name) : name(_name)
  116. {
  117. }
  118. virtual void start(const char *namePrefix)
  119. {
  120. StringBuffer s(namePrefix);
  121. s.append(name);
  122. {
  123. CriticalBlock b(crit);
  124. assertex(!thread);
  125. thread.setown(new MyThread(this, s));
  126. thread->start();
  127. }
  128. started.wait();
  129. }
  130. virtual void join()
  131. {
  132. {
  133. Owned<Thread> tthread;
  134. {
  135. CriticalBlock b(crit);
  136. tthread.setown(thread.getClear());
  137. }
  138. if (tthread)
  139. tthread->join();
  140. }
  141. }
  142. virtual int run() = 0;
  143. };
  144. //================================================================================
  145. //The following don't link their arguments because that creates a circular reference
  146. //But I wish there was a better way
  147. class IndirectSlaveContext : implements IRoxieSlaveContext, public CInterface
  148. {
  149. public:
  150. IndirectSlaveContext(IRoxieSlaveContext * _ctx) : ctx(_ctx) {}
  151. IMPLEMENT_IINTERFACE
  152. // void set(IRoxieSlaveContext * _ctx) { ctx = _ctx; }
  153. virtual ICodeContext *queryCodeContext()
  154. {
  155. return ctx->queryCodeContext();
  156. }
  157. virtual void checkAbort()
  158. {
  159. ctx->checkAbort();
  160. }
  161. virtual void notifyAbort(IException *E)
  162. {
  163. ctx->notifyAbort(E);
  164. }
  165. virtual IActivityGraph * queryChildGraph(unsigned id)
  166. {
  167. return ctx->queryChildGraph(id);
  168. }
  169. virtual void noteChildGraph(unsigned id, IActivityGraph *childGraph)
  170. {
  171. ctx->noteChildGraph(id, childGraph) ;
  172. }
  173. virtual IRowManager &queryRowManager()
  174. {
  175. return ctx->queryRowManager();
  176. }
  177. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value) const
  178. {
  179. ctx->noteStatistic(kind, value);
  180. }
  181. virtual void mergeStats(const CRuntimeStatisticCollection &from) const
  182. {
  183. ctx->mergeStats(from);
  184. }
  185. virtual const CRuntimeStatisticCollection &queryStats() const
  186. {
  187. return ctx->queryStats();
  188. }
  189. virtual void CTXLOGva(const char *format, va_list args) const __attribute__((format(printf,2,0)))
  190. {
  191. ctx->CTXLOGva(format, args);
  192. }
  193. virtual void CTXLOGa(TracingCategory category, const char *prefix, const char *text) const
  194. {
  195. ctx->CTXLOGa(category, prefix, text);
  196. }
  197. virtual void logOperatorExceptionVA(IException *E, const char *file, unsigned line, const char *format, va_list args) const __attribute__((format(printf,5,0)))
  198. {
  199. ctx->logOperatorExceptionVA(E, file, line, format, args);
  200. }
  201. virtual void CTXLOGaeva(IException *E, const char *file, unsigned line, const char *prefix, const char *format, va_list args) const __attribute__((format(printf,6,0)))
  202. {
  203. ctx->CTXLOGaeva(E, file, line, prefix, format, args);
  204. }
  205. virtual void CTXLOGl(LogItem *log) const
  206. {
  207. ctx->CTXLOGl(log);
  208. }
  209. virtual StringBuffer &getLogPrefix(StringBuffer &ret) const
  210. {
  211. return ctx->getLogPrefix(ret);
  212. }
  213. virtual unsigned queryTraceLevel() const
  214. {
  215. return ctx->queryTraceLevel();
  216. }
  217. virtual bool isIntercepted() const
  218. {
  219. return ctx->isIntercepted();
  220. }
  221. virtual bool isBlind() const
  222. {
  223. return ctx->isBlind();
  224. }
  225. virtual const QueryOptions &queryOptions() const
  226. {
  227. return ctx->queryOptions();
  228. }
  229. virtual void addSlavesReplyLen(unsigned len)
  230. {
  231. ctx->addSlavesReplyLen(len);
  232. }
  233. virtual const char *queryAuthToken()
  234. {
  235. return ctx->queryAuthToken();
  236. }
  237. virtual const IResolvedFile *resolveLFN(const char *filename, bool isOpt)
  238. {
  239. return ctx->resolveLFN(filename, isOpt);
  240. }
  241. virtual IRoxieWriteHandler *createLFN(const char *filename, bool overwrite, bool extend, const StringArray &clusters)
  242. {
  243. return ctx->createLFN(filename, overwrite, extend, clusters);
  244. }
  245. virtual void onFileCallback(const RoxiePacketHeader &header, const char *lfn, bool isOpt, bool isLocal)
  246. {
  247. ctx->onFileCallback(header, lfn, isOpt, isLocal);
  248. }
  249. virtual IActivityGraph *getLibraryGraph(const LibraryCallFactoryExtra &extra, IRoxieServerActivity *parentActivity)
  250. {
  251. return ctx->getLibraryGraph(extra, parentActivity);
  252. }
  253. virtual void noteProcessed(unsigned subgraphId, unsigned activityId, unsigned _idx, unsigned _processed, unsigned _strands) const
  254. {
  255. ctx->noteProcessed(subgraphId, activityId, _idx, _processed, _strands);
  256. }
  257. virtual void mergeActivityStats(const CRuntimeStatisticCollection &fromStats, unsigned subgraphId, unsigned activityId, const ActivityTimeAccumulator &_totalCycles, cycle_t _localCycles) const
  258. {
  259. ctx->mergeActivityStats(fromStats, subgraphId, activityId, _totalCycles, _localCycles);
  260. }
  261. virtual IProbeManager *queryProbeManager() const
  262. {
  263. return ctx->queryProbeManager();
  264. }
  265. virtual IDebuggableContext *queryDebugContext() const
  266. {
  267. return ctx->queryDebugContext();
  268. }
  269. virtual void printResults(IXmlWriter *output, const char *name, unsigned sequence)
  270. {
  271. ctx->printResults(output, name, sequence);
  272. }
  273. virtual void setWUState(WUState state)
  274. {
  275. ctx->setWUState(state);
  276. }
  277. virtual bool checkWuAborted()
  278. {
  279. return ctx->checkWuAborted();
  280. }
  281. virtual IWorkUnit *updateWorkUnit() const
  282. {
  283. return ctx->updateWorkUnit();
  284. }
  285. virtual IConstWorkUnit *queryWorkUnit() const
  286. {
  287. return ctx->queryWorkUnit();
  288. }
  289. virtual IRoxieServerContext *queryServerContext()
  290. {
  291. return ctx->queryServerContext();
  292. }
  293. virtual IWorkUnitRowReader *getWorkunitRowReader(const char *wuid, const char * name, unsigned sequence, IXmlToRowTransformer * xmlTransformer, IEngineRowAllocator *rowAllocator, bool isGrouped)
  294. {
  295. return ctx->getWorkunitRowReader(wuid, name, sequence, xmlTransformer, rowAllocator, isGrouped);
  296. }
  297. virtual IEngineRowAllocator *getRowAllocatorEx(IOutputMetaData * meta, unsigned activityId, roxiemem::RoxieHeapFlags flags) const
  298. {
  299. return ctx->getRowAllocatorEx(meta, activityId, flags);
  300. }
  301. protected:
  302. IRoxieSlaveContext * ctx;
  303. };
  304. //=================================================================================
  305. #define RESULT_FLUSH_THRESHOLD 10000u
  306. #ifdef _DEBUG
  307. #define SOAP_SPLIT_THRESHOLD 100u
  308. #define SOAP_SPLIT_RESERVE 200u
  309. #else
  310. #define SOAP_SPLIT_THRESHOLD 64000u
  311. #define SOAP_SPLIT_RESERVE 65535u
  312. #endif
  313. //=================================================================================
  314. // General activity statistics
  315. static const StatisticsMapping actStatistics(StWhenFirstRow, StTimeElapsed, StTimeLocalExecute, StTimeTotalExecute, StSizeMaxRowSize,
  316. StNumRowsProcessed, StNumSlaves, StNumStarted, StNumStopped, StNumStrands,
  317. StNumScansPerRow, StNumAllocations, StNumAllocationScans, StKindNone);
  318. static const StatisticsMapping joinStatistics(&actStatistics, StNumAtmostTriggered, StKindNone);
  319. static const StatisticsMapping keyedJoinStatistics(&joinStatistics, StNumServerCacheHits, StNumIndexSeeks, StNumIndexScans, StNumIndexWildSeeks,
  320. StNumIndexSkips, StNumIndexNullSkips, StNumIndexMerges, StNumIndexMergeCompares,
  321. StNumPreFiltered, StNumPostFiltered, StNumIndexAccepted, StNumIndexRejected,
  322. StNumIndexRowsRead, StNumDiskRowsRead, StNumDiskSeeks, StNumDiskAccepted,
  323. StNumBlobCacheHits, StNumLeafCacheHits, StNumNodeCacheHits,
  324. StNumBlobCacheAdds, StNumLeafCacheAdds, StNumNodeCacheAdds,
  325. StNumDiskRejected, StKindNone);
  326. static const StatisticsMapping indexStatistics(&actStatistics, StNumServerCacheHits, StNumIndexSeeks, StNumIndexScans, StNumIndexWildSeeks,
  327. StNumIndexSkips, StNumIndexNullSkips, StNumIndexMerges, StNumIndexMergeCompares,
  328. StNumPreFiltered, StNumPostFiltered, StNumIndexAccepted, StNumIndexRejected,
  329. StNumBlobCacheHits, StNumLeafCacheHits, StNumNodeCacheHits,
  330. StNumBlobCacheAdds, StNumLeafCacheAdds, StNumNodeCacheAdds,
  331. StNumIndexRowsRead, StKindNone);
  332. static const StatisticsMapping diskStatistics(&actStatistics, StNumServerCacheHits, StNumDiskRowsRead, StNumDiskSeeks, StNumDiskAccepted,
  333. StNumDiskRejected, StKindNone);
  334. static const StatisticsMapping soapStatistics(&actStatistics, StTimeSoapcall, StKindNone);
  335. static const StatisticsMapping groupStatistics(&actStatistics, StNumGroups, StNumGroupMax, StKindNone);
  336. static const StatisticsMapping sortStatistics(&actStatistics, StTimeSortElapsed, StKindNone);
  337. //=================================================================================
  338. const static unsigned minus1U = (0U-1U);
  339. class CRoxieServerActivityFactoryBase : public CActivityFactory, implements IRoxieServerActivityFactory
  340. {
  341. protected:
  342. IntArray dependencies; // things I am dependent on
  343. IntArray dependencyIndexes; // things I am dependent on
  344. IntArray dependencyControlIds; // things I am dependent on
  345. StringArray dependencyEdgeIds; // How to describe them to the debugger
  346. unsigned dependentCount; // things dependent on me
  347. unsigned optParallel = 0; // -1=enable,0=not specified,1=single-threaded,n=<num threads>
  348. bool optStableInput = true; // is the input forced to ordered?
  349. bool optUnstableInput = false; // is the input forced to unordered?
  350. bool optUnordered = false; // is the output specified as unordered?
  351. unsigned heapFlags;
  352. mutable CriticalSection statsCrit;
  353. mutable __int64 processed;
  354. mutable __int64 started;
  355. mutable __int64 totalCycles;
  356. mutable __int64 localCycles;
  357. public:
  358. IMPLEMENT_IINTERFACE;
  359. CRoxieServerActivityFactoryBase(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  360. : CActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  361. {
  362. processed = 0;
  363. started = 0;
  364. totalCycles = 0;
  365. localCycles = 0;
  366. dependentCount = 0;
  367. optParallel = _graphNode.getPropInt("att[@name='parallel']/@value", 0);
  368. optUnordered = !_graphNode.getPropBool("att[@name='ordered']/@value", true);
  369. heapFlags = _graphNode.getPropInt("hint[@name='heapflags']/@value", _queryFactory.queryOptions().heapFlags);
  370. }
  371. ~CRoxieServerActivityFactoryBase()
  372. {
  373. }
  374. StringBuffer &toString(StringBuffer &ret) const
  375. {
  376. return ret.appendf("%p", this);
  377. }
  378. virtual void addDependency(unsigned _source, ThorActivityKind _kind, unsigned _sourceIdx, int controlId, const char *edgeId)
  379. {
  380. dependencies.append(_source);
  381. dependencyIndexes.append(_sourceIdx);
  382. dependencyControlIds.append(controlId);
  383. dependencyEdgeIds.append(edgeId);
  384. }
  385. virtual bool isInputOrdered(bool consumerOrdered, unsigned idx) const
  386. {
  387. if (optStableInput)
  388. return true;
  389. if (optUnstableInput)
  390. return false;
  391. if (optUnordered)
  392. return false;
  393. return consumerOrdered;
  394. }
  395. virtual void noteDependent(unsigned target)
  396. {
  397. dependentCount++;
  398. }
  399. virtual IntArray &queryDependencies() { return dependencies; }
  400. virtual IntArray &queryDependencyIndexes() { return dependencyIndexes; }
  401. virtual IntArray &queryDependencyControlIds() { return dependencyControlIds; }
  402. virtual StringArray &queryDependencyEdgeIds() { return dependencyEdgeIds; }
  403. virtual unsigned queryId() const { return id; }
  404. virtual unsigned querySubgraphId() const { return subgraphId; }
  405. virtual ThorActivityKind getKind() const { return kind; }
  406. virtual IOutputMetaData * queryOutputMeta() const
  407. {
  408. return meta;
  409. }
  410. virtual bool isSink() const
  411. {
  412. return false;
  413. }
  414. virtual bool isFunction() const
  415. {
  416. return false;
  417. }
  418. virtual bool isGraphInvariant() const
  419. {
  420. return false;
  421. }
  422. virtual IHThorArg &getHelper() const
  423. {
  424. return *helperFactory();
  425. }
  426. virtual IRoxieServerActivity *createFunction(IHThorArg &arg, IProbeManager *_probeManager) const
  427. {
  428. arg.Release();
  429. throwUnexpected();
  430. }
  431. virtual void mergeStats(const CRuntimeStatisticCollection &from) const
  432. {
  433. CActivityFactory::mergeStats(from);
  434. }
  435. virtual void noteProcessed(unsigned _idx, unsigned _processed) const
  436. {
  437. dbgassertex(!_idx);
  438. if (_processed)
  439. {
  440. CriticalBlock b(statsCrit);
  441. processed += _processed;
  442. }
  443. }
  444. virtual void mergeActivityStats(const CRuntimeStatisticCollection &fromStats, const ActivityTimeAccumulator &_totalCycles, cycle_t _localCycles) const
  445. {
  446. if (_totalCycles.totalCycles || _localCycles)
  447. {
  448. CriticalBlock b(statsCrit);
  449. dbgassertex(_totalCycles.totalCycles >= _localCycles);
  450. totalCycles += _totalCycles.totalCycles;
  451. localCycles += _localCycles;
  452. }
  453. CActivityFactory::mergeStats(fromStats);
  454. }
  455. virtual void noteStarted() const
  456. {
  457. CriticalBlock b(statsCrit);
  458. started ++;
  459. }
  460. virtual void noteStarted(unsigned idx) const
  461. {
  462. throwUnexpected(); // should be implemented/required by multiOutput cases only
  463. }
  464. virtual void getEdgeProgressInfo(unsigned output, IPropertyTree &edge) const
  465. {
  466. CriticalBlock b(statsCrit);
  467. if (output == 0)
  468. {
  469. putStatsValue(&edge, "count", "sum", processed);
  470. if (started)
  471. putStatsValue(&edge, "started", "sum", started);
  472. }
  473. else
  474. ERRLOG("unexpected call to getEdgeProcessInfo for output %d in activity %d", output, queryId());
  475. }
  476. virtual void getNodeProgressInfo(IPropertyTree &node) const
  477. {
  478. CActivityFactory::getNodeProgressInfo(node);
  479. CriticalBlock b(statsCrit);
  480. if (started)
  481. putStatsValue(&node, "_roxieStarted", "sum", started);
  482. if (totalCycles)
  483. putStatsValue(&node, "totalTime", "sum", (unsigned) (cycle_to_nanosec(totalCycles)/1000));
  484. if (localCycles)
  485. putStatsValue(&node, "localTime", "sum", (unsigned) (cycle_to_nanosec(localCycles)/1000));
  486. }
  487. virtual void resetNodeProgressInfo()
  488. {
  489. CActivityFactory::resetNodeProgressInfo();
  490. CriticalBlock b(statsCrit);
  491. processed = 0;
  492. started = 0;
  493. totalCycles = 0;
  494. localCycles = 0;
  495. }
  496. virtual void getActivityMetrics(StringBuffer &reply) const
  497. {
  498. CActivityFactory::getActivityMetrics(reply);
  499. CriticalBlock b(statsCrit);
  500. putStatsValue(reply, "_roxieStarted", "sum", started);
  501. putStatsValue(reply, "totalTime", "sum", (unsigned) (cycle_to_nanosec(totalCycles)/1000));
  502. putStatsValue(reply, "localTime", "sum", (unsigned) (cycle_to_nanosec(localCycles)/1000));
  503. }
  504. virtual unsigned __int64 queryLocalCycles() const
  505. {
  506. return localCycles;
  507. }
  508. virtual IQueryFactory &queryQueryFactory() const
  509. {
  510. return CActivityFactory::queryQueryFactory();
  511. }
  512. virtual ActivityArray *queryChildQuery(unsigned idx, unsigned &id)
  513. {
  514. return CActivityFactory::queryChildQuery(idx, id);
  515. }
  516. virtual void addChildQuery(unsigned id, ActivityArray *childQuery)
  517. {
  518. CActivityFactory::addChildQuery(id, childQuery);
  519. }
  520. virtual void onCreateChildQueries(IRoxieSlaveContext *ctx, IHThorArg *colocalArg, IArrayOf<IActivityGraph> &childGraphs, IRoxieServerActivity *parentActivity, IProbeManager *_probeManager, const IRoxieContextLogger &_logctx, unsigned numParallel) const
  521. {
  522. ForEachItemIn(idx, childQueries)
  523. {
  524. childGraphs.append(*createActivityGraph(ctx, NULL, childQueryIndexes.item(idx), childQueries.item(idx), parentActivity, _probeManager, _logctx, numParallel));
  525. ctx->noteChildGraph(childQueryIndexes.item(idx), &childGraphs.item(idx));
  526. childGraphs.item(idx).onCreate(colocalArg);
  527. }
  528. }
  529. IActivityGraph * createChildGraph(IRoxieSlaveContext * ctx, IHThorArg *colocalArg, unsigned childId, IRoxieServerActivity *parentActivity, IProbeManager * _probeManager, const IRoxieContextLogger &_logctx) const
  530. {
  531. unsigned match = childQueryIndexes.find(childId);
  532. assertex(match != NotFound);
  533. Owned<IActivityGraph> graph = createActivityGraph(ctx, NULL, childQueryIndexes.item(match), childQueries.item(match), parentActivity, _probeManager, _logctx, 1);
  534. graph->onCreate(colocalArg);
  535. return graph.getClear();
  536. }
  537. virtual IRoxieServerSideCache *queryServerSideCache() const
  538. {
  539. return NULL; // Activities that wish to support server-side caching will need to do better....
  540. }
  541. virtual bool getEnableFieldTranslation() const
  542. {
  543. throwUnexpected(); // only implemented by index-related subclasses
  544. }
  545. virtual IDefRecordMeta *queryActivityMeta() const
  546. {
  547. throwUnexpected(); // only implemented by index-related subclasses
  548. }
  549. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  550. {
  551. // Most activities have nothing to say...
  552. }
  553. virtual const StatisticsMapping &queryStatsMapping() const
  554. {
  555. return actStatistics; // Overridden by anyone that needs more
  556. }
  557. virtual roxiemem::RoxieHeapFlags getHeapFlags() const
  558. {
  559. return (roxiemem::RoxieHeapFlags)heapFlags;
  560. }
  561. };
  562. class CRoxieServerMultiInputInfo
  563. {
  564. private:
  565. UnsignedArray inputs;
  566. UnsignedArray inputIndexes;
  567. public:
  568. void set(unsigned idx, unsigned source, unsigned sourceidx)
  569. {
  570. if (idx==inputs.length())
  571. {
  572. inputs.append(source);
  573. inputIndexes.append(sourceidx);
  574. }
  575. else
  576. {
  577. while (!inputs.isItem(idx))
  578. {
  579. inputs.append(0);
  580. inputIndexes.append(0);
  581. }
  582. inputs.replace(source, idx);
  583. inputIndexes.replace(sourceidx, idx);
  584. }
  585. }
  586. unsigned get(unsigned idx, unsigned &sourceidx) const
  587. {
  588. if (inputs.isItem(idx))
  589. {
  590. sourceidx = inputIndexes.item(idx);
  591. return inputs.item(idx);
  592. }
  593. else
  594. return (unsigned) -1;
  595. }
  596. inline unsigned ordinality() const { return inputs.ordinality(); }
  597. };
  598. class CRoxieServerMultiInputFactory : public CRoxieServerActivityFactoryBase
  599. {
  600. private:
  601. CRoxieServerMultiInputInfo inputs;
  602. public:
  603. CRoxieServerMultiInputFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  604. : CRoxieServerActivityFactoryBase(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  605. {
  606. }
  607. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  608. {
  609. inputs.set(idx, source, sourceidx);
  610. }
  611. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  612. {
  613. return inputs.get(idx, sourceidx);
  614. }
  615. virtual unsigned numInputs() const { return inputs.ordinality(); }
  616. };
  617. class DECL_EXCEPTION CWrappedException : implements IException, public CInterface
  618. {
  619. Owned<IException> wrapped;
  620. ThorActivityKind kind;
  621. unsigned queryId;
  622. public:
  623. IMPLEMENT_IINTERFACE;
  624. CWrappedException(IException *_wrapped, ThorActivityKind _kind, unsigned _queryId)
  625. : wrapped(_wrapped), kind(_kind), queryId(_queryId)
  626. {
  627. }
  628. virtual int errorCode() const { return wrapped->errorCode(); }
  629. virtual StringBuffer & errorMessage(StringBuffer &msg) const { return wrapped->errorMessage(msg).appendf(" (in %s %d)", getActivityText(kind), queryId); }
  630. virtual MessageAudience errorAudience() const { return wrapped->errorAudience(); }
  631. };
  632. class CRoxieServerActivityFactory : public CRoxieServerActivityFactoryBase
  633. {
  634. protected:
  635. unsigned input;
  636. unsigned inputidx;
  637. public:
  638. CRoxieServerActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  639. : CRoxieServerActivityFactoryBase(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  640. {
  641. input = (unsigned) -1;
  642. inputidx = 0;
  643. }
  644. inline void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  645. {
  646. if (idx != 0)
  647. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: id = %d : setInput() parameter out of bounds idx = %d at %s(%d)", id, idx, sanitizeSourceFile(__FILE__), __LINE__);
  648. if (input != -1)
  649. 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__);
  650. input = source;
  651. inputidx = sourceidx;
  652. }
  653. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  654. {
  655. if (!idx)
  656. {
  657. sourceidx = inputidx;
  658. return input;
  659. }
  660. return (unsigned) -1;
  661. }
  662. virtual unsigned numInputs() const { return (input == (unsigned)-1) ? 0 : 1; }
  663. };
  664. class CRoxieServerMultiOutputFactory : public CRoxieServerActivityFactory
  665. {
  666. protected:
  667. unsigned numOutputs;
  668. unsigned __int64 *processedArray;
  669. bool *startedArray;
  670. CRoxieServerMultiOutputFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  671. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  672. {
  673. numOutputs = 0;
  674. processedArray = NULL;
  675. startedArray = NULL;
  676. }
  677. ~CRoxieServerMultiOutputFactory()
  678. {
  679. delete [] processedArray;
  680. delete [] startedArray;
  681. }
  682. void setNumOutputs(unsigned num)
  683. {
  684. numOutputs = num;
  685. if (!num)
  686. num = 1; // Even sink activities like to track how many records they process
  687. processedArray = new unsigned __int64[num];
  688. startedArray = new bool[num];
  689. for (unsigned i = 0; i < num; i++)
  690. {
  691. processedArray[i] = 0;
  692. startedArray[i] = 0;
  693. }
  694. }
  695. virtual void getEdgeProgressInfo(unsigned idx, IPropertyTree &edge) const
  696. {
  697. assertex(numOutputs ? idx < numOutputs : idx==0);
  698. CriticalBlock b(statsCrit);
  699. putStatsValue(&edge, "count", "sum", processedArray[idx]);
  700. putStatsValue(&edge, "started", "sum", startedArray[idx]);
  701. }
  702. virtual void resetNodeProgressInfo()
  703. {
  704. CRoxieServerActivityFactory::resetNodeProgressInfo();
  705. CriticalBlock b(statsCrit);
  706. for (unsigned i = 0; i < numOutputs; i++)
  707. {
  708. processedArray[i] = 0;
  709. startedArray[i] = 0;
  710. }
  711. }
  712. virtual void noteProcessed(unsigned idx, unsigned _processed) const
  713. {
  714. assertex(numOutputs ? idx < numOutputs : idx==0);
  715. CriticalBlock b(statsCrit);
  716. processedArray[idx] += _processed;
  717. }
  718. virtual void noteStarted(unsigned idx) const
  719. {
  720. assertex(numOutputs ? idx < numOutputs : idx==0);
  721. CriticalBlock b(statsCrit);
  722. startedArray[idx] = true;
  723. }
  724. };
  725. class CRoxieServerInternalSinkFactory : public CRoxieServerActivityFactory
  726. {
  727. protected:
  728. bool isInternal;
  729. bool isRoot;
  730. unsigned usageCount;
  731. public:
  732. CRoxieServerInternalSinkFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  733. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  734. {
  735. usageCount = _usageCount;
  736. isRoot = _isRoot;
  737. isInternal = false; // filled in by derived class constructor
  738. }
  739. virtual bool isSink() const
  740. {
  741. //only a sink if a root activity
  742. 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?
  743. }
  744. virtual void getEdgeProgressInfo(unsigned idx, IPropertyTree &edge) const
  745. {
  746. // 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
  747. // Just leave it blank is safest.
  748. }
  749. };
  750. typedef enum { STATEreset, STATEstarted, STATEstopped, STATEstarting } activityState;
  751. const char *queryStateText(activityState state)
  752. {
  753. switch (state)
  754. {
  755. case STATEreset: return "reset";
  756. case STATEstarted: return "started";
  757. case STATEstopped: return "stopped";
  758. case STATEstarting: return "starting";
  759. default: return "unknown";
  760. }
  761. }
  762. typedef ICopyArrayOf<IRoxieServerActivity> IRoxieServerActivityCopyArray;
  763. class CParallelActivityExecutor : public CAsyncFor
  764. {
  765. public:
  766. unsigned parentExtractSize;
  767. const byte * parentExtract;
  768. CParallelActivityExecutor(IRoxieServerActivityCopyArray & _activities, unsigned _parentExtractSize, const byte * _parentExtract) :
  769. activities(_activities), parentExtractSize(_parentExtractSize), parentExtract(_parentExtract) { }
  770. void Do(unsigned i)
  771. {
  772. activities.item(i).execute(parentExtractSize, parentExtract);
  773. }
  774. private:
  775. IRoxieServerActivityCopyArray & activities;
  776. };
  777. extern IEngineRowStream * ensureSingleStream(IRoxieSlaveContext *ctx, PointerArrayOf<IEngineRowStream> & instreams, Owned<IStrandJunction> &junction)
  778. {
  779. if (instreams.length() != 1)
  780. {
  781. assertex(instreams.length());
  782. if (!junction)
  783. junction.setown(createStrandJunction(ctx->queryRowManager(), instreams.length(), 1, ctx->queryOptions().strandBlockSize, false));
  784. ForEachItemIn(stream, instreams)
  785. {
  786. junction->setInput(stream, instreams.item(stream));
  787. }
  788. return junction->queryOutput(0);
  789. }
  790. else
  791. return instreams.item(0);
  792. }
  793. extern IEngineRowStream *connectSingleStream(IRoxieSlaveContext *ctx, IFinalRoxieInput *input, unsigned idx, Owned<IStrandJunction> &junction, bool consumerOrdered)
  794. {
  795. if (input)
  796. {
  797. PointerArrayOf<IEngineRowStream> instreams;
  798. junction.setown(input->getOutputStreams(ctx, idx, instreams, NULL, consumerOrdered, nullptr));
  799. return ensureSingleStream(ctx, instreams, junction);
  800. }
  801. else
  802. return NULL;
  803. }
  804. extern IEngineRowStream *connectSingleStream(IRoxieSlaveContext *ctx, IFinalRoxieInput *input, unsigned idx, bool consumerOrdered)
  805. {
  806. Owned<IStrandJunction> junction;
  807. IEngineRowStream * result = connectSingleStream(ctx, input, idx, junction, consumerOrdered);
  808. assertex(!junction);
  809. return result;
  810. }
  811. class CRoxieServerActivity : implements CInterfaceOf<IRoxieServerActivity>, implements IFinalRoxieInput, implements IEngineRowStream, implements IRoxieContextLogger
  812. {
  813. friend class StrandProcessor;
  814. protected:
  815. IFinalRoxieInput *input;
  816. unsigned sourceIdx;
  817. IEngineRowStream *inputStream;
  818. Owned<IStrandJunction> junction;
  819. IHThorArg &basehelper;
  820. IRoxieSlaveContext *ctx;
  821. class InterceptRegisterTimer : public IndirectCodeContext
  822. {
  823. public:
  824. InterceptRegisterTimer(CRoxieServerActivity &_activity) : activity(_activity) {}
  825. virtual ISectionTimer *registerTimer(unsigned activityId, const char * name)
  826. {
  827. if (activityId == activity.queryId())
  828. return activity.registerTimer(activityId, name);
  829. else
  830. return ctx->registerTimer(activityId, name);
  831. }
  832. private:
  833. CRoxieServerActivity &activity;
  834. } interceptedCtx;
  835. const IRoxieServerActivityFactory *factory;
  836. IRoxieServerActivityCopyArray dependencies;
  837. IntArray dependencyIndexes;
  838. IntArray dependencyControlIds;
  839. IArrayOf<IActivityGraph> childGraphs;
  840. CachedOutputMetaData meta;
  841. IHThorArg *colocalParent;
  842. IEngineRowAllocator *rowAllocator;
  843. CriticalSection statecrit;
  844. CriticalSection statscrit;
  845. mutable CRuntimeStatisticCollection stats;
  846. MapStringToMyClass<ThorSectionTimer> functionTimers;
  847. unsigned processed;
  848. ActivityTimeAccumulator totalCycles;
  849. cycle_t localCycles;
  850. unsigned activityId;
  851. activityState state;
  852. bool createPending;
  853. bool debugging;
  854. bool timeActivities;
  855. bool aborted;
  856. bool connected = false;
  857. IProbeManager *probeManager = NULL;
  858. public:
  859. IMPLEMENT_IINTERFACE_USING(CInterfaceOf<IRoxieServerActivity>)
  860. CRoxieServerActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  861. : ctx(_ctx),
  862. interceptedCtx(*this),
  863. factory(_factory),
  864. basehelper(_factory->getHelper()),
  865. activityId(_factory->queryId()),
  866. stats(_factory->queryStatsMapping()),
  867. probeManager(_probeManager)
  868. {
  869. input = NULL;
  870. sourceIdx = 0;
  871. inputStream = NULL;
  872. meta.set(basehelper.queryOutputMeta());
  873. processed = 0;
  874. localCycles = 0;
  875. state=STATEreset;
  876. rowAllocator = NULL;
  877. debugging = _probeManager != NULL; // Don't want to collect timing stats from debug sessions
  878. colocalParent = NULL;
  879. createPending = true;
  880. timeActivities = defaultTimeActivities;
  881. aborted = false;
  882. }
  883. CRoxieServerActivity(IRoxieSlaveContext *_ctx, IHThorArg & _helper)
  884. : ctx(_ctx),
  885. interceptedCtx(*this),
  886. factory(NULL), basehelper(_helper), stats(allStatistics)
  887. {
  888. activityId = 0;
  889. input = NULL;
  890. sourceIdx = 0;
  891. inputStream = NULL;
  892. ctx = NULL;
  893. meta.set(basehelper.queryOutputMeta());
  894. processed = 0;
  895. localCycles = 0;
  896. state=STATEreset;
  897. rowAllocator = NULL;
  898. debugging = false;
  899. colocalParent = NULL;
  900. createPending = true;
  901. timeActivities = defaultTimeActivities;
  902. aborted = false;
  903. }
  904. ~CRoxieServerActivity()
  905. {
  906. if (traceStartStop)
  907. {
  908. // There was an old comment here stating // Note- CTXLOG may not be safe
  909. // There were problems in the destruction order of graphs that might mean an IndirectSlaveContext
  910. // was released while activities still referenced it.
  911. // However these should now all be fixed
  912. DBGLOG("%p destroy %d state=%s", this, activityId, queryStateText(state));
  913. if (watchActivityId && watchActivityId==activityId)
  914. {
  915. DBGLOG("WATCH: %p destroy %d state=%s", this, activityId, queryStateText(state));
  916. }
  917. }
  918. if (state!=STATEreset)
  919. {
  920. DBGLOG("STATE: Activity %d destroyed but not reset", activityId);
  921. state = STATEreset; // bit pointless but there you go...
  922. }
  923. if (factory && !debugging)
  924. {
  925. if (processed)
  926. factory->noteProcessed(0, processed);
  927. factory->mergeActivityStats(stats, totalCycles, localCycles);
  928. }
  929. if (ctx && factory)
  930. {
  931. if (processed)
  932. ctx->noteProcessed(factory->querySubgraphId(), activityId, 0, processed, 0);
  933. ctx->mergeActivityStats(stats, factory->querySubgraphId(), activityId, totalCycles, localCycles);
  934. }
  935. basehelper.Release();
  936. ::Release(rowAllocator);
  937. }
  938. virtual const IRoxieContextLogger &queryLogCtx()const
  939. {
  940. return *this;
  941. }
  942. inline const StatisticsMapping & queryStatsMapping() const
  943. {
  944. return factory ? factory->queryStatsMapping() : actStatistics;
  945. }
  946. virtual void mergeStats(MemoryBuffer &buf)
  947. {
  948. stats.deserializeMerge(buf);
  949. }
  950. virtual ISectionTimer *registerTimer(unsigned _activityId, const char * name)
  951. {
  952. CriticalBlock b(statscrit); // reuse statscrit to protect functionTimers - it will not be held concurrently
  953. ISectionTimer *timer = functionTimers.getValue(name);
  954. if (!timer)
  955. {
  956. timer = ThorSectionTimer::createTimer(stats, name);
  957. functionTimers.setValue(name, timer);
  958. timer->Release(); // Value returned is not linked
  959. }
  960. return timer;
  961. }
  962. void mergeStrandStats(unsigned strandProcessed, const ActivityTimeAccumulator & strandCycles, const CRuntimeStatisticCollection & strandStats)
  963. {
  964. CriticalBlock cb(statscrit);
  965. processed += strandProcessed;
  966. totalCycles.merge(strandCycles);
  967. stats.merge(strandStats);
  968. }
  969. inline void ensureRowAllocator()
  970. {
  971. if (!rowAllocator)
  972. rowAllocator = createRowAllocator(meta.queryOriginal());
  973. }
  974. virtual IEngineRowAllocator * createRowAllocator(IOutputMetaData * metadata)
  975. {
  976. return ctx->getRowAllocatorEx(metadata, activityId, factory->getHeapFlags());
  977. }
  978. virtual IEngineRowAllocator * createRowAllocatorEx(IOutputMetaData * metadata, roxiemem::RoxieHeapFlags extraFlags)
  979. {
  980. return ctx->getRowAllocatorEx(metadata, activityId, (roxiemem::RoxieHeapFlags)(factory->getHeapFlags()|extraFlags));
  981. }
  982. inline ICodeContext *queryCodeContext()
  983. {
  984. return ctx->queryCodeContext();
  985. }
  986. // MORE - most of this is copied from ccd.hpp - can't we refactor?
  987. virtual void CTXLOGa(TracingCategory category, const char *prefix, const char *text) const
  988. {
  989. if (ctx)
  990. ctx->CTXLOGa(category, prefix, text);
  991. else
  992. DBGLOG("[%s] %s", prefix, text);
  993. }
  994. 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)))
  995. {
  996. if (ctx)
  997. ctx->CTXLOGaeva(E, file, line, prefix, format, args);
  998. else
  999. {
  1000. StringBuffer ss;
  1001. ss.appendf("[%s] ERROR", prefix);
  1002. if (E)
  1003. ss.append(": ").append(E->errorCode());
  1004. if (file)
  1005. ss.appendf(": %s(%d) ", file, line);
  1006. if (E)
  1007. E->errorMessage(ss.append(": "));
  1008. if (format)
  1009. {
  1010. ss.append(": ").valist_appendf(format, args);
  1011. }
  1012. LOG(MCoperatorProgress, unknownJob, "%s", ss.str());
  1013. }
  1014. }
  1015. virtual void CTXLOGl(LogItem *log) const
  1016. {
  1017. if (ctx)
  1018. ctx->CTXLOGl(log);
  1019. else
  1020. {
  1021. assert(ctx);
  1022. log->Release(); // Should never happen
  1023. }
  1024. }
  1025. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value) const
  1026. {
  1027. stats.addStatistic(kind, value);
  1028. }
  1029. virtual void mergeStats(const CRuntimeStatisticCollection &from) const
  1030. {
  1031. stats.merge(from);
  1032. }
  1033. virtual const CRuntimeStatisticCollection &queryStats() const
  1034. {
  1035. return stats;
  1036. }
  1037. virtual StringBuffer &getLogPrefix(StringBuffer &ret) const
  1038. {
  1039. if (ctx)
  1040. ctx->getLogPrefix(ret);
  1041. return ret.append('@').append(activityId);
  1042. }
  1043. virtual bool isIntercepted() const
  1044. {
  1045. return ctx ? ctx->isIntercepted() : false;
  1046. }
  1047. virtual bool isBlind() const
  1048. {
  1049. return ctx ? ctx->isBlind() : blindLogging;
  1050. }
  1051. virtual unsigned queryTraceLevel() const
  1052. {
  1053. if (ctx)
  1054. return ctx->queryTraceLevel();
  1055. else
  1056. return traceLevel;
  1057. }
  1058. virtual bool isPassThrough()
  1059. {
  1060. return false;
  1061. }
  1062. virtual const IResolvedFile *resolveLFN(const char *filename, bool isOpt)
  1063. {
  1064. return ctx->resolveLFN(filename, isOpt);
  1065. }
  1066. virtual const IResolvedFile *queryVarFileInfo() const
  1067. {
  1068. throwUnexpected(); // should be implemented in more derived class by anyone that has a remote adaptor
  1069. return NULL;
  1070. }
  1071. virtual void serializeSkipInfo(MemoryBuffer &out, unsigned seekLen, const void *rawSeek, unsigned numFields, const void * seek, const SmartStepExtra &stepExtra) const
  1072. {
  1073. throwUnexpected(); // should be implemented in more derived class wherever needed
  1074. }
  1075. virtual IRoxieSlaveContext *queryContext()
  1076. {
  1077. return ctx;
  1078. }
  1079. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { assertex(whichInput==0); return this; }
  1080. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { assertex(idx==0); return junction; }
  1081. virtual IRoxieServerActivity *queryActivity() { return this; }
  1082. virtual IIndexReadActivityInfo *queryIndexReadActivity() { return NULL; }
  1083. virtual bool needsAllocator() const { return false; }
  1084. void _onCreate(IHThorArg *_colocalParent, unsigned _numParallel)
  1085. {
  1086. colocalParent = _colocalParent;
  1087. createPending = true;
  1088. if (needsAllocator())
  1089. ensureRowAllocator();
  1090. processed = 0;
  1091. if (factory)
  1092. factory->onCreateChildQueries(ctx, &basehelper, childGraphs, this, probeManager, *this, _numParallel);
  1093. if (ctx)
  1094. timeActivities = ctx->queryOptions().timeActivities;
  1095. }
  1096. virtual void onCreate(IHThorArg *_colocalParent)
  1097. {
  1098. _onCreate(_colocalParent, 1);
  1099. }
  1100. virtual void serializeCreateStartContext(MemoryBuffer &out)
  1101. {
  1102. //This should only be called after onStart has been called on the helper
  1103. assertex(!createPending);
  1104. assertex(state==STATEstarted);
  1105. unsigned startlen = out.length();
  1106. basehelper.serializeCreateContext(out);
  1107. basehelper.serializeStartContext(out);
  1108. if (queryTraceLevel() > 10)
  1109. CTXLOG("serializeCreateStartContext for %d added %d bytes", activityId, out.length()-startlen);
  1110. }
  1111. virtual void serializeExtra(MemoryBuffer &out) {}
  1112. inline void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  1113. {
  1114. CriticalBlock cb(statecrit);
  1115. if (state != STATEreset && state != STATEstarting)
  1116. {
  1117. CTXLOG("STATE: Expected state to be reset, but was %s, in activity %d", queryStateText(state), activityId);
  1118. }
  1119. state=STATEstarted;
  1120. #ifdef TRACE_STARTSTOP
  1121. if (traceStartStop)
  1122. {
  1123. CTXLOG("start %p %d", this, activityId);
  1124. if (watchActivityId && watchActivityId==activityId)
  1125. {
  1126. CTXLOG("WATCH: start %p %d", this, activityId);
  1127. }
  1128. }
  1129. #endif
  1130. executeDependencies(parentExtractSize, parentExtract, 0);
  1131. if (input)
  1132. input->start(parentExtractSize, parentExtract, paused);
  1133. ensureCreated();
  1134. basehelper.onStart(parentExtract, NULL);
  1135. if (factory)
  1136. factory->noteStarted();
  1137. startJunction(junction);
  1138. }
  1139. void executeDependencies(unsigned parentExtractSize, const byte *parentExtract, unsigned controlId)
  1140. {
  1141. //MORE: Create a filtered list and then use asyncfor
  1142. ForEachItemIn(idx, dependencies)
  1143. {
  1144. if (dependencyControlIds.item(idx) == controlId)
  1145. dependencies.item(idx).execute(parentExtractSize, parentExtract);
  1146. }
  1147. }
  1148. void stopDependencies(unsigned parentExtractSize, const byte *parentExtract, unsigned controlId)
  1149. {
  1150. ForEachItemIn(idx, dependencies)
  1151. {
  1152. if (dependencyControlIds.item(idx) == controlId)
  1153. dependencies.item(idx).stop();
  1154. }
  1155. }
  1156. virtual unsigned __int64 queryTotalCycles() const
  1157. {
  1158. return totalCycles.totalCycles;
  1159. }
  1160. virtual unsigned __int64 queryLocalCycles() const
  1161. {
  1162. __int64 ret = totalCycles.totalCycles;
  1163. if (input) ret -= input->queryTotalCycles();
  1164. if (ret < 0)
  1165. ret = 0;
  1166. return ret;
  1167. }
  1168. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  1169. {
  1170. if (idx==0)
  1171. return input;
  1172. else
  1173. return NULL;
  1174. }
  1175. inline void ensureCreated()
  1176. {
  1177. if (createPending)
  1178. {
  1179. createPending = false;
  1180. interceptedCtx.set(ctx->queryCodeContext());
  1181. basehelper.onCreate(&interceptedCtx, colocalParent, NULL);
  1182. }
  1183. }
  1184. virtual void stop()
  1185. {
  1186. // NOTE - don't be tempted to skip the stop for activities that are reset - splitters need to see the stops
  1187. if (state != STATEstopped)
  1188. {
  1189. CriticalBlock cb(statecrit);
  1190. if (state != STATEstopped)
  1191. {
  1192. #ifdef TRACE_STARTSTOP
  1193. if (traceStartStop)
  1194. {
  1195. CTXLOG("stop %p %d (state currently %s)", this, activityId, queryStateText(state));
  1196. if (watchActivityId && watchActivityId==activityId)
  1197. {
  1198. CTXLOG("WATCH: stop %p %d", this, activityId);
  1199. }
  1200. }
  1201. #endif
  1202. state=STATEstopped;
  1203. // NOTE - this is needed to ensure that dependencies which were not used are properly stopped
  1204. ForEachItemIn(idx, dependencies)
  1205. {
  1206. if (dependencyControlIds.item(idx) == 0)
  1207. dependencies.item(idx).stopSink(dependencyIndexes.item(idx));
  1208. }
  1209. if (inputStream)
  1210. inputStream->stop();
  1211. if (rowAllocator)
  1212. {
  1213. stats.reset(heapStatistics);
  1214. rowAllocator->gatherStats(stats);
  1215. }
  1216. }
  1217. }
  1218. }
  1219. virtual void abort()
  1220. {
  1221. aborted = true;
  1222. // MORE - should abort dependencies here?
  1223. stop();
  1224. }
  1225. inline void reset()
  1226. {
  1227. if (state != STATEreset)
  1228. {
  1229. CriticalBlock cb(statecrit);
  1230. if (state != STATEreset)
  1231. {
  1232. if (state==STATEstarted || state==STATEstarting)
  1233. {
  1234. if (ctx->queryOptions().failOnLeaks)
  1235. throw makeStringExceptionV(ROXIE_INTERNAL_ERROR, "STATE: activity %d reset without stop", activityId);
  1236. if (traceStartStop || traceLevel > 2)
  1237. CTXLOG("STATE: activity %d reset without stop", activityId);
  1238. stop();
  1239. }
  1240. state = STATEreset;
  1241. #ifdef TRACE_STARTSTOP
  1242. if (traceStartStop)
  1243. {
  1244. CTXLOG("reset %p %d", this, activityId);
  1245. if (watchActivityId && watchActivityId==activityId)
  1246. {
  1247. CTXLOG("WATCH: reset %p %d", this, activityId);
  1248. }
  1249. }
  1250. #endif
  1251. resetJunction(junction);
  1252. ForEachItemIn(idx, dependencies)
  1253. dependencies.item(idx).reset();
  1254. localCycles = queryLocalCycles(); // We can't call queryLocalCycles() in the destructor, so save the information here when we can.
  1255. if (input)
  1256. input->reset();
  1257. }
  1258. }
  1259. aborted = false;
  1260. }
  1261. virtual void addDependency(IRoxieServerActivity &source, unsigned sourceIdx, int controlId)
  1262. {
  1263. dependencies.append(source);
  1264. dependencyIndexes.append(sourceIdx);
  1265. dependencyControlIds.append(controlId);
  1266. }
  1267. virtual void resetEOF()
  1268. {
  1269. //would make more sense if the default implementation (and eof member) were in the base class
  1270. }
  1271. // Sink activities should override this....
  1272. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  1273. {
  1274. throw MakeStringException(ROXIE_SINK, "Internal error: execute() requires a sink");
  1275. }
  1276. virtual void executeChild(size32_t & retSize, void * & ret, unsigned parentExtractSize, const byte * parentExtract)
  1277. {
  1278. throw MakeStringException(ROXIE_SINK, "Internal error: executeChild() requires a suitable sink");
  1279. }
  1280. virtual void stopSink(unsigned idx)
  1281. {
  1282. throw MakeStringException(ROXIE_SINK, "Internal error: stopSink() requires a suitable sink");
  1283. }
  1284. virtual void connectInputStreams(bool consumerOrdered)
  1285. {
  1286. if (input && !inputStream)
  1287. inputStream = connectSingleStream(ctx, input, sourceIdx, junction, isInputOrdered(consumerOrdered, 0));
  1288. if (!connected)
  1289. {
  1290. connectDependencies();
  1291. connected = true;
  1292. }
  1293. }
  1294. void connectDependencies()
  1295. {
  1296. ForEachItemIn(i, dependencies)
  1297. dependencies.item(i).connectInputStreams(true);
  1298. }
  1299. virtual __int64 evaluate()
  1300. {
  1301. throw MakeStringException(ROXIE_SINK, "Internal error: evaluate() requires a function");
  1302. }
  1303. virtual IFinalRoxieInput * querySelectOutput(unsigned id)
  1304. {
  1305. return NULL;
  1306. }
  1307. virtual bool querySetStreamInput(unsigned id, unsigned _sourceIdx, IFinalRoxieInput * _input)
  1308. {
  1309. return false;
  1310. }
  1311. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  1312. {
  1313. assertex(!idx);
  1314. input = _in;
  1315. sourceIdx = _sourceIdx;
  1316. inputStream = NULL;
  1317. }
  1318. bool isInputOrdered(bool consumerOrdered, unsigned idx) const
  1319. {
  1320. if (!factory)
  1321. return true;
  1322. //Grouping implies the stream processing must be ordered - I think this always applies
  1323. IFinalRoxieInput * curInput = queryInput(idx);
  1324. if (curInput && curInput->queryOutputMeta()->isGrouped())
  1325. return true;
  1326. return factory->isInputOrdered(consumerOrdered, idx);
  1327. }
  1328. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  1329. {
  1330. assertex(!idx);
  1331. // By default, activities are assumed NOT to support streams
  1332. bool inputOrdered = isInputOrdered(consumerOrdered, 0);
  1333. connectInputStreams(inputOrdered);
  1334. // Return a single stream
  1335. streams.append(this);
  1336. return NULL;
  1337. }
  1338. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  1339. {
  1340. if (idx == (unsigned) -1)
  1341. idx = 0;
  1342. return idx ? NULL : this;
  1343. }
  1344. virtual IOutputMetaData *queryOutputMeta() const
  1345. {
  1346. return meta.queryOriginal();
  1347. }
  1348. virtual unsigned queryId() const
  1349. {
  1350. return activityId;
  1351. }
  1352. virtual unsigned querySubgraphId() const
  1353. {
  1354. return factory->querySubgraphId();
  1355. }
  1356. virtual void checkAbort()
  1357. {
  1358. ctx->checkAbort();
  1359. }
  1360. IException *makeWrappedException(IException *e)
  1361. {
  1362. StringBuffer msg;
  1363. ThorActivityKind activityKind = factory ? factory->getKind() : TAKnone;
  1364. CTXLOG("makeWrappedException - %s (in %s %d)", e->errorMessage(msg).str(), getActivityText(activityKind), activityId);
  1365. if (QUERYINTERFACE(e, CWrappedException) || QUERYINTERFACE(e, IUserException))
  1366. return e;
  1367. else
  1368. return new CWrappedException(e, activityKind, activityId);
  1369. }
  1370. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract)
  1371. {
  1372. }
  1373. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract, IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes)
  1374. {
  1375. }
  1376. virtual void resetOutputsUsed()
  1377. {
  1378. }
  1379. virtual void noteOutputUsed()
  1380. {
  1381. }
  1382. virtual IRoxieServerSideCache *queryServerSideCache() const
  1383. {
  1384. return factory->queryServerSideCache();
  1385. }
  1386. virtual const IRoxieServerActivityFactory *queryFactory() const
  1387. {
  1388. return factory;
  1389. }
  1390. inline ThorActivityKind getKind() const
  1391. {
  1392. return factory->getKind();
  1393. }
  1394. inline bool isSink() const
  1395. {
  1396. return (factory != NULL) && factory->isSink();
  1397. }
  1398. };
  1399. //=====================================================================================================
  1400. class CRoxieServerLateStartActivity : public CRoxieServerActivity
  1401. {
  1402. protected:
  1403. bool prefiltered;
  1404. bool eof;
  1405. void lateStart(unsigned parentExtractSize, const byte *parentExtract, bool any)
  1406. {
  1407. prefiltered = !any;
  1408. eof = prefiltered;
  1409. if (!prefiltered)
  1410. {
  1411. input->start(parentExtractSize, parentExtract, false);
  1412. startJunction(junction);
  1413. }
  1414. else
  1415. {
  1416. if (traceStartStop)
  1417. CTXLOG("lateStart activity stopping input early as prefiltered");
  1418. inputStream->stop();
  1419. }
  1420. }
  1421. public:
  1422. CRoxieServerLateStartActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  1423. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  1424. {
  1425. prefiltered = false;
  1426. eof = false;
  1427. }
  1428. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  1429. {
  1430. IFinalRoxieInput *saveInput = input;
  1431. Owned<IStrandJunction> saveJunction = junction.getClear();
  1432. input = NULL; // Make sure parent does not start the chain yet
  1433. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  1434. input = saveInput;
  1435. junction.setown(saveJunction.getClear());
  1436. }
  1437. virtual void stop()
  1438. {
  1439. if (!prefiltered)
  1440. {
  1441. inputStream->stop();
  1442. }
  1443. else if (traceStartStop)
  1444. CTXLOG("lateStart activity NOT stopping input late as prefiltered");
  1445. IEngineRowStream *save = inputStream;
  1446. inputStream = NULL; // We already stopped inputStream - prevent parent from doing so again
  1447. CRoxieServerActivity::stop();
  1448. inputStream = save;
  1449. }
  1450. virtual void reset()
  1451. {
  1452. CRoxieServerActivity::reset();
  1453. prefiltered = false;
  1454. }
  1455. };
  1456. //=================================================================================
  1457. class StrandOptions
  1458. {
  1459. // Typically set from hints, common to many stranded activities
  1460. public:
  1461. explicit StrandOptions(IPropertyTree &_graphNode)
  1462. {
  1463. //PARALLEL(1) can be used to explicitly disable parallel processing.
  1464. numStrands = _graphNode.getPropInt("att[@name='parallel']/@value", 0);
  1465. if ((numStrands == minus1U) || (numStrands > MAX_SENSIBLE_STRANDS))
  1466. numStrands = getAffinityCpus();
  1467. blockSize = _graphNode.getPropInt("hint[@name='strandblocksize']/@value", 0);
  1468. }
  1469. StrandOptions(const StrandOptions &from, IRoxieSlaveContext *ctx)
  1470. {
  1471. numStrands = from.numStrands;
  1472. blockSize = from.blockSize;
  1473. if (!blockSize)
  1474. blockSize = ctx->queryOptions().strandBlockSize;
  1475. if (numStrands == 0)
  1476. numStrands = ctx->queryOptions().forceNumStrands;
  1477. }
  1478. public:
  1479. unsigned numStrands = 0; // if 1 it forces single-stranded operations. (Useful for testing.)
  1480. unsigned blockSize = 0;
  1481. };
  1482. class StrandProcessor : public CInterfaceOf<IEngineRowStream>
  1483. {
  1484. protected:
  1485. CRoxieServerActivity &parent;
  1486. IEngineRowAllocator *rowAllocator;
  1487. IEngineRowStream *inputStream;
  1488. ActivityTimeAccumulator totalCycles;
  1489. mutable CRuntimeStatisticCollection stats;
  1490. unsigned processed = 0;
  1491. unsigned numProcessedLastGroup = 0;
  1492. const bool timeActivities;
  1493. bool stopped = false;
  1494. std::atomic<bool> abortRequested;
  1495. public:
  1496. explicit StrandProcessor(CRoxieServerActivity &_parent, IEngineRowStream *_inputStream, bool needsAllocator)
  1497. : parent(_parent), inputStream(_inputStream), stats(parent.queryStatsMapping()), timeActivities(_parent.timeActivities), abortRequested(false)
  1498. {
  1499. if (needsAllocator)
  1500. {
  1501. rowAllocator = parent.createRowAllocatorEx(parent.queryOutputMeta(), roxiemem::RHFunique);
  1502. }
  1503. else
  1504. rowAllocator = NULL;
  1505. }
  1506. ~StrandProcessor()
  1507. {
  1508. ::Release(rowAllocator);
  1509. }
  1510. virtual void start()
  1511. {
  1512. processed = 0;
  1513. numProcessedLastGroup = 0;
  1514. totalCycles.reset();
  1515. stats.reset();
  1516. }
  1517. virtual void stop()
  1518. {
  1519. if (!stopped)
  1520. {
  1521. if (inputStream)
  1522. inputStream->stop();
  1523. stats.reset(heapStatistics); // Heap stats are always gathered from scratch each time
  1524. if (rowAllocator)
  1525. rowAllocator->gatherStats(stats);
  1526. parent.stop();
  1527. parent.mergeStrandStats(processed, totalCycles, stats);
  1528. }
  1529. stopped = true;
  1530. }
  1531. virtual void reset()
  1532. {
  1533. stopped = false;
  1534. abortRequested.store(false, std::memory_order_relaxed);
  1535. }
  1536. virtual void resetEOF()
  1537. {
  1538. inputStream->resetEOF();
  1539. }
  1540. inline void requestAbort() { abortRequested.store(true, std::memory_order_relaxed); }
  1541. inline bool isAborting() { return abortRequested.load(std::memory_order_relaxed); }
  1542. };
  1543. class CRoxieServerStrandedActivity : public CRoxieServerActivity
  1544. {
  1545. protected:
  1546. StrandOptions strandOptions;
  1547. IArrayOf<StrandProcessor> strands;
  1548. Owned<IStrandBranch> branch;
  1549. Owned<IStrandJunction> splitter;
  1550. Owned<IStrandJunction> sourceJunction; // A junction applied to the output of a source activity
  1551. std::atomic<unsigned> active;
  1552. public:
  1553. CRoxieServerStrandedActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const StrandOptions &_strandOptions)
  1554. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  1555. strandOptions(_strandOptions, ctx)
  1556. {
  1557. active = 0;
  1558. }
  1559. ~CRoxieServerStrandedActivity()
  1560. {
  1561. if (strands.ordinality() > 1)
  1562. {
  1563. if (factory && !debugging)
  1564. factory->noteProcessed(0, processed);
  1565. if (ctx && factory)
  1566. ctx->noteProcessed(factory->querySubgraphId(), activityId, 0, processed, strands.ordinality());
  1567. processed = 0; // To avoid reprocessing in base destructor
  1568. }
  1569. }
  1570. virtual void onCreate(IHThorArg *_colocalArg)
  1571. {
  1572. CRoxieServerActivity::_onCreate(_colocalArg, strands.ordinality());
  1573. }
  1574. //This function is pure (But also implemented out of line) to force the derived classes to implement it.
  1575. //After calling the base class start method, and initialising any values from the helper they must call onStartStrands(),
  1576. //this must also happen before any rows are read from the strands (e.g., by a source junction)
  1577. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused) = 0;
  1578. virtual void reset()
  1579. {
  1580. assertex(active==0);
  1581. ForEachItemIn(idx, strands)
  1582. strands.item(idx).reset();
  1583. resetJunction(splitter);
  1584. CRoxieServerActivity::reset();
  1585. resetJunction(sourceJunction);
  1586. }
  1587. virtual void stop()
  1588. {
  1589. // Called from the strands... which should ensure that stop is not called more than once per strand
  1590. //The first strand to call
  1591. if (active)
  1592. --active;
  1593. if (!active)
  1594. CRoxieServerActivity::stop();
  1595. }
  1596. void requestAbort()
  1597. {
  1598. ForEachItemIn(idx, strands)
  1599. strands.item(idx).requestAbort();
  1600. }
  1601. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  1602. {
  1603. assertex(idx == 0);
  1604. assertex(strands.empty());
  1605. CRoxieServerActivity::connectDependencies();
  1606. bool inputOrdered = isInputOrdered(consumerOrdered, idx);
  1607. //Note, numStrands == 1 is an explicit request to disable threading
  1608. if (consumerOptions && (consumerOptions->numStrands != 1) && (strandOptions.numStrands != 1))
  1609. {
  1610. //Check to see if the consumer's settings should override
  1611. if (strandOptions.numStrands == 0)
  1612. {
  1613. strandOptions.numStrands = consumerOptions->numStrands;
  1614. strandOptions.blockSize = consumerOptions->blockSize;
  1615. }
  1616. else if (consumerOptions->numStrands > strandOptions.numStrands)
  1617. {
  1618. strandOptions.numStrands = consumerOptions->numStrands;
  1619. }
  1620. }
  1621. Owned <IStrandJunction> recombiner;
  1622. if (input)
  1623. {
  1624. if (strandOptions.numStrands == 1)
  1625. {
  1626. // 1 means explicitly requested single-strand.
  1627. IEngineRowStream *instream = connectSingleStream(ctx, input, sourceIdx, junction, inputOrdered);
  1628. strands.append(*createStrandProcessor(instream));
  1629. }
  1630. else
  1631. {
  1632. PointerArrayOf<IEngineRowStream> instreams;
  1633. recombiner.setown(input->getOutputStreams(ctx, sourceIdx, instreams, &strandOptions, inputOrdered, orderedCallbacks));
  1634. if ((instreams.length() == 1) && (strandOptions.numStrands != 0)) // 0 means did not specify - we should use the strands that our upstream provides
  1635. {
  1636. assertex(recombiner == NULL);
  1637. // Create a splitter to split the input into n... and a recombiner if need to preserve sorting
  1638. if (inputOrdered)
  1639. {
  1640. branch.setown(createStrandBranch(ctx->queryRowManager(), strandOptions.numStrands, strandOptions.blockSize, true, input->queryOutputMeta()->isGrouped(), false, orderedCallbacks));
  1641. splitter.set(branch->queryInputJunction());
  1642. recombiner.set(branch->queryOutputJunction());
  1643. }
  1644. else
  1645. {
  1646. splitter.setown(createStrandJunction(ctx->queryRowManager(), 1, strandOptions.numStrands, strandOptions.blockSize, false));
  1647. }
  1648. splitter->setInput(0, instreams.item(0));
  1649. for (unsigned strandNo = 0; strandNo < strandOptions.numStrands; strandNo++)
  1650. strands.append(*createStrandProcessor(splitter->queryOutput(strandNo)));
  1651. }
  1652. else
  1653. {
  1654. // Ignore my hint and just use the width already split into...
  1655. ForEachItemIn(strandNo, instreams)
  1656. strands.append(*createStrandProcessor(instreams.item(strandNo)));
  1657. }
  1658. }
  1659. }
  1660. else
  1661. {
  1662. unsigned numStrands = strandOptions.numStrands ? strandOptions.numStrands : 1;
  1663. for (unsigned i=0; i < numStrands; i++)
  1664. strands.append(*createStrandSourceProcessor(inputOrdered));
  1665. if (inputOrdered && (numStrands > 1))
  1666. {
  1667. if (consumerOptions)
  1668. {
  1669. //If the output activities are also stranded then need to create a version of the branch
  1670. bool isGrouped = queryOutputMeta()->isGrouped();
  1671. branch.setown(createStrandBranch(ctx->queryRowManager(), strandOptions.numStrands, strandOptions.blockSize, true, isGrouped, true, orderedCallbacks));
  1672. sourceJunction.set(branch->queryInputJunction());
  1673. recombiner.set(branch->queryOutputJunction());
  1674. assertex((orderedCallbacks && !recombiner) || (!orderedCallbacks && recombiner));
  1675. //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
  1676. for (unsigned strandNo = 0; strandNo < strandOptions.numStrands; strandNo++)
  1677. {
  1678. sourceJunction->setInput(strandNo, &strands.item(strandNo));
  1679. streams.append(sourceJunction->queryOutput(strandNo));
  1680. }
  1681. #ifdef TRACE_STRANDS
  1682. if (traceLevel > 2)
  1683. DBGLOG("Executing activity %u with %u strands", activityId, strands.ordinality());
  1684. #endif
  1685. return recombiner.getClear();
  1686. }
  1687. else
  1688. {
  1689. //Feeding into a non threaded activity, so create a M:1 junction to combine the source strands
  1690. recombiner.setown(createStrandJunction(ctx->queryRowManager(), numStrands, 1, strandOptions.blockSize, inputOrdered));
  1691. }
  1692. }
  1693. }
  1694. ForEachItemIn(i, strands)
  1695. streams.append(&strands.item(i));
  1696. #ifdef TRACE_STRANDS
  1697. if (traceLevel > 2)
  1698. DBGLOG("Executing activity %u with %u strands", activityId, strands.ordinality());
  1699. #endif
  1700. return recombiner.getClear();
  1701. }
  1702. virtual StrandProcessor *createStrandProcessor(IEngineRowStream *instream) = 0;
  1703. //MORE: Possibly this class should be split into two for sinks and non sinks...
  1704. virtual StrandProcessor *createStrandSourceProcessor(bool inputOrdered) = 0;
  1705. virtual const void * nextRow()
  1706. {
  1707. throwUnexpected();
  1708. }
  1709. inline unsigned numStrands() const { return strands.ordinality(); }
  1710. protected:
  1711. void onStartStrands()
  1712. {
  1713. ForEachItemIn(idx, strands)
  1714. {
  1715. strands.item(idx).start();
  1716. active++;
  1717. }
  1718. }
  1719. };
  1720. //For some reason gcc doesn't let you specify a function as pure virtual and define it at the same time.
  1721. void CRoxieServerStrandedActivity::start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  1722. {
  1723. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  1724. startJunction(splitter);
  1725. }
  1726. class CRoxieServerStrandedLateStartActivity : public CRoxieServerStrandedActivity
  1727. {
  1728. protected:
  1729. bool prefiltered;
  1730. bool eof;
  1731. void lateStart(unsigned parentExtractSize, const byte *parentExtract, bool any)
  1732. {
  1733. prefiltered = !any;
  1734. eof = prefiltered;
  1735. if (!prefiltered)
  1736. {
  1737. //At this point
  1738. input->start(parentExtractSize, parentExtract, false);
  1739. startJunction(splitter);
  1740. onStartStrands(); // Initialise the strands - the helper will have been correctly initialized by this point.
  1741. startJunction(sourceJunction);
  1742. }
  1743. else
  1744. {
  1745. if (traceStartStop)
  1746. CTXLOG("strandedLateStart activity stopping input early as prefiltered");
  1747. ForEachItemIn(idx, strands)
  1748. strands.item(idx).stop();
  1749. }
  1750. }
  1751. public:
  1752. CRoxieServerStrandedLateStartActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const StrandOptions &_strandOptions)
  1753. : CRoxieServerStrandedActivity(_ctx, _factory, _probeManager, _strandOptions)
  1754. {
  1755. prefiltered = false;
  1756. eof = false;
  1757. }
  1758. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  1759. {
  1760. IFinalRoxieInput *save = input;
  1761. 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)
  1762. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  1763. input = save;
  1764. }
  1765. virtual void reset()
  1766. {
  1767. CRoxieServerStrandedActivity::reset();
  1768. prefiltered = false;
  1769. }
  1770. };
  1771. //=====================================================================================================
  1772. atomic_t nextInstanceId;
  1773. extern unsigned getNextInstanceId()
  1774. {
  1775. return atomic_add_exchange(&nextInstanceId, 1)+1;
  1776. }
  1777. atomic_t nextRuid;
  1778. ruid_t getNextRuid()
  1779. {
  1780. ruid_t ret = atomic_add_exchange(&nextRuid, 1)+1;
  1781. while (ret < RUID_FIRST)
  1782. ret = atomic_add_exchange(&nextRuid, 1)+1; // ruids 0 and 1 are reserved for pings/unwanted discarder.
  1783. return ret;
  1784. }
  1785. void setStartRuid(unsigned restarts)
  1786. {
  1787. atomic_set(&nextRuid, restarts * 0x10000);
  1788. atomic_set(&nextInstanceId, restarts * 10000);
  1789. }
  1790. enum { LimitSkipErrorCode = 0, KeyedLimitSkipErrorCode = 1 };
  1791. class DECL_EXCEPTION LimitSkipException : public IException, public CInterface
  1792. {
  1793. int code;
  1794. public:
  1795. LimitSkipException(int _code) { code = _code; }
  1796. IMPLEMENT_IINTERFACE;
  1797. virtual int errorCode() const { return code; }
  1798. virtual StringBuffer & errorMessage(StringBuffer &msg) const { return msg.append("LimitSkipException"); }
  1799. virtual MessageAudience errorAudience() const { return MSGAUD_internal; }
  1800. };
  1801. IException *makeLimitSkipException(bool isKeyed)
  1802. {
  1803. // We need to make sure what we throw is IException not something derived from it....
  1804. return new LimitSkipException(isKeyed ? KeyedLimitSkipErrorCode : LimitSkipErrorCode);
  1805. }
  1806. //=================================================================================
  1807. interface IRecordPullerCallback : extends IExceptionHandler
  1808. {
  1809. virtual void processRow(const void *row) = 0;
  1810. virtual void processEOG() = 0;
  1811. virtual void processGroup(const ConstPointerArray &rows) = 0;
  1812. virtual void processDone() = 0;
  1813. };
  1814. class RecordPullerThread : public RestartableThread
  1815. {
  1816. protected:
  1817. IFinalRoxieInput *input;
  1818. Owned<IStrandJunction> junction;
  1819. unsigned sourceIdx = 0;
  1820. IEngineRowStream *inputStream;
  1821. IRecordPullerCallback *helper;
  1822. Semaphore started; // MORE: GH->RKC I'm pretty sure this can be deleted, since handled by RestartableThread
  1823. bool groupAtOnce, eof, eog;
  1824. CriticalSection crit;
  1825. public:
  1826. RecordPullerThread(bool _groupAtOnce)
  1827. : RestartableThread("RecordPullerThread"), groupAtOnce(_groupAtOnce)
  1828. {
  1829. input = NULL;
  1830. inputStream = NULL;
  1831. helper = NULL;
  1832. eof = eog = FALSE;
  1833. }
  1834. inline unsigned __int64 queryTotalCycles() const
  1835. {
  1836. return input->queryTotalCycles();
  1837. }
  1838. void setInput(IRecordPullerCallback *_helper, unsigned _sourceIdx, IFinalRoxieInput *_input)
  1839. {
  1840. helper = _helper;
  1841. input = _input;
  1842. sourceIdx = _sourceIdx;
  1843. }
  1844. IFinalRoxieInput *queryInput() const
  1845. {
  1846. return input;
  1847. }
  1848. virtual void connectInputStreams(IRoxieSlaveContext *ctx, bool consumerOrdered)
  1849. {
  1850. inputStream = connectSingleStream(ctx, input, sourceIdx, junction, consumerOrdered);
  1851. }
  1852. IEngineRowStream *queryStream() const
  1853. {
  1854. return inputStream;
  1855. }
  1856. void start(unsigned parentExtractSize, const byte *parentExtract, bool paused, unsigned preload, bool noThread, IRoxieSlaveContext *ctx)
  1857. {
  1858. eof = false;
  1859. eog = false;
  1860. input->start(parentExtractSize, parentExtract, paused);
  1861. startJunction(junction);
  1862. try
  1863. {
  1864. if (preload && !paused)
  1865. {
  1866. if (traceLevel > 4)
  1867. DBGLOG("Preload fetching first %d records", preload);
  1868. if (groupAtOnce)
  1869. pullGroups(preload);
  1870. else
  1871. pullRecords(preload);
  1872. }
  1873. if (eof)
  1874. {
  1875. if (traceLevel > 4)
  1876. DBGLOG("No need to start puller after preload");
  1877. helper->processDone();
  1878. }
  1879. else
  1880. {
  1881. if (!noThread)
  1882. {
  1883. StringBuffer logPrefix("[");
  1884. if (ctx) ctx->getLogPrefix(logPrefix);
  1885. logPrefix.append("] ");
  1886. RestartableThread::start(logPrefix);
  1887. started.wait();
  1888. }
  1889. }
  1890. }
  1891. catch (IException *e)
  1892. {
  1893. helper->fireException(e);
  1894. }
  1895. catch (...)
  1896. {
  1897. helper->fireException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unexpected exception caught in RecordPullerThread::start"));
  1898. }
  1899. }
  1900. void stop()
  1901. {
  1902. if (traceStartStop)
  1903. DBGLOG("RecordPullerThread::stop");
  1904. {
  1905. 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.
  1906. if (inputStream)
  1907. inputStream->stop();
  1908. }
  1909. RestartableThread::join();
  1910. }
  1911. void reset()
  1912. {
  1913. input->reset();
  1914. resetJunction(junction);
  1915. }
  1916. virtual int run()
  1917. {
  1918. started.signal();
  1919. try
  1920. {
  1921. if (groupAtOnce)
  1922. pullGroups((unsigned) -1);
  1923. else
  1924. pullRecords((unsigned) -1);
  1925. helper->processDone();
  1926. }
  1927. catch (IException *e)
  1928. {
  1929. helper->fireException(e);
  1930. }
  1931. catch (...)
  1932. {
  1933. helper->fireException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unexpected exception caught in RecordPullerThread::run"));
  1934. }
  1935. return 0;
  1936. }
  1937. void done()
  1938. {
  1939. helper->processDone();
  1940. }
  1941. bool pullRecords(unsigned preload)
  1942. {
  1943. if (eof)
  1944. return false;
  1945. while (preload)
  1946. {
  1947. const void * row;
  1948. {
  1949. CriticalBlock c(crit); // See comments in stop for why this is needed
  1950. row = inputStream->nextRow();
  1951. }
  1952. if (row)
  1953. {
  1954. eog = false;
  1955. helper->processRow(row);
  1956. }
  1957. else if (!eog)
  1958. {
  1959. helper->processEOG();
  1960. eog = true;
  1961. }
  1962. else
  1963. {
  1964. eof = true;
  1965. return false;
  1966. }
  1967. if (preload != (unsigned) -1)
  1968. preload--;
  1969. }
  1970. return true;
  1971. }
  1972. void pullGroups(unsigned preload)
  1973. {
  1974. ConstPointerArray thisGroup;
  1975. unsigned rowsDone = 0;
  1976. while (preload && !eof)
  1977. {
  1978. const void *row;
  1979. {
  1980. CriticalBlock c(crit);
  1981. row = inputStream->nextRow();
  1982. }
  1983. if (row)
  1984. {
  1985. thisGroup.append(row);
  1986. rowsDone++;
  1987. }
  1988. else if (thisGroup.length())
  1989. {
  1990. helper->processGroup(thisGroup);
  1991. thisGroup.kill();
  1992. if (preload != (unsigned) -1)
  1993. {
  1994. if (preload > rowsDone)
  1995. preload -= rowsDone;
  1996. else
  1997. break;
  1998. }
  1999. rowsDone = 0;
  2000. }
  2001. else
  2002. {
  2003. eof = true;
  2004. break;
  2005. }
  2006. }
  2007. }
  2008. };
  2009. //=================================================================================
  2010. #define READAHEAD_SIZE 1000
  2011. // MORE - this code copied from ThreadedConcat code - may be able to common up some.
  2012. class CRoxieServerReadAheadInput : implements IEngineRowStream, implements IFinalRoxieInput, implements IRecordPullerCallback, public CInterface
  2013. {
  2014. QueueOf<const void, true> buffer;
  2015. InterruptableSemaphore ready;
  2016. InterruptableSemaphore space;
  2017. CriticalSection crit;
  2018. bool eof;
  2019. bool disabled;
  2020. IRoxieSlaveContext *ctx;
  2021. RecordPullerThread puller;
  2022. unsigned preload;
  2023. cycle_t totalCycles;
  2024. bool timeActivities;
  2025. public:
  2026. IMPLEMENT_IINTERFACE;
  2027. CRoxieServerReadAheadInput(IRoxieSlaveContext *_ctx, unsigned _preload) : ctx(_ctx), puller(true), preload(_preload)
  2028. {
  2029. eof = false;
  2030. disabled = (ctx->queryDebugContext() != NULL);
  2031. totalCycles = 0;
  2032. timeActivities = ctx->queryOptions().timeActivities;
  2033. }
  2034. virtual IRoxieServerActivity *queryActivity()
  2035. {
  2036. return puller.queryInput()->queryActivity();
  2037. }
  2038. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  2039. {
  2040. assertex(!idx);
  2041. puller.connectInputStreams(ctx, consumerOrdered);
  2042. streams.append(this);
  2043. return NULL;
  2044. }
  2045. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { return this; }
  2046. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { return nullptr; }
  2047. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  2048. {
  2049. return puller.queryInput()->queryIndexReadActivity();
  2050. }
  2051. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  2052. {
  2053. eof = false;
  2054. if (disabled)
  2055. puller.queryInput()->start(parentExtractSize, parentExtract, paused);
  2056. else
  2057. {
  2058. space.reinit(READAHEAD_SIZE);
  2059. ready.reinit();
  2060. puller.start(parentExtractSize, parentExtract, paused, preload, false, ctx);
  2061. }
  2062. }
  2063. virtual void stop()
  2064. {
  2065. if (disabled)
  2066. puller.queryStream()->stop();
  2067. else
  2068. {
  2069. space.interrupt();
  2070. ready.interrupt();
  2071. puller.stop();
  2072. }
  2073. }
  2074. virtual void reset()
  2075. {
  2076. if (disabled)
  2077. puller.queryInput()->reset();
  2078. else
  2079. {
  2080. puller.reset();
  2081. ForEachItemIn(idx1, buffer)
  2082. ReleaseRoxieRow(buffer.item(idx1));
  2083. buffer.clear();
  2084. }
  2085. }
  2086. virtual void resetEOF()
  2087. {
  2088. throwUnexpected();
  2089. }
  2090. virtual IOutputMetaData * queryOutputMeta() const
  2091. {
  2092. return puller.queryInput()->queryOutputMeta();
  2093. }
  2094. void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  2095. {
  2096. assertex(!idx);
  2097. puller.setInput(this, _sourceIdx, _in);
  2098. }
  2099. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  2100. {
  2101. if (idx==0)
  2102. return puller.queryInput();
  2103. else
  2104. return NULL;
  2105. }
  2106. virtual unsigned __int64 queryTotalCycles() const
  2107. {
  2108. return totalCycles;
  2109. }
  2110. virtual const void * nextRow()
  2111. {
  2112. SimpleActivityTimer t(totalCycles, timeActivities);
  2113. if (disabled)
  2114. return puller.queryStream()->nextRow();
  2115. else
  2116. {
  2117. for (;;)
  2118. {
  2119. {
  2120. CriticalBlock b(crit);
  2121. if (eof && !buffer.ordinality())
  2122. return NULL; // eof
  2123. }
  2124. ready.wait();
  2125. const void *ret;
  2126. {
  2127. CriticalBlock b(crit);
  2128. ret = buffer.dequeue();
  2129. }
  2130. space.signal();
  2131. return ret;
  2132. }
  2133. }
  2134. }
  2135. virtual bool fireException(IException *e)
  2136. {
  2137. // called from puller thread on failure
  2138. ready.interrupt(LINK(e));
  2139. space.interrupt(e);
  2140. return true;
  2141. }
  2142. virtual void processRow(const void *row)
  2143. {
  2144. {
  2145. CriticalBlock b(crit);
  2146. buffer.enqueue(row);
  2147. }
  2148. ready.signal();
  2149. space.wait();
  2150. }
  2151. virtual void processGroup(const ConstPointerArray &rows)
  2152. {
  2153. // NOTE - a bit bizarre in that it waits for the space AFTER using it.
  2154. // But the space semaphore is only there to stop infinite readahead. And otherwise it would deadlock
  2155. // if group was larger than max(space)
  2156. {
  2157. CriticalBlock b(crit);
  2158. ForEachItemIn(idx, rows)
  2159. buffer.enqueue(rows.item(idx));
  2160. buffer.enqueue(NULL);
  2161. }
  2162. for (unsigned i2 = 0; i2 <= rows.length(); i2++) // note - does 1 extra for the null
  2163. {
  2164. ready.signal();
  2165. space.wait();
  2166. }
  2167. }
  2168. virtual void processEOG()
  2169. {
  2170. // Used when output is not grouped - just ignore
  2171. }
  2172. virtual void processDone()
  2173. {
  2174. CriticalBlock b(crit);
  2175. eof = true;
  2176. ready.signal();
  2177. }
  2178. };
  2179. //=================================================================================
  2180. class CRoxieServerTwoInputActivity : public CRoxieServerActivity
  2181. {
  2182. protected:
  2183. IFinalRoxieInput *input1;
  2184. IEngineRowStream *inputStream1;
  2185. Owned<IStrandJunction> junction1;
  2186. unsigned sourceIdx1 = 0;
  2187. Owned<CRoxieServerReadAheadInput> puller;
  2188. public:
  2189. CRoxieServerTwoInputActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  2190. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  2191. {
  2192. input1 = NULL;
  2193. inputStream1 = NULL;
  2194. }
  2195. ~CRoxieServerTwoInputActivity()
  2196. {
  2197. }
  2198. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  2199. {
  2200. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  2201. input1->start(parentExtractSize, parentExtract, paused);
  2202. startJunction(junction1);
  2203. }
  2204. virtual void stop()
  2205. {
  2206. inputStream1->stop();
  2207. CRoxieServerActivity::stop();
  2208. }
  2209. virtual unsigned __int64 queryLocalCycles() const
  2210. {
  2211. __int64 ret;
  2212. __int64 inputCycles = input->queryTotalCycles();
  2213. __int64 input1Cycles = input1->queryTotalCycles();
  2214. if (puller)
  2215. ret = totalCycles.totalCycles - (inputCycles > input1Cycles ? inputCycles : input1Cycles);
  2216. else
  2217. ret = totalCycles.totalCycles - (inputCycles + input1Cycles);
  2218. if (ret < 0)
  2219. ret = 0;
  2220. return ret;
  2221. }
  2222. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  2223. {
  2224. switch (idx)
  2225. {
  2226. case 0:
  2227. return input;
  2228. case 1:
  2229. return input1;
  2230. default:
  2231. return NULL;
  2232. }
  2233. }
  2234. virtual void reset()
  2235. {
  2236. CRoxieServerActivity::reset();
  2237. if (input1)
  2238. input1->reset();
  2239. resetJunction(junction1);
  2240. }
  2241. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  2242. {
  2243. switch(idx)
  2244. {
  2245. case 0:
  2246. CRoxieServerActivity::setInput(idx, _sourceIdx, _in);
  2247. break;
  2248. case 1:
  2249. input1 = _in;
  2250. sourceIdx1 = _sourceIdx;
  2251. break;
  2252. default:
  2253. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
  2254. }
  2255. }
  2256. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  2257. {
  2258. inputStream1 = connectSingleStream(ctx, input1, sourceIdx1, junction1, isInputOrdered(consumerOrdered, 1));
  2259. //Assumes input1 will be stranded if any.
  2260. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
  2261. }
  2262. };
  2263. //=================================================================================
  2264. class CRoxieServerMultiInputBaseActivity : public CRoxieServerActivity
  2265. {
  2266. protected:
  2267. unsigned numInputs;
  2268. unsigned numStreams;
  2269. IFinalRoxieInput **inputArray;
  2270. unsigned *sourceIdxArray;
  2271. IEngineRowStream **streamArray;
  2272. Owned<IStrandJunction> *junctionArray;
  2273. public:
  2274. CRoxieServerMultiInputBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  2275. : CRoxieServerActivity(_ctx, _factory, _probeManager), numInputs(_numInputs)
  2276. {
  2277. numStreams = numInputs;
  2278. inputArray = new IFinalRoxieInput*[numInputs];
  2279. sourceIdxArray = new unsigned[numInputs];
  2280. streamArray = new IEngineRowStream*[numStreams];
  2281. junctionArray = new Owned<IStrandJunction>[numStreams];
  2282. for (unsigned i1 = 0; i1 < numInputs; i1++)
  2283. {
  2284. inputArray[i1] = NULL;
  2285. sourceIdxArray[i1] = 0;
  2286. }
  2287. for (unsigned i2 = 0; i2 < numStreams; i2++)
  2288. streamArray[i2] = NULL;
  2289. }
  2290. ~CRoxieServerMultiInputBaseActivity()
  2291. {
  2292. delete [] inputArray;
  2293. delete [] sourceIdxArray;
  2294. delete [] streamArray;
  2295. delete [] junctionArray;
  2296. }
  2297. virtual unsigned __int64 queryLocalCycles() const
  2298. {
  2299. __int64 localCycles = totalCycles.totalCycles;
  2300. for (unsigned i = 0; i < numInputs; i++)
  2301. localCycles -= inputArray[i]->queryTotalCycles();
  2302. if (localCycles < 0)
  2303. localCycles = 0;
  2304. return localCycles;
  2305. }
  2306. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  2307. {
  2308. if (idx < numInputs)
  2309. return inputArray[idx];
  2310. else
  2311. return NULL;
  2312. }
  2313. virtual IFinalRoxieInput * queryConcreteInput(unsigned idx)
  2314. {
  2315. return queryInput(idx);
  2316. }
  2317. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput)
  2318. {
  2319. if (whichInput < numInputs)
  2320. return streamArray[whichInput];
  2321. else
  2322. return NULL;
  2323. }
  2324. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const
  2325. {
  2326. if (idx < numInputs)
  2327. return junctionArray[idx];
  2328. else
  2329. return NULL;
  2330. }
  2331. virtual void reset()
  2332. {
  2333. for (unsigned i = 0; i < numInputs; i++)
  2334. inputArray[i]->reset();
  2335. for (unsigned iS = 0; iS < numStreams; iS++)
  2336. {
  2337. resetJunction(junctionArray[iS]);
  2338. }
  2339. CRoxieServerActivity::reset();
  2340. }
  2341. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  2342. {
  2343. assertex(idx < numInputs && idx < numStreams);
  2344. inputArray[idx] = _in;
  2345. sourceIdxArray[idx] = _sourceIdx;
  2346. }
  2347. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  2348. {
  2349. //There could be situations (e.g., NONEMPTY), where you might want to strand the activity.
  2350. for (unsigned i = 0; i < numInputs; i++)
  2351. streamArray[i] = connectSingleStream(ctx, inputArray[i], sourceIdxArray[i], junctionArray[i], consumerOrdered);
  2352. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, NULL, consumerOrdered, nullptr); // The input basesclass does not have an input
  2353. }
  2354. };
  2355. //=================================================================================
  2356. class CRoxieServerMultiInputActivity : public CRoxieServerMultiInputBaseActivity
  2357. {
  2358. public:
  2359. CRoxieServerMultiInputActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  2360. : CRoxieServerMultiInputBaseActivity(_ctx, _factory, _probeManager, _numInputs)
  2361. {
  2362. }
  2363. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  2364. {
  2365. CRoxieServerMultiInputBaseActivity::start(parentExtractSize, parentExtract, paused);
  2366. for (unsigned i = 0; i < numInputs; i++)
  2367. {
  2368. inputArray[i]->start(parentExtractSize, parentExtract, paused);
  2369. }
  2370. for (unsigned iS = 0; iS < numStreams; iS++)
  2371. {
  2372. startJunction(junctionArray[iS]);
  2373. }
  2374. }
  2375. virtual void stop()
  2376. {
  2377. for (unsigned i = 0; i < numStreams; i++)
  2378. {
  2379. streamArray[i]->stop();
  2380. }
  2381. CRoxieServerMultiInputBaseActivity::stop();
  2382. }
  2383. };
  2384. //=====================================================================================================
  2385. class CRoxieServerInternalSinkActivity : public CRoxieServerActivity
  2386. {
  2387. protected:
  2388. unsigned numOutputs;
  2389. bool executed;
  2390. bool *stopped;
  2391. CriticalSection ecrit;
  2392. Owned<IException> exception;
  2393. public:
  2394. CRoxieServerInternalSinkActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  2395. : CRoxieServerActivity(_ctx, _factory, _probeManager), numOutputs(_numOutputs)
  2396. {
  2397. executed = false;
  2398. stopped = new bool[numOutputs];
  2399. for (unsigned s = 0; s < numOutputs; s++)
  2400. stopped[s] = false;
  2401. }
  2402. ~CRoxieServerInternalSinkActivity()
  2403. {
  2404. delete [] stopped;
  2405. }
  2406. virtual void reset()
  2407. {
  2408. for (unsigned s = 0; s < numOutputs; s++)
  2409. stopped[s] = false;
  2410. executed = false;
  2411. exception.clear();
  2412. CRoxieServerActivity::reset();
  2413. }
  2414. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  2415. {
  2416. return NULL;
  2417. }
  2418. virtual void stopSink(unsigned outputIdx)
  2419. {
  2420. if (outputIdx < numOutputs && !stopped[outputIdx]) // Implicit dependencies on DiskWrite activities do not count as outputs
  2421. {
  2422. stopped[outputIdx] = true;
  2423. for (unsigned s = 0; s < numOutputs; s++)
  2424. if (!stopped[s])
  2425. return;
  2426. stop(); // all outputs stopped - stop parent.
  2427. }
  2428. }
  2429. virtual const void *nextRow()
  2430. {
  2431. throwUnexpected(); // I am nobody's input
  2432. }
  2433. virtual void onExecute() = 0;
  2434. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  2435. {
  2436. CriticalBlock b(ecrit);
  2437. if (exception)
  2438. throw exception.getLink();
  2439. if (!executed)
  2440. {
  2441. try
  2442. {
  2443. start(parentExtractSize, parentExtract, false);
  2444. {
  2445. ActivityTimer t(totalCycles, timeActivities); // unfortunately this is not really best place for seeing in debugger.
  2446. onExecute();
  2447. }
  2448. stop();
  2449. executed = true;
  2450. }
  2451. catch (IException *E)
  2452. {
  2453. exception.set(E); // (or maybe makeWrappedException?)
  2454. abort();
  2455. throw;
  2456. }
  2457. catch (...)
  2458. {
  2459. exception.set(MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught at %s:%d", sanitizeSourceFile(__FILE__), __LINE__));
  2460. abort();
  2461. throw;
  2462. }
  2463. }
  2464. }
  2465. };
  2466. //=================================================================================
  2467. class CRoxieServerQueryPacket : implements IRoxieServerQueryPacket, public CInterface
  2468. {
  2469. protected:
  2470. Owned<IMessageResult> result;
  2471. Owned<IRoxieQueryPacket> packet;
  2472. Linked<IRoxieServerQueryPacket> continuation;
  2473. unsigned hash;
  2474. unsigned seq;
  2475. unsigned lastDebugSequence;
  2476. Owned<IRoxieQueryPacket> lastDebugResponse;
  2477. ILRUChain *prev;
  2478. ILRUChain *next;
  2479. bool delayed;
  2480. public:
  2481. IMPLEMENT_IINTERFACE;
  2482. CRoxieServerQueryPacket(IRoxieQueryPacket *p) : packet(p)
  2483. {
  2484. hash = 0;
  2485. seq = 0;
  2486. prev = NULL;
  2487. next = NULL;
  2488. delayed = false;
  2489. lastDebugSequence = 0;
  2490. }
  2491. virtual IRoxieQueryPacket *queryPacket() const
  2492. {
  2493. return packet;
  2494. }
  2495. virtual bool isContinuation() const
  2496. {
  2497. return packet && (packet->queryHeader().continueSequence & ~CONTINUE_SEQUENCE_SKIPTO) != 0;
  2498. }
  2499. virtual bool isDelayed() const
  2500. {
  2501. return delayed;
  2502. }
  2503. virtual bool isEnd() const
  2504. {
  2505. return false;
  2506. }
  2507. virtual bool isLimit(unsigned __int64 &_rowLimit, unsigned __int64 &_keyedLimit, unsigned __int64 &_stopAfter) const
  2508. {
  2509. return false;
  2510. }
  2511. virtual bool hasResult() const
  2512. {
  2513. return result != NULL;
  2514. }
  2515. virtual bool hasContinuation() const
  2516. {
  2517. return continuation != NULL;
  2518. }
  2519. virtual void setDelayed(bool _delayed)
  2520. {
  2521. delayed = _delayed;
  2522. }
  2523. virtual void setPacket(IRoxieQueryPacket *_packet)
  2524. {
  2525. packet.setown(_packet);
  2526. }
  2527. virtual void setSequence(unsigned _seq)
  2528. {
  2529. assertex(!IsShared());
  2530. seq = _seq;
  2531. }
  2532. virtual unsigned getSequence() const
  2533. {
  2534. return seq;
  2535. }
  2536. IMessageResult *getResult()
  2537. {
  2538. return result.getLink();
  2539. }
  2540. IMessageResult *queryResult()
  2541. {
  2542. return result;
  2543. }
  2544. void setResult(IMessageResult *r)
  2545. {
  2546. result.setown(r);
  2547. }
  2548. IRoxieServerQueryPacket *queryContinuation()
  2549. {
  2550. return continuation;
  2551. }
  2552. void setContinuation(IRoxieServerQueryPacket *c)
  2553. {
  2554. continuation.setown(c);
  2555. }
  2556. virtual unsigned queryHash() const
  2557. {
  2558. return hash;
  2559. }
  2560. virtual void setHash(unsigned _hash)
  2561. {
  2562. hash = _hash;
  2563. }
  2564. virtual ILRUChain *queryPrev() const { return prev; }
  2565. virtual ILRUChain *queryNext() const { return next; }
  2566. virtual void setPrev(ILRUChain *p) { prev = p; }
  2567. virtual void setNext(ILRUChain *n) { next = n; }
  2568. virtual void unchain()
  2569. {
  2570. if (prev && next)
  2571. {
  2572. prev->setNext(next);
  2573. next->setPrev(prev);
  2574. }
  2575. next = NULL;
  2576. prev = NULL;
  2577. }
  2578. virtual IRoxieQueryPacket *getDebugResponse(unsigned sequence)
  2579. {
  2580. if (sequence == lastDebugSequence)
  2581. return lastDebugResponse.getLink();
  2582. else if (sequence > lastDebugSequence)
  2583. {
  2584. lastDebugResponse.clear();
  2585. return NULL;
  2586. }
  2587. else
  2588. throwUnexpected();
  2589. }
  2590. virtual void setDebugResponse(unsigned sequence, IRoxieQueryPacket *response)
  2591. {
  2592. lastDebugSequence = sequence;
  2593. lastDebugResponse.set(response);
  2594. }
  2595. };
  2596. class CRoxieServerQueryPacketEndMarker : public CRoxieServerQueryPacket
  2597. {
  2598. public:
  2599. CRoxieServerQueryPacketEndMarker() : CRoxieServerQueryPacket(NULL)
  2600. {
  2601. }
  2602. virtual bool isEnd() const
  2603. {
  2604. return true;
  2605. }
  2606. };
  2607. class CRoxieServerQueryPacketLimitMarker : public CRoxieServerQueryPacket
  2608. {
  2609. unsigned __int64 rowLimit;
  2610. unsigned __int64 keyedLimit;
  2611. unsigned __int64 stopAfter;
  2612. public:
  2613. CRoxieServerQueryPacketLimitMarker(unsigned __int64 _rowLimit, unsigned __int64 _keyedLimit, unsigned __int64 _stopAfter) : CRoxieServerQueryPacket(NULL)
  2614. {
  2615. rowLimit = _rowLimit;
  2616. keyedLimit = _keyedLimit;
  2617. stopAfter = _stopAfter;
  2618. }
  2619. virtual bool isLimit(unsigned __int64 &_rowLimit, unsigned __int64 &_keyedLimit, unsigned __int64 &_stopAfter) const
  2620. {
  2621. _rowLimit = rowLimit;
  2622. _keyedLimit = keyedLimit;
  2623. _stopAfter = stopAfter;
  2624. return true;
  2625. }
  2626. };
  2627. class CRoxieServerSideCache : implements IRoxieServerSideCache, implements ILRUChain
  2628. {
  2629. protected:
  2630. unsigned cacheTableSize;
  2631. unsigned cacheTableSpace;
  2632. IRoxieServerQueryPacket **cacheTable;
  2633. mutable ILRUChain *prev;
  2634. mutable ILRUChain *next;
  2635. mutable CriticalSection crit;
  2636. virtual ILRUChain *queryPrev() const { return prev; }
  2637. virtual ILRUChain *queryNext() const { return next; }
  2638. virtual void setPrev(ILRUChain *p) { prev = p; }
  2639. virtual void setNext(ILRUChain *n) { next = n; }
  2640. virtual void unchain()
  2641. {
  2642. prev->setNext(next);
  2643. next->setPrev(prev);
  2644. next = NULL;
  2645. prev = NULL;
  2646. }
  2647. void moveToHead(IRoxieServerQueryPacket *mru)
  2648. {
  2649. mru->unchain();
  2650. mru->setNext(next);
  2651. next->setPrev(mru);
  2652. mru->setPrev(this);
  2653. next = mru;
  2654. }
  2655. IRoxieServerQueryPacket *removeLRU()
  2656. {
  2657. if (next==this)
  2658. assertex(next != this);
  2659. IRoxieServerQueryPacket *goer = (IRoxieServerQueryPacket *) next;
  2660. goer->unchain(); // NOTE - this will modify the value of next
  2661. return goer;
  2662. }
  2663. void removeEntry(IRoxieServerQueryPacket *goer)
  2664. {
  2665. unsigned v = goer->queryHash() % cacheTableSize;
  2666. for (;;)
  2667. {
  2668. IRoxieServerQueryPacket *found = cacheTable[v];
  2669. assertex(found);
  2670. if (found == goer)
  2671. {
  2672. cacheTable[v] = NULL;
  2673. unsigned vn = v;
  2674. for (;;)
  2675. {
  2676. vn++;
  2677. if (vn==cacheTableSize) vn = 0;
  2678. IRoxieServerQueryPacket *found2 = cacheTable[vn];
  2679. if (!found2)
  2680. break;
  2681. unsigned vm = found2->queryHash() % cacheTableSize;
  2682. if (((vn+cacheTableSize-vm) % cacheTableSize)>=((vn+cacheTableSize-v) % cacheTableSize)) // diff(vn,vm)>=diff(vn,v)
  2683. {
  2684. cacheTable[v] = found2;
  2685. v = vn;
  2686. cacheTable[v] = NULL;
  2687. }
  2688. }
  2689. cacheTableSpace++;
  2690. break;
  2691. }
  2692. v++;
  2693. if (v==cacheTableSize)
  2694. v = 0;
  2695. }
  2696. goer->Release();
  2697. }
  2698. public:
  2699. CRoxieServerSideCache(unsigned _cacheSize)
  2700. {
  2701. cacheTableSize = (_cacheSize*4)/3;
  2702. cacheTable = new IRoxieServerQueryPacket *[cacheTableSize];
  2703. memset(cacheTable, 0, cacheTableSize * sizeof(IRoxieServerQueryPacket *));
  2704. cacheTableSpace = _cacheSize;
  2705. prev = this;
  2706. next = this;
  2707. }
  2708. ~CRoxieServerSideCache()
  2709. {
  2710. for (unsigned i = 0; i < cacheTableSize; i++)
  2711. {
  2712. ::Release(cacheTable[i]);
  2713. }
  2714. delete [] cacheTable;
  2715. }
  2716. virtual IRoxieServerQueryPacket *findCachedResult(const IRoxieContextLogger &logctx, IRoxieQueryPacket *p) const
  2717. {
  2718. unsigned hash = p->hash();
  2719. unsigned et = hash % cacheTableSize;
  2720. if (traceServerSideCache)
  2721. {
  2722. StringBuffer s;
  2723. logctx.CTXLOG("CRoxieServerSideCache::findCachedResult hash %x slot %d %s", hash, et, p->queryHeader().toString(s).str());
  2724. }
  2725. CriticalBlock b(crit);
  2726. for (;;)
  2727. {
  2728. IRoxieServerQueryPacket *found = cacheTable[et];
  2729. if (!found)
  2730. return NULL;
  2731. if (found->queryHash() == hash && found->queryPacket()->cacheMatch(p))
  2732. {
  2733. const_cast<CRoxieServerSideCache *>(this)->moveToHead(found);
  2734. if (traceServerSideCache)
  2735. logctx.CTXLOG("CRoxieServerSideCache::findCachedResult cache hit");
  2736. logctx.noteStatistic(StNumServerCacheHits, 1);
  2737. return NULL;
  2738. // 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....
  2739. //IRoxieServerQueryPacket *ret = new CRoxieServerQueryPacket(p);
  2740. //ret->setResult(found->getResult());
  2741. //return ret;
  2742. }
  2743. et++;
  2744. if (et == cacheTableSize)
  2745. et = 0;
  2746. }
  2747. }
  2748. virtual void noteCachedResult(IRoxieServerQueryPacket *out, IMessageResult *in)
  2749. {
  2750. if (true) //!in->getLength()) // MORE - separate caches for hits and nohits
  2751. {
  2752. unsigned hash = out->queryPacket()->hash();
  2753. out->setHash(hash);
  2754. unsigned et = hash % cacheTableSize;
  2755. if (traceServerSideCache)
  2756. {
  2757. StringBuffer s;
  2758. DBGLOG("CRoxieServerSideCache::noteCachedResult hash %x slot %d %s", hash, et, out->queryPacket()->queryHeader().toString(s).str());
  2759. }
  2760. CriticalBlock b(crit);
  2761. for (;;)
  2762. {
  2763. IRoxieServerQueryPacket *found = cacheTable[et];
  2764. if (!found)
  2765. {
  2766. if (cacheTableSpace)
  2767. {
  2768. out->setResult(LINK(in));
  2769. cacheTable[et] = LINK(out);
  2770. cacheTableSpace--;
  2771. moveToHead(out);
  2772. break;
  2773. }
  2774. else
  2775. {
  2776. IRoxieServerQueryPacket *goer = removeLRU();
  2777. removeEntry(goer);
  2778. et = hash % cacheTableSize;
  2779. continue;
  2780. }
  2781. }
  2782. else if (found->queryHash()==hash && found->queryPacket()->cacheMatch(out->queryPacket()))
  2783. {
  2784. moveToHead(found);
  2785. return; // already in the cache. Because we don't cache until we have result, this can happen where
  2786. // multiple copies of a slave query are in-flight at once.
  2787. }
  2788. et++;
  2789. if (et == cacheTableSize)
  2790. et = 0;
  2791. }
  2792. }
  2793. // MORE - do we need to worry about the attachment between the MessageUnpacker and the current row manager. May all fall out ok...
  2794. // Can I easily spot a null result? Do I want to cache null results separately? only?
  2795. }
  2796. // Note that this caching mechanism (unlike the old keyed-join specific one) does not common up cases where multiple
  2797. // identical queries are in-flight at the same time. But if we can make it persistent between queries that will
  2798. // more than make up for it
  2799. };
  2800. class CRowArrayMessageUnpackCursor : implements IMessageUnpackCursor, public CInterface
  2801. {
  2802. ConstPointerArray &data;
  2803. Linked<IMessageResult> result;
  2804. public:
  2805. IMPLEMENT_IINTERFACE;
  2806. CRowArrayMessageUnpackCursor(ConstPointerArray &_data, IMessageResult *_result)
  2807. : data(_data), result(_result)
  2808. {
  2809. }
  2810. virtual bool atEOF() const
  2811. {
  2812. return data.length()==0;
  2813. }
  2814. virtual bool isSerialized() const
  2815. {
  2816. return false;
  2817. }
  2818. virtual const void * getNext(int length)
  2819. {
  2820. if (!data.length())
  2821. return NULL;
  2822. const void *ret = data.item(0);
  2823. data.remove(0);
  2824. return ret;
  2825. }
  2826. };
  2827. // MORE - should possibly move more over to the lazy version used in indexread?
  2828. class CRowArrayMessageResult : implements IMessageResult, public CInterface
  2829. {
  2830. ConstPointerArray data;
  2831. IRowManager &rowManager;
  2832. bool variableSize;
  2833. public:
  2834. IMPLEMENT_IINTERFACE;
  2835. CRowArrayMessageResult(IRowManager &_rowManager, bool _variableSize) : rowManager(_rowManager), variableSize(_variableSize)
  2836. {
  2837. }
  2838. ~CRowArrayMessageResult()
  2839. {
  2840. ReleaseRoxieRows(data);
  2841. }
  2842. virtual IMessageUnpackCursor *getCursor(IRowManager *rowMgr) const
  2843. {
  2844. CRowArrayMessageResult *_this = (CRowArrayMessageResult *) this;
  2845. return new CRowArrayMessageUnpackCursor(_this->data, _this);
  2846. }
  2847. virtual const void *getMessageHeader(unsigned &length) const
  2848. {
  2849. throwUnexpected(); // should never get called - I don't have a header available
  2850. }
  2851. virtual const void *getMessageMetadata(unsigned &length) const
  2852. {
  2853. length = 0;
  2854. return NULL;
  2855. }
  2856. virtual void discard() const
  2857. {
  2858. throwUnexpected();
  2859. }
  2860. void append(const void *row)
  2861. {
  2862. data.append(row);
  2863. }
  2864. };
  2865. void throwRemoteException(IMessageUnpackCursor *extra)
  2866. {
  2867. RecordLengthType *rowlen = (RecordLengthType *) extra->getNext(sizeof(RecordLengthType));
  2868. if (rowlen)
  2869. {
  2870. char *xml = (char *) extra->getNext(*rowlen);
  2871. ReleaseRoxieRow(rowlen);
  2872. Owned<IPropertyTree> p = createPTreeFromXMLString(xml, ipt_fast);
  2873. ReleaseRoxieRow(xml);
  2874. unsigned code = p->getPropInt("Code", 0);
  2875. const char *msg = p->queryProp("Message");
  2876. if (!msg)
  2877. msg = xml;
  2878. throw MakeStringException(code, "%s", msg);
  2879. }
  2880. throwUnexpected();
  2881. }
  2882. class CRemoteResultAdaptor : implements IEngineRowStream, implements IFinalRoxieInput, implements IExceptionHandler, public CInterface
  2883. {
  2884. friend class CRemoteResultMerger;
  2885. class CRemoteResultMerger
  2886. {
  2887. class HeapEntry : public CInterface
  2888. {
  2889. private:
  2890. CRemoteResultAdaptor &adaptor;
  2891. IMessageUnpackCursor *cursor;
  2892. public:
  2893. const void *current;
  2894. bool isLast;
  2895. bool lastIsComplete;
  2896. IRoxieServerQueryPacket *packet;
  2897. unsigned seq;
  2898. public:
  2899. inline const void *noteResult(IMessageUnpackCursor *_cursor, bool _lastIsComplete)
  2900. {
  2901. cursor = _cursor;
  2902. lastIsComplete = _lastIsComplete;
  2903. return next();
  2904. }
  2905. public:
  2906. HeapEntry(CRemoteResultAdaptor &_adaptor, IRoxieServerQueryPacket *_packet, unsigned _seq) : adaptor(_adaptor), packet(_packet), seq(_seq)
  2907. {
  2908. cursor = NULL;
  2909. current = NULL;
  2910. isLast = false;
  2911. lastIsComplete = true;
  2912. }
  2913. ~HeapEntry()
  2914. {
  2915. ::Release(packet);
  2916. ::Release(cursor);
  2917. ReleaseRoxieRow(current);
  2918. }
  2919. bool isCompleteMatch() const
  2920. {
  2921. if (!isLast || lastIsComplete)
  2922. return true;
  2923. else
  2924. return false;
  2925. }
  2926. const void *next()
  2927. {
  2928. if (cursor)
  2929. {
  2930. ReleaseClearRoxieRow(current);
  2931. current = adaptor.getRow(cursor);
  2932. isLast = cursor->atEOF();
  2933. if (!current)
  2934. {
  2935. cursor->Release();
  2936. cursor = NULL;
  2937. }
  2938. }
  2939. return current;
  2940. }
  2941. unsigned skipTo(IRangeCompare *compare, const void *seek, unsigned numFields, bool requireExactMatch)
  2942. {
  2943. // MORE - This loop should possibly be a binchop... though it's not absolutely clear that is true (depends on term frequencies)
  2944. unsigned skipped = 0;
  2945. for (;;)
  2946. {
  2947. int c = compare->docompare(current, seek, numFields);
  2948. //If larger than the seek values, then we may be allowed to return an inexact match,
  2949. //if equal then it is required to be an exact match,
  2950. if (c > 0)
  2951. {
  2952. if (!requireExactMatch || isCompleteMatch())
  2953. break;
  2954. }
  2955. else if ((c == 0) && isCompleteMatch())
  2956. break;
  2957. skipped++;
  2958. if (!next())
  2959. break;
  2960. }
  2961. return skipped;
  2962. }
  2963. };
  2964. CRemoteResultAdaptor &adaptor;
  2965. CIArrayOf<HeapEntry> heapEntries;
  2966. UnsignedArray heap;
  2967. IRowManager *rowManager;
  2968. unsigned numPending;
  2969. unsigned numFields;
  2970. bool endSeen;
  2971. bool remakePending;
  2972. IRangeCompare *compare;
  2973. bool deferredContinuation;
  2974. inline int doCompare(unsigned l, unsigned r)
  2975. {
  2976. int ret = compare->docompare(heapEntries.item(l).current, heapEntries.item(r).current, numFields);
  2977. if (!ret) ret = heapEntries.item(l).seq - heapEntries.item(r).seq;
  2978. return ret;
  2979. }
  2980. void makeHeap()
  2981. {
  2982. /* Permute blocks to establish the heap property
  2983. For each element p, the children are p*2+1 and p*2+2 (provided these are in range)
  2984. The children of p must both be greater than or equal to p
  2985. The parent of a child c is given by p = (c-1)/2
  2986. */
  2987. unsigned i;
  2988. unsigned n = heap.length();
  2989. unsigned *s = heap.getArray();
  2990. for (i=1; i<n; i++)
  2991. {
  2992. unsigned r = s[i];
  2993. int c = i; /* child */
  2994. while (c > 0)
  2995. {
  2996. int p = (c-1)/2; /* parent */
  2997. if ( doCompare( s[c], s[p] ) >= 0 )
  2998. break;
  2999. s[c] = s[p];
  3000. s[p] = r;
  3001. c = p;
  3002. }
  3003. }
  3004. remakePending = false;
  3005. }
  3006. void remakeHeap()
  3007. {
  3008. /* The row associated with block[0] will have changed
  3009. This code restores the heap property
  3010. */
  3011. unsigned p = 0; /* parent */
  3012. unsigned n = heap.length();
  3013. unsigned *s = heap.getArray();
  3014. while (1)
  3015. {
  3016. unsigned c = p*2 + 1; /* child */
  3017. if ( c >= n )
  3018. break;
  3019. /* Select smaller child */
  3020. if ( c+1 < n && doCompare( s[c+1], s[c] ) < 0 ) c += 1;
  3021. /* If child is greater or equal than parent then we are done */
  3022. if ( doCompare( s[c], s[p] ) >= 0 )
  3023. break;
  3024. /* Swap parent and child */
  3025. unsigned r = s[c];
  3026. s[c] = s[p];
  3027. s[p] = r;
  3028. /* child becomes parent */
  3029. p = c;
  3030. }
  3031. remakePending = false;
  3032. }
  3033. void append(IRoxieServerQueryPacket *p, unsigned seq)
  3034. {
  3035. HeapEntry &h = *new HeapEntry(adaptor, LINK(p), seq);
  3036. IMessageResult *result = p->queryResult();
  3037. assertex(result);
  3038. if (h.noteResult(result->getCursor(rowManager), isCompleteMatchFlag(result)))
  3039. {
  3040. heapEntries.append(h);
  3041. heap.append(heap.ordinality());
  3042. }
  3043. else
  3044. h.Release();
  3045. }
  3046. void removeHeap(unsigned idx)
  3047. {
  3048. heapEntries.remove(idx);
  3049. ForEachItemIn(i, heap)
  3050. {
  3051. unsigned v = heap.item(i);
  3052. assertex(v != idx);
  3053. if (v > idx)
  3054. heap.replace(v-1, i);
  3055. }
  3056. }
  3057. bool isCompleteMatchFlag(IMessageResult *result)
  3058. {
  3059. unsigned metaLen;
  3060. const byte *metaInfo = (const byte *) result->getMessageMetadata(metaLen);
  3061. if (metaLen)
  3062. {
  3063. unsigned short continuationLen = *(unsigned short *) metaInfo;
  3064. if (continuationLen >= sizeof(bool))
  3065. {
  3066. metaInfo += sizeof(unsigned short);
  3067. return *(bool *) metaInfo;
  3068. }
  3069. }
  3070. return true; // if no continuation info, last row was complete.
  3071. }
  3072. public:
  3073. CRemoteResultMerger(CRemoteResultAdaptor &_adaptor) : adaptor(_adaptor)
  3074. {
  3075. init(NULL, NULL);
  3076. }
  3077. void init(ISteppingMeta *meta, IRowManager *_rowManager)
  3078. {
  3079. if (meta)
  3080. {
  3081. numFields = meta->getNumFields();
  3082. compare = meta->queryCompare();
  3083. }
  3084. else
  3085. {
  3086. numFields = 0;
  3087. compare = NULL;
  3088. }
  3089. rowManager = _rowManager;
  3090. numPending = 0;
  3091. endSeen = false;
  3092. remakePending = false;
  3093. deferredContinuation = false;
  3094. }
  3095. void reset()
  3096. {
  3097. heapEntries.kill();
  3098. heap.kill();
  3099. numPending = 0;
  3100. endSeen = false;
  3101. remakePending = false;
  3102. deferredContinuation = false;
  3103. }
  3104. inline bool noteEndSeen()
  3105. {
  3106. bool hadSeen = endSeen;
  3107. if (!endSeen)
  3108. makeHeap();
  3109. endSeen = true;
  3110. return !hadSeen;
  3111. }
  3112. void noteResult(IRoxieServerQueryPacket *p, unsigned seq)
  3113. {
  3114. if (!p->isContinuation())
  3115. append(p, seq);
  3116. else
  3117. {
  3118. ForEachItemIn(idx, heapEntries)
  3119. {
  3120. HeapEntry &h = heapEntries.item(idx);
  3121. if (h.packet == p)
  3122. {
  3123. IMessageResult *result = p->queryResult();
  3124. if (!h.noteResult(result->getCursor(rowManager), isCompleteMatchFlag(result)))
  3125. {
  3126. heap.zap(idx);
  3127. removeHeap(idx);
  3128. }
  3129. numPending--;
  3130. if (!numPending)
  3131. makeHeap();
  3132. return;
  3133. }
  3134. }
  3135. }
  3136. // If we get here it must be a continuation for one that I have not yet consumed... we don't need to do anything.
  3137. return;
  3138. }
  3139. unsigned skipRows(unsigned &idx, const void *seek, const void *rawSeek, unsigned numFields, unsigned seekLen, const SmartStepExtra & stepExtra)
  3140. {
  3141. HeapEntry &entry = heapEntries.item(idx);
  3142. unsigned skipped = entry.current ? entry.skipTo(compare, seek, numFields, !stepExtra.returnMismatches()) : 0;
  3143. if (!entry.current)
  3144. {
  3145. IRoxieServerQueryPacket *continuation = entry.packet->queryContinuation();
  3146. if (continuation)
  3147. {
  3148. continuation->Link();
  3149. entry.packet->Release();
  3150. entry.packet = continuation;
  3151. if (continuation->hasResult())
  3152. {
  3153. IMessageResult *result = continuation->queryResult();
  3154. bool lastIsCompleteMatch = isCompleteMatchFlag(result);
  3155. entry.noteResult(result->getCursor(rowManager), lastIsCompleteMatch);
  3156. }
  3157. else
  3158. {
  3159. if (continuation->isDelayed())
  3160. {
  3161. continuation->setDelayed(false);
  3162. MemoryBuffer serializedSkip;
  3163. adaptor.activity.serializeSkipInfo(serializedSkip, seekLen, rawSeek, numFields, seek, stepExtra);
  3164. continuation->setPacket(continuation->queryPacket()->insertSkipData(serializedSkip.length(), serializedSkip.toByteArray()));
  3165. ROQ->sendPacket(continuation->queryPacket(), adaptor.activity.queryLogCtx());
  3166. adaptor.sentsome.signal();
  3167. }
  3168. numPending++;
  3169. }
  3170. }
  3171. else
  3172. {
  3173. heap.zap(idx);
  3174. removeHeap(idx);
  3175. idx--;
  3176. }
  3177. }
  3178. return skipped;
  3179. }
  3180. const void * nextRowGE(const void * seek, const void *rawSeek, unsigned numFields, unsigned seeklen, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  3181. {
  3182. // We discard all rows < seekval from all entries in heap
  3183. // If this results in additional slave requests, we return NULL so that we can wait for them
  3184. // If not, we rebuild the heap (if any were skipped) and return the first row
  3185. deferredContinuation = false;
  3186. if (heap.length())
  3187. {
  3188. unsigned skipped = 0;
  3189. unsigned idx = 0;
  3190. while(heapEntries.isItem(idx))
  3191. {
  3192. skipped += skipRows(idx, seek, rawSeek, numFields, seeklen, stepExtra);
  3193. idx++;
  3194. }
  3195. if (numPending)
  3196. return NULL; // can't answer yet, need more results from slaves
  3197. else
  3198. {
  3199. if (skipped)
  3200. makeHeap();
  3201. return next(wasCompleteMatch, stepExtra);
  3202. }
  3203. }
  3204. else
  3205. return NULL;
  3206. }
  3207. bool doContinuation(HeapEntry &topEntry, bool canDefer)
  3208. {
  3209. IRoxieServerQueryPacket *continuation = topEntry.packet->queryContinuation();
  3210. if (continuation)
  3211. {
  3212. if (continuation->isDelayed() && canDefer)
  3213. {
  3214. if (adaptor.activity.queryLogCtx().queryTraceLevel() > 10)
  3215. adaptor.activity.queryLogCtx().CTXLOG("Deferring continuation");
  3216. deferredContinuation = true;
  3217. }
  3218. else
  3219. {
  3220. deferredContinuation = false;
  3221. continuation->Link();
  3222. topEntry.packet->Release();
  3223. topEntry.packet = continuation;
  3224. if (continuation->hasResult())
  3225. {
  3226. IMessageResult *result = continuation->queryResult();
  3227. bool lastIsCompleteMatch = isCompleteMatchFlag(result);
  3228. topEntry.noteResult(result->getCursor(rowManager), lastIsCompleteMatch);
  3229. }
  3230. else
  3231. {
  3232. if (continuation->isDelayed()) // has the continuation been requested yet?
  3233. {
  3234. continuation->Link();
  3235. topEntry.packet->Release();
  3236. topEntry.packet = continuation;
  3237. continuation->setDelayed(false);
  3238. if (adaptor.activity.queryLogCtx().queryTraceLevel() > 10)
  3239. adaptor.activity.queryLogCtx().CTXLOG("About to send continuation, from doContinuation");
  3240. ROQ->sendPacket(continuation->queryPacket(), adaptor.activity.queryLogCtx());
  3241. adaptor.sentsome.signal();
  3242. }
  3243. numPending++; // we are waiting for one that is already in flight
  3244. }
  3245. }
  3246. return true; // next not known yet
  3247. }
  3248. else
  3249. return false;
  3250. }
  3251. const void *next(bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  3252. {
  3253. OwnedConstRoxieRow ret;
  3254. if (heap.length())
  3255. {
  3256. if (deferredContinuation)
  3257. {
  3258. unsigned top = heap.item(0);
  3259. HeapEntry &topEntry = heapEntries.item(top);
  3260. doContinuation(topEntry, false);
  3261. return NULL;
  3262. }
  3263. if (remakePending)
  3264. remakeHeap();
  3265. unsigned top = heap.item(0);
  3266. HeapEntry &topEntry = heapEntries.item(top);
  3267. ret.set(topEntry.current);
  3268. wasCompleteMatch = topEntry.isCompleteMatch();
  3269. const void *next = topEntry.next();
  3270. if (!next)
  3271. {
  3272. if (!doContinuation(topEntry, stepExtra.returnMismatches()))
  3273. {
  3274. unsigned last = heap.popGet();
  3275. if (heap.length())
  3276. heap.replace(last, 0);
  3277. removeHeap(top);
  3278. }
  3279. }
  3280. remakePending = true;
  3281. }
  3282. return ret.getClear();
  3283. }
  3284. bool ready()
  3285. {
  3286. return endSeen && numPending == 0;
  3287. }
  3288. };
  3289. IRoxieServerQueryPacket *createRoxieServerQueryPacket(IRoxieQueryPacket *p, bool &cached)
  3290. {
  3291. if (serverSideCache && !debugContext)
  3292. {
  3293. IRoxieServerQueryPacket *ret = serverSideCache->findCachedResult(activity.queryLogCtx(), p);
  3294. if (ret)
  3295. {
  3296. p->Release();
  3297. cached = true;
  3298. return ret;
  3299. }
  3300. }
  3301. cached = false;
  3302. return new CRoxieServerQueryPacket(p);
  3303. }
  3304. #ifdef _DEBUG
  3305. void dumpPending()
  3306. {
  3307. CriticalBlock b(pendingCrit);
  3308. ForEachItemIn(idx, pending)
  3309. {
  3310. IRoxieServerQueryPacket &p = pending.item(idx);
  3311. StringBuffer s;
  3312. unsigned __int64 dummy;
  3313. if (p.isEnd())
  3314. s.append("END");
  3315. else if (p.isLimit(dummy, dummy, dummy))
  3316. s.append("LIMIT");
  3317. else
  3318. {
  3319. IRoxieQueryPacket *i = p.queryPacket();
  3320. s.appendf("%s", p.hasResult() ? "COMPLETE " : "PENDING ");
  3321. if (i)
  3322. {
  3323. RoxiePacketHeader &header = i->queryHeader();
  3324. header.toString(s);
  3325. }
  3326. }
  3327. DBGLOG("Pending %d %s", idx, s.str());
  3328. }
  3329. }
  3330. #endif
  3331. void abortPending()
  3332. {
  3333. CriticalBlock b(pendingCrit);
  3334. ForEachItemIn(idx, pending)
  3335. {
  3336. IRoxieServerQueryPacket &p = pending.item(idx);
  3337. if (!p.hasResult())
  3338. {
  3339. IRoxieQueryPacket *i = p.queryPacket();
  3340. if (i)
  3341. {
  3342. RoxiePacketHeader &header = i->queryHeader();
  3343. ROQ->sendAbort(header, activity.queryLogCtx());
  3344. }
  3345. }
  3346. }
  3347. pending.kill();
  3348. }
  3349. void checkDelayed()
  3350. {
  3351. if (ctx->queryDebugContext() && ctx->queryDebugContext()->getExecuteSequentially())
  3352. {
  3353. bool allDelayed = true;
  3354. CriticalBlock b(pendingCrit);
  3355. unsigned sendIdx = (unsigned) -1;
  3356. ForEachItemIn(idx, pending)
  3357. {
  3358. IRoxieServerQueryPacket &p = pending.item(idx);
  3359. if (p.queryPacket())
  3360. {
  3361. if (p.isDelayed())
  3362. {
  3363. if (sendIdx == (unsigned) -1)
  3364. sendIdx = idx;
  3365. }
  3366. else if (!p.hasResult())
  3367. {
  3368. allDelayed = false;
  3369. break;
  3370. }
  3371. }
  3372. }
  3373. if (allDelayed && sendIdx != (unsigned) -1)
  3374. {
  3375. if (activity.queryLogCtx().queryTraceLevel() > 10)
  3376. activity.queryLogCtx().CTXLOG("About to send debug-deferred from next");
  3377. pending.item(sendIdx).setDelayed(false);
  3378. ROQ->sendPacket(pending.item(sendIdx).queryPacket(), activity.queryLogCtx());
  3379. sentsome.signal();
  3380. }
  3381. }
  3382. else if (deferredStart)
  3383. {
  3384. CriticalBlock b(pendingCrit);
  3385. ForEachItemIn(idx, pending)
  3386. {
  3387. IRoxieServerQueryPacket &p = pending.item(idx);
  3388. if (p.isDelayed())
  3389. {
  3390. if (activity.queryLogCtx().queryTraceLevel() > 10)
  3391. activity.queryLogCtx().CTXLOG("About to send deferred start from next");
  3392. p.setDelayed(false);
  3393. ROQ->sendPacket(p.queryPacket(), activity.queryLogCtx());
  3394. sentsome.signal();
  3395. }
  3396. }
  3397. deferredStart = false;
  3398. }
  3399. }
  3400. void retryPending()
  3401. {
  3402. CriticalBlock b(pendingCrit);
  3403. checkDelayed();
  3404. ForEachItemIn(idx, pending)
  3405. {
  3406. IRoxieServerQueryPacket &p = pending.item(idx);
  3407. if (!p.hasResult() && !p.isDelayed())
  3408. {
  3409. IRoxieQueryPacket *i = p.queryPacket();
  3410. if (i)
  3411. {
  3412. if (!i->queryHeader().retry())
  3413. {
  3414. StringBuffer s;
  3415. 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());
  3416. activity.queryLogCtx().logOperatorException(E, __FILE__, __LINE__, "CRemoteResultAdaptor::retry");
  3417. throw E;
  3418. }
  3419. if (!localSlave)
  3420. {
  3421. ROQ->sendPacket(i, activity.queryLogCtx());
  3422. atomic_inc(&retriesSent);
  3423. }
  3424. }
  3425. }
  3426. }
  3427. }
  3428. class ChannelBuffer
  3429. {
  3430. protected:
  3431. unsigned bufferLeft;
  3432. MemoryBuffer buffer;
  3433. char *nextBuf;
  3434. unsigned overflowSequence;
  3435. unsigned channel; // == bonded channel
  3436. bool needsFlush;
  3437. InterruptableSemaphore flowController;
  3438. const CRemoteResultAdaptor &owner;
  3439. CriticalSection crit;
  3440. public:
  3441. ChannelBuffer(const CRemoteResultAdaptor &_owner, unsigned _channel) : owner(_owner), channel(_channel), flowController(perChannelFlowLimit)
  3442. {
  3443. overflowSequence = 0;
  3444. needsFlush = false;
  3445. bufferLeft = 0;
  3446. nextBuf = NULL;
  3447. }
  3448. void init(unsigned minSize)
  3449. {
  3450. assertex(!buffer.length());
  3451. if (minSize < MIN_PAYLOAD_SIZE)
  3452. minSize = MIN_PAYLOAD_SIZE;
  3453. unsigned headerSize = sizeof(RoxiePacketHeader)+owner.headerLength();
  3454. unsigned bufferSize = headerSize+minSize;
  3455. if (bufferSize < mtu_size)
  3456. bufferSize = mtu_size;
  3457. buffer.reserveTruncate(bufferSize);
  3458. bufferLeft = bufferSize - headerSize;
  3459. assertex(buffer.toByteArray());
  3460. nextBuf = (char *) buffer.toByteArray() + headerSize;
  3461. needsFlush = false;
  3462. }
  3463. inline IRoxieQueryPacket *flush()
  3464. {
  3465. CriticalBlock cb(crit);
  3466. Owned<IRoxieQueryPacket> ret;
  3467. if (needsFlush)
  3468. {
  3469. buffer.setLength(nextBuf - buffer.toByteArray());
  3470. RoxiePacketHeader *h = (RoxiePacketHeader *) buffer.toByteArray();
  3471. h->init(owner.remoteId, owner.ruid, channel, overflowSequence);
  3472. //patch logPrefix, cachedContext and parent extract into the place reserved in the message buffer
  3473. byte * tgt = (byte*)(h+1);
  3474. owner.copyHeader(tgt, channel);
  3475. ret.setown(createRoxiePacket(buffer));
  3476. if (overflowSequence == OVERFLOWSEQUENCE_MAX)
  3477. overflowSequence = 1; // don't wrap to 0 - that is a bit special
  3478. else
  3479. overflowSequence++;
  3480. needsFlush = false;
  3481. bufferLeft = 0;
  3482. if (owner.flowControlled)
  3483. {
  3484. CriticalUnblock cub(crit);
  3485. while (!flowController.wait(1000))
  3486. {
  3487. StringBuffer s;
  3488. owner.activity.queryLogCtx().CTXLOG("Channel %d blocked by flow control: %s", channel, h->toString(s).str());
  3489. }
  3490. }
  3491. }
  3492. return ret.getClear();
  3493. }
  3494. inline void signal()
  3495. {
  3496. if (owner.flowControlled)
  3497. flowController.signal();
  3498. }
  3499. inline void interrupt(IException *e)
  3500. {
  3501. flowController.interrupt(e);
  3502. }
  3503. inline void *getBuffer(unsigned size)
  3504. {
  3505. CriticalBlock cb(crit);
  3506. if (bufferLeft >= size)
  3507. {
  3508. needsFlush = true;
  3509. void * ret = nextBuf;
  3510. nextBuf += size;
  3511. bufferLeft -= size;
  3512. return ret;
  3513. }
  3514. else if (!needsFlush)
  3515. {
  3516. init(size);
  3517. return getBuffer(size);
  3518. }
  3519. else if (owner.mergeOrder)
  3520. {
  3521. return buffer.reserve(size); // whole query needs to go as single packet if we are to merge
  3522. }
  3523. else
  3524. return NULL; // will force it to flush and start a new packet
  3525. }
  3526. };
  3527. private:
  3528. friend class CRemoteResultMerger;
  3529. bool allread;
  3530. bool contextCached;
  3531. bool preserveOrder;
  3532. bool eogSent = false;
  3533. InterruptableSemaphore sentsome;
  3534. Owned <IMessageCollator> mc;
  3535. Owned<IMessageUnpackCursor> mu;
  3536. Owned<IMessageResult> mr;
  3537. ChannelBuffer **buffers;
  3538. IHThorArg &helper;
  3539. unsigned __int64 stopAfter;
  3540. unsigned resendSequence;
  3541. IHThorArg *colocalArg;
  3542. IArrayOf<IRoxieServerQueryPacket> pending;
  3543. CriticalSection pendingCrit;
  3544. IRoxieServerSideCache *serverSideCache;
  3545. unsigned sentSequence;
  3546. Owned<IOutputRowDeserializer> deserializer;
  3547. Owned<IEngineRowAllocator> rowAllocator;
  3548. CRemoteResultMerger merger;
  3549. // this is only used to avoid recreating a bufferStream for each row. A better solution may be needed
  3550. MemoryBuffer tempRowBuffer;
  3551. Owned<ISerialStream> bufferStream;
  3552. CThorStreamDeserializerSource rowSource;
  3553. protected:
  3554. IRowManager *rowManager;
  3555. unsigned __int64 rowLimit;
  3556. unsigned __int64 keyedLimit;
  3557. IRoxieServerErrorHandler *errorHandler;
  3558. CachedOutputMetaData meta;
  3559. public:
  3560. ISteppingMeta *mergeOrder;
  3561. IRoxieSlaveContext *ctx;
  3562. IDebuggableContext *debugContext;
  3563. IRoxieServerActivity &activity;
  3564. unsigned parentExtractSize;
  3565. const byte * parentExtract;
  3566. bool flowControlled;
  3567. bool deferredStart;
  3568. MemoryBuffer logInfo;
  3569. MemoryBuffer cachedContext;
  3570. const RemoteActivityId &remoteId;
  3571. ruid_t ruid;
  3572. mutable CriticalSection buffersCrit;
  3573. unsigned processed;
  3574. cycle_t totalCycles;
  3575. bool timeActivities;
  3576. //private: //vc6 doesn't like this being private yet accessed by nested class...
  3577. const void *getRow(IMessageUnpackCursor *mu)
  3578. {
  3579. if (!mu->isSerialized() || (meta.isFixedSize() && !deserializer))
  3580. return mu->getNext(meta.getFixedSize());
  3581. else
  3582. {
  3583. RecordLengthType *rowlen = (RecordLengthType *) mu->getNext(sizeof(RecordLengthType));
  3584. if (rowlen)
  3585. {
  3586. RecordLengthType len = *rowlen;
  3587. ReleaseRoxieRow(rowlen);
  3588. const void *slaveRec = mu->getNext(len);
  3589. if (deserializer && mu->isSerialized())
  3590. {
  3591. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  3592. tempRowBuffer.setBuffer(len, const_cast<void *>(slaveRec), false);
  3593. size_t outsize = deserializer->deserialize(rowBuilder, rowSource);
  3594. ReleaseRoxieRow(slaveRec);
  3595. return rowBuilder.finalizeRowClear(outsize);
  3596. }
  3597. else
  3598. return slaveRec;
  3599. }
  3600. else
  3601. return NULL;
  3602. }
  3603. }
  3604. private:
  3605. ChannelBuffer *queryChannelBuffer(unsigned channel, bool force=false)
  3606. {
  3607. CriticalBlock cb(buffersCrit);
  3608. ChannelBuffer *b = buffers[channel];
  3609. if (!b && force)
  3610. {
  3611. if (!contextCached)
  3612. {
  3613. logInfo.clear();
  3614. unsigned char loggingFlags = LOGGING_FLAGSPRESENT | LOGGING_TRACELEVELSET;
  3615. unsigned char ctxTraceLevel = activity.queryLogCtx().queryTraceLevel() + 1; // Avoid passing a 0
  3616. const QueryOptions &options = ctx->queryOptions();
  3617. if (activity.queryLogCtx().isIntercepted())
  3618. loggingFlags |= LOGGING_INTERCEPTED;
  3619. if (options.timeActivities)
  3620. loggingFlags |= LOGGING_TIMEACTIVITIES;
  3621. if (activity.queryLogCtx().isBlind())
  3622. loggingFlags |= LOGGING_BLIND;
  3623. if (options.checkingHeap)
  3624. loggingFlags |= LOGGING_CHECKINGHEAP;
  3625. if (ctx->queryWorkUnit())
  3626. loggingFlags |= LOGGING_WUID;
  3627. if (debugContext)
  3628. {
  3629. loggingFlags |= LOGGING_DEBUGGERACTIVE;
  3630. logInfo.append(loggingFlags).append(ctxTraceLevel);
  3631. MemoryBuffer bpInfo;
  3632. debugContext->serialize(bpInfo);
  3633. bpInfo.append((__uint64)(memsize_t) &activity);
  3634. logInfo.append((unsigned short) bpInfo.length());
  3635. logInfo.append(bpInfo.length(), bpInfo.toByteArray());
  3636. }
  3637. else
  3638. logInfo.append(loggingFlags).append(ctxTraceLevel);
  3639. StringBuffer logPrefix;
  3640. activity.queryLogCtx().getLogPrefix(logPrefix);
  3641. logInfo.append(logPrefix);
  3642. activity.serializeCreateStartContext(cachedContext.clear());
  3643. activity.serializeExtra(cachedContext);
  3644. if (activity.queryVarFileInfo())
  3645. {
  3646. activity.queryVarFileInfo()->queryTimeStamp().serialize(cachedContext);
  3647. cachedContext.append(activity.queryVarFileInfo()->queryCheckSum());
  3648. }
  3649. contextCached = true;
  3650. }
  3651. b = buffers[channel] = new ChannelBuffer(*this, channel);
  3652. }
  3653. return b;
  3654. }
  3655. void processRow(const void *got)
  3656. {
  3657. processed++;
  3658. if (processed > rowLimit)
  3659. {
  3660. ReleaseRoxieRow(got);
  3661. errorHandler->onLimitExceeded(false); // NOTE - should throw exception
  3662. throwUnexpected();
  3663. }
  3664. else if (processed > keyedLimit)
  3665. {
  3666. ReleaseRoxieRow(got);
  3667. errorHandler->onLimitExceeded(true); // NOTE - should throw exception
  3668. throwUnexpected();
  3669. }
  3670. }
  3671. public:
  3672. IMPLEMENT_IINTERFACE;
  3673. CRemoteResultAdaptor(IRoxieSlaveContext *_ctx, IRoxieServerErrorHandler *_errorHandler, const RemoteActivityId &_remoteId, IOutputMetaData *_meta, IHThorArg &_helper, IRoxieServerActivity &_activity, bool _preserveOrder, bool _flowControlled)
  3674. : remoteId(_remoteId), meta(_meta), activity(_activity), helper(_helper), preserveOrder(_preserveOrder), flowControlled(_flowControlled), merger(*this)
  3675. {
  3676. ctx = _ctx;
  3677. errorHandler = _errorHandler;
  3678. colocalArg = NULL;
  3679. allread = false;
  3680. ruid = 0;
  3681. rowLimit = (unsigned __int64) -1;
  3682. keyedLimit = (unsigned __int64) -1;
  3683. contextCached = false;
  3684. stopAfter = I64C(0x7FFFFFFFFFFFFFFF);
  3685. buffers = new ChannelBuffer*[numChannels+1];
  3686. memset(buffers, 0, (numChannels+1)*sizeof(ChannelBuffer *));
  3687. parentExtractSize = 0;
  3688. rowManager = NULL;
  3689. parentExtract = NULL;
  3690. debugContext = NULL;
  3691. mergeOrder = NULL;
  3692. deferredStart = false;
  3693. processed = 0;
  3694. sentSequence = 0;
  3695. resendSequence = 0;
  3696. totalCycles = 0;
  3697. serverSideCache = activity.queryServerSideCache();
  3698. bufferStream.setown(createMemoryBufferSerialStream(tempRowBuffer));
  3699. rowSource.setStream(bufferStream);
  3700. timeActivities = defaultTimeActivities;
  3701. }
  3702. ~CRemoteResultAdaptor()
  3703. {
  3704. if (mc)
  3705. {
  3706. ROQ->queryReceiveManager()->detachCollator(mc);
  3707. mc.clear();
  3708. }
  3709. for (unsigned channel = 0; channel <= numChannels; channel++)
  3710. {
  3711. delete(buffers[channel]);
  3712. }
  3713. delete [] buffers;
  3714. }
  3715. void setMeta(IOutputMetaData *newmeta)
  3716. {
  3717. meta.set(newmeta);
  3718. }
  3719. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { assertex(whichInput==0); return this; }
  3720. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { assertex(idx==0); return nullptr; }
  3721. virtual IRoxieServerActivity *queryActivity()
  3722. {
  3723. return &activity;
  3724. }
  3725. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  3726. {
  3727. return NULL;
  3728. }
  3729. void setMergeInfo(ISteppingMeta *_mergeOrder)
  3730. {
  3731. mergeOrder = _mergeOrder;
  3732. deferredStart = true;
  3733. }
  3734. void send(IRoxieQueryPacket *p)
  3735. {
  3736. if (p)
  3737. {
  3738. Linked<IRoxieQueryPacket> saver(p); // avoids a race with abortPending, without keeping pendingCrit locked over the send which we might prefer not to
  3739. assertex(p->queryHeader().uid==ruid);
  3740. // MORE: Maybe we should base the fastlane flag on some other
  3741. // criteria !! (i.e A Roxie server prediction based on the
  3742. // activity type/activity behaviour/expected reply size .. etc).
  3743. //
  3744. // Currently (code below) based on high priority, seq=0, and none-child activity.
  3745. // But this could still cause too many reply packets on the fatlane
  3746. // (higher priority output Q), which may cause the activities on the
  3747. // low priority output Q to not get service on time.
  3748. if ((colocalArg == 0) && // not a child query activity??
  3749. (p->queryHeader().activityId & (ROXIE_SLA_PRIORITY | ROXIE_HIGH_PRIORITY)) &&
  3750. (p->queryHeader().overflowSequence == 0) &&
  3751. (p->queryHeader().continueSequence & ~CONTINUE_SEQUENCE_SKIPTO)==0)
  3752. p->queryHeader().retries |= ROXIE_FASTLANE;
  3753. if (p->queryHeader().channel)
  3754. {
  3755. bool cached = false;
  3756. IRoxieServerQueryPacket *rsqp = createRoxieServerQueryPacket(p, cached);
  3757. if (deferredStart)
  3758. rsqp->setDelayed(true);
  3759. rsqp->setSequence(sentSequence++);
  3760. {
  3761. CriticalBlock b(pendingCrit);
  3762. pending.append(*rsqp);
  3763. }
  3764. if (!deferredStart)
  3765. {
  3766. if (!cached)
  3767. ROQ->sendPacket(p, activity.queryLogCtx());
  3768. sentsome.signal();
  3769. }
  3770. }
  3771. else
  3772. {
  3773. // 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
  3774. // Need to add first, then send
  3775. unsigned i;
  3776. bool allCached = true;
  3777. for (i = 1; i <= numChannels; i++)
  3778. {
  3779. IRoxieQueryPacket *q = p->clonePacket(i);
  3780. bool thisChannelCached;
  3781. IRoxieServerQueryPacket *rsqp = createRoxieServerQueryPacket(q, thisChannelCached);
  3782. if (!thisChannelCached)
  3783. allCached = false;
  3784. rsqp->setSequence(sentSequence++);
  3785. if (deferredStart)
  3786. {
  3787. rsqp->setDelayed(true);
  3788. }
  3789. {
  3790. CriticalBlock b(pendingCrit);
  3791. pending.append(*rsqp);
  3792. }
  3793. if (!deferredStart)
  3794. sentsome.signal();
  3795. }
  3796. if (!allCached && !deferredStart)
  3797. ROQ->sendPacket(p, activity.queryLogCtx());
  3798. buffers[0]->signal(); // since replies won't come back on that channel...
  3799. p->Release();
  3800. }
  3801. }
  3802. }
  3803. void *getMem(unsigned partNo, unsigned fileNo, unsigned size)
  3804. {
  3805. unsigned channel = partNo ? getBondedChannel(partNo) : 0;
  3806. size += sizeof(PartNoType);
  3807. ChannelBuffer *b = queryChannelBuffer(channel, true);
  3808. char *buffer = (char *) b->getBuffer(size);
  3809. if (!buffer)
  3810. {
  3811. send(b->flush());
  3812. buffer = (char *) b->getBuffer(size);
  3813. }
  3814. PartNoType sp;
  3815. sp.partNo = partNo;
  3816. sp.fileNo = fileNo;
  3817. memcpy(buffer, &sp, sizeof(sp));
  3818. buffer += sizeof(sp);
  3819. return buffer;
  3820. }
  3821. void injectResult(IMessageResult *result)
  3822. {
  3823. IRoxieServerQueryPacket *f = new CRoxieServerQueryPacket(NULL);
  3824. f->setSequence(sentSequence++);
  3825. f->setResult(result);
  3826. CriticalBlock b(pendingCrit);
  3827. pending.append(*f);
  3828. sentsome.signal(); // MORE - arguably should only send if there is any point waking up the listener thread, to save context swicth
  3829. }
  3830. void flush()
  3831. {
  3832. for (unsigned channel = 0; channel <= numChannels; channel++)
  3833. {
  3834. ChannelBuffer *b = queryChannelBuffer(channel, false);
  3835. if (b)
  3836. send(b->flush());
  3837. }
  3838. }
  3839. void interruptBuffers(IException *e)
  3840. {
  3841. for (unsigned channel = 0; channel <= numChannels; channel++)
  3842. {
  3843. ChannelBuffer *b = queryChannelBuffer(channel, false);
  3844. if (b)
  3845. b->interrupt(LINK(e));
  3846. }
  3847. }
  3848. void senddone()
  3849. {
  3850. CriticalBlock b(pendingCrit);
  3851. pending.append(*new CRoxieServerQueryPacketEndMarker);
  3852. sentsome.signal();
  3853. }
  3854. bool fireException(IException *e)
  3855. {
  3856. {
  3857. CriticalBlock b(pendingCrit);
  3858. pending.append(*new CRoxieServerQueryPacketEndMarker);
  3859. }
  3860. interruptBuffers(e);
  3861. if (mc)
  3862. mc->interrupt(LINK(e));
  3863. sentsome.interrupt(e);
  3864. return true;
  3865. }
  3866. virtual void onCreate(IHThorArg *_colocalArg)
  3867. {
  3868. debugContext = ctx->queryDebugContext();
  3869. colocalArg = _colocalArg;
  3870. if (meta.needsSerializeDisk())
  3871. {
  3872. deserializer.setown(meta.createDiskDeserializer(ctx->queryCodeContext(), activity.queryId()));
  3873. rowAllocator.setown(activity.createRowAllocator(meta.queryOriginal()));
  3874. }
  3875. if (ctx->queryDebugContext() && ctx->queryDebugContext()->getExecuteSequentially())
  3876. deferredStart = true;
  3877. timeActivities = ctx->queryOptions().timeActivities;
  3878. }
  3879. virtual void onStart(unsigned _parentExtractSize, const byte * _parentExtract)
  3880. {
  3881. #ifdef TRACE_STARTSTOP
  3882. if (traceStartStop)
  3883. activity.queryLogCtx().CTXLOG("RRAonstart");
  3884. #endif
  3885. sentsome.reinit();
  3886. ruid = getNextRuid();
  3887. rowManager = &ctx->queryRowManager();
  3888. if (mergeOrder)
  3889. merger.init(mergeOrder, rowManager);
  3890. if (mc)
  3891. {
  3892. ROQ->queryReceiveManager()->detachCollator(mc); // Should never happen - implies someone forgot to call onReset!
  3893. }
  3894. mc.setown(ROQ->queryReceiveManager()->createMessageCollator(rowManager, ruid));
  3895. allread = false;
  3896. mu.clear();
  3897. contextCached = false;
  3898. processed = 0;
  3899. resendSequence = 0;
  3900. sentSequence = 0;
  3901. for (unsigned channel = 0; channel <= numChannels; channel++)
  3902. {
  3903. delete(buffers[channel]);
  3904. buffers[channel] = NULL;
  3905. }
  3906. flush();
  3907. parentExtractSize = _parentExtractSize;
  3908. parentExtract = _parentExtract;
  3909. }
  3910. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  3911. {
  3912. #ifdef TRACE_STARTSTOP
  3913. if (traceStartStop)
  3914. activity.queryLogCtx().CTXLOG("RRAstart");
  3915. #endif
  3916. activity.start(parentExtractSize, parentExtract, paused);
  3917. }
  3918. void setLimits(unsigned __int64 _rowLimit, unsigned __int64 _keyedLimit, unsigned __int64 _stopAfter)
  3919. {
  3920. if (ctx->queryProbeManager())
  3921. {
  3922. if (_rowLimit != (unsigned __int64) -1) ctx->queryProbeManager()->setNodePropertyInt(&activity, "rowLimit", _rowLimit);
  3923. if (_keyedLimit != (unsigned __int64) -1) ctx->queryProbeManager()->setNodePropertyInt(&activity, "keyedLimit", _keyedLimit);
  3924. if (_stopAfter != I64C(0x7FFFFFFFFFFFFFFF)) ctx->queryProbeManager()->setNodePropertyInt(&activity, "choosenLimit", _stopAfter);
  3925. }
  3926. {
  3927. CriticalBlock b(pendingCrit);
  3928. if (pending.length())
  3929. {
  3930. #ifdef _DEBUG
  3931. dumpPending(); // MORE - only defined in debug build - could have put the ifdef inside the dumpPending method
  3932. #endif
  3933. assertex(pending.length()==0);
  3934. }
  3935. pending.append(*new CRoxieServerQueryPacketLimitMarker(_rowLimit, _keyedLimit, _stopAfter));
  3936. }
  3937. sentsome.signal();
  3938. rowLimit = _rowLimit;
  3939. keyedLimit = _keyedLimit;
  3940. stopAfter = _stopAfter;
  3941. }
  3942. virtual void stop()
  3943. {
  3944. #ifdef TRACE_STARTSTOP
  3945. if (traceStartStop)
  3946. activity.queryLogCtx().CTXLOG("RRAstop");
  3947. #endif
  3948. onStop();
  3949. activity.stop();
  3950. }
  3951. void onStop()
  3952. {
  3953. #ifdef TRACE_STARTSTOP
  3954. if (traceStartStop)
  3955. activity.queryLogCtx().CTXLOG("RRAonstop");
  3956. #endif
  3957. abortPending();
  3958. interruptBuffers(NULL);
  3959. sentsome.interrupt();
  3960. if (mc) // May not be set if start() chain threw exception
  3961. mc->interrupt();
  3962. }
  3963. virtual void reset()
  3964. {
  3965. #ifdef TRACE_STARTSTOP
  3966. if (traceStartStop)
  3967. activity.queryLogCtx().CTXLOG("RRAreset");
  3968. #endif
  3969. activity.reset();
  3970. onReset();
  3971. }
  3972. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  3973. {
  3974. // Make sure parent activity calls up the tree
  3975. PointerArrayOf<IEngineRowStream> instreams;
  3976. IStrandJunction *junction = activity.getOutputStreams(ctx, idx, instreams, consumerOptions, consumerOrdered, orderedCallbacks);
  3977. assertex (junction == NULL);
  3978. // I return a single strand (we could change that sometime I guess...)
  3979. streams.append(this);
  3980. return NULL;
  3981. }
  3982. virtual void resetEOF()
  3983. {
  3984. throwUnexpected();
  3985. }
  3986. virtual void onReset()
  3987. {
  3988. #ifdef TRACE_STARTSTOP
  3989. if (traceStartStop)
  3990. activity.queryLogCtx().CTXLOG("RRAonreset");
  3991. #endif
  3992. if (mc)
  3993. ROQ->queryReceiveManager()->detachCollator(mc);
  3994. merger.reset();
  3995. pending.kill();
  3996. if (mc && ctx)
  3997. ctx->addSlavesReplyLen(mc->queryBytesReceived());
  3998. mc.clear(); // Or we won't free memory for graphs that get recreated
  3999. mu.clear(); //ditto
  4000. deferredStart = false;
  4001. // NOTE: do NOT clear mergeOrder - this is set at create time not per child query
  4002. }
  4003. virtual IOutputMetaData * queryOutputMeta() const
  4004. {
  4005. return helper.queryOutputMeta();
  4006. }
  4007. virtual unsigned __int64 queryTotalCycles() const
  4008. {
  4009. return totalCycles;
  4010. }
  4011. const void * nextRowGE(const void *seek, const void *rawSeek, unsigned numFields, unsigned seekLen, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  4012. {
  4013. if (activity.queryLogCtx().queryTraceLevel() > 20)
  4014. {
  4015. StringBuffer recstr;
  4016. unsigned i;
  4017. for (i = 0; i < seekLen; i++)
  4018. {
  4019. recstr.appendf("%02x ", ((unsigned char *) rawSeek)[i]);
  4020. }
  4021. activity.queryLogCtx().CTXLOG("CRemoteResultAdaptor::nextRowGE(rawSeek=%s numFields=%d, seeklen=%d, returnMismatches=%d)", recstr.str(), numFields, seekLen, stepExtra.returnMismatches());
  4022. }
  4023. assertex(mergeOrder);
  4024. if (deferredStart)
  4025. {
  4026. CriticalBlock b(pendingCrit);
  4027. ForEachItemIn(idx, pending)
  4028. {
  4029. IRoxieServerQueryPacket &p = pending.item(idx);
  4030. if (p.isDelayed())
  4031. {
  4032. p.setDelayed(false);
  4033. if (activity.queryLogCtx().queryTraceLevel() > 10)
  4034. activity.queryLogCtx().CTXLOG("About to send deferred start from nextRowGE, setting requireExact to %d", !stepExtra.returnMismatches());
  4035. MemoryBuffer serializedSkip;
  4036. activity.serializeSkipInfo(serializedSkip, seekLen, rawSeek, numFields, seek, stepExtra);
  4037. p.setPacket(p.queryPacket()->insertSkipData(serializedSkip.length(), serializedSkip.toByteArray()));
  4038. ROQ->sendPacket(p.queryPacket(), activity.queryLogCtx());
  4039. sentsome.signal();
  4040. }
  4041. }
  4042. deferredStart = false;
  4043. }
  4044. SimpleActivityTimer t(totalCycles, timeActivities);
  4045. if (processed==stopAfter)
  4046. return NULL;
  4047. if (allread)
  4048. return NULL;
  4049. for (;;)
  4050. {
  4051. if (merger.ready())
  4052. {
  4053. const void *got = merger.nextRowGE(seek, rawSeek, numFields, seekLen, wasCompleteMatch, stepExtra);
  4054. if (got)
  4055. {
  4056. processRow(got);
  4057. return got;
  4058. }
  4059. }
  4060. if (!reload()) // MORE - should pass the seek info here...
  4061. return NULL;
  4062. }
  4063. }
  4064. virtual const void *nextRow()
  4065. {
  4066. // If we are merging then we need to do a heapsort on all
  4067. SimpleActivityTimer t(totalCycles, timeActivities);
  4068. if (activity.queryLogCtx().queryTraceLevel() > 10)
  4069. {
  4070. activity.queryLogCtx().CTXLOG("CRemoteResultAdaptor::nextRow()");
  4071. }
  4072. for (;;)
  4073. {
  4074. checkDelayed();
  4075. if (processed==stopAfter)
  4076. return NULL;
  4077. if (allread)
  4078. return NULL;
  4079. // If we can still consume from the merger or the most recently retrieved mu, do so.
  4080. const void *got = NULL;
  4081. if (mergeOrder && merger.ready())
  4082. {
  4083. bool matched = true;
  4084. got = merger.next(matched, dummySmartStepExtra);
  4085. }
  4086. else if (mu)
  4087. {
  4088. got = getRow(mu);
  4089. if (!got && meta.isGrouped() && !eogSent)
  4090. {
  4091. eogSent = true;
  4092. return NULL;
  4093. }
  4094. }
  4095. if (got)
  4096. {
  4097. processRow(got);
  4098. return got;
  4099. }
  4100. eogSent = false;
  4101. if (!reload())
  4102. return NULL;
  4103. }
  4104. }
  4105. bool reload()
  4106. {
  4107. // Wait for something to be returned from a slave....
  4108. mu.clear();
  4109. sentsome.wait();
  4110. // must be at least an endMarker on the queue since sentsome was signalled
  4111. {
  4112. CriticalBlock b(pendingCrit);
  4113. IRoxieServerQueryPacket &top = pending.item(0);
  4114. if (top.isLimit(rowLimit, keyedLimit, stopAfter)) // This is really a start marker...
  4115. {
  4116. pending.remove(0);
  4117. return true;
  4118. }
  4119. else if (top.isEnd())
  4120. {
  4121. pending.remove(0);
  4122. allread = true;
  4123. if (activity.queryLogCtx().queryTraceLevel() > 5)
  4124. activity.queryLogCtx().CTXLOG("All read on ruid %x", ruid);
  4125. return false;
  4126. }
  4127. else if (mergeOrder)
  4128. {
  4129. unsigned idx = 0;
  4130. bool added = false;
  4131. while (pending.isItem(idx))
  4132. {
  4133. IRoxieServerQueryPacket &item = pending.item(idx);
  4134. if (item.isEnd())
  4135. {
  4136. if (merger.noteEndSeen())
  4137. {
  4138. sentsome.signal(); // Because we waited, yet didn't actually consume anything
  4139. added = true;
  4140. }
  4141. break;
  4142. }
  4143. else if (item.hasResult())
  4144. {
  4145. merger.noteResult(&item, item.getSequence());
  4146. pending.remove(idx);
  4147. added = true;
  4148. }
  4149. else if (item.isContinuation())
  4150. idx++;
  4151. else
  4152. break;
  4153. }
  4154. if (added)
  4155. return true;
  4156. }
  4157. else if (top.hasResult())
  4158. {
  4159. mr.setown(pending.item(0).getResult());
  4160. mu.setown(mr->getCursor(rowManager));
  4161. pending.remove(0);
  4162. return true;
  4163. }
  4164. }
  4165. getNextUnpacker();
  4166. return true;
  4167. }
  4168. void getNextUnpacker()
  4169. {
  4170. mu.clear();
  4171. unsigned ctxTraceLevel = activity.queryLogCtx().queryTraceLevel();
  4172. for (;;)
  4173. {
  4174. checkDelayed();
  4175. unsigned timeout = remoteId.isSLAPriority() ? slaTimeout : (remoteId.isHighPriority() ? highTimeout : lowTimeout);
  4176. activity.queryContext()->checkAbort();
  4177. bool anyActivity;
  4178. if (ctxTraceLevel > 5)
  4179. activity.queryLogCtx().CTXLOG("Calling getNextUnpacker(%d)", timeout);
  4180. mr.setown(mc->getNextResult(timeout, anyActivity));
  4181. if (ctxTraceLevel > 6)
  4182. activity.queryLogCtx().CTXLOG("Called getNextUnpacker(%d), activity=%d", timeout, anyActivity);
  4183. activity.queryContext()->checkAbort();
  4184. if (mr)
  4185. {
  4186. unsigned roxieHeaderLen;
  4187. const RoxiePacketHeader &header = *(const RoxiePacketHeader *) mr->getMessageHeader(roxieHeaderLen);
  4188. #ifdef _DEBUG
  4189. assertex(roxieHeaderLen == sizeof(RoxiePacketHeader));
  4190. #endif
  4191. if (ctxTraceLevel > 5)
  4192. {
  4193. StringBuffer s;
  4194. activity.queryLogCtx().CTXLOG("getNextUnpacker got packet %s", header.toString(s).str());
  4195. }
  4196. CriticalBlock b(pendingCrit);
  4197. unsigned idx = 0;
  4198. IRoxieServerQueryPacket *original = NULL;
  4199. IRoxieQueryPacket *op;
  4200. while (pending.isItem(idx))
  4201. {
  4202. original = &pending.item(idx);
  4203. op = original->queryPacket();
  4204. if (op && header.matchPacket(op->queryHeader()))
  4205. break;
  4206. original = NULL;
  4207. idx++;
  4208. }
  4209. if (!original || original->hasResult())
  4210. {
  4211. switch (header.activityId)
  4212. {
  4213. case ROXIE_FILECALLBACK:
  4214. {
  4215. // tell slave to abort
  4216. //if (ctxTraceLevel > 5)
  4217. {
  4218. StringBuffer s;
  4219. activity.queryLogCtx().CTXLOG("Redundant callback on query %s", header.toString(s).str());
  4220. }
  4221. Owned<IMessageUnpackCursor> callbackData = mr->getCursor(rowManager);
  4222. OwnedConstRoxieRow len = callbackData->getNext(sizeof(RecordLengthType));
  4223. if (len)
  4224. {
  4225. RecordLengthType *rowlen = (RecordLengthType *) len.get();
  4226. OwnedConstRoxieRow row = callbackData->getNext(*rowlen);
  4227. const char *rowdata = (const char *) row.get();
  4228. // bool isOpt = * (bool *) rowdata;
  4229. // bool isLocal = * (bool *) (rowdata+1);
  4230. ROQ->sendAbortCallback(header, rowdata+2, activity.queryLogCtx());
  4231. }
  4232. else
  4233. throwUnexpected();
  4234. break;
  4235. }
  4236. // MORE - ROXIE_ALIVE perhaps should go here too
  4237. default:
  4238. if (ctxTraceLevel > 3)
  4239. activity.queryLogCtx().CTXLOG("Discarding packet %p - original %p is NULL or has result already", mr.get(), original);
  4240. mr->discard();
  4241. break;
  4242. }
  4243. mr.clear();
  4244. }
  4245. else
  4246. {
  4247. atomic_inc(&resultsReceived);
  4248. switch (header.activityId)
  4249. {
  4250. case ROXIE_DEBUGCALLBACK:
  4251. {
  4252. Owned<IMessageUnpackCursor> callbackData = mr->getCursor(rowManager);
  4253. OwnedConstRoxieRow len = callbackData->getNext(sizeof(RecordLengthType));
  4254. if (len)
  4255. {
  4256. RecordLengthType *rowlen = (RecordLengthType *) len.get();
  4257. OwnedConstRoxieRow row = callbackData->getNext(*rowlen);
  4258. char *rowdata = (char *) row.get();
  4259. if (ctxTraceLevel > 5)
  4260. {
  4261. StringBuffer s;
  4262. activity.queryLogCtx().CTXLOG("Callback on query %s for debug", header.toString(s).str());
  4263. }
  4264. MemoryBuffer slaveInfo;
  4265. slaveInfo.setBuffer(*rowlen, rowdata, false);
  4266. unsigned debugSequence;
  4267. slaveInfo.read(debugSequence);
  4268. Owned<IRoxieQueryPacket> reply = original->getDebugResponse(debugSequence);
  4269. if (!reply)
  4270. reply.setown(activity.queryContext()->queryDebugContext()->onDebugCallback(header, *rowlen, rowdata));
  4271. if (reply)
  4272. {
  4273. original->setDebugResponse(debugSequence, reply);
  4274. ROQ->sendPacket(reply, activity.queryLogCtx());
  4275. }
  4276. }
  4277. else
  4278. throwUnexpected();
  4279. // MORE - somehow we need to make sure slave gets a reply even if I'm not waiting (in udp layer)
  4280. // Leave original message on pending queue in original location - this is not a reply to it.
  4281. break;
  4282. }
  4283. case ROXIE_FILECALLBACK:
  4284. {
  4285. // we need to send back to the slave a message containing the file info requested.
  4286. Owned<IMessageUnpackCursor> callbackData = mr->getCursor(rowManager);
  4287. OwnedConstRoxieRow len = callbackData->getNext(sizeof(RecordLengthType));
  4288. if (len)
  4289. {
  4290. RecordLengthType *rowlen = (RecordLengthType *) len.get();
  4291. OwnedConstRoxieRow row = callbackData->getNext(*rowlen);
  4292. const char *rowdata = (const char *) row.get();
  4293. bool isOpt = * (bool *) rowdata;
  4294. bool isLocal = * (bool *) (rowdata+1);
  4295. const char *lfn = rowdata+2;
  4296. if (ctxTraceLevel > 5)
  4297. {
  4298. StringBuffer s;
  4299. activity.queryLogCtx().CTXLOG("Callback on query %s file %s", header.toString(s).str(),(const char *) lfn);
  4300. }
  4301. activity.queryContext()->onFileCallback(header, lfn, isOpt, isLocal);
  4302. }
  4303. else
  4304. throwUnexpected();
  4305. // MORE - somehow we need to make sure slave gets a reply even if I'm not waiting (in udp layer)
  4306. // Leave original message on pending queue in original location - this is not a reply to it.
  4307. break;
  4308. }
  4309. case ROXIE_KEYEDLIMIT_EXCEEDED:
  4310. activity.queryLogCtx().CTXLOG("ROXIE_KEYEDLIMIT_EXCEEDED");
  4311. errorHandler->onLimitExceeded(true); // NOTE - should throw exception!
  4312. throwUnexpected();
  4313. case ROXIE_LIMIT_EXCEEDED:
  4314. activity.queryLogCtx().CTXLOG("ROXIE_LIMIT_EXCEEDED");
  4315. errorHandler->onLimitExceeded(false); // NOTE - should throw exception!
  4316. throwUnexpected();
  4317. case ROXIE_TRACEINFO:
  4318. {
  4319. Owned<IMessageUnpackCursor> extra = mr->getCursor(rowManager);
  4320. for (;;)
  4321. {
  4322. RecordLengthType *rowlen = (RecordLengthType *) extra->getNext(sizeof(RecordLengthType));
  4323. if (rowlen)
  4324. {
  4325. char *logInfo = (char *) extra->getNext(*rowlen);
  4326. MemoryBuffer buf;
  4327. buf.setBuffer(*rowlen, logInfo, false);
  4328. switch ((TracingCategory) *logInfo)
  4329. {
  4330. case LOG_TRACING:
  4331. case LOG_ERROR:
  4332. activity.queryLogCtx().CTXLOGl(new LogItem(buf));
  4333. break;
  4334. case LOG_STATVALUES:
  4335. buf.skip(1);
  4336. activity.mergeStats(buf);
  4337. break;
  4338. case LOG_CHILDCOUNT:
  4339. case LOG_CHILDSTATS:
  4340. unsigned graphId, childId;
  4341. buf.skip(1);
  4342. buf.read(graphId);
  4343. buf.read(childId);
  4344. if (*logInfo == LOG_CHILDCOUNT)
  4345. {
  4346. unsigned idx;
  4347. unsigned childProcessed;
  4348. unsigned childStrands;
  4349. buf.read(idx);
  4350. buf.read(childProcessed);
  4351. buf.read(childStrands);
  4352. if (traceLevel > 5)
  4353. activity.queryLogCtx().CTXLOG("Processing ChildCount %d idx %d strands %d for child %d subgraph %d", childProcessed, idx, childStrands, childId, graphId);
  4354. activity.queryContext()->noteProcessed(graphId, childId, idx, childProcessed, childStrands);
  4355. }
  4356. else
  4357. {
  4358. ActivityTimeAccumulator dummy; // We could serialize from slave? Would get confusing though
  4359. CRuntimeStatisticCollection childStats(allStatistics);
  4360. childStats.deserialize(buf);
  4361. if (traceLevel > 5)
  4362. {
  4363. StringBuffer s;
  4364. activity.queryLogCtx().CTXLOG("Processing ChildStats for child %d subgraph %d: %s", childId, graphId, childStats.toStr(s).str());
  4365. }
  4366. activity.queryContext()->mergeActivityStats(childStats, graphId, childId, dummy, 0);
  4367. }
  4368. }
  4369. ReleaseRoxieRow(rowlen);
  4370. ReleaseRoxieRow(logInfo);
  4371. }
  4372. else
  4373. break;
  4374. }
  4375. break;
  4376. }
  4377. case ROXIE_EXCEPTION:
  4378. if (ctxTraceLevel > 1)
  4379. {
  4380. StringBuffer s;
  4381. activity.queryLogCtx().CTXLOG("Exception on query %s", header.toString(s).str());
  4382. }
  4383. op->queryHeader().noteException(header.retries);
  4384. if (op->queryHeader().allChannelsFailed())
  4385. {
  4386. activity.queryLogCtx().CTXLOG("Multiple exceptions on query - aborting");
  4387. Owned<IMessageUnpackCursor> exceptionData = mr->getCursor(rowManager);
  4388. throwRemoteException(exceptionData);
  4389. }
  4390. // Leave it on pending queue in original location
  4391. break;
  4392. case ROXIE_ALIVE:
  4393. if (ctxTraceLevel > 4)
  4394. {
  4395. StringBuffer s;
  4396. activity.queryLogCtx().CTXLOG("ROXIE_ALIVE: %s", header.toString(s).str());
  4397. }
  4398. op->queryHeader().noteAlive(header.retries & ROXIE_RETRIES_MASK);
  4399. // Leave it on pending queue in original location
  4400. break;
  4401. default:
  4402. if (header.retries & ROXIE_RETRIES_MASK)
  4403. atomic_inc(&retriesNeeded);
  4404. unsigned metaLen;
  4405. const void *metaData = mr->getMessageMetadata(metaLen);
  4406. if (metaLen)
  4407. {
  4408. // We got back first chunk but there is more.
  4409. // resend the packet, with the cursor info provided.
  4410. // MORE - if smart-stepping, we don't want to send the continuation immediately. Other cases it's not clear that we do.
  4411. if (ctxTraceLevel > 1)
  4412. {
  4413. StringBuffer s;
  4414. activity.queryLogCtx().CTXLOG("Additional data size %d on query %s mergeOrder %p", metaLen, header.toString(s).str(), mergeOrder);
  4415. }
  4416. if (*((unsigned short *) metaData) + sizeof(unsigned short) != metaLen)
  4417. {
  4418. StringBuffer s;
  4419. activity.queryLogCtx().CTXLOG("Additional data size %d on query %s mergeOrder %p", metaLen, header.toString(s).str(), mergeOrder);
  4420. activity.queryLogCtx().CTXLOG("Additional data is corrupt");
  4421. throwUnexpected();
  4422. }
  4423. MemoryBuffer nextQuery;
  4424. nextQuery.append(sizeof(RoxiePacketHeader), &header);
  4425. nextQuery.append(metaLen, metaData);
  4426. nextQuery.append(op->getTraceLength(), op->queryTraceInfo());
  4427. nextQuery.append(op->getContextLength(), op->queryContextData());
  4428. if (resendSequence == CONTINUESEQUENCE_MAX)
  4429. {
  4430. activity.queryLogCtx().CTXLOG("ERROR: Continuation sequence wrapped"); // shouldn't actually matter.... but suggests a very iffy query!
  4431. resendSequence = 1;
  4432. }
  4433. else
  4434. resendSequence++;
  4435. RoxiePacketHeader *newHeader = (RoxiePacketHeader *) nextQuery.toByteArray();
  4436. newHeader->continueSequence = resendSequence; // NOTE - we clear the skipTo flag since continuation of a skip is NOT a skip...
  4437. newHeader->retries &= ~ROXIE_RETRIES_MASK;
  4438. IRoxieQueryPacket *resend = createRoxiePacket(nextQuery);
  4439. CRoxieServerQueryPacket *fqp = new CRoxieServerQueryPacket(resend);
  4440. fqp->setSequence(original->getSequence());
  4441. pending.add(*fqp, idx+1); // note that pending takes ownership. sendPacket does not release.
  4442. original->setContinuation(LINK(fqp));
  4443. if (mergeOrder)
  4444. fqp->setDelayed(true);
  4445. else
  4446. {
  4447. ROQ->sendPacket(resend, activity.queryLogCtx());
  4448. sentsome.signal();
  4449. }
  4450. // Note that we don't attempt to cache results that have continuation records - too tricky !
  4451. }
  4452. else
  4453. {
  4454. if (serverSideCache)
  4455. serverSideCache->noteCachedResult(original, mr);
  4456. }
  4457. unsigned channel = header.channel;
  4458. {
  4459. ChannelBuffer *b = queryChannelBuffer(channel); // If not something is wrong, or we sent out on channel 0?
  4460. if (b)
  4461. b->signal();
  4462. }
  4463. original->setResult(mr.getClear());
  4464. sentsome.signal();
  4465. return;
  4466. }
  4467. }
  4468. }
  4469. else
  4470. {
  4471. if (!anyActivity && !localSlave)
  4472. {
  4473. activity.queryLogCtx().CTXLOG("Input has stalled - retry required?");
  4474. retryPending();
  4475. }
  4476. }
  4477. }
  4478. }
  4479. inline unsigned headerLength() const
  4480. {
  4481. return logInfo.length() + cachedContext.length() + sizeof(unsigned) + parentExtractSize;
  4482. }
  4483. void copyHeader(byte *tgt, unsigned channel) const
  4484. {
  4485. unsigned len = logInfo.length();
  4486. memcpy(tgt, logInfo.toByteArray(), len);
  4487. tgt += len;
  4488. *(unsigned *) tgt = parentExtractSize;
  4489. tgt += sizeof(unsigned);
  4490. memcpy(tgt, parentExtract, parentExtractSize);
  4491. tgt += parentExtractSize;
  4492. memcpy(tgt, cachedContext.toByteArray(), cachedContext.length());
  4493. tgt += cachedContext.length();
  4494. }
  4495. };
  4496. class CSkippableRemoteResultAdaptor : public CRemoteResultAdaptor
  4497. {
  4498. Owned <IException> exception;
  4499. bool skipping;
  4500. ConstPointerArray buff;
  4501. unsigned index;
  4502. bool pulled;
  4503. void pullInput()
  4504. {
  4505. try
  4506. {
  4507. if (exception)
  4508. throw exception.getClear();
  4509. unsigned __int64 count = 0;
  4510. for (;;)
  4511. {
  4512. const void * next = CRemoteResultAdaptor::nextRow();
  4513. if (next == NULL)
  4514. {
  4515. next = CRemoteResultAdaptor::nextRow();
  4516. if(next == NULL)
  4517. break;
  4518. buff.append(NULL);
  4519. }
  4520. count++;
  4521. if (count > rowLimit)
  4522. {
  4523. ReleaseRoxieRow(next);
  4524. ReleaseRoxieRows(buff);
  4525. errorHandler->onLimitExceeded(false); // throws an exception - user or LimitSkipException
  4526. throwUnexpected();
  4527. }
  4528. else if (count > keyedLimit)
  4529. {
  4530. ReleaseRoxieRow(next);
  4531. ReleaseRoxieRows(buff);
  4532. errorHandler->onLimitExceeded(true); // throws an exception - user or LimitSkipException
  4533. throwUnexpected();
  4534. }
  4535. buff.append(next);
  4536. }
  4537. }
  4538. catch (IException *E)
  4539. {
  4540. if (QUERYINTERFACE(E, LimitSkipException))
  4541. {
  4542. Owned<IException> cleanup = E;
  4543. ReleaseRoxieRows(buff);
  4544. const void *onfail = errorHandler->createLimitFailRow(E->errorCode() == KeyedLimitSkipErrorCode);
  4545. if (onfail)
  4546. buff.append(onfail);
  4547. }
  4548. else
  4549. throw;
  4550. }
  4551. pulled = true;
  4552. }
  4553. public:
  4554. CSkippableRemoteResultAdaptor(IRoxieSlaveContext *_ctx, IRoxieServerErrorHandler *_errorHandler, const RemoteActivityId &_remoteId, IOutputMetaData *_meta, IHThorArg &_helper, IRoxieServerActivity &_activity, bool _preserveOrder, bool _flowControlled, bool _skipping) :
  4555. CRemoteResultAdaptor(_ctx, _errorHandler, _remoteId, _meta, _helper, _activity, _preserveOrder, _flowControlled)
  4556. {
  4557. skipping = _skipping;
  4558. index = 0;
  4559. pulled = false;
  4560. }
  4561. void setException(IException *E)
  4562. {
  4563. exception.setown(E);
  4564. }
  4565. virtual void onReset()
  4566. {
  4567. roxiemem::ReleaseRoxieRowRange(buff.getArray(), index, buff.ordinality());
  4568. buff.kill();
  4569. index = 0;
  4570. pulled = false;
  4571. exception.clear();
  4572. CRemoteResultAdaptor::onReset();
  4573. }
  4574. void onStart(unsigned _parentExtractSize, const byte * _parentExtract)
  4575. {
  4576. index = 0;
  4577. pulled = false;
  4578. CRemoteResultAdaptor::onStart(_parentExtractSize, _parentExtract);
  4579. }
  4580. virtual const void * nextRowGE(const void *seek, const void *rawSeek, unsigned numFields, unsigned seeklen, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  4581. {
  4582. // 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
  4583. if (exception)
  4584. throw exception.getClear();
  4585. return CRemoteResultAdaptor::nextRowGE(seek, rawSeek, numFields, seeklen, wasCompleteMatch, stepExtra);
  4586. }
  4587. virtual const void *nextRow()
  4588. {
  4589. if (skipping)
  4590. {
  4591. if(!pulled)
  4592. pullInput();
  4593. if(buff.isItem(index))
  4594. {
  4595. const void * next = buff.item(index++);
  4596. if(next)
  4597. processed++;
  4598. return next;
  4599. }
  4600. return NULL;
  4601. }
  4602. else
  4603. {
  4604. if (exception)
  4605. throw exception.getClear();
  4606. return CRemoteResultAdaptor::nextRow();
  4607. }
  4608. }
  4609. };
  4610. //=================================================================================
  4611. class CRoxieServerApplyActivity : public CRoxieServerInternalSinkActivity
  4612. {
  4613. IHThorApplyArg &helper;
  4614. public:
  4615. CRoxieServerApplyActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4616. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, 0), helper((IHThorApplyArg &) basehelper)
  4617. {
  4618. }
  4619. virtual void onExecute()
  4620. {
  4621. helper.start();
  4622. for (;;)
  4623. {
  4624. const void * next = inputStream->ungroupedNextRow();
  4625. if (!next)
  4626. break;
  4627. helper.apply(next);
  4628. ReleaseRoxieRow(next);
  4629. }
  4630. helper.end();
  4631. }
  4632. };
  4633. class CRoxieServerApplyActivityFactory : public CRoxieServerActivityFactory
  4634. {
  4635. bool isRoot;
  4636. public:
  4637. CRoxieServerApplyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  4638. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  4639. {
  4640. }
  4641. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  4642. {
  4643. return new CRoxieServerApplyActivity(_ctx, this, _probeManager);
  4644. }
  4645. virtual bool isSink() const
  4646. {
  4647. return isRoot;
  4648. }
  4649. };
  4650. IRoxieServerActivityFactory *createRoxieServerApplyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  4651. {
  4652. return new CRoxieServerApplyActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  4653. }
  4654. //=================================================================================
  4655. class CRoxieServerNullActivity : public CRoxieServerActivity
  4656. {
  4657. public:
  4658. CRoxieServerNullActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4659. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  4660. {
  4661. }
  4662. virtual const void *nextRow()
  4663. {
  4664. return NULL;
  4665. }
  4666. };
  4667. IRoxieServerActivity * createRoxieServerNullActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4668. {
  4669. return new CRoxieServerNullActivity(_ctx, _factory, _probeManager);
  4670. }
  4671. class CRoxieServerNullActivityFactory : public CRoxieServerActivityFactory
  4672. {
  4673. public:
  4674. CRoxieServerNullActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4675. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  4676. {
  4677. }
  4678. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  4679. {
  4680. return new CRoxieServerNullActivity(_ctx, this, _probeManager);
  4681. }
  4682. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  4683. {
  4684. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for null activity");
  4685. }
  4686. };
  4687. IRoxieServerActivityFactory *createRoxieServerNullActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4688. {
  4689. return new CRoxieServerNullActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  4690. }
  4691. //=================================================================================
  4692. class CRoxieServerPassThroughActivity : public CRoxieServerActivity
  4693. {
  4694. public:
  4695. CRoxieServerPassThroughActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4696. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  4697. {
  4698. }
  4699. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  4700. {
  4701. return input->gatherConjunctions(collector);
  4702. }
  4703. virtual void resetEOF()
  4704. {
  4705. inputStream->resetEOF();
  4706. }
  4707. virtual const void *nextRow()
  4708. {
  4709. const void * next = inputStream->nextRow();
  4710. if (next)
  4711. processed++;
  4712. return next;
  4713. }
  4714. virtual bool isPassThrough()
  4715. {
  4716. return true;
  4717. }
  4718. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  4719. {
  4720. ActivityTimer t(totalCycles, timeActivities);
  4721. const void * next = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  4722. if (next)
  4723. processed++;
  4724. return next;
  4725. }
  4726. IInputSteppingMeta * querySteppingMeta()
  4727. {
  4728. return input->querySteppingMeta();
  4729. }
  4730. };
  4731. IRoxieServerActivity * createRoxieServerPassThroughActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4732. {
  4733. return new CRoxieServerPassThroughActivity(_ctx, _factory, _probeManager);
  4734. }
  4735. //=================================================================================
  4736. class CRoxieServerChildBaseActivity : public CRoxieServerActivity
  4737. {
  4738. protected:
  4739. bool eof;
  4740. bool first;
  4741. public:
  4742. CRoxieServerChildBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4743. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  4744. {
  4745. eof = false;
  4746. first = true;
  4747. }
  4748. ~CRoxieServerChildBaseActivity()
  4749. {
  4750. }
  4751. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4752. {
  4753. eof = false;
  4754. first = true;
  4755. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  4756. }
  4757. };
  4758. class CRoxieServerChildBaseActivityFactory : public CRoxieServerActivityFactory
  4759. {
  4760. public:
  4761. CRoxieServerChildBaseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4762. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  4763. {
  4764. }
  4765. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  4766. {
  4767. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  4768. }
  4769. };
  4770. //=================================================================================
  4771. class CRoxieServerChildIteratorActivity : public CRoxieServerChildBaseActivity
  4772. {
  4773. IHThorChildIteratorArg &helper;
  4774. public:
  4775. CRoxieServerChildIteratorActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4776. : CRoxieServerChildBaseActivity(_ctx, _factory, _probeManager), helper((IHThorChildIteratorArg &) basehelper)
  4777. {
  4778. }
  4779. virtual bool needsAllocator() const { return true; }
  4780. virtual const void *nextRow()
  4781. {
  4782. ActivityTimer t(totalCycles, timeActivities);
  4783. if (eof)
  4784. return NULL;
  4785. bool ok;
  4786. if (first)
  4787. {
  4788. ok = helper.first();
  4789. first = false;
  4790. }
  4791. else
  4792. ok = helper.next();
  4793. try
  4794. {
  4795. while (ok)
  4796. {
  4797. processed++;
  4798. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  4799. unsigned outSize = helper.transform(rowBuilder);
  4800. if (outSize)
  4801. return rowBuilder.finalizeRowClear(outSize);
  4802. ok = helper.next();
  4803. }
  4804. }
  4805. catch (IException *E)
  4806. {
  4807. throw makeWrappedException(E);
  4808. }
  4809. eof = true;
  4810. return NULL;
  4811. }
  4812. };
  4813. class CRoxieServerChildIteratorActivityFactory : public CRoxieServerChildBaseActivityFactory
  4814. {
  4815. public:
  4816. CRoxieServerChildIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4817. : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  4818. {
  4819. }
  4820. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  4821. {
  4822. return new CRoxieServerChildIteratorActivity(_ctx, this, _probeManager);
  4823. }
  4824. };
  4825. IRoxieServerActivityFactory *createRoxieServerChildIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4826. {
  4827. return new CRoxieServerChildIteratorActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  4828. }
  4829. //=================================================================================
  4830. class CRoxieServerChildNormalizeActivity : public CRoxieServerChildBaseActivity
  4831. {
  4832. IHThorChildNormalizeArg &helper;
  4833. public:
  4834. CRoxieServerChildNormalizeActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4835. : CRoxieServerChildBaseActivity(_ctx, _factory, _probeManager), helper((IHThorChildNormalizeArg &) basehelper)
  4836. {
  4837. }
  4838. virtual bool needsAllocator() const { return true; }
  4839. virtual const void *nextRow()
  4840. {
  4841. ActivityTimer t(totalCycles, timeActivities);
  4842. if (eof)
  4843. return NULL;
  4844. bool ok;
  4845. if (first)
  4846. {
  4847. ok = helper.first();
  4848. first = false;
  4849. }
  4850. else
  4851. ok = helper.next();
  4852. if (ok)
  4853. {
  4854. try
  4855. {
  4856. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  4857. do {
  4858. unsigned outSize = helper.transform(rowBuilder);
  4859. if (outSize)
  4860. {
  4861. processed++;
  4862. return rowBuilder.finalizeRowClear(outSize);
  4863. }
  4864. ok = helper.next();
  4865. }
  4866. while (ok);
  4867. }
  4868. catch (IException *E)
  4869. {
  4870. throw makeWrappedException(E);
  4871. }
  4872. }
  4873. eof = true;
  4874. return NULL;
  4875. }
  4876. };
  4877. class CRoxieServerChildNormalizeActivityFactory : public CRoxieServerChildBaseActivityFactory
  4878. {
  4879. public:
  4880. CRoxieServerChildNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4881. : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  4882. {
  4883. }
  4884. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  4885. {
  4886. return new CRoxieServerChildNormalizeActivity(_ctx, this, _probeManager);
  4887. }
  4888. };
  4889. IRoxieServerActivityFactory *createRoxieServerNewChildNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4890. {
  4891. return new CRoxieServerChildNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  4892. }
  4893. //=================================================================================
  4894. class CRoxieServerChildAggregateActivity : public CRoxieServerChildBaseActivity
  4895. {
  4896. IHThorChildAggregateArg &helper;
  4897. public:
  4898. CRoxieServerChildAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4899. : CRoxieServerChildBaseActivity(_ctx, _factory, _probeManager), helper((IHThorChildAggregateArg &) basehelper)
  4900. {
  4901. }
  4902. virtual bool needsAllocator() const { return true; }
  4903. virtual const void *nextRow()
  4904. {
  4905. ActivityTimer t(totalCycles, timeActivities);
  4906. if (eof)
  4907. return NULL;
  4908. eof = true;
  4909. processed++;
  4910. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  4911. helper.clearAggregate(rowBuilder);
  4912. helper.processRows(rowBuilder);
  4913. size32_t finalSize = meta.getRecordSize(rowBuilder.getSelf());
  4914. return rowBuilder.finalizeRowClear(finalSize);
  4915. }
  4916. };
  4917. class CRoxieServerChildAggregateActivityFactory : public CRoxieServerChildBaseActivityFactory
  4918. {
  4919. public:
  4920. CRoxieServerChildAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4921. : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  4922. {
  4923. }
  4924. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  4925. {
  4926. return new CRoxieServerChildAggregateActivity(_ctx, this, _probeManager);
  4927. }
  4928. };
  4929. IRoxieServerActivityFactory *createRoxieServerNewChildAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4930. {
  4931. return new CRoxieServerChildAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  4932. }
  4933. //=================================================================================
  4934. class CRoxieServerChildGroupAggregateActivity : public CRoxieServerChildBaseActivity, public IHThorGroupAggregateCallback
  4935. {
  4936. IHThorChildGroupAggregateArg &helper;
  4937. RowAggregator aggregated;
  4938. public:
  4939. IMPLEMENT_IINTERFACE_USING(CRoxieServerChildBaseActivity)
  4940. CRoxieServerChildGroupAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4941. : CRoxieServerChildBaseActivity(_ctx, _factory, _probeManager), helper((IHThorChildGroupAggregateArg &) basehelper),
  4942. aggregated(helper, helper)
  4943. {
  4944. }
  4945. void processRow(const void * next)
  4946. {
  4947. aggregated.addRow(next);
  4948. }
  4949. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4950. {
  4951. CRoxieServerChildBaseActivity::start(parentExtractSize, parentExtract, paused);
  4952. aggregated.start(rowAllocator);
  4953. }
  4954. virtual void reset()
  4955. {
  4956. aggregated.reset();
  4957. CRoxieServerChildBaseActivity::reset();
  4958. }
  4959. virtual bool needsAllocator() const { return true; }
  4960. virtual const void *nextRow()
  4961. {
  4962. ActivityTimer t(totalCycles, timeActivities);
  4963. if (eof)
  4964. return NULL;
  4965. if (first)
  4966. {
  4967. helper.processRows(this);
  4968. first = false;
  4969. }
  4970. Owned<AggregateRowBuilder> next = aggregated.nextResult();
  4971. if (next)
  4972. {
  4973. processed++;
  4974. return next->finalizeRowClear();
  4975. }
  4976. eof = true;
  4977. return NULL;
  4978. }
  4979. };
  4980. class CRoxieServerChildGroupAggregateActivityFactory : public CRoxieServerChildBaseActivityFactory
  4981. {
  4982. public:
  4983. CRoxieServerChildGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4984. : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  4985. {
  4986. }
  4987. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  4988. {
  4989. return new CRoxieServerChildGroupAggregateActivity(_ctx, this, _probeManager);
  4990. }
  4991. };
  4992. IRoxieServerActivityFactory *createRoxieServerNewChildGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4993. {
  4994. return new CRoxieServerChildGroupAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  4995. }
  4996. //=================================================================================
  4997. class CRoxieServerChildThroughNormalizeActivity : public CRoxieServerChildBaseActivity
  4998. {
  4999. IHThorChildThroughNormalizeArg &helper;
  5000. const void * lastInput;
  5001. unsigned numProcessedLastGroup;
  5002. bool ok;
  5003. public:
  5004. CRoxieServerChildThroughNormalizeActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5005. : CRoxieServerChildBaseActivity(_ctx, _factory, _probeManager), helper((IHThorChildThroughNormalizeArg &) basehelper)
  5006. {
  5007. lastInput = NULL;
  5008. numProcessedLastGroup = 0;
  5009. ok = false;
  5010. }
  5011. virtual void stop()
  5012. {
  5013. CRoxieServerChildBaseActivity::stop();
  5014. ReleaseRoxieRow(lastInput);
  5015. lastInput = NULL;
  5016. }
  5017. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5018. {
  5019. CRoxieServerChildBaseActivity::start(parentExtractSize, parentExtract, paused);
  5020. numProcessedLastGroup = processed;
  5021. ok = false;
  5022. }
  5023. virtual bool needsAllocator() const { return true; }
  5024. virtual const void *nextRow()
  5025. {
  5026. ActivityTimer t(totalCycles, timeActivities);
  5027. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  5028. for (;;)
  5029. {
  5030. if (ok)
  5031. ok = helper.next();
  5032. while (!ok)
  5033. {
  5034. ReleaseRoxieRow(lastInput);
  5035. lastInput = inputStream->nextRow();
  5036. if (!lastInput)
  5037. {
  5038. if (numProcessedLastGroup != processed)
  5039. {
  5040. numProcessedLastGroup = processed;
  5041. return NULL;
  5042. }
  5043. lastInput = inputStream->nextRow();
  5044. if (!lastInput)
  5045. return NULL;
  5046. }
  5047. ok = helper.first(lastInput);
  5048. }
  5049. try
  5050. {
  5051. do
  5052. {
  5053. unsigned outSize = helper.transform(rowBuilder);
  5054. if (outSize)
  5055. {
  5056. processed++;
  5057. return rowBuilder.finalizeRowClear(outSize);
  5058. }
  5059. ok = helper.next();
  5060. } while (ok);
  5061. }
  5062. catch (IException *E)
  5063. {
  5064. throw makeWrappedException(E);
  5065. }
  5066. }
  5067. }
  5068. };
  5069. class CRoxieServerChildThroughNormalizeActivityFactory : public CRoxieServerActivityFactory
  5070. {
  5071. public:
  5072. CRoxieServerChildThroughNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5073. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  5074. {
  5075. }
  5076. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  5077. {
  5078. return new CRoxieServerChildThroughNormalizeActivity(_ctx, this, _probeManager);
  5079. }
  5080. };
  5081. IRoxieServerActivityFactory *createRoxieServerNewChildThroughNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5082. {
  5083. return new CRoxieServerChildThroughNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  5084. }
  5085. //=================================================================================
  5086. class CRoxieServerDistributionActivity : public CRoxieServerInternalSinkActivity
  5087. {
  5088. IHThorDistributionArg &helper;
  5089. public:
  5090. CRoxieServerDistributionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5091. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, 0), helper((IHThorDistributionArg &)basehelper)
  5092. {
  5093. }
  5094. virtual void onExecute()
  5095. {
  5096. MemoryAttr ma;
  5097. IDistributionTable * * accumulator = (IDistributionTable * *)ma.allocate(helper.queryInternalRecordSize()->getMinRecordSize());
  5098. helper.clearAggregate(accumulator);
  5099. OwnedConstRoxieRow nextrec(inputStream->nextRow());
  5100. for (;;)
  5101. {
  5102. if (!nextrec)
  5103. {
  5104. nextrec.setown(inputStream->nextRow());
  5105. if (!nextrec)
  5106. break;
  5107. }
  5108. helper.process(accumulator, nextrec);
  5109. nextrec.setown(inputStream->nextRow());
  5110. }
  5111. StringBuffer result;
  5112. result.append("<XML>");
  5113. helper.gatherResult(accumulator, result);
  5114. result.append("</XML>");
  5115. helper.sendResult(result.length(), result.str());
  5116. helper.destruct(accumulator);
  5117. }
  5118. };
  5119. class CRoxieServerDistributionActivityFactory : public CRoxieServerActivityFactory
  5120. {
  5121. bool isRoot;
  5122. public:
  5123. CRoxieServerDistributionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  5124. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  5125. {
  5126. }
  5127. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  5128. {
  5129. return new CRoxieServerDistributionActivity(_ctx, this, _probeManager);
  5130. }
  5131. virtual bool isSink() const
  5132. {
  5133. return isRoot;
  5134. }
  5135. };
  5136. IRoxieServerActivityFactory *createRoxieServerDistributionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  5137. {
  5138. return new CRoxieServerDistributionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  5139. }
  5140. //=================================================================================
  5141. class CRoxieServerLinkedRawIteratorActivity : public CRoxieServerActivity
  5142. {
  5143. IHThorLinkedRawIteratorArg &helper;
  5144. public:
  5145. CRoxieServerLinkedRawIteratorActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5146. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorLinkedRawIteratorArg &) basehelper)
  5147. {
  5148. }
  5149. virtual const void *nextRow()
  5150. {
  5151. ActivityTimer t(totalCycles, timeActivities);
  5152. const void *ret =helper.next();
  5153. if (ret)
  5154. {
  5155. LinkRoxieRow(ret);
  5156. processed++;
  5157. }
  5158. return ret;
  5159. }
  5160. };
  5161. class CRoxieServerLinkedRawIteratorActivityFactory : public CRoxieServerActivityFactory
  5162. {
  5163. public:
  5164. CRoxieServerLinkedRawIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5165. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  5166. {
  5167. }
  5168. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  5169. {
  5170. return new CRoxieServerLinkedRawIteratorActivity(_ctx, this, _probeManager);
  5171. }
  5172. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  5173. {
  5174. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  5175. }
  5176. };
  5177. IRoxieServerActivityFactory *createRoxieServerLinkedRawIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5178. {
  5179. return new CRoxieServerLinkedRawIteratorActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  5180. }
  5181. //=================================================================================
  5182. class CRoxieServerDatasetResultActivity : public CRoxieServerActivity
  5183. {
  5184. public:
  5185. CRoxieServerDatasetResultActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5186. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  5187. {
  5188. }
  5189. virtual const void *nextRow()
  5190. {
  5191. throwUnexpected();
  5192. }
  5193. virtual void executeChild(size32_t & retSize, void * & ret, unsigned parentExtractSize, const byte * parentExtract)
  5194. {
  5195. try
  5196. {
  5197. start(parentExtractSize, parentExtract, false);
  5198. {
  5199. ActivityTimer t(totalCycles, timeActivities);
  5200. MemoryBuffer result;
  5201. IRecordSize * inputMeta = input->queryOutputMeta();
  5202. for (;;)
  5203. {
  5204. const void *nextrec = inputStream->ungroupedNextRow();
  5205. if (!nextrec)
  5206. break;
  5207. result.append(inputMeta->getRecordSize(nextrec), nextrec);
  5208. ReleaseRoxieRow(nextrec);
  5209. }
  5210. retSize = result.length();
  5211. ret = result.detach();
  5212. }
  5213. stop();
  5214. reset();
  5215. }
  5216. catch(IException *E)
  5217. {
  5218. ctx->notifyAbort(E);
  5219. abort();
  5220. reset();
  5221. throw;
  5222. }
  5223. catch(...)
  5224. {
  5225. Owned<IException> E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught at %s:%d", sanitizeSourceFile(__FILE__), __LINE__);
  5226. ctx->notifyAbort(E);
  5227. abort();
  5228. reset();
  5229. throw;
  5230. }
  5231. }
  5232. };
  5233. class CRoxieServerDatasetResultActivityFactory : public CRoxieServerActivityFactory
  5234. {
  5235. bool isRoot;
  5236. public:
  5237. CRoxieServerDatasetResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  5238. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  5239. {
  5240. }
  5241. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  5242. {
  5243. return new CRoxieServerDatasetResultActivity(_ctx, this, _probeManager);
  5244. }
  5245. virtual bool isSink() const
  5246. {
  5247. return isRoot;
  5248. }
  5249. };
  5250. IRoxieServerActivityFactory *createRoxieServerDatasetResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  5251. {
  5252. return new CRoxieServerDatasetResultActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  5253. }
  5254. //=================================================================================
  5255. class CRoxieServerInlineTableActivity : public CRoxieServerActivity
  5256. {
  5257. IHThorInlineTableArg &helper;
  5258. __uint64 curRow;
  5259. __uint64 numRows;
  5260. public:
  5261. CRoxieServerInlineTableActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5262. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorInlineTableArg &) basehelper)
  5263. {
  5264. curRow = 0;
  5265. numRows = 0;
  5266. }
  5267. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5268. {
  5269. curRow = 0;
  5270. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5271. numRows = helper.numRows();
  5272. }
  5273. virtual bool needsAllocator() const { return true; }
  5274. virtual const void *nextRow()
  5275. {
  5276. ActivityTimer t(totalCycles, timeActivities);
  5277. // Filtering empty rows, returns the next valid row
  5278. while (curRow < numRows)
  5279. {
  5280. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  5281. unsigned outSize = helper.getRow(rowBuilder, curRow++);
  5282. if (outSize)
  5283. {
  5284. processed++;
  5285. return rowBuilder.finalizeRowClear(outSize);
  5286. }
  5287. }
  5288. return NULL;
  5289. }
  5290. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  5291. {
  5292. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  5293. }
  5294. };
  5295. class CRoxieServerStrandedInlineTableActivity : public CRoxieServerStrandedActivity
  5296. {
  5297. IHThorInlineTableArg &helper;
  5298. __uint64 numRows;
  5299. //An inline table that isn't stranded
  5300. class InlineTableSimpleProcessor : public StrandProcessor
  5301. {
  5302. protected:
  5303. IHThorInlineTableArg &helper;
  5304. __uint64 curRow;
  5305. __uint64 maxRows;
  5306. public:
  5307. InlineTableSimpleProcessor(CRoxieServerActivity &_parent, IHThorInlineTableArg &_helper)
  5308. : StrandProcessor(_parent, NULL, true), helper(_helper), curRow(0), maxRows(0)
  5309. {
  5310. }
  5311. virtual void start() override
  5312. {
  5313. StrandProcessor::start();
  5314. curRow = 0;
  5315. maxRows = queryParent().numRows;
  5316. }
  5317. virtual const void * nextRow()
  5318. {
  5319. ActivityTimer t(totalCycles, timeActivities);
  5320. //Return rows while the current section is active
  5321. while (curRow < maxRows)
  5322. {
  5323. RtlDynamicRowBuilder rowBuilder(*rowAllocator);
  5324. unsigned outSize = helper.getRow(rowBuilder, curRow++);
  5325. if (outSize)
  5326. {
  5327. processed++;
  5328. return rowBuilder.finalizeRowClear(outSize);
  5329. }
  5330. }
  5331. return NULL;
  5332. }
  5333. CRoxieServerStrandedInlineTableActivity & queryParent() { return static_cast<CRoxieServerStrandedInlineTableActivity&>(parent); }
  5334. };
  5335. class InlineTableStrandProcessor : public StrandProcessor
  5336. {
  5337. protected:
  5338. IHThorInlineTableArg &helper;
  5339. unsigned whichStrand;
  5340. unsigned numStrands = 0;
  5341. __uint64 sectionSize;
  5342. __uint64 curRow = 0;
  5343. __uint64 sectionMaxRows = 0;
  5344. __uint64 maxRows = 0;
  5345. bool isOrdered;
  5346. bool eosPending;
  5347. public:
  5348. InlineTableStrandProcessor(CRoxieServerActivity &_parent, IHThorInlineTableArg &_helper, unsigned _whichStrand, bool _isOrdered)
  5349. : StrandProcessor(_parent, NULL, true), helper(_helper), whichStrand(_whichStrand), isOrdered(_isOrdered)
  5350. {
  5351. sectionSize = queryParent().strandOptions.blockSize;
  5352. eosPending = false;
  5353. }
  5354. virtual void start() override
  5355. {
  5356. StrandProcessor::start();
  5357. numStrands = queryParent().numStrands();
  5358. maxRows = queryParent().numRows;
  5359. curRow = std::min(whichStrand * sectionSize, maxRows);
  5360. sectionMaxRows = std::min(curRow + sectionSize, maxRows);
  5361. eosPending = isOrdered && (curRow != maxRows);
  5362. }
  5363. virtual const void * nextRow()
  5364. {
  5365. ActivityTimer t(totalCycles, timeActivities);
  5366. for (;;)
  5367. {
  5368. //Return rows while the current section is active
  5369. while (curRow < sectionMaxRows)
  5370. {
  5371. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  5372. unsigned outSize = helper.getRow(rowBuilder, curRow++);
  5373. if (outSize)
  5374. {
  5375. processed++;
  5376. return rowBuilder.finalizeRowClear(outSize);
  5377. }
  5378. }
  5379. if (curRow == maxRows)
  5380. return NULL;
  5381. //Update current position to the next section
  5382. curRow += (numStrands - 1) * sectionSize;
  5383. if (curRow > maxRows)
  5384. curRow = maxRows;
  5385. sectionMaxRows = std::min(curRow + sectionSize, maxRows);
  5386. //If we have output a block of rows, then send the block as a unit - results now come from the next strand
  5387. if (eosPending)
  5388. {
  5389. //If there is another block, then second an end of section marker after it, otherwise make sure NULL is returned next.
  5390. eosPending = isOrdered && (curRow != maxRows);
  5391. return queryEndOfSectionMarker();
  5392. }
  5393. }
  5394. }
  5395. CRoxieServerStrandedInlineTableActivity & queryParent() { return static_cast<CRoxieServerStrandedInlineTableActivity&>(parent); }
  5396. };
  5397. public:
  5398. CRoxieServerStrandedInlineTableActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const StrandOptions &_strandOptions)
  5399. : CRoxieServerStrandedActivity(_ctx, _factory, _probeManager, _strandOptions), helper((IHThorInlineTableArg &) basehelper)
  5400. {
  5401. numRows = 0;
  5402. }
  5403. virtual StrandProcessor *createStrandProcessor(IEngineRowStream *instream) { throwUnexpected(); }
  5404. virtual StrandProcessor *createStrandSourceProcessor(bool inputOrdered)
  5405. {
  5406. if (strandOptions.numStrands <= 1)
  5407. return new InlineTableSimpleProcessor(*this, helper);
  5408. return new InlineTableStrandProcessor(*this, helper, strands.ordinality(), inputOrdered);
  5409. }
  5410. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5411. {
  5412. CRoxieServerStrandedActivity::start(parentExtractSize, parentExtract, paused);
  5413. numRows = helper.numRows();
  5414. onStartStrands();
  5415. startJunction(sourceJunction); // This must be started *after* all the strands have been initialised
  5416. }
  5417. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  5418. {
  5419. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  5420. }
  5421. };
  5422. class CRoxieServerInlineTableActivityFactory : public CRoxieServerActivityFactory
  5423. {
  5424. StrandOptions strandOptions;
  5425. public:
  5426. CRoxieServerInlineTableActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5427. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), strandOptions(_graphNode)
  5428. {
  5429. optStableInput = false; // do not force the output to be ordered
  5430. }
  5431. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  5432. {
  5433. return new CRoxieServerStrandedInlineTableActivity(_ctx, this, _probeManager, strandOptions);
  5434. }
  5435. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  5436. {
  5437. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for InlineTable activity");
  5438. }
  5439. };
  5440. IRoxieServerActivityFactory *createRoxieServerInlineTableActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5441. {
  5442. return new CRoxieServerInlineTableActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  5443. }
  5444. //=================================================================================
  5445. class CRoxieServerWorkUnitReadActivity : public CRoxieServerActivity
  5446. {
  5447. IHThorWorkunitReadArg &helper;
  5448. CriticalSection readerCrit;
  5449. Owned<IWorkUnitRowReader> wuReader;
  5450. public:
  5451. CRoxieServerWorkUnitReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5452. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorWorkunitReadArg &)basehelper)
  5453. {
  5454. }
  5455. virtual void onCreate(IHThorArg *_colocalParent)
  5456. {
  5457. CRoxieServerActivity::onCreate(_colocalParent);
  5458. if (!ctx->queryServerContext())
  5459. {
  5460. throw MakeStringException(ROXIE_INTERNAL_ERROR, "Workunit read activity cannot be executed in slave context");
  5461. }
  5462. }
  5463. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5464. {
  5465. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5466. IXmlToRowTransformer * xmlTransformer = helper.queryXmlTransformer();
  5467. OwnedRoxieString fromWuid(helper.getWUID());
  5468. wuReader.setown(ctx->getWorkunitRowReader(fromWuid, helper.queryName(), helper.querySequence(), xmlTransformer, rowAllocator, meta.isGrouped()));
  5469. // MORE _ should that be in onCreate?
  5470. }
  5471. virtual void reset()
  5472. {
  5473. {
  5474. CriticalBlock b(readerCrit);
  5475. wuReader.clear();
  5476. }
  5477. CRoxieServerActivity::reset();
  5478. };
  5479. virtual bool needsAllocator() const { return true; }
  5480. virtual const void *nextRow()
  5481. {
  5482. ActivityTimer t(totalCycles, timeActivities);
  5483. Linked<IWorkUnitRowReader> useReader;
  5484. {
  5485. CriticalBlock b(readerCrit);
  5486. if (!wuReader)
  5487. return NULL;
  5488. useReader.set(wuReader);
  5489. }
  5490. const void *ret = useReader->nextRow();
  5491. if (ret)
  5492. processed++;
  5493. return ret;
  5494. }
  5495. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  5496. {
  5497. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  5498. }
  5499. };
  5500. class CRoxieServerWorkUnitReadActivityFactory : public CRoxieServerActivityFactory
  5501. {
  5502. public:
  5503. CRoxieServerWorkUnitReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5504. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  5505. {
  5506. }
  5507. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  5508. {
  5509. return new CRoxieServerWorkUnitReadActivity(_ctx, this, _probeManager);
  5510. }
  5511. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  5512. {
  5513. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for WorkUnitRead activity");
  5514. }
  5515. };
  5516. IRoxieServerActivityFactory *createRoxieServerWorkUnitReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5517. {
  5518. return new CRoxieServerWorkUnitReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  5519. }
  5520. //=================================================================================
  5521. interface ILocalGraphEx : public IEclGraphResults
  5522. {
  5523. public:
  5524. virtual void setResult(unsigned id, IGraphResult * result) = 0;
  5525. virtual IEngineRowStream * createResultIterator(unsigned id) = 0;
  5526. virtual void setGraphLoopResult(IGraphResult * result) = 0;
  5527. virtual IEngineRowStream * createGraphLoopResultIterator(unsigned id) = 0;
  5528. };
  5529. class CSafeRoxieInput : implements IEngineRowStream, implements IFinalRoxieInput, public CInterface
  5530. {
  5531. public:
  5532. CSafeRoxieInput(unsigned _sourceIdx, IFinalRoxieInput * _input) : input(_input), inputStream(NULL), sourceIdx(_sourceIdx) {}
  5533. IMPLEMENT_IINTERFACE
  5534. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  5535. {
  5536. connectInputStreams(ctx, consumerOrdered);
  5537. streams.append(this);
  5538. return NULL;
  5539. }
  5540. void connectInputStreams(IRoxieSlaveContext *ctx, bool consumerOrdered)
  5541. {
  5542. inputStream.set(connectSingleStream(ctx, input, sourceIdx, junction, consumerOrdered));
  5543. }
  5544. virtual IOutputMetaData * queryOutputMeta() const
  5545. {
  5546. return input->queryOutputMeta();
  5547. }
  5548. virtual unsigned __int64 queryTotalCycles() const
  5549. {
  5550. return input->queryTotalCycles();
  5551. }
  5552. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { assertex(whichInput==0); return this; }
  5553. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { assertex(idx==0); return nullptr; }
  5554. virtual IRoxieServerActivity *queryActivity()
  5555. {
  5556. return input->queryActivity();
  5557. }
  5558. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  5559. {
  5560. return input->queryIndexReadActivity();
  5561. }
  5562. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5563. {
  5564. CriticalBlock procedure(cs);
  5565. input->start(parentExtractSize, parentExtract, paused);
  5566. startJunction(junction);
  5567. }
  5568. virtual void stop()
  5569. {
  5570. CriticalBlock procedure(cs);
  5571. inputStream->stop();
  5572. }
  5573. virtual void reset()
  5574. {
  5575. CriticalBlock procedure(cs);
  5576. input->reset();
  5577. resetJunction(junction);
  5578. }
  5579. virtual void resetEOF()
  5580. {
  5581. CriticalBlock procedure(cs);
  5582. inputStream->resetEOF();
  5583. }
  5584. virtual const void *nextRow()
  5585. {
  5586. CriticalBlock procedure(cs);
  5587. return inputStream->nextRow();
  5588. }
  5589. virtual bool nextGroup(ConstPointerArray & group)
  5590. {
  5591. CriticalBlock procedure(cs);
  5592. return inputStream->nextGroup(group);
  5593. }
  5594. private:
  5595. CriticalSection cs;
  5596. Linked<IFinalRoxieInput> input;
  5597. Linked<IEngineRowStream> inputStream;
  5598. Owned<IStrandJunction> junction;
  5599. unsigned sourceIdx;
  5600. };
  5601. //=================================================================================
  5602. class CPseudoRoxieInput : implements IEngineRowStream, implements IFinalRoxieInput, public CInterface
  5603. {
  5604. public:
  5605. IMPLEMENT_IINTERFACE;
  5606. CPseudoRoxieInput()
  5607. {
  5608. }
  5609. virtual unsigned __int64 queryTotalCycles() const
  5610. {
  5611. return 0;
  5612. }
  5613. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { assertex(whichInput==0); return this; }
  5614. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { assertex(idx==0); return nullptr; }
  5615. virtual IRoxieServerActivity *queryActivity()
  5616. {
  5617. throwUnexpected();
  5618. }
  5619. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  5620. {
  5621. throwUnexpected();
  5622. }
  5623. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  5624. {
  5625. assertex(!idx);
  5626. streams.append(this);
  5627. return NULL;
  5628. }
  5629. virtual IOutputMetaData * queryOutputMeta() const { throwUnexpected(); }
  5630. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused) { }
  5631. virtual void stop() { }
  5632. virtual void reset() { }
  5633. virtual void checkAbort() { }
  5634. virtual void resetEOF() { }
  5635. };
  5636. class CIndirectRoxieInput : public CPseudoRoxieInput
  5637. {
  5638. public:
  5639. CIndirectRoxieInput() : input(NULL)
  5640. {
  5641. stream = NULL;
  5642. sourceIdx = 0;
  5643. }
  5644. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5645. {
  5646. input->start(parentExtractSize, parentExtract, paused);
  5647. startJunction(junction);
  5648. }
  5649. virtual void stop()
  5650. {
  5651. stream->stop();
  5652. }
  5653. virtual void reset()
  5654. {
  5655. input->reset();
  5656. resetJunction(junction);
  5657. }
  5658. virtual const void * nextRow()
  5659. {
  5660. return stream->nextRow();
  5661. }
  5662. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  5663. {
  5664. return stream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  5665. }
  5666. virtual unsigned __int64 queryTotalCycles() const
  5667. {
  5668. return input->queryTotalCycles();
  5669. }
  5670. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  5671. {
  5672. return input->gatherConjunctions(collector);
  5673. }
  5674. virtual void resetEOF()
  5675. {
  5676. stream->resetEOF();
  5677. }
  5678. virtual unsigned numConcreteOutputs() const
  5679. {
  5680. return input->numConcreteOutputs();
  5681. }
  5682. virtual IFinalRoxieInput * queryConcreteInput(unsigned idx)
  5683. {
  5684. return input->queryConcreteInput(idx);
  5685. }
  5686. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput)
  5687. {
  5688. return input->queryConcreteOutputStream(whichInput);
  5689. }
  5690. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const
  5691. {
  5692. return input->queryConcreteOutputJunction(idx);
  5693. }
  5694. virtual IOutputMetaData * queryOutputMeta() const
  5695. {
  5696. return input->queryOutputMeta();
  5697. }
  5698. virtual IRoxieServerActivity *queryActivity()
  5699. {
  5700. return input->queryActivity();
  5701. }
  5702. inline void setInput(unsigned _sourceIdx, IFinalRoxieInput * _input)
  5703. {
  5704. input = _input;
  5705. sourceIdx = _sourceIdx;
  5706. }
  5707. inline void connectInputStreams(IRoxieSlaveContext *ctx, bool consumerOrdered)
  5708. {
  5709. stream = connectSingleStream(ctx, input, sourceIdx, junction, consumerOrdered);
  5710. }
  5711. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  5712. {
  5713. assertex(idx == 0);
  5714. connectInputStreams(ctx, consumerOrdered);
  5715. streams.append(this);
  5716. return NULL;
  5717. }
  5718. inline IFinalRoxieInput *queryInput() const
  5719. {
  5720. return input;
  5721. }
  5722. protected:
  5723. unsigned sourceIdx;
  5724. IFinalRoxieInput *input;
  5725. IEngineRowStream *stream;
  5726. Owned<IStrandJunction> junction;
  5727. };
  5728. class CExtractMapperInput : public CIndirectRoxieInput
  5729. {
  5730. unsigned savedParentExtractSize;
  5731. const byte * savedParentExtract;
  5732. public:
  5733. CExtractMapperInput()
  5734. {
  5735. savedParentExtractSize = 0;
  5736. savedParentExtract = NULL;
  5737. }
  5738. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5739. {
  5740. CIndirectRoxieInput::start(savedParentExtractSize, savedParentExtract, paused);
  5741. }
  5742. void setParentExtract(unsigned _savedParentExtractSize, const byte * _savedParentExtract)
  5743. {
  5744. savedParentExtractSize = _savedParentExtractSize;
  5745. savedParentExtract = _savedParentExtract;
  5746. }
  5747. };
  5748. class CGraphResult : implements IGraphResult, public CInterface
  5749. {
  5750. CriticalSection cs;
  5751. byte **rowset;
  5752. size32_t count;
  5753. bool complete;
  5754. void clear()
  5755. {
  5756. CriticalBlock func(cs);
  5757. rtlReleaseRowset(count, rowset);
  5758. rowset = NULL;
  5759. count = 0;
  5760. complete = false;
  5761. }
  5762. public:
  5763. IMPLEMENT_IINTERFACE
  5764. CGraphResult()
  5765. {
  5766. complete = false; // dummy result is not supposed to be used...
  5767. rowset = NULL;
  5768. count = 0;
  5769. }
  5770. CGraphResult(size32_t _count, byte **_rowset)
  5771. : count(_count), rowset(_rowset)
  5772. {
  5773. complete = true;
  5774. }
  5775. ~CGraphResult()
  5776. {
  5777. clear();
  5778. }
  5779. // interface IGraphResult
  5780. virtual IEngineRowStream * createIterator()
  5781. {
  5782. if (!complete)
  5783. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Internal Error: Reading uninitialised graph result");
  5784. return new CGraphResultIterator(this);
  5785. }
  5786. virtual void getLinkedResult(unsigned & countResult, byte * * & result)
  5787. {
  5788. if (!complete)
  5789. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Internal Error: Reading uninitialised graph result");
  5790. result = rtlLinkRowset(rowset);
  5791. countResult = count;
  5792. }
  5793. virtual const void * getLinkedRowResult()
  5794. {
  5795. if (!complete)
  5796. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Internal Error: Reading uninitialised graph result");
  5797. if (count != 1)
  5798. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Internal Error: Expected a single row result");
  5799. const void * ret = rowset[0];
  5800. LinkRoxieRow(ret);
  5801. return ret;
  5802. }
  5803. //other
  5804. const void * getRow(unsigned i)
  5805. {
  5806. CriticalBlock func(cs);
  5807. if (i >= count)
  5808. return NULL;
  5809. const void * ret = rowset[i];
  5810. if (ret) LinkRoxieRow(ret);
  5811. return ret;
  5812. }
  5813. protected:
  5814. class CGraphResultIterator : public CInterfaceOf<IEngineRowStream>
  5815. {
  5816. unsigned i;
  5817. Linked<CGraphResult> result;
  5818. public:
  5819. CGraphResultIterator(CGraphResult * _result) : result(_result) { i = 0; }
  5820. public:
  5821. virtual const void * nextRow()
  5822. {
  5823. return result->getRow(i++);
  5824. }
  5825. virtual void stop()
  5826. {
  5827. }
  5828. virtual void resetEOF()
  5829. {
  5830. throwUnexpected();
  5831. }
  5832. };
  5833. };
  5834. //=================================================================================
  5835. class CRoxieServerLocalResultReadActivity : public CRoxieServerActivity
  5836. {
  5837. IHThorLocalResultReadArg &helper;
  5838. CriticalSection iterCrit;
  5839. Owned<IEngineRowStream> iter;
  5840. ILocalGraphEx * graph;
  5841. unsigned graphId;
  5842. unsigned sequence;
  5843. public:
  5844. CRoxieServerLocalResultReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId)
  5845. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorLocalResultReadArg &)basehelper), graphId(_graphId)
  5846. {
  5847. graph = NULL;
  5848. sequence = 0;
  5849. }
  5850. virtual void onCreate(IHThorArg *_colocalParent)
  5851. {
  5852. CRoxieServerActivity::onCreate(_colocalParent);
  5853. graph = static_cast<ILocalGraphEx *>(ctx->queryCodeContext()->resolveLocalQuery(graphId));
  5854. sequence = helper.querySequence();
  5855. }
  5856. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5857. {
  5858. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5859. iter.setown(graph->createResultIterator(sequence));
  5860. }
  5861. virtual void reset()
  5862. {
  5863. {
  5864. CriticalBlock b(iterCrit);
  5865. iter.clear();
  5866. }
  5867. CRoxieServerActivity::reset();
  5868. };
  5869. virtual const void *nextRow()
  5870. {
  5871. ActivityTimer t(totalCycles, timeActivities);
  5872. Linked<IEngineRowStream> useIter;
  5873. {
  5874. CriticalBlock b(iterCrit);
  5875. if (!iter)
  5876. return NULL;
  5877. useIter.set(iter);
  5878. }
  5879. const void * next = useIter->nextRow();
  5880. if (next)
  5881. {
  5882. processed++;
  5883. atomic_inc(&rowsIn);
  5884. }
  5885. return next;
  5886. }
  5887. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  5888. {
  5889. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  5890. }
  5891. };
  5892. class CRoxieServerLocalResultReadActivityFactory : public CRoxieServerActivityFactory
  5893. {
  5894. unsigned graphId;
  5895. public:
  5896. CRoxieServerLocalResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _graphId)
  5897. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), graphId(_graphId)
  5898. {
  5899. }
  5900. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  5901. {
  5902. return new CRoxieServerLocalResultReadActivity(_ctx, this, _probeManager, graphId);
  5903. }
  5904. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  5905. {
  5906. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for LocalResultRead activity");
  5907. }
  5908. };
  5909. IRoxieServerActivityFactory *createRoxieServerLocalResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned graphId)
  5910. {
  5911. return new CRoxieServerLocalResultReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, graphId);
  5912. }
  5913. //=================================================================================
  5914. class CRoxieServerLocalResultStreamReadActivity : public CRoxieServerActivity
  5915. {
  5916. IHThorLocalResultReadArg &helper;
  5917. unsigned sequence;
  5918. public:
  5919. CRoxieServerLocalResultStreamReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5920. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorLocalResultReadArg &)basehelper)
  5921. {
  5922. sequence = 0;
  5923. }
  5924. virtual void onCreate(IHThorArg *_colocalParent)
  5925. {
  5926. CRoxieServerActivity::onCreate(_colocalParent);
  5927. sequence = helper.querySequence();
  5928. }
  5929. virtual const void *nextRow()
  5930. {
  5931. ActivityTimer t(totalCycles, timeActivities);
  5932. const void * next = inputStream->nextRow();
  5933. if (next)
  5934. {
  5935. processed++;
  5936. atomic_inc(&rowsIn);
  5937. }
  5938. return next;
  5939. }
  5940. virtual bool querySetStreamInput(unsigned id, unsigned _sourceIdx, IFinalRoxieInput * _input)
  5941. {
  5942. if (id == sequence)
  5943. {
  5944. CRoxieServerActivity::setInput(0, _sourceIdx, _input);
  5945. connectInputStreams(true);
  5946. return true;
  5947. }
  5948. return false;
  5949. }
  5950. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  5951. {
  5952. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  5953. }
  5954. };
  5955. class CRoxieServerLocalResultStreamReadActivityFactory : public CRoxieServerActivityFactory
  5956. {
  5957. public:
  5958. CRoxieServerLocalResultStreamReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5959. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  5960. {
  5961. }
  5962. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  5963. {
  5964. return new CRoxieServerLocalResultStreamReadActivity(_ctx, this, _probeManager);
  5965. }
  5966. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  5967. {
  5968. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for LocalResultRead activity");
  5969. }
  5970. };
  5971. IRoxieServerActivityFactory *createRoxieServerLocalResultStreamReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5972. {
  5973. return new CRoxieServerLocalResultStreamReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  5974. }
  5975. //=====================================================================================================
  5976. class CRoxieServerLocalResultWriteActivity : public CRoxieServerInternalSinkActivity
  5977. {
  5978. IHThorLocalResultWriteArg &helper;
  5979. ILocalGraphEx * graph;
  5980. unsigned graphId;
  5981. public:
  5982. CRoxieServerLocalResultWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId, unsigned _numOutputs)
  5983. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _numOutputs), helper((IHThorLocalResultWriteArg &)basehelper), graphId(_graphId)
  5984. {
  5985. graph = NULL;
  5986. }
  5987. virtual bool needsAllocator() const { return true; }
  5988. virtual void onCreate(IHThorArg *_colocalParent)
  5989. {
  5990. CRoxieServerInternalSinkActivity::onCreate(_colocalParent);
  5991. graph = static_cast<ILocalGraphEx *>(ctx->queryCodeContext()->resolveLocalQuery(graphId));
  5992. }
  5993. virtual void onExecute()
  5994. {
  5995. RtlLinkedDatasetBuilder builder(rowAllocator);
  5996. inputStream->readAll(builder);
  5997. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  5998. graph->setResult(helper.querySequence(), result);
  5999. }
  6000. virtual const void *nextRow()
  6001. {
  6002. return inputStream->nextRow(); // I can act as a passthrough input
  6003. }
  6004. IFinalRoxieInput * querySelectOutput(unsigned id)
  6005. {
  6006. if (id == helper.querySequence())
  6007. {
  6008. executed = true; // Ensure that we don't try to pull as a sink as well as via the passthrough
  6009. return LINK(this);
  6010. }
  6011. return NULL;
  6012. }
  6013. };
  6014. class CRoxieServerLocalResultWriteActivityFactory : public CRoxieServerInternalSinkFactory
  6015. {
  6016. unsigned graphId;
  6017. public:
  6018. CRoxieServerLocalResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, unsigned _graphId, bool _isRoot)
  6019. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot), graphId(_graphId)
  6020. {
  6021. isInternal = true;
  6022. Owned<IHThorLocalResultWriteArg> helper = (IHThorLocalResultWriteArg *) helperFactory();
  6023. }
  6024. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  6025. {
  6026. return new CRoxieServerLocalResultWriteActivity(_ctx, this, _probeManager, graphId, usageCount);
  6027. }
  6028. };
  6029. IRoxieServerActivityFactory *createRoxieServerLocalResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, unsigned _graphId, bool _isRoot)
  6030. {
  6031. return new CRoxieServerLocalResultWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _graphId, _isRoot);
  6032. }
  6033. //=====================================================================================================
  6034. class CRoxieServerDictionaryResultWriteActivity : public CRoxieServerInternalSinkActivity
  6035. {
  6036. IHThorDictionaryResultWriteArg &helper;
  6037. ILocalGraphEx * graph;
  6038. unsigned graphId;
  6039. public:
  6040. CRoxieServerDictionaryResultWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _usageCount, unsigned _graphId)
  6041. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _usageCount), helper((IHThorDictionaryResultWriteArg &)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. unsigned sequence = helper.querySequence();
  6054. RtlLinkedDictionaryBuilder builder(rowAllocator, helper.queryHashLookupInfo());
  6055. for (;;)
  6056. {
  6057. const void *row = inputStream->ungroupedNextRow();
  6058. if (!row)
  6059. break;
  6060. builder.appendOwn(row);
  6061. processed++;
  6062. }
  6063. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  6064. graph->setResult(helper.querySequence(), result);
  6065. }
  6066. virtual const void *nextRow()
  6067. {
  6068. return inputStream->nextRow(); // I can act as a passthrough input
  6069. }
  6070. IFinalRoxieInput * querySelectOutput(unsigned id)
  6071. {
  6072. if (id == helper.querySequence())
  6073. {
  6074. executed = true; // Ensure that we don't try to pull as a sink as well as via the passthrough
  6075. return LINK(this);
  6076. }
  6077. return NULL;
  6078. }
  6079. };
  6080. class CRoxieServerDictionaryResultWriteActivityFactory : public CRoxieServerInternalSinkFactory
  6081. {
  6082. unsigned graphId;
  6083. public:
  6084. CRoxieServerDictionaryResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, unsigned _graphId, bool _isRoot)
  6085. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot), graphId(_graphId)
  6086. {
  6087. isInternal = true;
  6088. }
  6089. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  6090. {
  6091. return new CRoxieServerDictionaryResultWriteActivity(_ctx, this, _probeManager, usageCount, graphId);
  6092. }
  6093. };
  6094. IRoxieServerActivityFactory *createRoxieServerDictionaryResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, unsigned _graphId, bool _isRoot)
  6095. {
  6096. return new CRoxieServerDictionaryResultWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _graphId, _isRoot);
  6097. }
  6098. //=================================================================================
  6099. class CRoxieServerGraphLoopResultReadActivity : public CRoxieServerActivity
  6100. {
  6101. protected:
  6102. IHThorGraphLoopResultReadArg &helper;
  6103. CriticalSection iterCrit;
  6104. Owned<IFinalRoxieInput> iterInput;
  6105. Owned<IEngineRowStream> iterStream;
  6106. Owned<IStrandJunction> iterJunction;
  6107. ILocalGraphEx * graph;
  6108. unsigned graphId;
  6109. unsigned sequence;
  6110. public:
  6111. CRoxieServerGraphLoopResultReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId)
  6112. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorGraphLoopResultReadArg &)basehelper), graphId(_graphId)
  6113. {
  6114. graph = NULL;
  6115. sequence = 0;
  6116. }
  6117. virtual void onCreate(IHThorArg *_colocalParent)
  6118. {
  6119. CRoxieServerActivity::onCreate(_colocalParent);
  6120. graph = static_cast<ILocalGraphEx *>(ctx->queryCodeContext()->resolveLocalQuery(graphId));
  6121. }
  6122. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6123. {
  6124. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6125. if (iterInput)
  6126. iterInput->start(parentExtractSize, parentExtract, paused);
  6127. else
  6128. {
  6129. sequence = helper.querySequence();
  6130. if ((int)sequence >= 0)
  6131. {
  6132. try
  6133. {
  6134. iterStream.setown(graph->createGraphLoopResultIterator(sequence));
  6135. iterInput.clear();
  6136. }
  6137. catch (IException * E)
  6138. {
  6139. throw makeWrappedException(E);
  6140. }
  6141. }
  6142. }
  6143. startJunction(iterJunction);
  6144. }
  6145. virtual void stop()
  6146. {
  6147. if (iterStream)
  6148. iterStream->stop();
  6149. CRoxieServerActivity::stop();
  6150. }
  6151. virtual void reset()
  6152. {
  6153. {
  6154. CriticalBlock b(iterCrit);
  6155. if (iterInput)
  6156. iterInput->reset();
  6157. resetJunction(iterJunction);
  6158. iterInput.clear();
  6159. iterStream.clear();
  6160. iterJunction.clear();
  6161. }
  6162. CRoxieServerActivity::reset();
  6163. };
  6164. virtual const void *nextRow()
  6165. {
  6166. ActivityTimer t(totalCycles, timeActivities);
  6167. Linked<IEngineRowStream> useStream;
  6168. {
  6169. CriticalBlock b(iterCrit);
  6170. if (!iterStream)
  6171. return NULL;
  6172. useStream.set(iterStream);
  6173. }
  6174. const void * next = useStream->nextRow();
  6175. if (next)
  6176. {
  6177. processed++;
  6178. atomic_inc(&rowsIn);
  6179. }
  6180. return next;
  6181. }
  6182. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  6183. {
  6184. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  6185. }
  6186. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract)
  6187. {
  6188. ensureCreated();
  6189. basehelper.onStart(parentExtract, NULL);
  6190. processor.noteUseIteration(helper.querySequence());
  6191. }
  6192. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract, IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes)
  6193. {
  6194. //helper already initialised from the gatherIterationUsage() call.
  6195. CRoxieServerActivity::connectInputStreams(true);
  6196. iterInput.set(processor.connectIterationOutput(helper.querySequence(), probeManager, probes, this, 0));
  6197. iterStream.set(connectSingleStream(ctx, iterInput, 0, iterJunction, true));
  6198. }
  6199. virtual IInputSteppingMeta * querySteppingMeta()
  6200. {
  6201. assertex(iterInput);
  6202. return iterInput->querySteppingMeta();
  6203. }
  6204. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  6205. {
  6206. assertex(iterStream);
  6207. return iterStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  6208. }
  6209. };
  6210. //variety of CRoxieServerGraphLoopResultReadActivity created internally with a predefined sequence number
  6211. class CRoxieServerInternalGraphLoopResultReadActivity : public CRoxieServerGraphLoopResultReadActivity
  6212. {
  6213. public:
  6214. CRoxieServerInternalGraphLoopResultReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId, unsigned _sequence)
  6215. : CRoxieServerGraphLoopResultReadActivity(_ctx, _factory, _probeManager, _graphId)
  6216. {
  6217. sequence = _sequence;
  6218. }
  6219. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6220. {
  6221. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6222. if ((int)sequence >= 0)
  6223. {
  6224. try
  6225. {
  6226. iterStream.setown(graph->createGraphLoopResultIterator(sequence));
  6227. iterInput.clear();
  6228. }
  6229. catch (IException * E)
  6230. {
  6231. throw makeWrappedException(E);
  6232. }
  6233. }
  6234. }
  6235. };
  6236. class CRoxieServerGraphLoopResultReadActivityFactory : public CRoxieServerActivityFactory
  6237. {
  6238. unsigned graphId;
  6239. public:
  6240. CRoxieServerGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _graphId)
  6241. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), graphId(_graphId)
  6242. {
  6243. }
  6244. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  6245. {
  6246. return new CRoxieServerGraphLoopResultReadActivity(_ctx, this, _probeManager, graphId);
  6247. }
  6248. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  6249. {
  6250. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for GraphLoopResultRead activity");
  6251. }
  6252. };
  6253. IRoxieServerActivityFactory *createRoxieServerGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned graphId)
  6254. {
  6255. return new CRoxieServerGraphLoopResultReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, graphId);
  6256. }
  6257. //=====================================================================================================
  6258. class CRoxieServerGraphLoopResultWriteActivity : public CRoxieServerInternalSinkActivity
  6259. {
  6260. IHThorGraphLoopResultWriteArg &helper;
  6261. ILocalGraphEx * graph;
  6262. unsigned graphId;
  6263. public:
  6264. CRoxieServerGraphLoopResultWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId, unsigned _numOutputs)
  6265. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _numOutputs), helper((IHThorGraphLoopResultWriteArg &)basehelper), graphId(_graphId)
  6266. {
  6267. graph = NULL;
  6268. }
  6269. virtual bool needsAllocator() const { return true; }
  6270. virtual void onCreate(IHThorArg *_colocalParent)
  6271. {
  6272. CRoxieServerInternalSinkActivity::onCreate(_colocalParent);
  6273. graph = static_cast<ILocalGraphEx *>(ctx->queryCodeContext()->resolveLocalQuery(graphId));
  6274. }
  6275. virtual void onExecute()
  6276. {
  6277. RtlLinkedDatasetBuilder builder(rowAllocator);
  6278. inputStream->readAll(builder);
  6279. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  6280. graph->setGraphLoopResult(result);
  6281. }
  6282. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  6283. {
  6284. if (idx==0)
  6285. return this;
  6286. else
  6287. return NULL;
  6288. }
  6289. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  6290. {
  6291. return input->gatherConjunctions(collector);
  6292. }
  6293. virtual void resetEOF()
  6294. {
  6295. inputStream->resetEOF();
  6296. }
  6297. virtual const void *nextRow()
  6298. {
  6299. const void * next = inputStream->nextRow();
  6300. if (next)
  6301. processed++;
  6302. return next;
  6303. }
  6304. virtual bool isPassThrough()
  6305. {
  6306. return true;
  6307. }
  6308. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  6309. {
  6310. ActivityTimer t(totalCycles, timeActivities);
  6311. const void * next = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  6312. if (next)
  6313. processed++;
  6314. return next;
  6315. }
  6316. IInputSteppingMeta * querySteppingMeta()
  6317. {
  6318. return input->querySteppingMeta();
  6319. }
  6320. virtual IOutputMetaData * queryOutputMeta() const
  6321. {
  6322. return input->queryOutputMeta();
  6323. }
  6324. };
  6325. class CRoxieServerGraphLoopResultWriteActivityFactory : public CRoxieServerInternalSinkFactory
  6326. {
  6327. unsigned graphId;
  6328. public:
  6329. CRoxieServerGraphLoopResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, unsigned _graphId)
  6330. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, true), graphId(_graphId)
  6331. {
  6332. isInternal = true;
  6333. Owned<IHThorGraphLoopResultWriteArg> helper = (IHThorGraphLoopResultWriteArg *) helperFactory();
  6334. }
  6335. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  6336. {
  6337. return new CRoxieServerGraphLoopResultWriteActivity(_ctx, this, _probeManager, graphId, usageCount);
  6338. }
  6339. };
  6340. IRoxieServerActivityFactory *createRoxieServerGraphLoopResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, unsigned _graphId)
  6341. {
  6342. return new CRoxieServerGraphLoopResultWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _graphId);
  6343. }
  6344. //=================================================================================
  6345. class CRoxieServerDedupActivity : public CRoxieServerActivity
  6346. {
  6347. protected:
  6348. IHThorDedupArg &helper;
  6349. unsigned numKept;
  6350. unsigned numToKeep;
  6351. public:
  6352. CRoxieServerDedupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6353. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorDedupArg &)basehelper)
  6354. {
  6355. numKept = 0;
  6356. numToKeep = 0;
  6357. }
  6358. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6359. {
  6360. numKept = 0;
  6361. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6362. numToKeep = helper.numToKeep();
  6363. }
  6364. };
  6365. class CRoxieServerDedupKeepLeftActivity : public CRoxieServerDedupActivity
  6366. {
  6367. IRangeCompare * stepCompare;
  6368. const void *prev;
  6369. public:
  6370. CRoxieServerDedupKeepLeftActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6371. : CRoxieServerDedupActivity(_ctx, _factory, _probeManager)
  6372. {
  6373. prev = NULL;
  6374. stepCompare = NULL;
  6375. }
  6376. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6377. {
  6378. prev = NULL;
  6379. CRoxieServerDedupActivity::start(parentExtractSize, parentExtract, paused);
  6380. IInputSteppingMeta * stepMeta = input->querySteppingMeta();
  6381. stepCompare = NULL;
  6382. if (stepMeta)
  6383. stepCompare = stepMeta->queryCompare();
  6384. }
  6385. virtual void reset()
  6386. {
  6387. ReleaseClearRoxieRow(prev);
  6388. CRoxieServerDedupActivity::reset();
  6389. }
  6390. virtual const void * nextRow()
  6391. {
  6392. ActivityTimer t(totalCycles, timeActivities);
  6393. const void * next;
  6394. for (;;)
  6395. {
  6396. next = inputStream->nextRow();
  6397. if (!prev || !next || !helper.matches(prev,next))
  6398. {
  6399. numKept = 0;
  6400. break;
  6401. }
  6402. if (numKept < numToKeep-1)
  6403. {
  6404. numKept++;
  6405. break;
  6406. }
  6407. ReleaseRoxieRow(next);
  6408. }
  6409. ReleaseRoxieRow(prev);
  6410. prev = next;
  6411. if (next)
  6412. {
  6413. LinkRoxieRow(next);
  6414. processed++;
  6415. }
  6416. return next;
  6417. }
  6418. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  6419. {
  6420. ActivityTimer t(totalCycles, timeActivities);
  6421. const void * next;
  6422. for (;;)
  6423. {
  6424. next = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  6425. //If the record was an in-exact match from the index then return it immediately
  6426. //and don't cause it to dedup following legal records.
  6427. if (!wasCompleteMatch)
  6428. {
  6429. assertex(stepExtra.returnMismatches());
  6430. return next;
  6431. }
  6432. if (!prev || !next || !helper.matches(prev,next))
  6433. {
  6434. numKept = 0;
  6435. break;
  6436. }
  6437. if (numKept < numToKeep-1)
  6438. {
  6439. numKept++;
  6440. break;
  6441. }
  6442. //Unusual - deduping by x,y stepped on x,y,z - still want any record back as soon as possible.
  6443. if (stepExtra.returnMismatches())
  6444. {
  6445. //If asked to return mismatches we are only interested in mismatches that will force the stepped
  6446. //condition to advance
  6447. if (stepCompare->docompare(next, seek, numFields) != 0)
  6448. {
  6449. wasCompleteMatch = false;
  6450. break;
  6451. }
  6452. }
  6453. ReleaseRoxieRow(next);
  6454. }
  6455. ReleaseRoxieRow(prev);
  6456. prev = next;
  6457. if (next)
  6458. {
  6459. LinkRoxieRow(next);
  6460. processed++;
  6461. }
  6462. return next;
  6463. }
  6464. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  6465. {
  6466. return input->gatherConjunctions(collector);
  6467. }
  6468. virtual void resetEOF()
  6469. {
  6470. inputStream->resetEOF();
  6471. }
  6472. IInputSteppingMeta * querySteppingMeta()
  6473. {
  6474. return input->querySteppingMeta();
  6475. }
  6476. };
  6477. //=================================================================================
  6478. class CRoxieServerDedupKeepRightActivity : public CRoxieServerDedupActivity
  6479. {
  6480. const void *kept;
  6481. bool first;
  6482. public:
  6483. CRoxieServerDedupKeepRightActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6484. : CRoxieServerDedupActivity(_ctx, _factory, _probeManager)
  6485. {
  6486. kept = NULL;
  6487. first = true;
  6488. }
  6489. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6490. {
  6491. first = true;
  6492. kept = NULL;
  6493. CRoxieServerDedupActivity::start(parentExtractSize, parentExtract, paused);
  6494. if (numToKeep>1)
  6495. throw MakeStringException(ROXIE_UNIMPLEMENTED_ERROR, "DEDUP with RIGHT and NumToKeep>1 not supported");
  6496. }
  6497. virtual void reset()
  6498. {
  6499. ReleaseClearRoxieRow(kept);
  6500. CRoxieServerActivity::reset();
  6501. }
  6502. virtual const void * nextRow()
  6503. {
  6504. ActivityTimer t(totalCycles, timeActivities);
  6505. if (first)
  6506. {
  6507. kept = inputStream->nextRow();
  6508. first = false;
  6509. }
  6510. const void * next;
  6511. for (;;)
  6512. {
  6513. next = inputStream->nextRow();
  6514. if (!kept || !next || !helper.matches(kept,next))
  6515. break;
  6516. ReleaseRoxieRow(kept);
  6517. kept = next;
  6518. }
  6519. const void * ret = kept;
  6520. kept = next;
  6521. // CTXLOG("dedup returns %p", ret);
  6522. if (ret) processed++;
  6523. return ret;
  6524. }
  6525. };
  6526. class CRoxieServerDedupAllActivity : public CRoxieServerActivity
  6527. {
  6528. IHThorDedupArg &helper;
  6529. unsigned survivorIndex;
  6530. ConstPointerArray survivors;
  6531. bool keepLeft;
  6532. bool eof;
  6533. bool first;
  6534. ICompare *primaryCompare;
  6535. public:
  6536. CRoxieServerDedupAllActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _keepLeft)
  6537. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorDedupArg &)basehelper)
  6538. {
  6539. keepLeft = _keepLeft;
  6540. primaryCompare = helper.queryComparePrimary();
  6541. eof = false;
  6542. first = true;
  6543. survivorIndex = 0;
  6544. }
  6545. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6546. {
  6547. eof = false;
  6548. first = true;
  6549. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6550. }
  6551. virtual void reset()
  6552. {
  6553. while (survivors.isItem(survivorIndex))
  6554. {
  6555. ReleaseRoxieRow(survivors.item(survivorIndex++));
  6556. }
  6557. survivors.kill();
  6558. eof = false;
  6559. first = true;
  6560. CRoxieServerActivity::reset();
  6561. }
  6562. void dedupRange(unsigned first, unsigned last, ConstPointerArray & group)
  6563. {
  6564. for (unsigned idxL = first; idxL < last; idxL++)
  6565. {
  6566. const void * left = group.item(idxL);
  6567. if (left)
  6568. {
  6569. for (unsigned idxR = first; idxR < last; idxR++)
  6570. {
  6571. const void * right = group.item(idxR);
  6572. if ((idxL != idxR) && right)
  6573. {
  6574. if (helper.matches(left, right))
  6575. {
  6576. if (keepLeft)
  6577. {
  6578. group.replace(NULL, idxR);
  6579. ReleaseRoxieRow(right);
  6580. }
  6581. else
  6582. {
  6583. group.replace(NULL, idxL);
  6584. ReleaseRoxieRow(left);
  6585. break;
  6586. }
  6587. }
  6588. }
  6589. }
  6590. }
  6591. }
  6592. }
  6593. void dedupRange(unsigned first, unsigned last, void ** rows)
  6594. {
  6595. for (unsigned idxL = first; idxL < last; idxL++)
  6596. {
  6597. void * left = rows[idxL];
  6598. if (left)
  6599. {
  6600. for (unsigned idxR = first; idxR < last; idxR++)
  6601. {
  6602. void * right = rows[idxR];
  6603. if ((idxL != idxR) && right)
  6604. {
  6605. if (helper.matches(left, right))
  6606. {
  6607. if (keepLeft)
  6608. {
  6609. rows[idxR] = NULL;
  6610. ReleaseRoxieRow(right);
  6611. }
  6612. else
  6613. {
  6614. rows[idxL] = NULL;
  6615. ReleaseRoxieRow(left);
  6616. break;
  6617. }
  6618. }
  6619. }
  6620. }
  6621. }
  6622. }
  6623. }
  6624. bool calcNextDedupAll()
  6625. {
  6626. survivors.kill();
  6627. survivorIndex = 0;
  6628. ConstPointerArray group;
  6629. if (eof || !inputStream->nextGroup(group))
  6630. {
  6631. eof = true;
  6632. return false;
  6633. }
  6634. unsigned max = group.ordinality();
  6635. if (primaryCompare)
  6636. {
  6637. //hard, if not impossible, to hit this code once optimisations in place
  6638. MemoryAttr indexbuff(max*sizeof(void *));
  6639. void ** temp = (void **)indexbuff.bufferBase();
  6640. void * *rows = const_cast<void * *>(group.getArray());
  6641. msortvecstableinplace(rows, max, *primaryCompare, temp);
  6642. unsigned first = 0;
  6643. for (unsigned idx = 1; idx < max; idx++)
  6644. {
  6645. if (primaryCompare->docompare(rows[first], rows[idx]) != 0)
  6646. {
  6647. dedupRange(first, idx, rows);
  6648. first = idx;
  6649. }
  6650. }
  6651. dedupRange(first, max, rows);
  6652. for(unsigned idx2=0; idx2<max; ++idx2)
  6653. {
  6654. void * cur = rows[idx2];
  6655. if(cur)
  6656. survivors.append(cur);
  6657. }
  6658. }
  6659. else
  6660. {
  6661. dedupRange(0, max, group);
  6662. for(unsigned idx=0; idx<max; ++idx)
  6663. {
  6664. const void * cur = group.item(idx);
  6665. if(cur)
  6666. survivors.append(cur);
  6667. }
  6668. }
  6669. return true;
  6670. }
  6671. virtual const void *nextRow()
  6672. {
  6673. ActivityTimer t(totalCycles, timeActivities);
  6674. if (first)
  6675. {
  6676. calcNextDedupAll();
  6677. first = false;
  6678. }
  6679. while (survivors.isItem(survivorIndex))
  6680. {
  6681. const void *ret = survivors.item(survivorIndex++);
  6682. if (ret)
  6683. {
  6684. processed++;
  6685. return ret;
  6686. }
  6687. }
  6688. calcNextDedupAll();
  6689. return NULL;
  6690. }
  6691. };
  6692. class CRoxieServerDedupActivityFactory : public CRoxieServerActivityFactory
  6693. {
  6694. bool compareAll;
  6695. bool keepLeft;
  6696. public:
  6697. CRoxieServerDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  6698. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  6699. {
  6700. Owned<IHThorDedupArg> helper = (IHThorDedupArg *) helperFactory();
  6701. compareAll = helper->compareAll();
  6702. keepLeft = helper->keepLeft();
  6703. }
  6704. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  6705. {
  6706. if (compareAll)
  6707. return new CRoxieServerDedupAllActivity(_ctx, this, _probeManager, keepLeft);
  6708. else if (keepLeft)
  6709. return new CRoxieServerDedupKeepLeftActivity(_ctx, this, _probeManager);
  6710. else
  6711. return new CRoxieServerDedupKeepRightActivity(_ctx, this, _probeManager);
  6712. }
  6713. };
  6714. IRoxieServerActivityFactory *createRoxieServerDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  6715. {
  6716. return new CRoxieServerDedupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  6717. }
  6718. //=================================================================================
  6719. class CRoxieServerHashDedupActivity : public CRoxieServerActivity
  6720. {
  6721. bool eof;
  6722. IHThorHashDedupArg &helper;
  6723. class HashDedupElement
  6724. {
  6725. public:
  6726. HashDedupElement(unsigned _hash, const void *_keyRow)
  6727. : hash(_hash), keyRow(_keyRow)
  6728. {
  6729. }
  6730. ~HashDedupElement()
  6731. {
  6732. ReleaseRoxieRow(keyRow);
  6733. }
  6734. inline unsigned queryHash() const
  6735. {
  6736. return hash;
  6737. }
  6738. inline const void *queryRow() const
  6739. {
  6740. return keyRow;
  6741. }
  6742. private:
  6743. unsigned hash;
  6744. const void *keyRow;
  6745. };
  6746. class HashDedupTable : public SuperHashTable
  6747. {
  6748. public:
  6749. HashDedupTable(IHThorHashDedupArg & _helper, CRoxieServerHashDedupActivity & _activity)
  6750. : helper(_helper),
  6751. activity(_activity),
  6752. keySize(helper.queryKeySize())
  6753. {
  6754. }
  6755. virtual ~HashDedupTable() { _releaseAll(); }
  6756. virtual unsigned getHashFromElement(const void *et) const
  6757. {
  6758. const HashDedupElement *element = reinterpret_cast<const HashDedupElement *>(et);
  6759. return element->queryHash();
  6760. }
  6761. virtual unsigned getHashFromFindParam(const void *fp) const { throwUnexpected(); }
  6762. virtual const void * getFindParam(const void *et) const { throwUnexpected(); }
  6763. virtual bool matchesElement(const void *et, const void *searchET) const { throwUnexpected(); }
  6764. virtual bool matchesFindParam(const void *et, const void *key, unsigned fphash) const
  6765. {
  6766. const HashDedupElement *element = reinterpret_cast<const HashDedupElement *>(et);
  6767. if (fphash != element->queryHash())
  6768. return false;
  6769. return (helper.queryKeyCompare()->docompare(element->queryRow(), key) == 0);
  6770. }
  6771. virtual void onAdd(void *et) {}
  6772. virtual void onRemove(void *et)
  6773. {
  6774. const HashDedupElement *element = reinterpret_cast<const HashDedupElement *>(et);
  6775. delete element;
  6776. }
  6777. void onCreate(IRoxieSlaveContext *ctx)
  6778. {
  6779. keyRowAllocator.setown(activity.createRowAllocator(keySize.queryOriginal()));
  6780. }
  6781. void reset()
  6782. {
  6783. kill();
  6784. }
  6785. bool insert(const void * row)
  6786. {
  6787. unsigned hash = helper.queryHash()->hash(row);
  6788. RtlDynamicRowBuilder keyRowBuilder(keyRowAllocator, true);
  6789. size32_t thisKeySize = helper.recordToKey(keyRowBuilder, row);
  6790. OwnedConstRoxieRow keyRow = keyRowBuilder.finalizeRowClear(thisKeySize);
  6791. if (find(hash, keyRow.get()))
  6792. return false;
  6793. addNew(new HashDedupElement(hash, keyRow.getClear()), hash);
  6794. return true;
  6795. }
  6796. private:
  6797. IHThorHashDedupArg & helper;
  6798. CachedOutputMetaData keySize;
  6799. Owned<IEngineRowAllocator> keyRowAllocator;
  6800. CRoxieServerHashDedupActivity & activity;
  6801. } table;
  6802. public:
  6803. CRoxieServerHashDedupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6804. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorHashDedupArg &)basehelper), table(helper, *this)
  6805. {
  6806. eof = false;
  6807. }
  6808. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6809. {
  6810. eof = false;
  6811. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6812. }
  6813. virtual void onCreate(IHThorArg *_colocalParent)
  6814. {
  6815. CRoxieServerActivity::onCreate(colocalParent);
  6816. table.onCreate(ctx);
  6817. }
  6818. virtual void reset()
  6819. {
  6820. table.reset();
  6821. eof = false;
  6822. CRoxieServerActivity::reset();
  6823. }
  6824. virtual const void *nextRow()
  6825. {
  6826. ActivityTimer t(totalCycles, timeActivities);
  6827. while(!eof)
  6828. {
  6829. const void * next = inputStream->nextRow();
  6830. if(!next)
  6831. {
  6832. if (table.count() == 0)
  6833. eof = true;
  6834. table.reset();
  6835. return NULL;
  6836. }
  6837. if(table.insert(next))
  6838. return next;
  6839. else
  6840. ReleaseRoxieRow(next);
  6841. }
  6842. return NULL;
  6843. }
  6844. };
  6845. class CRoxieServerHashDedupActivityFactory : public CRoxieServerActivityFactory
  6846. {
  6847. public:
  6848. CRoxieServerHashDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  6849. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  6850. {
  6851. }
  6852. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  6853. {
  6854. return new CRoxieServerHashDedupActivity(_ctx, this, _probeManager);
  6855. }
  6856. };
  6857. IRoxieServerActivityFactory *createRoxieServerHashDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  6858. {
  6859. return new CRoxieServerHashDedupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  6860. }
  6861. //=================================================================================
  6862. class CRoxieServerRollupActivity : public CRoxieServerActivity
  6863. {
  6864. IHThorRollupArg &helper;
  6865. OwnedConstRoxieRow left;
  6866. OwnedConstRoxieRow prev;
  6867. OwnedConstRoxieRow right;
  6868. bool readFirstRow;
  6869. public:
  6870. CRoxieServerRollupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6871. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorRollupArg &)basehelper)
  6872. {
  6873. readFirstRow = false;
  6874. }
  6875. ~CRoxieServerRollupActivity()
  6876. {
  6877. }
  6878. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6879. {
  6880. readFirstRow = false;
  6881. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6882. }
  6883. virtual void reset()
  6884. {
  6885. left.clear();
  6886. prev.clear();
  6887. right.clear();
  6888. CRoxieServerActivity::reset();
  6889. }
  6890. virtual bool needsAllocator() const { return true; }
  6891. virtual const void * nextRow()
  6892. {
  6893. ActivityTimer t(totalCycles, timeActivities);
  6894. if (!readFirstRow)
  6895. {
  6896. left.setown(inputStream->nextRow());
  6897. prev.set(left);
  6898. readFirstRow = true;
  6899. }
  6900. for (;;)
  6901. {
  6902. right.setown(inputStream->nextRow());
  6903. if(!prev || !right || !helper.matches(prev,right))
  6904. {
  6905. const void * ret = left.getClear();
  6906. if(ret)
  6907. processed++;
  6908. left.setown(right.getClear());
  6909. prev.set(left);
  6910. return ret;
  6911. }
  6912. try
  6913. {
  6914. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  6915. unsigned outSize = helper.transform(rowBuilder, left, right);
  6916. if (outSize)
  6917. left.setown(rowBuilder.finalizeRowClear(outSize));
  6918. if (helper.getFlags() & RFrolledismatchleft)
  6919. prev.set(left);
  6920. else
  6921. prev.set(right);
  6922. }
  6923. catch(IException * E)
  6924. {
  6925. throw makeWrappedException(E);
  6926. }
  6927. }
  6928. }
  6929. };
  6930. class CRoxieServerRollupActivityFactory : public CRoxieServerActivityFactory
  6931. {
  6932. public:
  6933. CRoxieServerRollupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  6934. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  6935. {
  6936. }
  6937. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  6938. {
  6939. return new CRoxieServerRollupActivity(_ctx, this, _probeManager);
  6940. }
  6941. };
  6942. IRoxieServerActivityFactory *createRoxieServerRollupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  6943. {
  6944. return new CRoxieServerRollupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  6945. }
  6946. //=================================================================================
  6947. class CRoxieServerNormalizeActivity : public CRoxieServerActivity
  6948. {
  6949. IHThorNormalizeArg &helper;
  6950. unsigned numThisRow;
  6951. unsigned curRow;
  6952. const void *buffer;
  6953. unsigned numProcessedLastGroup;
  6954. public:
  6955. CRoxieServerNormalizeActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6956. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorNormalizeArg &)basehelper)
  6957. {
  6958. buffer = NULL;
  6959. numThisRow = 0;
  6960. curRow = 0;
  6961. numProcessedLastGroup = 0;
  6962. }
  6963. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6964. {
  6965. numThisRow = 0;
  6966. curRow = 0;
  6967. numProcessedLastGroup = 0;
  6968. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6969. }
  6970. virtual void reset()
  6971. {
  6972. ReleaseClearRoxieRow(buffer);
  6973. CRoxieServerActivity::reset();
  6974. }
  6975. virtual bool needsAllocator() const { return true; }
  6976. virtual const void * nextRow()
  6977. {
  6978. ActivityTimer t(totalCycles, timeActivities);
  6979. for (;;)
  6980. {
  6981. while (curRow == numThisRow)
  6982. {
  6983. if (buffer)
  6984. ReleaseClearRoxieRow(buffer);
  6985. buffer = inputStream->nextRow();
  6986. if (!buffer && (processed == numProcessedLastGroup))
  6987. buffer = inputStream->nextRow();
  6988. if (!buffer)
  6989. {
  6990. numProcessedLastGroup = processed;
  6991. return NULL;
  6992. }
  6993. curRow = 0;
  6994. numThisRow = helper.numExpandedRows(buffer);
  6995. }
  6996. try
  6997. {
  6998. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  6999. unsigned actualSize = helper.transform(rowBuilder, buffer, ++curRow);
  7000. if (actualSize != 0)
  7001. {
  7002. processed++;
  7003. return rowBuilder.finalizeRowClear(actualSize);
  7004. }
  7005. }
  7006. catch (IException *E)
  7007. {
  7008. throw makeWrappedException(E);
  7009. }
  7010. }
  7011. }
  7012. };
  7013. class CRoxieServerNormalizeActivityFactory : public CRoxieServerActivityFactory
  7014. {
  7015. public:
  7016. CRoxieServerNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7017. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  7018. {
  7019. }
  7020. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  7021. {
  7022. return new CRoxieServerNormalizeActivity(_ctx, this, _probeManager);
  7023. }
  7024. };
  7025. IRoxieServerActivityFactory *createRoxieServerNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7026. {
  7027. return new CRoxieServerNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  7028. }
  7029. //=================================================================================
  7030. class CRoxieServerNormalizeChildActivity : public CRoxieServerActivity
  7031. {
  7032. IHThorNormalizeChildArg &helper;
  7033. unsigned numThisRow;
  7034. unsigned curRow;
  7035. const void *buffer;
  7036. unsigned numProcessedLastGroup;
  7037. INormalizeChildIterator * cursor;
  7038. const void * curChildRow;
  7039. bool advanceInput()
  7040. {
  7041. for (;;)
  7042. {
  7043. ReleaseClearRoxieRow(buffer);
  7044. buffer = inputStream->nextRow();
  7045. if (!buffer && (processed == numProcessedLastGroup))
  7046. buffer = inputStream->nextRow();
  7047. if (!buffer)
  7048. {
  7049. numProcessedLastGroup = processed;
  7050. return false;
  7051. }
  7052. curChildRow = cursor->first(buffer);
  7053. if (curChildRow)
  7054. {
  7055. curRow = 0;
  7056. return true;
  7057. }
  7058. }
  7059. }
  7060. public:
  7061. CRoxieServerNormalizeChildActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  7062. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorNormalizeChildArg &)basehelper)
  7063. {
  7064. buffer = NULL;
  7065. cursor = NULL;
  7066. numThisRow = 0;
  7067. curRow = 0;
  7068. numProcessedLastGroup = 0;
  7069. curChildRow = NULL;
  7070. }
  7071. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7072. {
  7073. numThisRow = 0;
  7074. curRow = 0;
  7075. numProcessedLastGroup = 0;
  7076. curChildRow = NULL;
  7077. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7078. cursor = helper.queryIterator();
  7079. }
  7080. virtual void stop()
  7081. {
  7082. CRoxieServerActivity::stop();
  7083. }
  7084. virtual void reset()
  7085. {
  7086. cursor = NULL;
  7087. ReleaseClearRoxieRow(buffer);
  7088. CRoxieServerActivity::reset();
  7089. }
  7090. virtual bool needsAllocator() const { return true; }
  7091. const void *nextRow()
  7092. {
  7093. ActivityTimer t(totalCycles, timeActivities);
  7094. for (;;)
  7095. {
  7096. if (!buffer)
  7097. {
  7098. if (!advanceInput())
  7099. return NULL;
  7100. }
  7101. try
  7102. {
  7103. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  7104. size32_t outSize = helper.transform(rowBuilder, buffer, curChildRow, ++curRow);
  7105. curChildRow = cursor->next();
  7106. if (!curChildRow)
  7107. ReleaseClearRoxieRow(buffer);
  7108. if (outSize != 0)
  7109. {
  7110. processed++;
  7111. return rowBuilder.finalizeRowClear(outSize);
  7112. }
  7113. }
  7114. catch (IException *E)
  7115. {
  7116. throw makeWrappedException(E);
  7117. }
  7118. }
  7119. }
  7120. };
  7121. class CRoxieServerNormalizeChildActivityFactory : public CRoxieServerActivityFactory
  7122. {
  7123. public:
  7124. CRoxieServerNormalizeChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7125. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  7126. {
  7127. }
  7128. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  7129. {
  7130. return new CRoxieServerNormalizeChildActivity(_ctx, this, _probeManager);
  7131. }
  7132. };
  7133. IRoxieServerActivityFactory *createRoxieServerNormalizeChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7134. {
  7135. return new CRoxieServerNormalizeChildActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  7136. }
  7137. //=================================================================================
  7138. class CRoxieServerNormalizeLinkedChildActivity : public CRoxieServerActivity
  7139. {
  7140. IHThorNormalizeLinkedChildArg &helper;
  7141. OwnedConstRoxieRow curParent;
  7142. OwnedConstRoxieRow curChild;
  7143. unsigned numProcessedLastGroup;
  7144. bool advanceInput()
  7145. {
  7146. for (;;)
  7147. {
  7148. curParent.setown(inputStream->nextRow());
  7149. if (!curParent && (processed == numProcessedLastGroup))
  7150. curParent.setown(inputStream->nextRow());
  7151. if (!curParent)
  7152. {
  7153. numProcessedLastGroup = processed;
  7154. return false;
  7155. }
  7156. curChild.set(helper.first(curParent));
  7157. if (curChild)
  7158. return true;
  7159. }
  7160. }
  7161. public:
  7162. CRoxieServerNormalizeLinkedChildActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  7163. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorNormalizeLinkedChildArg &)basehelper)
  7164. {
  7165. numProcessedLastGroup = 0;
  7166. }
  7167. ~CRoxieServerNormalizeLinkedChildActivity()
  7168. {
  7169. }
  7170. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7171. {
  7172. numProcessedLastGroup = 0;
  7173. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7174. }
  7175. virtual void reset()
  7176. {
  7177. curParent.clear();
  7178. curChild.clear();
  7179. CRoxieServerActivity::reset();
  7180. }
  7181. const void *nextRow()
  7182. {
  7183. ActivityTimer t(totalCycles, timeActivities);
  7184. for (;;)
  7185. {
  7186. if (!curParent)
  7187. {
  7188. if (!advanceInput())
  7189. return NULL;
  7190. }
  7191. try
  7192. {
  7193. const void *ret = curChild.getClear();
  7194. curChild.set(helper.next());
  7195. if (!curChild)
  7196. curParent.clear();
  7197. if (ret)
  7198. {
  7199. processed++;
  7200. return ret;
  7201. }
  7202. }
  7203. catch (IException *E)
  7204. {
  7205. throw makeWrappedException(E);
  7206. }
  7207. }
  7208. }
  7209. };
  7210. class CRoxieServerNormalizeLinkedChildActivityFactory : public CRoxieServerActivityFactory
  7211. {
  7212. public:
  7213. CRoxieServerNormalizeLinkedChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7214. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  7215. {
  7216. }
  7217. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  7218. {
  7219. return new CRoxieServerNormalizeLinkedChildActivity(_ctx, this, _probeManager);
  7220. }
  7221. };
  7222. IRoxieServerActivityFactory *createRoxieServerNormalizeLinkedChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7223. {
  7224. return new CRoxieServerNormalizeLinkedChildActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  7225. }
  7226. //=================================================================================
  7227. class CRoxieServerSortActivity : public CRoxieServerActivity
  7228. {
  7229. protected:
  7230. IHThorSortArg &helper;
  7231. ICompare *compare;
  7232. Owned<ISortAlgorithm> sorter;
  7233. bool readInput;
  7234. RoxieSortAlgorithm sortAlgorithm;
  7235. unsigned sortFlags;
  7236. public:
  7237. CRoxieServerSortActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, RoxieSortAlgorithm _sortAlgorithm, unsigned _sortFlags)
  7238. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorSortArg &)basehelper), sortAlgorithm(_sortAlgorithm), sortFlags(_sortFlags)
  7239. {
  7240. compare = helper.queryCompare();
  7241. readInput = false;
  7242. }
  7243. virtual void onCreate(IHThorArg *_colocalParent)
  7244. {
  7245. CRoxieServerActivity::onCreate(_colocalParent);
  7246. if (sortAlgorithm==unknownSortAlgorithm)
  7247. sorter.clear();
  7248. else
  7249. sorter.setown(createSortAlgorithm(sortAlgorithm, compare, ctx->queryRowManager(), meta, ctx->queryCodeContext(), tempDirectory, activityId));
  7250. }
  7251. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7252. {
  7253. assertex(!readInput);
  7254. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7255. }
  7256. virtual void reset()
  7257. {
  7258. if (sorter)
  7259. sorter->reset();
  7260. readInput = false;
  7261. CRoxieServerActivity::reset();
  7262. }
  7263. static RoxieSortAlgorithm useAlgorithm(const char *algorithmName, unsigned sortFlags)
  7264. {
  7265. RoxieSortAlgorithm sortAlgorithm = unknownSortAlgorithm;
  7266. if (!algorithmName)
  7267. algorithmName = "";
  7268. if (stricmp(algorithmName, "quicksort")==0)
  7269. {
  7270. switch (sortFlags & (TAFstable|TAFspill))
  7271. {
  7272. case 0: sortAlgorithm = quickSortAlgorithm; break;
  7273. case TAFstable: sortAlgorithm = stableQuickSortAlgorithm; break;
  7274. case TAFspill: sortAlgorithm = spillingQuickSortAlgorithm; break;
  7275. case TAFstable|TAFspill: sortAlgorithm = stableSpillingQuickSortAlgorithm; break;
  7276. }
  7277. }
  7278. else if (stricmp(algorithmName, "parquicksort")==0)
  7279. {
  7280. switch (sortFlags & TAFstable)
  7281. {
  7282. case 0: sortAlgorithm = parallelQuickSortAlgorithm; break;
  7283. case TAFstable: sortAlgorithm = parallelStableQuickSortAlgorithm; break;
  7284. default: throwUnexpected();
  7285. }
  7286. }
  7287. else if (stricmp(algorithmName, "heapsort")==0)
  7288. sortAlgorithm = heapSortAlgorithm; // NOTE - we do allow UNSTABLE('heapsort') in order to facilitate runtime selection. Also explicit selection of heapsort overrides request to spill
  7289. else if (stricmp(algorithmName, "mergesort")==0)
  7290. sortAlgorithm = (sortFlags & TAFspill) ? spillingMergeSortAlgorithm : mergeSortAlgorithm;
  7291. else if (stricmp(algorithmName, "parmergesort")==0)
  7292. sortAlgorithm = (sortFlags & TAFspill) ? spillingParallelMergeSortAlgorithm : parallelMergeSortAlgorithm;
  7293. else if (stricmp(algorithmName, "tbbqsort")==0)
  7294. sortAlgorithm = tbbQuickSortAlgorithm;
  7295. else if (stricmp(algorithmName, "tbbstableqsort")==0)
  7296. sortAlgorithm = tbbStableQuickSortAlgorithm;
  7297. else
  7298. {
  7299. if (*algorithmName)
  7300. WARNLOG(ROXIE_UNKNOWN_ALGORITHM, "Ignoring unsupported sort order algorithm '%s', using default", algorithmName);
  7301. if (sortFlags & TAFspill)
  7302. sortAlgorithm = ((sortFlags & TAFunstable) != 0) ? spillingQuickSortAlgorithm : stableSpillingQuickSortAlgorithm;
  7303. else if (sortFlags & TAFunstable)
  7304. sortAlgorithm = quickSortAlgorithm;
  7305. else
  7306. sortAlgorithm = heapSortAlgorithm;
  7307. }
  7308. return sortAlgorithm;
  7309. }
  7310. virtual const void * nextRow()
  7311. {
  7312. ActivityTimer t(totalCycles, timeActivities);
  7313. if (!readInput)
  7314. {
  7315. if (sortAlgorithm == unknownSortAlgorithm)
  7316. {
  7317. sorter.clear();
  7318. IHThorAlgorithm *sortMethod = static_cast<IHThorAlgorithm *>(helper.selectInterface(TAIalgorithm_1));
  7319. OwnedRoxieString algorithmName(sortMethod->getAlgorithm());
  7320. sortAlgorithm = useAlgorithm(algorithmName, sortFlags);
  7321. sorter.setown(createSortAlgorithm(sortAlgorithm, compare, ctx->queryRowManager(), meta, ctx->queryCodeContext(), tempDirectory, activityId));
  7322. }
  7323. sorter->prepare(inputStream);
  7324. noteStatistic(StTimeSortElapsed, cycle_to_nanosec(sorter->getElapsedCycles(true)));
  7325. readInput = true;
  7326. }
  7327. const void *ret = sorter->next();
  7328. if (ret)
  7329. processed++;
  7330. else
  7331. {
  7332. sorter->reset();
  7333. readInput = false; // ready for next group
  7334. }
  7335. return ret;
  7336. }
  7337. };
  7338. class CRoxieServerSortActivityFactory : public CRoxieServerActivityFactory
  7339. {
  7340. RoxieSortAlgorithm sortAlgorithm;
  7341. unsigned sortFlags;
  7342. public:
  7343. CRoxieServerSortActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7344. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  7345. {
  7346. Owned<IHThorSortArg> sortHelper = (IHThorSortArg *) helperFactory();
  7347. const char *algorithmName = NULL;
  7348. IHThorAlgorithm *sortMethod = static_cast<IHThorAlgorithm *>(sortHelper->selectInterface(TAIalgorithm_1));
  7349. if (sortMethod)
  7350. {
  7351. sortFlags = sortMethod->getAlgorithmFlags();
  7352. if (sortFlags & TAFconstant)
  7353. algorithmName = sortMethod->getAlgorithm();
  7354. }
  7355. else
  7356. sortFlags = TAFstable|TAFconstant;
  7357. bool forceSpill = _queryFactory.queryOptions().allSortsMaySpill || _graphNode.getPropBool("hint[@name='spill']/@value", false);
  7358. if (forceSpill)
  7359. sortFlags |= TAFspill;
  7360. if (!(sortFlags & TAFunstable))
  7361. sortFlags |= TAFstable; // Assume stable unless specifically requested otherwise
  7362. if (sortFlags & TAFconstant)
  7363. sortAlgorithm = CRoxieServerSortActivity::useAlgorithm(algorithmName, sortFlags);
  7364. else
  7365. sortAlgorithm = unknownSortAlgorithm;
  7366. }
  7367. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  7368. {
  7369. return new CRoxieServerSortActivity(_ctx, this, _probeManager, sortAlgorithm, sortFlags);
  7370. }
  7371. virtual const StatisticsMapping &queryStatsMapping() const
  7372. {
  7373. return sortStatistics;
  7374. }
  7375. };
  7376. IRoxieServerActivityFactory *createRoxieServerSortActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7377. {
  7378. return new CRoxieServerSortActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  7379. }
  7380. //=====================================================================================================
  7381. static int compareUint64(const void * _left, const void * _right)
  7382. {
  7383. const unsigned __int64 left = *static_cast<const unsigned __int64 *>(_left);
  7384. const unsigned __int64 right = *static_cast<const unsigned __int64 *>(_right);
  7385. if (left < right)
  7386. return -1;
  7387. if (left > right)
  7388. return -1;
  7389. return 0;
  7390. }
  7391. class CRoxieServerQuantileActivity : public CRoxieServerActivity
  7392. {
  7393. protected:
  7394. Owned<ISortAlgorithm> sorter;
  7395. IHThorQuantileArg &helper;
  7396. ConstPointerArray sorted;
  7397. ICompare *compare;
  7398. unsigned flags;
  7399. double skew;
  7400. unsigned __int64 numDivisions;
  7401. bool rangeIsAll;
  7402. size32_t rangeSize;
  7403. rtlDataAttr rangeValues;
  7404. bool calculated;
  7405. bool processedAny;
  7406. bool anyThisGroup;
  7407. bool eof;
  7408. unsigned curQuantile;
  7409. unsigned curIndex;
  7410. unsigned curIndexExtra;
  7411. unsigned skipSize;
  7412. unsigned skipExtra;
  7413. unsigned prevIndex;
  7414. public:
  7415. CRoxieServerQuantileActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _flags)
  7416. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorQuantileArg &)basehelper), flags(_flags)
  7417. {
  7418. compare = helper.queryCompare();
  7419. skew = 0.0;
  7420. numDivisions = 0;
  7421. calculated = false;
  7422. processedAny = false;
  7423. anyThisGroup = false;
  7424. eof = false;
  7425. rangeIsAll = true;
  7426. rangeSize = 0;
  7427. curQuantile = 0;
  7428. prevIndex = 0;
  7429. curIndex = 0;
  7430. curIndexExtra = 0;
  7431. skipSize = 0;
  7432. skipExtra = 0;
  7433. if (flags & TQFunstable)
  7434. sorter.setown(createQuickSortAlgorithm(compare));
  7435. else
  7436. sorter.setown(createMergeSortAlgorithm(compare));
  7437. }
  7438. virtual void reset()
  7439. {
  7440. sorter->reset();
  7441. calculated = false;
  7442. processedAny = false;
  7443. anyThisGroup = false;
  7444. ReleaseRoxieRows(sorted);
  7445. CRoxieServerActivity::reset();
  7446. }
  7447. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7448. {
  7449. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7450. skew = helper.getSkew();
  7451. numDivisions = helper.getNumDivisions();
  7452. //Check for -ve integer values and treat as out of range
  7453. if ((__int64)numDivisions < 1)
  7454. numDivisions = 1;
  7455. if (flags & TQFhasrange)
  7456. helper.getRange(rangeIsAll, rangeSize, rangeValues.refdata());
  7457. else
  7458. {
  7459. rangeIsAll = true;
  7460. rangeSize = 0;
  7461. }
  7462. if (rangeSize)
  7463. {
  7464. //Sort the range items into order to allow quick comparison
  7465. qsort(rangeValues.getdata(), rangeSize / sizeof(unsigned __int64), sizeof(unsigned __int64), compareUint64);
  7466. }
  7467. calculated = false;
  7468. processedAny = false;
  7469. anyThisGroup = false;
  7470. eof = false;
  7471. curQuantile = 0;
  7472. prevIndex = 0;
  7473. curIndex = 0;
  7474. curIndexExtra = 0;
  7475. }
  7476. virtual bool needsAllocator() const { return true; }
  7477. virtual const void * nextRow()
  7478. {
  7479. ActivityTimer t(totalCycles, timeActivities);
  7480. if (eof)
  7481. return NULL;
  7482. const void * ret = NULL;
  7483. for(;;)
  7484. {
  7485. if (!calculated)
  7486. {
  7487. if (flags & TQFlocalsorted)
  7488. {
  7489. for (;;)
  7490. {
  7491. const void * next = inputStream->nextRow();
  7492. if (!next)
  7493. break;
  7494. sorted.append(next);
  7495. }
  7496. }
  7497. else
  7498. {
  7499. sorter->prepare(inputStream);
  7500. sorter->getSortedGroup(sorted);
  7501. }
  7502. if (sorted.ordinality() == 0)
  7503. {
  7504. if (processedAny)
  7505. {
  7506. eof = true;
  7507. return NULL;
  7508. }
  7509. //Unusual case 0 rows - add a default row instead
  7510. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  7511. size32_t thisSize = helper.createDefault(rowBuilder);
  7512. sorted.append(rowBuilder.finalizeRowClear(thisSize));
  7513. }
  7514. calculated = true;
  7515. processedAny = true;
  7516. anyThisGroup = false;
  7517. curQuantile = 0;
  7518. curIndex = 0;
  7519. curIndexExtra = (numDivisions-1) / 2; // to ensure correctly rounded up
  7520. prevIndex = curIndex-1; // Ensure it doesn't match
  7521. skipSize = (sorted.ordinality() / numDivisions);
  7522. skipExtra = (sorted.ordinality() % numDivisions);
  7523. }
  7524. if (isQuantileIncluded(curQuantile))
  7525. {
  7526. if (!(flags & TQFdedup) || (prevIndex != curIndex))
  7527. {
  7528. const void * lhs = sorted.item(curIndex);
  7529. if (flags & TQFneedtransform)
  7530. {
  7531. unsigned outSize;
  7532. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  7533. try
  7534. {
  7535. outSize = helper.transform(rowBuilder, lhs, curQuantile);
  7536. }
  7537. catch (IException *E)
  7538. {
  7539. throw makeWrappedException(E);
  7540. }
  7541. if (outSize)
  7542. ret = rowBuilder.finalizeRowClear(outSize);
  7543. }
  7544. else
  7545. {
  7546. LinkRoxieRow(lhs);
  7547. ret = lhs;
  7548. }
  7549. prevIndex = curIndex; // even if output was skipped?
  7550. }
  7551. }
  7552. curIndex += skipSize;
  7553. curIndexExtra += skipExtra;
  7554. if (curIndexExtra >= numDivisions)
  7555. {
  7556. curIndex++;
  7557. curIndexExtra -= numDivisions;
  7558. }
  7559. //Ensure the current index always stays valid.
  7560. if (curIndex >= sorted.ordinality())
  7561. curIndex = sorted.ordinality()-1;
  7562. curQuantile++;
  7563. if (curQuantile > numDivisions)
  7564. {
  7565. ReleaseRoxieRows(sorted);
  7566. sorter->reset();
  7567. calculated = false; // ready for next group
  7568. }
  7569. if (ret)
  7570. {
  7571. anyThisGroup = true;
  7572. processed++;
  7573. return ret;
  7574. }
  7575. if (curQuantile > numDivisions)
  7576. {
  7577. if (anyThisGroup)
  7578. return NULL;
  7579. }
  7580. }
  7581. }
  7582. bool isQuantileIncluded(unsigned quantile) const
  7583. {
  7584. if (quantile == 0)
  7585. return (flags & TQFfirst) != 0;
  7586. if (quantile == numDivisions)
  7587. return (flags & TQFlast) != 0;
  7588. if (rangeIsAll)
  7589. return true;
  7590. //Compare against the list of ranges provided
  7591. //MORE: Since the list is sorted should only need to compare the next (and allow for dups)
  7592. unsigned rangeNum = rangeSize / sizeof(unsigned __int64);
  7593. const unsigned __int64 * ranges = static_cast<const unsigned __int64 *>(rangeValues.getdata());
  7594. for (unsigned i = 0; i < rangeNum; i++)
  7595. {
  7596. if (ranges[i] == quantile)
  7597. return true;
  7598. }
  7599. return false;
  7600. }
  7601. };
  7602. class CRoxieServerQuantileActivityFactory : public CRoxieServerActivityFactory
  7603. {
  7604. unsigned flags;
  7605. public:
  7606. CRoxieServerQuantileActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7607. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  7608. {
  7609. Owned<IHThorQuantileArg> quantileHelper = (IHThorQuantileArg *) helperFactory();
  7610. flags = quantileHelper->getFlags();
  7611. }
  7612. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  7613. {
  7614. return new CRoxieServerQuantileActivity(_ctx, this, _probeManager, flags);
  7615. }
  7616. };
  7617. IRoxieServerActivityFactory *createRoxieServerQuantileActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7618. {
  7619. return new CRoxieServerQuantileActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  7620. }
  7621. //=====================================================================================================
  7622. class CRoxieServerSortedActivity : public CRoxieServerActivity
  7623. {
  7624. IHThorSortedArg &helper;
  7625. ICompare * compare;
  7626. const void *prev;
  7627. IRangeCompare * stepCompare;
  7628. public:
  7629. CRoxieServerSortedActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  7630. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorSortedArg &)basehelper)
  7631. {
  7632. prev = NULL;
  7633. compare = helper.queryCompare();
  7634. stepCompare = NULL;
  7635. }
  7636. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7637. {
  7638. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7639. IInputSteppingMeta * stepMeta = input->querySteppingMeta();
  7640. if (stepMeta)
  7641. stepCompare = stepMeta->queryCompare();
  7642. prev = NULL;
  7643. }
  7644. virtual void reset()
  7645. {
  7646. ReleaseClearRoxieRow(prev);
  7647. CRoxieServerActivity::reset();
  7648. }
  7649. virtual const void * nextRow()
  7650. {
  7651. ActivityTimer t(totalCycles, timeActivities);
  7652. const void *ret = inputStream->nextRow();
  7653. if (ret && prev && compare->docompare(prev, ret) > 0)
  7654. {
  7655. // MORE - better to give mismatching rows that indexes?
  7656. throw MakeStringException(ROXIE_NOT_SORTED, "SORTED(%u) detected incorrectly sorted rows (row %d, %d))", activityId, processed, processed+1);
  7657. }
  7658. ReleaseRoxieRow(prev);
  7659. prev = ret;
  7660. if (ret)
  7661. {
  7662. LinkRoxieRow(prev);
  7663. processed++;
  7664. }
  7665. return ret;
  7666. }
  7667. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  7668. {
  7669. ActivityTimer t(totalCycles, timeActivities);
  7670. const void *ret = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  7671. if (ret && prev && compare->docompare(prev, ret) > 0)
  7672. {
  7673. // MORE - better to give mismatching rows that indexes?
  7674. throw MakeStringException(ROXIE_NOT_SORTED, "SORTED(%u) detected incorrectly sorted rows (row %d, %d))", activityId, processed, processed+1);
  7675. }
  7676. ReleaseRoxieRow(prev);
  7677. prev = ret;
  7678. if (ret)
  7679. {
  7680. LinkRoxieRow(prev);
  7681. processed++;
  7682. }
  7683. return ret;
  7684. }
  7685. IInputSteppingMeta * querySteppingMeta()
  7686. {
  7687. return input->querySteppingMeta();
  7688. }
  7689. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  7690. {
  7691. return input->gatherConjunctions(collector);
  7692. }
  7693. virtual void resetEOF()
  7694. {
  7695. inputStream->resetEOF();
  7696. }
  7697. };
  7698. class CRoxieServerSortedActivityFactory : public CRoxieServerActivityFactory
  7699. {
  7700. public:
  7701. CRoxieServerSortedActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7702. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  7703. {
  7704. }
  7705. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  7706. {
  7707. return new CRoxieServerSortedActivity(_ctx, this, _probeManager);
  7708. }
  7709. };
  7710. IRoxieServerActivityFactory *createRoxieServerSortedActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7711. {
  7712. return new CRoxieServerSortedActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  7713. }
  7714. //=====================================================================================================
  7715. class CRoxieServerThroughSpillActivity : public CRoxieServerActivity
  7716. {
  7717. /*
  7718. BE VERY CAREFUL - this code is tricky.
  7719. Note that starts and stops (and resets) can occur in strange orders
  7720. The FIRST start OR stop must initialize the activity but only the first START should call the upstream start.
  7721. The last stop should call the upstream stop.
  7722. The first reset should call the upstream reset.
  7723. 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
  7724. not yet had start or stop called - for this to happen init() is called on all outputs on the first start or stop.
  7725. Some outputs may be completely pruned away when used in a GRAPH - these outputs should not receive any start/stop/reset and should be
  7726. ignored in the minIndex calculation
  7727. */
  7728. public:
  7729. IHThorArg &helper;
  7730. unsigned activeOutputs;
  7731. unsigned numOutputs;
  7732. unsigned numOriginalOutputs;
  7733. QueueOf<const void, true> buffer;
  7734. CriticalSection crit;
  7735. CriticalSection crit2;
  7736. unsigned tailIdx;
  7737. unsigned headIdx;
  7738. Owned<IException> error;
  7739. class OutputAdaptor : implements IEngineRowStream, implements IFinalRoxieInput, public CInterface
  7740. {
  7741. bool eof, eofpending, stopped;
  7742. public:
  7743. CRoxieServerThroughSpillActivity *parent;
  7744. unsigned idx;
  7745. unsigned oid;
  7746. unsigned processed;
  7747. cycle_t totalCycles; // We track this per output so that the pullers get a meaningful value to use when calculating their localtime
  7748. public:
  7749. IMPLEMENT_IINTERFACE;
  7750. OutputAdaptor()
  7751. {
  7752. parent = NULL;
  7753. oid = 0;
  7754. idx = 0;
  7755. processed = 0;
  7756. totalCycles = 0;
  7757. eofpending = false;
  7758. eof = false;
  7759. stopped = false;
  7760. }
  7761. ~OutputAdaptor()
  7762. {
  7763. if (traceStartStop)
  7764. DBGLOG("%p ~OutputAdaptor %d", this, oid);
  7765. if (processed && parent && parent->factory)
  7766. {
  7767. parent->factory->noteProcessed(oid, processed);
  7768. if (parent->ctx)
  7769. parent->ctx->noteProcessed(parent->querySubgraphId(), parent->activityId, oid, processed, 0);
  7770. }
  7771. }
  7772. void init()
  7773. {
  7774. if (traceStartStop)
  7775. DBGLOG("%p init Input adaptor %d", this, oid);
  7776. idx = 0;
  7777. processed = 0;
  7778. eofpending = false;
  7779. eof = false;
  7780. stopped = false;
  7781. }
  7782. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { assertex(idx==0); return this; }
  7783. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { assertex(idx==0); return nullptr; }
  7784. virtual IRoxieServerActivity *queryActivity()
  7785. {
  7786. return parent;
  7787. }
  7788. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  7789. {
  7790. return parent->queryIndexReadActivity();
  7791. }
  7792. virtual unsigned __int64 queryTotalCycles() const
  7793. {
  7794. return totalCycles;
  7795. }
  7796. virtual const void * nextRow()
  7797. {
  7798. SimpleActivityTimer t(totalCycles, parent->timeActivities);
  7799. if (eof)
  7800. return NULL;
  7801. const void *ret = parent->readBuffered(idx, oid);
  7802. #ifdef TRACE_SPLIT
  7803. parent->CTXLOG("Adaptor %d got back %p for record %d", oid, ret, idx);
  7804. #endif
  7805. if (ret)
  7806. {
  7807. processed++;
  7808. eofpending = false;
  7809. }
  7810. else if (eofpending)
  7811. eof = true;
  7812. else
  7813. eofpending = true;
  7814. return ret;
  7815. }
  7816. virtual IOutputMetaData * queryOutputMeta() const
  7817. {
  7818. return parent->queryOutputMeta();
  7819. }
  7820. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7821. {
  7822. // NOTE: it is tempting to move the init() of all output adaptors here. However that is not a good idea,
  7823. // since adaptors that have not yet started or stopped (but are going to) still need to have been init()'ed
  7824. // for minIndex to give the correct answers
  7825. // therefore, we call init() on all adaptors on receipt of the first start() or stop()
  7826. if (traceStartStop)
  7827. parent->CTXLOG("%p start Input adaptor %d stopped = %d", this, oid, stopped);
  7828. parent->start(oid, parentExtractSize, parentExtract, paused);
  7829. }
  7830. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  7831. {
  7832. parent->connectInputStreams(consumerOrdered);
  7833. streams.append(this);
  7834. return NULL;
  7835. }
  7836. virtual void stop()
  7837. {
  7838. if (traceStartStop)
  7839. parent->CTXLOG("%p stop Input adaptor %d stopped = %d", this, oid, stopped);
  7840. if (!stopped)
  7841. {
  7842. parent->stop(oid, idx); // NOTE - may call init()
  7843. stopped = true; // parent code relies on stop being called exactly once per adaptor, so make sure it is!
  7844. }
  7845. };
  7846. virtual void reset()
  7847. {
  7848. if (traceStartStop)
  7849. parent->CTXLOG("%p reset Input adaptor %d stopped = %d", this, oid, stopped);
  7850. parent->reset(oid);
  7851. idx = 0; // value should not be relevant really but this is the safest...
  7852. stopped = false;
  7853. };
  7854. virtual void resetEOF()
  7855. {
  7856. parent->resetEOF();
  7857. }
  7858. virtual void checkAbort()
  7859. {
  7860. parent->checkAbort();
  7861. }
  7862. } *adaptors;
  7863. bool *used;
  7864. unsigned nextFreeOutput()
  7865. {
  7866. unsigned i = numOutputs;
  7867. while (i)
  7868. {
  7869. i--;
  7870. if (!used[i])
  7871. return i;
  7872. }
  7873. throwUnexpected();
  7874. }
  7875. unsigned minIndex(unsigned exceptOid)
  7876. {
  7877. // MORE - yukky code (and slow). Could keep them heapsorted by idx or something
  7878. // this is trying to determine whether any of the adaptors will in the future read a given record
  7879. unsigned minIdx = (unsigned) -1;
  7880. for (unsigned i = 0; i < numOutputs; i++)
  7881. {
  7882. if (i != exceptOid && used[i] && adaptors[i].idx < minIdx)
  7883. minIdx = adaptors[i].idx;
  7884. }
  7885. return minIdx;
  7886. }
  7887. inline bool isLastTailReader(unsigned exceptOid)
  7888. {
  7889. for (unsigned i = 0; i < numOutputs; i++)
  7890. {
  7891. if (i != exceptOid && adaptors[i].idx == tailIdx && used[i])
  7892. return false;
  7893. }
  7894. return true;
  7895. }
  7896. void initOutputs()
  7897. {
  7898. activeOutputs = numOutputs;
  7899. for (unsigned i = 0; i < numOriginalOutputs; i++)
  7900. if (used[i])
  7901. adaptors[i].init();
  7902. state = STATEstarting;
  7903. }
  7904. public:
  7905. CRoxieServerThroughSpillActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  7906. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper(basehelper), numOutputs(_numOutputs)
  7907. {
  7908. numOriginalOutputs = numOutputs;
  7909. adaptors = new OutputAdaptor[numOutputs];
  7910. used = new bool[numOutputs];
  7911. for (unsigned i = 0; i < numOutputs; i++)
  7912. {
  7913. adaptors[i].parent = this;
  7914. adaptors[i].oid = i;
  7915. used[i] = false;
  7916. }
  7917. tailIdx = 0;
  7918. headIdx = 0;
  7919. activeOutputs = numOutputs;
  7920. }
  7921. ~CRoxieServerThroughSpillActivity()
  7922. {
  7923. delete [] adaptors;
  7924. delete [] used;
  7925. }
  7926. const void *readBuffered(unsigned &idx, unsigned oid)
  7927. {
  7928. //False positives are fine, false negatives are not.. so headIdx must only be updated when a row will be available.
  7929. const unsigned curIdx = idx;
  7930. if (curIdx == headIdx) // test once without getting the crit2 sec
  7931. {
  7932. CriticalBlock b2(crit2); // but only one puller gets to read the head
  7933. if (curIdx == headIdx) // test again now that we have it
  7934. {
  7935. 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
  7936. if (error)
  7937. throw error.getLink();
  7938. try
  7939. {
  7940. const void *row = inputStream->nextRow();
  7941. if (activeOutputs==1)
  7942. {
  7943. #ifdef TRACE_SPLIT
  7944. CTXLOG("spill %d optimised return of %p", activityId, row);
  7945. #endif
  7946. headIdx++;
  7947. idx++;
  7948. return row; // optimization for the case where only one output still active.
  7949. }
  7950. CriticalBlock b(crit);
  7951. headIdx++;
  7952. idx++;
  7953. if (activeOutputs==1)
  7954. return row; // optimization for the case where only one output still active.
  7955. buffer.enqueue(row);
  7956. if (row) LinkRoxieRow(row);
  7957. return row;
  7958. }
  7959. catch (IException *E)
  7960. {
  7961. #ifdef TRACE_SPLIT
  7962. CTXLOG("spill %d caught exception", activityId);
  7963. #endif
  7964. error.set(E);
  7965. throw;
  7966. }
  7967. catch (...)
  7968. {
  7969. IException *E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught in CRoxieServerThroughSpillActivity::readBuffered");
  7970. error.set(E);
  7971. throw E;
  7972. }
  7973. }
  7974. }
  7975. CriticalBlock b(crit);
  7976. 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
  7977. unsigned lidx = curIdx - tailIdx;
  7978. idx++;
  7979. if (!lidx)
  7980. {
  7981. // The numOutputs <= 2 check optimizes slightly the common case of 2-way splitters.
  7982. // 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
  7983. if (numOutputs <= 2 || isLastTailReader(oid)) // NOTE - this includes the case where minIndex returns (unsigned) -1, meaning no other active pullers
  7984. {
  7985. tailIdx++;
  7986. const void *ret = buffer.dequeue(); // no need to link - last puller
  7987. #ifdef TRACE_SPLIT
  7988. CTXLOG("last puller return of %p", ret);
  7989. #endif
  7990. return ret;
  7991. }
  7992. }
  7993. const void *ret = buffer.item(lidx);
  7994. if (ret) LinkRoxieRow(ret);
  7995. #ifdef TRACE_SPLIT
  7996. CTXLOG("standard return of %p", ret);
  7997. #endif
  7998. return ret;
  7999. }
  8000. virtual void start(unsigned oid, unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8001. {
  8002. CriticalBlock b(crit);
  8003. if (error)
  8004. throw error.getLink();
  8005. if (factory)
  8006. factory->noteStarted(oid);
  8007. if (traceStartStop)
  8008. CTXLOG("SPLIT %p: start %d child %d activeOutputs %d numOutputs %d numOriginalOutputs %d state %s", this, activityId, oid, activeOutputs, numOutputs, numOriginalOutputs, queryStateText(state));
  8009. if (state != STATEstarted)
  8010. {
  8011. if (state != STATEstarting)
  8012. initOutputs();
  8013. tailIdx = 0;
  8014. headIdx = 0;
  8015. error.clear();
  8016. try
  8017. {
  8018. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8019. }
  8020. catch (IException *E)
  8021. {
  8022. #ifdef TRACE_SPLIT
  8023. CTXLOG("spill %d caught exception in start", activityId);
  8024. #endif
  8025. error.set(E);
  8026. throw;
  8027. }
  8028. catch (...)
  8029. {
  8030. IException *E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught in CRoxieServerThroughSpillActivity::start");
  8031. error.set(E);
  8032. throw E;
  8033. }
  8034. }
  8035. }
  8036. void stop(unsigned oid, unsigned & idx)
  8037. {
  8038. // Note that OutputAdaptor code ensures that stop is not called more than once per adaptor
  8039. CriticalBlock b(crit);
  8040. #ifdef TRACE_STARTSTOP
  8041. if (traceStartStop)
  8042. {
  8043. CTXLOG("SPLIT %p: stop %d child %d activeOutputs %d numOutputs %d numOriginalOutputs %d state %s", this, activityId, oid, activeOutputs, numOutputs, numOriginalOutputs, queryStateText(state));
  8044. if (watchActivityId && watchActivityId==activityId)
  8045. {
  8046. CTXLOG("WATCH: stop %d", activityId);
  8047. }
  8048. }
  8049. #endif
  8050. if (state != STATEstarting && state != STATEstarted)
  8051. initOutputs();
  8052. if (activeOutputs > 1)
  8053. {
  8054. if (tailIdx==idx)
  8055. {
  8056. // Discard all buffered rows that are there purely for this adaptor to read them
  8057. unsigned min = minIndex(oid);
  8058. if (min != (unsigned) -1)
  8059. // what does -1 signify?? No-one wants anything? In which case can't we kill all rows??
  8060. // Should never happen though if there are still some active.
  8061. // there may be a small window where adaptors are blocked on the semaphore...
  8062. {
  8063. #ifdef TRACE_SPLIT
  8064. CTXLOG("%p: Discarding buffered rows from %d to %d for oid %x (%d outputs active)", this, idx, min, oid, activeOutputs);
  8065. #endif
  8066. while (tailIdx < min)
  8067. {
  8068. ReleaseRoxieRow(buffer.dequeue());
  8069. tailIdx++;
  8070. }
  8071. }
  8072. }
  8073. activeOutputs--;
  8074. idx = (unsigned) -1; // causes minIndex not to save rows for me...
  8075. return;
  8076. }
  8077. #ifdef TRACE_SPLIT
  8078. CTXLOG("%p: All outputs done", this);
  8079. #endif
  8080. activeOutputs = numOutputs;
  8081. CRoxieServerActivity::stop();
  8082. };
  8083. void reset(unsigned oid)
  8084. {
  8085. if (traceStartStop)
  8086. CTXLOG("SPLIT %p: reset %d child %d activeOutputs %d numOutputs %d numOriginalOutputs %d state %s", this, activityId, oid, activeOutputs, numOutputs, numOriginalOutputs, queryStateText(state));
  8087. activeOutputs = numOutputs;
  8088. while (buffer.ordinality())
  8089. ReleaseRoxieRow(buffer.dequeue());
  8090. error.clear();
  8091. if (state != STATEreset) // make sure input is only reset once
  8092. CRoxieServerActivity::reset();
  8093. };
  8094. void connectInputStreams(bool consumerOrdered)
  8095. {
  8096. if (!inputStream)
  8097. CRoxieServerActivity::connectInputStreams(consumerOrdered);
  8098. }
  8099. virtual const void *nextRow()
  8100. {
  8101. throwUnexpected(); // Internal logic error - we are not anybody's input
  8102. }
  8103. virtual IOutputMetaData * queryOutputMeta() const
  8104. {
  8105. // if (outputMeta)
  8106. // return outputMeta;
  8107. // else
  8108. return input->queryOutputMeta(); // not always known (e.g. disk write - though Gavin _could_ fill it in)
  8109. }
  8110. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  8111. {
  8112. if (idx==(unsigned)-1)
  8113. idx = nextFreeOutput(); // MORE - what is this used for?
  8114. assertex(idx < numOriginalOutputs);
  8115. assertex(!used[idx]);
  8116. used[idx] = true;
  8117. return &adaptors[idx];
  8118. }
  8119. virtual void resetOutputsUsed()
  8120. {
  8121. numOutputs = 1;
  8122. activeOutputs = 1;
  8123. // MORE RKC->GH should we be clearing the used array here? anywhere?
  8124. }
  8125. virtual void noteOutputUsed()
  8126. {
  8127. assertex(numOutputs < numOriginalOutputs);
  8128. numOutputs++;
  8129. activeOutputs = numOutputs;
  8130. }
  8131. virtual bool isPassThrough()
  8132. {
  8133. return numOutputs==1;
  8134. }
  8135. };
  8136. class CRoxieServerThroughSpillActivityFactory : public CRoxieServerMultiOutputFactory
  8137. {
  8138. public:
  8139. CRoxieServerThroughSpillActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8140. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  8141. {
  8142. Owned<IHThorSpillArg> helper = (IHThorSpillArg *) helperFactory();
  8143. setNumOutputs(helper->getTempUsageCount() + 1);
  8144. }
  8145. CRoxieServerThroughSpillActivityFactory(IQueryFactory &_queryFactory, HelperFactory *_helperFactory, unsigned _numOutputs, IPropertyTree &_graphNode)
  8146. : CRoxieServerMultiOutputFactory(0, 0, _queryFactory, _helperFactory, TAKsplit, _graphNode)
  8147. {
  8148. setNumOutputs(_numOutputs);
  8149. }
  8150. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  8151. {
  8152. return new CRoxieServerThroughSpillActivity(_ctx, this, _probeManager, numOutputs);
  8153. }
  8154. };
  8155. IRoxieServerActivityFactory *createRoxieServerThroughSpillActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8156. {
  8157. return new CRoxieServerThroughSpillActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  8158. }
  8159. IRoxieServerActivityFactory *createRoxieServerThroughSpillActivityFactory(IQueryFactory &_queryFactory, HelperFactory *_factory, unsigned _numOutputs, IPropertyTree &_graphNode)
  8160. {
  8161. return new CRoxieServerThroughSpillActivityFactory(_queryFactory, _factory, _numOutputs, _graphNode);
  8162. }
  8163. //----------------------------------------------------------------------------------------------
  8164. class CRoxieServerSplitActivityFactory : public CRoxieServerMultiOutputFactory
  8165. {
  8166. public:
  8167. CRoxieServerSplitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8168. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  8169. {
  8170. Owned<IHThorSplitArg> helper = (IHThorSplitArg *) helperFactory();
  8171. setNumOutputs(helper->numBranches());
  8172. }
  8173. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  8174. {
  8175. return new CRoxieServerThroughSpillActivity(_ctx, this, _probeManager, numOutputs);
  8176. }
  8177. };
  8178. IRoxieServerActivityFactory *createRoxieServerSplitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8179. {
  8180. return new CRoxieServerSplitActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  8181. }
  8182. //=====================================================================================================
  8183. #define PIPE_BUFSIZE 0x8000
  8184. static IException *createPipeFailureException(const char *cmd, unsigned retcode, IPipeProcess *pipe)
  8185. {
  8186. StringBuffer msg;
  8187. if(pipe->hasError())
  8188. {
  8189. try
  8190. {
  8191. char error[512];
  8192. size32_t sz = pipe->readError(sizeof(error), error);
  8193. if(sz && sz!=(size32_t)-1)
  8194. msg.append(", stderr: '").append(sz, error).append("'");
  8195. }
  8196. catch (IException *e)
  8197. {
  8198. EXCLOG(e, "Error reading pipe stderr");
  8199. e->Release();
  8200. }
  8201. }
  8202. return MakeStringException(ROXIE_PIPE_ERROR, "Pipe process %s returned error %u%s", cmd, retcode, msg.str());
  8203. }
  8204. class CRoxieServerPipeReadActivity : public CRoxieServerActivity
  8205. {
  8206. IHThorPipeReadArg &helper;
  8207. Owned<IPipeProcess> pipe;
  8208. StringAttr pipeCommand;
  8209. Owned<IOutputRowDeserializer> rowDeserializer;
  8210. Owned<IReadRowStream> readTransformer;
  8211. bool groupSignalled;
  8212. public:
  8213. CRoxieServerPipeReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8214. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorPipeReadArg &)basehelper)
  8215. {
  8216. groupSignalled = true;
  8217. }
  8218. virtual bool needsAllocator() const { return true; }
  8219. virtual void onCreate(IHThorArg *_colocalParent)
  8220. {
  8221. CRoxieServerActivity::onCreate(_colocalParent);
  8222. rowDeserializer.setown(rowAllocator->createDiskDeserializer(ctx->queryCodeContext()));
  8223. }
  8224. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8225. {
  8226. groupSignalled = true; // i.e. don't start with a NULL row
  8227. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8228. if (!readTransformer)
  8229. {
  8230. OwnedRoxieString xmlIteratorPath(helper.getXmlIteratorPath());
  8231. readTransformer.setown(createReadRowStream(rowAllocator, rowDeserializer, helper.queryXmlTransformer(), helper.queryCsvTransformer(), xmlIteratorPath, helper.getPipeFlags()));
  8232. }
  8233. OwnedRoxieString pipeProgram(helper.getPipeProgram());
  8234. openPipe(pipeProgram);
  8235. }
  8236. virtual void stop()
  8237. {
  8238. CRoxieServerActivity::stop();
  8239. pipe.clear();
  8240. readTransformer->setStream(NULL);
  8241. }
  8242. virtual const void *nextRow()
  8243. {
  8244. ActivityTimer t(totalCycles, timeActivities);
  8245. while (!waitForPipe())
  8246. {
  8247. if (!pipe)
  8248. return NULL;
  8249. if (helper.getPipeFlags() & TPFgroupeachrow)
  8250. {
  8251. if (!groupSignalled)
  8252. {
  8253. groupSignalled = true;
  8254. return NULL;
  8255. }
  8256. }
  8257. }
  8258. const void *ret = readTransformer->next();
  8259. assertex(ret != NULL); // if ret can ever be NULL then we need to recode this logic
  8260. processed++;
  8261. groupSignalled = false;
  8262. return ret;
  8263. }
  8264. protected:
  8265. bool waitForPipe()
  8266. {
  8267. if (!pipe)
  8268. return false; // done
  8269. if (!readTransformer->eos())
  8270. return true;
  8271. verifyPipe();
  8272. return false;
  8273. }
  8274. void openPipe(char const * cmd)
  8275. {
  8276. pipeCommand.setown(cmd);
  8277. pipe.setown(createPipeProcess());
  8278. if(!pipe->run(NULL, cmd, ".", false, true, true, 0x10000))
  8279. throw MakeStringException(ROXIE_PIPE_ERROR, "Could not run pipe process %s", cmd);
  8280. Owned<ISimpleReadStream> pipeReader = pipe->getOutputStream();
  8281. readTransformer->setStream(pipeReader.get());
  8282. }
  8283. void verifyPipe()
  8284. {
  8285. if (pipe)
  8286. {
  8287. unsigned err = pipe->wait();
  8288. if(err && !(helper.getPipeFlags() & TPFnofail))
  8289. {
  8290. throw createPipeFailureException(pipeCommand.get(), err, pipe);
  8291. }
  8292. pipe.clear();
  8293. }
  8294. }
  8295. };
  8296. class CRoxieServerPipeThroughActivity : public CRoxieServerActivity, implements IRecordPullerCallback
  8297. {
  8298. IHThorPipeThroughArg &helper;
  8299. RecordPullerThread puller;
  8300. Owned<IPipeProcess> pipe;
  8301. StringAttr pipeCommand;
  8302. InterruptableSemaphore pipeVerified;
  8303. InterruptableSemaphore pipeOpened;
  8304. CachedOutputMetaData inputMeta;
  8305. Owned<IOutputRowSerializer> rowSerializer;
  8306. Owned<IOutputRowDeserializer> rowDeserializer;
  8307. Owned<IPipeWriteXformHelper> writeTransformer;
  8308. Owned<IReadRowStream> readTransformer;
  8309. bool firstRead;
  8310. bool recreate;
  8311. bool inputExhausted;
  8312. bool groupSignalled;
  8313. public:
  8314. CRoxieServerPipeThroughActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8315. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorPipeThroughArg &)basehelper), puller(false)
  8316. {
  8317. recreate = helper.recreateEachRow();
  8318. groupSignalled = true;
  8319. firstRead = false;
  8320. inputExhausted = false;
  8321. }
  8322. virtual bool needsAllocator() const { return true; }
  8323. virtual void onCreate(IHThorArg *_colocalParent)
  8324. {
  8325. CRoxieServerActivity::onCreate(_colocalParent);
  8326. rowSerializer.setown(inputMeta.createDiskSerializer(ctx->queryCodeContext(), activityId));
  8327. rowDeserializer.setown(rowAllocator->createDiskDeserializer(ctx->queryCodeContext()));
  8328. writeTransformer.setown(createPipeWriteXformHelper(helper.getPipeFlags(), helper.queryXmlOutput(), helper.queryCsvOutput(), rowSerializer));
  8329. }
  8330. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8331. {
  8332. firstRead = true;
  8333. inputExhausted = false;
  8334. groupSignalled = true; // i.e. don't start with a NULL row
  8335. pipeVerified.reinit();
  8336. pipeOpened.reinit();
  8337. writeTransformer->ready();
  8338. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8339. if (!readTransformer)
  8340. {
  8341. OwnedRoxieString xmlIterator(helper.getXmlIteratorPath());
  8342. readTransformer.setown(createReadRowStream(rowAllocator, rowDeserializer, helper.queryXmlTransformer(), helper.queryCsvTransformer(), xmlIterator, helper.getPipeFlags()));
  8343. }
  8344. if(!recreate)
  8345. {
  8346. OwnedRoxieString pipeProgram(helper.getPipeProgram());
  8347. openPipe(pipeProgram);
  8348. }
  8349. puller.start(parentExtractSize, parentExtract, paused, 0, false, ctx); // Pipe does not support preload presently - locks up
  8350. }
  8351. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  8352. {
  8353. if (idx)
  8354. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
  8355. puller.setInput(this, _sourceIdx, _in);
  8356. inputMeta.set(_in->queryOutputMeta());
  8357. }
  8358. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  8359. {
  8360. puller.connectInputStreams(ctx, consumerOrdered);
  8361. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
  8362. }
  8363. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  8364. {
  8365. if (idx==0)
  8366. return puller.queryInput();
  8367. else
  8368. return NULL;
  8369. }
  8370. virtual void stop()
  8371. {
  8372. pipeVerified.interrupt(NULL);
  8373. pipeOpened.interrupt(NULL);
  8374. puller.stop();
  8375. CRoxieServerActivity::stop();
  8376. pipe.clear();
  8377. if (readTransformer)
  8378. readTransformer->setStream(NULL);
  8379. }
  8380. virtual void reset()
  8381. {
  8382. puller.reset();
  8383. CRoxieServerActivity::reset();
  8384. }
  8385. virtual const void *nextRow()
  8386. {
  8387. ActivityTimer t(totalCycles, timeActivities);
  8388. while (!waitForPipe())
  8389. {
  8390. if (!pipe)
  8391. return NULL;
  8392. if (helper.getPipeFlags() & TPFgroupeachrow)
  8393. {
  8394. if (!groupSignalled)
  8395. {
  8396. groupSignalled = true;
  8397. return NULL;
  8398. }
  8399. }
  8400. }
  8401. const void *ret = readTransformer->next();
  8402. assertex(ret != NULL); // if ret can ever be NULL then we need to recode this logic
  8403. processed++;
  8404. groupSignalled = false;
  8405. return ret;
  8406. }
  8407. virtual void processRow(const void *row)
  8408. {
  8409. // called from puller thread
  8410. if(recreate)
  8411. openPipe(helper.getNameFromRow(row));
  8412. writeTransformer->writeTranslatedText(row, pipe);
  8413. ReleaseRoxieRow(row);
  8414. if(recreate)
  8415. {
  8416. closePipe();
  8417. pipeVerified.wait();
  8418. }
  8419. }
  8420. virtual void processDone()
  8421. {
  8422. // called from puller thread
  8423. if(recreate)
  8424. {
  8425. inputExhausted = true;
  8426. pipeOpened.signal();
  8427. }
  8428. else
  8429. {
  8430. closePipe();
  8431. pipeVerified.wait();
  8432. }
  8433. }
  8434. virtual void processEOG()
  8435. {
  8436. }
  8437. void processGroup(const ConstPointerArray &)
  8438. {
  8439. throwUnexpected();
  8440. }
  8441. virtual bool fireException(IException *e)
  8442. {
  8443. pipeOpened.interrupt(LINK(e));
  8444. pipeVerified.interrupt(e);
  8445. return true;
  8446. }
  8447. private:
  8448. bool waitForPipe()
  8449. {
  8450. if (firstRead)
  8451. {
  8452. pipeOpened.wait();
  8453. firstRead = false;
  8454. }
  8455. if (!pipe)
  8456. return false; // done
  8457. if (!readTransformer->eos())
  8458. return true;
  8459. verifyPipe();
  8460. if (recreate && !inputExhausted)
  8461. pipeOpened.wait();
  8462. return false;
  8463. }
  8464. void openPipe(char const * cmd)
  8465. {
  8466. pipeCommand.setown(cmd);
  8467. pipe.setown(createPipeProcess());
  8468. if(!pipe->run(NULL, cmd, ".", true, true, true, 0x10000))
  8469. throw MakeStringException(ROXIE_PIPE_ERROR, "Could not run pipe process %s", cmd);
  8470. writeTransformer->writeHeader(pipe);
  8471. Owned<ISimpleReadStream> pipeReader = pipe->getOutputStream();
  8472. readTransformer->setStream(pipeReader.get());
  8473. pipeOpened.signal();
  8474. }
  8475. void closePipe()
  8476. {
  8477. writeTransformer->writeFooter(pipe);
  8478. pipe->closeInput();
  8479. }
  8480. void verifyPipe()
  8481. {
  8482. if (pipe)
  8483. {
  8484. unsigned err = pipe->wait();
  8485. if(err && !(helper.getPipeFlags() & TPFnofail))
  8486. {
  8487. throw createPipeFailureException(pipeCommand.get(), err, pipe);
  8488. }
  8489. pipe.clear();
  8490. pipeVerified.signal();
  8491. }
  8492. }
  8493. };
  8494. class CRoxieServerPipeWriteActivity : public CRoxieServerInternalSinkActivity
  8495. {
  8496. IHThorPipeWriteArg &helper;
  8497. Owned<IPipeProcess> pipe;
  8498. StringAttr pipeCommand;
  8499. CachedOutputMetaData inputMeta;
  8500. Owned<IOutputRowSerializer> rowSerializer;
  8501. Owned<IPipeWriteXformHelper> writeTransformer;
  8502. bool firstRead;
  8503. bool recreate;
  8504. bool inputExhausted;
  8505. public:
  8506. CRoxieServerPipeWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  8507. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _numOutputs), helper((IHThorPipeWriteArg &)basehelper)
  8508. {
  8509. recreate = helper.recreateEachRow();
  8510. firstRead = false;
  8511. inputExhausted = false;
  8512. }
  8513. virtual bool needsAllocator() const { return true; }
  8514. virtual void onCreate(IHThorArg *_colocalParent)
  8515. {
  8516. CRoxieServerActivity::onCreate(_colocalParent);
  8517. inputMeta.set(input->queryOutputMeta());
  8518. rowSerializer.setown(inputMeta.createDiskSerializer(ctx->queryCodeContext(), activityId));
  8519. writeTransformer.setown(createPipeWriteXformHelper(helper.getPipeFlags(), helper.queryXmlOutput(), helper.queryCsvOutput(), rowSerializer));
  8520. }
  8521. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8522. {
  8523. firstRead = true;
  8524. inputExhausted = false;
  8525. writeTransformer->ready();
  8526. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8527. if(!recreate)
  8528. {
  8529. OwnedRoxieString pipeProgram(helper.getPipeProgram());
  8530. openPipe(pipeProgram);
  8531. }
  8532. }
  8533. virtual void stop()
  8534. {
  8535. if (!aborted && helper.getSequence() >= 0)
  8536. {
  8537. WorkunitUpdate wu = ctx->updateWorkUnit();
  8538. if (wu)
  8539. {
  8540. Owned<IWUResult> result = wu->updateResultBySequence(helper.getSequence());
  8541. if (result)
  8542. {
  8543. result->setResultTotalRowCount(processed);
  8544. result->setResultStatus(ResultStatusCalculated);
  8545. }
  8546. }
  8547. }
  8548. CRoxieServerActivity::stop();
  8549. pipe.clear();
  8550. }
  8551. virtual void onExecute()
  8552. {
  8553. for (;;)
  8554. {
  8555. const void *row = inputStream->ungroupedNextRow();
  8556. if (!row)
  8557. break;
  8558. processed++;
  8559. if(recreate)
  8560. openPipe(helper.getNameFromRow(row));
  8561. writeTransformer->writeTranslatedText(row, pipe);
  8562. ReleaseRoxieRow(row);
  8563. if(recreate)
  8564. closePipe();
  8565. }
  8566. closePipe();
  8567. }
  8568. private:
  8569. void openPipe(char const * cmd)
  8570. {
  8571. pipeCommand.setown(cmd);
  8572. pipe.setown(createPipeProcess());
  8573. if(!pipe->run(NULL, cmd, ".", true, false, true, 0x10000))
  8574. throw MakeStringException(ROXIE_PIPE_ERROR, "Could not run pipe process %s", cmd);
  8575. writeTransformer->writeHeader(pipe);
  8576. }
  8577. void closePipe()
  8578. {
  8579. writeTransformer->writeFooter(pipe);
  8580. pipe->closeInput();
  8581. unsigned err = pipe->wait();
  8582. if(err && !(helper.getPipeFlags() & TPFnofail))
  8583. {
  8584. throw createPipeFailureException(pipeCommand.get(), err, pipe);
  8585. }
  8586. pipe.clear();
  8587. }
  8588. };
  8589. class CRoxieServerPipeReadActivityFactory : public CRoxieServerActivityFactory
  8590. {
  8591. public:
  8592. CRoxieServerPipeReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8593. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  8594. {
  8595. }
  8596. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  8597. {
  8598. return new CRoxieServerPipeReadActivity(_ctx, this, _probeManager);
  8599. }
  8600. };
  8601. class CRoxieServerPipeThroughActivityFactory : public CRoxieServerActivityFactory
  8602. {
  8603. public:
  8604. CRoxieServerPipeThroughActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8605. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  8606. {
  8607. }
  8608. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  8609. {
  8610. return new CRoxieServerPipeThroughActivity(_ctx, this, _probeManager);
  8611. }
  8612. };
  8613. class CRoxieServerPipeWriteActivityFactory : public CRoxieServerInternalSinkFactory
  8614. {
  8615. public:
  8616. CRoxieServerPipeWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  8617. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot)
  8618. {
  8619. }
  8620. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  8621. {
  8622. return new CRoxieServerPipeWriteActivity(_ctx, this, _probeManager, usageCount);
  8623. }
  8624. };
  8625. IRoxieServerActivityFactory *createRoxieServerPipeReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8626. {
  8627. return new CRoxieServerPipeReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  8628. }
  8629. IRoxieServerActivityFactory *createRoxieServerPipeThroughActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8630. {
  8631. return new CRoxieServerPipeThroughActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  8632. }
  8633. IRoxieServerActivityFactory *createRoxieServerPipeWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  8634. {
  8635. return new CRoxieServerPipeWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot);
  8636. }
  8637. //=====================================================================================================
  8638. class CRoxieServerStreamedIteratorActivity : public CRoxieServerActivity
  8639. {
  8640. IHThorStreamedIteratorArg &helper;
  8641. Owned<IRowStream> rows;
  8642. public:
  8643. CRoxieServerStreamedIteratorActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8644. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorStreamedIteratorArg &)basehelper)
  8645. {
  8646. }
  8647. ~CRoxieServerStreamedIteratorActivity()
  8648. {
  8649. }
  8650. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8651. {
  8652. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8653. rows.setown(helper.createInput());
  8654. }
  8655. virtual void stop()
  8656. {
  8657. if (rows)
  8658. {
  8659. rows->stop();
  8660. rows.clear();
  8661. }
  8662. CRoxieServerActivity::stop();
  8663. }
  8664. virtual const void *nextRow()
  8665. {
  8666. ActivityTimer t(totalCycles, timeActivities);
  8667. assertex(rows != NULL);
  8668. const void * next = rows->nextRow();
  8669. if (next)
  8670. processed++;
  8671. return next;
  8672. }
  8673. };
  8674. class CRoxieServerStreamedIteratorActivityFactory : public CRoxieServerActivityFactory
  8675. {
  8676. public:
  8677. CRoxieServerStreamedIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8678. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  8679. {
  8680. }
  8681. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  8682. {
  8683. return new CRoxieServerStreamedIteratorActivity(_ctx, this, _probeManager);
  8684. }
  8685. };
  8686. IRoxieServerActivityFactory *createRoxieServerStreamedIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8687. {
  8688. return new CRoxieServerStreamedIteratorActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  8689. }
  8690. //=====================================================================================================
  8691. class CRoxieServerFilterActivity : public CRoxieServerLateStartActivity
  8692. {
  8693. IHThorFilterArg &helper;
  8694. bool anyThisGroup;
  8695. IRangeCompare * stepCompare;
  8696. public:
  8697. CRoxieServerFilterActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8698. : CRoxieServerLateStartActivity(_ctx, _factory, _probeManager), helper((IHThorFilterArg &)basehelper)
  8699. {
  8700. anyThisGroup = false;
  8701. stepCompare = NULL;
  8702. }
  8703. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8704. {
  8705. anyThisGroup = false;
  8706. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  8707. lateStart(parentExtractSize, parentExtract, helper.canMatchAny());
  8708. stepCompare = NULL;
  8709. if (!eof)
  8710. {
  8711. IInputSteppingMeta * stepMeta = input->querySteppingMeta();
  8712. if (stepMeta)
  8713. stepCompare = stepMeta->queryCompare();
  8714. }
  8715. }
  8716. virtual const void * nextRow()
  8717. {
  8718. ActivityTimer t(totalCycles, timeActivities);
  8719. if (eof)
  8720. return NULL;
  8721. for (;;)
  8722. {
  8723. OwnedConstRoxieRow ret(inputStream->nextRow());
  8724. if (!ret)
  8725. {
  8726. //stop returning two NULLs in a row.
  8727. if (anyThisGroup)
  8728. {
  8729. anyThisGroup = false;
  8730. return NULL;
  8731. }
  8732. ret.setown(inputStream->nextRow());
  8733. if (!ret)
  8734. {
  8735. eof = true;
  8736. return NULL; // eof...
  8737. }
  8738. }
  8739. if (helper.isValid(ret))
  8740. {
  8741. anyThisGroup = true;
  8742. processed++;
  8743. return ret.getClear();
  8744. }
  8745. }
  8746. }
  8747. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  8748. {
  8749. //Could assert that this isn't grouped
  8750. // MORE - will need rethinking once we rethink the nextRowGE interface for global smart-stepping.
  8751. ActivityTimer t(totalCycles, timeActivities);
  8752. if (eof)
  8753. return NULL;
  8754. for (;;)
  8755. {
  8756. OwnedConstRoxieRow ret(inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra));
  8757. if (!ret)
  8758. {
  8759. eof = true;
  8760. return NULL;
  8761. }
  8762. if (!wasCompleteMatch)
  8763. {
  8764. anyThisGroup = false; // RKC->GH - is this right??
  8765. return ret.getClear();
  8766. }
  8767. if (helper.isValid(ret))
  8768. {
  8769. anyThisGroup = true;
  8770. processed++;
  8771. return ret.getClear();
  8772. }
  8773. if (!stepExtra.returnMismatches())
  8774. {
  8775. ret.clear();
  8776. return nextRow();
  8777. }
  8778. //If asked to return mismatches we are only interested in mismatches that will force the stepped
  8779. //condition to advance
  8780. if (stepCompare->docompare(ret, seek, numFields) != 0)
  8781. {
  8782. wasCompleteMatch = false;
  8783. anyThisGroup = false; // WHY?
  8784. return ret.getClear();
  8785. }
  8786. }
  8787. }
  8788. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  8789. {
  8790. return input->gatherConjunctions(collector);
  8791. }
  8792. virtual void resetEOF()
  8793. {
  8794. eof = prefiltered;
  8795. anyThisGroup = false;
  8796. inputStream->resetEOF();
  8797. }
  8798. IInputSteppingMeta * querySteppingMeta()
  8799. {
  8800. return input->querySteppingMeta();
  8801. }
  8802. };
  8803. class CRoxieServerFilterActivityFactory : public CRoxieServerActivityFactory
  8804. {
  8805. public:
  8806. CRoxieServerFilterActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8807. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  8808. {
  8809. optStableInput = false;
  8810. }
  8811. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  8812. {
  8813. return new CRoxieServerFilterActivity(_ctx, this, _probeManager);
  8814. }
  8815. };
  8816. IRoxieServerActivityFactory *createRoxieServerFilterActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8817. {
  8818. return new CRoxieServerFilterActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  8819. }
  8820. //=====================================================================================================
  8821. class CRoxieServerFilterGroupActivity : public CRoxieServerLateStartActivity
  8822. {
  8823. IHThorFilterGroupArg &helper;
  8824. unsigned curIndex;
  8825. ConstPointerArray gathered;
  8826. IRangeCompare * stepCompare;
  8827. public:
  8828. CRoxieServerFilterGroupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8829. : CRoxieServerLateStartActivity(_ctx, _factory, _probeManager), helper((IHThorFilterGroupArg &)basehelper)
  8830. {
  8831. curIndex = 0;
  8832. stepCompare = NULL;
  8833. }
  8834. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8835. {
  8836. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  8837. lateStart(parentExtractSize, parentExtract, helper.canMatchAny());//sets eof
  8838. assertex(eof == !helper.canMatchAny());
  8839. curIndex = 0;
  8840. stepCompare = NULL;
  8841. if (!eof)
  8842. {
  8843. IInputSteppingMeta * inputStepping = input->querySteppingMeta();
  8844. if (inputStepping)
  8845. stepCompare = inputStepping->queryCompare();
  8846. }
  8847. }
  8848. virtual void reset()
  8849. {
  8850. releaseGathered();
  8851. CRoxieServerLateStartActivity::reset();
  8852. }
  8853. inline void releaseGathered()
  8854. {
  8855. roxiemem::ReleaseRoxieRowRange(gathered.getArray(), curIndex, gathered.ordinality());
  8856. gathered.kill();
  8857. curIndex = 0;
  8858. }
  8859. virtual const void * nextRow()
  8860. {
  8861. ActivityTimer t(totalCycles, timeActivities);
  8862. for (;;)
  8863. {
  8864. if (eof)
  8865. return NULL;
  8866. if (gathered.ordinality())
  8867. {
  8868. if (gathered.isItem(curIndex))
  8869. {
  8870. const void * ret = gathered.item(curIndex++);
  8871. processed++;
  8872. return ret;
  8873. }
  8874. curIndex = 0;
  8875. gathered.kill();
  8876. return NULL;
  8877. }
  8878. const void * ret = inputStream->nextRow();
  8879. while (ret)
  8880. {
  8881. gathered.append(ret);
  8882. ret = inputStream->nextRow();
  8883. }
  8884. unsigned num = gathered.ordinality();
  8885. if (num != 0)
  8886. {
  8887. if (!helper.isValid(num, (const void * *)gathered.getArray()))
  8888. ReleaseRoxieRows(gathered); // read next group
  8889. }
  8890. else
  8891. eof = true;
  8892. }
  8893. }
  8894. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  8895. {
  8896. ActivityTimer t(totalCycles, timeActivities);
  8897. if (eof)
  8898. return NULL;
  8899. if (gathered.ordinality())
  8900. {
  8901. while (gathered.isItem(curIndex))
  8902. {
  8903. const void * ret = gathered.item(curIndex++);
  8904. if (stepCompare->docompare(ret, seek, numFields) >= 0)
  8905. {
  8906. processed++;
  8907. return ret;
  8908. }
  8909. ReleaseRoxieRow(ret);
  8910. }
  8911. curIndex = 0;
  8912. gathered.kill();
  8913. //nextRowGE never returns an end of group marker.
  8914. }
  8915. //Not completely sure about this - it could lead the the start of a group being skipped,
  8916. //so the group filter could potentially work on a different group. If so, we'd need to check the
  8917. //next fields were a subset of the grouping fields - more an issue for the group activity.
  8918. //MORE: What do we do with wasCompleteMatch? something like the following????
  8919. #if 0
  8920. for (;;)
  8921. {
  8922. const void * ret;
  8923. if (stepExtra.returnMismatches())
  8924. {
  8925. bool matchedCompletely = true;
  8926. ret = input->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  8927. if (!wasCompleteMatch)
  8928. return ret;
  8929. }
  8930. else
  8931. ret = input->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  8932. #endif
  8933. const void * ret = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  8934. while (ret)
  8935. {
  8936. gathered.append(ret);
  8937. ret = inputStream->nextRow();
  8938. }
  8939. unsigned num = gathered.ordinality();
  8940. if (num != 0)
  8941. {
  8942. if (!helper.isValid(num, (const void * *)gathered.getArray()))
  8943. ReleaseRoxieRows(gathered); // read next group
  8944. }
  8945. else
  8946. eof = true;
  8947. return IEngineRowStream::ungroupedNextRow();
  8948. }
  8949. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  8950. {
  8951. return input->gatherConjunctions(collector);
  8952. }
  8953. virtual void resetEOF()
  8954. {
  8955. eof = false;
  8956. releaseGathered();
  8957. inputStream->resetEOF();
  8958. }
  8959. IInputSteppingMeta * querySteppingMeta()
  8960. {
  8961. return input->querySteppingMeta();
  8962. }
  8963. };
  8964. class CRoxieServerFilterGroupActivityFactory : public CRoxieServerActivityFactory
  8965. {
  8966. public:
  8967. CRoxieServerFilterGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8968. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  8969. {
  8970. }
  8971. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  8972. {
  8973. return new CRoxieServerFilterGroupActivity(_ctx, this, _probeManager);
  8974. }
  8975. };
  8976. IRoxieServerActivityFactory *createRoxieServerFilterGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8977. {
  8978. return new CRoxieServerFilterGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  8979. }
  8980. //=================================================================================
  8981. class CRoxieServerSideEffectActivity : public CRoxieServerActivity
  8982. {
  8983. IHThorSideEffectArg &helper;
  8984. CriticalSection ecrit;
  8985. Owned<IException> exception;
  8986. bool executed;
  8987. public:
  8988. CRoxieServerSideEffectActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8989. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorSideEffectArg &)basehelper)
  8990. {
  8991. executed = false;
  8992. }
  8993. virtual const void * nextRow()
  8994. {
  8995. ActivityTimer t(totalCycles, timeActivities);
  8996. CriticalBlock b(ecrit);
  8997. if (exception)
  8998. throw(exception.getLink());
  8999. if (!executed)
  9000. {
  9001. try
  9002. {
  9003. executed = true;
  9004. helper.action();
  9005. }
  9006. catch(IException *E)
  9007. {
  9008. exception.set(E);
  9009. throw;
  9010. }
  9011. }
  9012. return NULL;
  9013. }
  9014. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  9015. {
  9016. CriticalBlock b(ecrit);
  9017. if (exception)
  9018. throw(exception.getLink());
  9019. if (!executed)
  9020. {
  9021. try
  9022. {
  9023. ActivityTimer t(totalCycles, timeActivities);
  9024. executed = true;
  9025. start(parentExtractSize, parentExtract, false);
  9026. helper.action();
  9027. stop();
  9028. }
  9029. catch(IException *E)
  9030. {
  9031. ctx->notifyAbort(E);
  9032. abort();
  9033. exception.set(E);
  9034. throw;
  9035. }
  9036. }
  9037. }
  9038. virtual void reset()
  9039. {
  9040. executed = false;
  9041. exception.clear();
  9042. CRoxieServerActivity::reset();
  9043. }
  9044. };
  9045. class CRoxieServerSideEffectActivityFactory : public CRoxieServerActivityFactory
  9046. {
  9047. bool isRoot;
  9048. public:
  9049. CRoxieServerSideEffectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  9050. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  9051. {
  9052. }
  9053. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9054. {
  9055. return new CRoxieServerSideEffectActivity(_ctx, this, _probeManager);
  9056. }
  9057. virtual bool isSink() const
  9058. {
  9059. return isRoot && !meta.queryOriginal();
  9060. }
  9061. };
  9062. IRoxieServerActivityFactory *createRoxieServerSideEffectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  9063. {
  9064. return new CRoxieServerSideEffectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  9065. }
  9066. //=================================================================================
  9067. class CRoxieServerActionActivity : public CRoxieServerInternalSinkActivity
  9068. {
  9069. IHThorActionArg &helper;
  9070. public:
  9071. CRoxieServerActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  9072. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _numOutputs), helper((IHThorActionArg &)basehelper)
  9073. {
  9074. }
  9075. virtual void onExecute()
  9076. {
  9077. helper.action();
  9078. }
  9079. };
  9080. class CRoxieServerActionActivityFactory : public CRoxieServerInternalSinkFactory
  9081. {
  9082. public:
  9083. CRoxieServerActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  9084. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot)
  9085. {
  9086. }
  9087. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9088. {
  9089. return new CRoxieServerActionActivity(_ctx, this, _probeManager, usageCount);
  9090. }
  9091. };
  9092. IRoxieServerActivityFactory *createRoxieServerActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  9093. {
  9094. return new CRoxieServerActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot);
  9095. }
  9096. //=================================================================================
  9097. class CRoxieServerSampleActivity : public CRoxieServerActivity
  9098. {
  9099. IHThorSampleArg &helper;
  9100. unsigned numSamples;
  9101. unsigned numToSkip;
  9102. unsigned whichSample;
  9103. bool anyThisGroup;
  9104. bool eof;
  9105. public:
  9106. CRoxieServerSampleActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9107. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorSampleArg &)basehelper)
  9108. {
  9109. numSamples = 0;
  9110. numToSkip = 0;
  9111. whichSample = 0;
  9112. anyThisGroup = false;
  9113. eof = false;
  9114. }
  9115. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9116. {
  9117. anyThisGroup = false;
  9118. eof = false;
  9119. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9120. numSamples = helper.getProportion();
  9121. whichSample = helper.getSampleNumber();
  9122. numToSkip = (whichSample ? whichSample-1 : 0);
  9123. }
  9124. virtual const void * nextRow()
  9125. {
  9126. ActivityTimer t(totalCycles, timeActivities);
  9127. if (eof)
  9128. return NULL;
  9129. for (;;)
  9130. {
  9131. const void * ret = inputStream->nextRow();
  9132. if (!ret)
  9133. {
  9134. //this does work with groups - may or may not be useful...
  9135. //reset the sample for each group.... probably best.
  9136. numToSkip = (whichSample ? whichSample-1 : 0);
  9137. if (anyThisGroup)
  9138. {
  9139. anyThisGroup = false;
  9140. return NULL;
  9141. }
  9142. ret = inputStream->nextRow();
  9143. if (!ret)
  9144. {
  9145. eof = true;
  9146. return NULL; // eof...
  9147. }
  9148. }
  9149. if (numToSkip == 0)
  9150. {
  9151. anyThisGroup = true;
  9152. numToSkip = numSamples-1;
  9153. processed++;
  9154. return ret;
  9155. }
  9156. numToSkip--;
  9157. ReleaseRoxieRow(ret);
  9158. }
  9159. }
  9160. };
  9161. class CRoxieServerSampleActivityFactory : public CRoxieServerActivityFactory
  9162. {
  9163. public:
  9164. CRoxieServerSampleActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9165. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  9166. {
  9167. }
  9168. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9169. {
  9170. return new CRoxieServerSampleActivity(_ctx, this, _probeManager);
  9171. }
  9172. };
  9173. IRoxieServerActivityFactory *createRoxieServerSampleActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9174. {
  9175. return new CRoxieServerSampleActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9176. }
  9177. //=================================================================================
  9178. class CRoxieServerChooseSetsActivity : public CRoxieServerActivity
  9179. {
  9180. IHThorChooseSetsArg &helper;
  9181. unsigned numSets;
  9182. unsigned * setCounts;
  9183. bool done;
  9184. public:
  9185. CRoxieServerChooseSetsActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9186. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorChooseSetsArg &)basehelper)
  9187. {
  9188. setCounts = NULL;
  9189. numSets = 0;
  9190. done = false;
  9191. }
  9192. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9193. {
  9194. done = false;
  9195. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9196. numSets = helper.getNumSets();
  9197. setCounts = new unsigned[numSets];
  9198. memset(setCounts, 0, sizeof(unsigned)*numSets);
  9199. helper.setCounts(setCounts);
  9200. }
  9201. virtual void reset()
  9202. {
  9203. delete [] setCounts;
  9204. setCounts = NULL;
  9205. CRoxieServerActivity::reset();
  9206. }
  9207. virtual const void * nextRow()
  9208. {
  9209. ActivityTimer t(totalCycles, timeActivities);
  9210. if (done)
  9211. return NULL;
  9212. for (;;)
  9213. {
  9214. const void * ret = inputStream->ungroupedNextRow();
  9215. if (!ret)
  9216. {
  9217. done = true;
  9218. return NULL;
  9219. }
  9220. processed++;
  9221. switch (helper.getRecordAction(ret))
  9222. {
  9223. case 2:
  9224. done = true;
  9225. return ret;
  9226. case 1:
  9227. return ret;
  9228. }
  9229. ReleaseRoxieRow(ret);
  9230. }
  9231. }
  9232. };
  9233. class CRoxieServerChooseSetsActivityFactory : public CRoxieServerActivityFactory
  9234. {
  9235. public:
  9236. CRoxieServerChooseSetsActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9237. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  9238. {
  9239. }
  9240. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9241. {
  9242. return new CRoxieServerChooseSetsActivity(_ctx, this, _probeManager);
  9243. }
  9244. };
  9245. IRoxieServerActivityFactory *createRoxieServerChooseSetsActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9246. {
  9247. return new CRoxieServerChooseSetsActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9248. }
  9249. //=================================================================================
  9250. class CRoxieServerChooseSetsExActivity : public CRoxieServerActivity
  9251. {
  9252. protected:
  9253. IHThorChooseSetsExArg &helper;
  9254. unsigned numSets;
  9255. unsigned curIndex;
  9256. unsigned * setCounts;
  9257. count_t * limits;
  9258. bool done;
  9259. ConstPointerArray gathered;
  9260. virtual bool includeRow(const void * row) = 0;
  9261. virtual void calculateSelection() = 0;
  9262. public:
  9263. CRoxieServerChooseSetsExActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9264. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorChooseSetsExArg &)basehelper)
  9265. {
  9266. setCounts = NULL;
  9267. limits = NULL;
  9268. done = false;
  9269. curIndex = 0;
  9270. numSets = 0;
  9271. }
  9272. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9273. {
  9274. done = false;
  9275. curIndex = 0;
  9276. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9277. numSets = helper.getNumSets();
  9278. setCounts = new unsigned[numSets];
  9279. memset(setCounts, 0, sizeof(unsigned)*numSets);
  9280. limits = (count_t *)calloc(sizeof(count_t), numSets);
  9281. helper.getLimits(limits);
  9282. }
  9283. virtual void reset()
  9284. {
  9285. delete [] setCounts;
  9286. setCounts = NULL;
  9287. free(limits);
  9288. limits = NULL;
  9289. roxiemem::ReleaseRoxieRowRange(gathered.getArray(), curIndex, gathered.ordinality());
  9290. gathered.kill();
  9291. curIndex = 0;
  9292. CRoxieServerActivity::reset();
  9293. }
  9294. virtual const void * nextRow()
  9295. {
  9296. ActivityTimer t(totalCycles, timeActivities);
  9297. if (gathered.ordinality() == 0)
  9298. {
  9299. curIndex = 0;
  9300. if (!inputStream->nextGroup(gathered))
  9301. {
  9302. done = true;
  9303. return NULL;
  9304. }
  9305. ForEachItemIn(idx1, gathered)
  9306. {
  9307. unsigned category = helper.getCategory(gathered.item(idx1));
  9308. if (category)
  9309. setCounts[category-1]++;
  9310. }
  9311. calculateSelection();
  9312. }
  9313. while (gathered.isItem(curIndex))
  9314. {
  9315. const void * row = gathered.item(curIndex);
  9316. gathered.replace(NULL, curIndex);
  9317. curIndex++;
  9318. if (includeRow(row))
  9319. {
  9320. processed++;
  9321. return row;
  9322. }
  9323. ReleaseRoxieRow(row);
  9324. }
  9325. gathered.kill();
  9326. return NULL;
  9327. }
  9328. };
  9329. class CRoxieServerChooseSetsLastActivity : public CRoxieServerChooseSetsExActivity
  9330. {
  9331. unsigned * numToSkip;
  9332. public:
  9333. CRoxieServerChooseSetsLastActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager) : CRoxieServerChooseSetsExActivity(_ctx, _factory, _probeManager)
  9334. {
  9335. numToSkip = NULL;
  9336. }
  9337. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9338. {
  9339. CRoxieServerChooseSetsExActivity::start(parentExtractSize, parentExtract, paused);
  9340. numToSkip = (unsigned *)calloc(sizeof(unsigned), numSets);
  9341. }
  9342. virtual void reset()
  9343. {
  9344. free(numToSkip);
  9345. numToSkip = NULL;
  9346. CRoxieServerChooseSetsExActivity::reset();
  9347. }
  9348. protected:
  9349. virtual void calculateSelection()
  9350. {
  9351. for (unsigned idx=0; idx < numSets; idx++)
  9352. {
  9353. if (setCounts[idx] < limits[idx])
  9354. numToSkip[idx] = 0;
  9355. else
  9356. numToSkip[idx] = (unsigned)(setCounts[idx] - limits[idx]);
  9357. }
  9358. }
  9359. virtual bool includeRow(const void * row)
  9360. {
  9361. unsigned category = helper.getCategory(row);
  9362. if (category)
  9363. {
  9364. if (numToSkip[category-1] == 0)
  9365. return true;
  9366. numToSkip[category-1]--;
  9367. }
  9368. return false;
  9369. }
  9370. };
  9371. class CRoxieServerChooseSetsEnthActivity : public CRoxieServerChooseSetsExActivity
  9372. {
  9373. count_t * counter;
  9374. public:
  9375. CRoxieServerChooseSetsEnthActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager) : CRoxieServerChooseSetsExActivity(_ctx, _factory, _probeManager)
  9376. {
  9377. counter = NULL;
  9378. }
  9379. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9380. {
  9381. CRoxieServerChooseSetsExActivity::start(parentExtractSize, parentExtract, paused);
  9382. counter = (count_t *)calloc(sizeof(count_t), numSets);
  9383. }
  9384. virtual void reset()
  9385. {
  9386. free(counter);
  9387. counter = NULL;
  9388. CRoxieServerChooseSetsExActivity::reset();
  9389. }
  9390. protected:
  9391. virtual void calculateSelection()
  9392. {
  9393. }
  9394. virtual bool includeRow(const void * row)
  9395. {
  9396. unsigned category = helper.getCategory(row);
  9397. if (category)
  9398. {
  9399. assertex(category <= numSets);
  9400. counter[category-1] += limits[category-1];
  9401. if(counter[category-1] >= setCounts[category-1])
  9402. {
  9403. counter[category-1] -= setCounts[category-1];
  9404. return true;
  9405. }
  9406. }
  9407. return false;
  9408. }
  9409. };
  9410. class CRoxieServerChooseSetsEnthActivityFactory : public CRoxieServerActivityFactory
  9411. {
  9412. public:
  9413. CRoxieServerChooseSetsEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9414. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  9415. {
  9416. }
  9417. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9418. {
  9419. return new CRoxieServerChooseSetsEnthActivity(_ctx, this, _probeManager);
  9420. }
  9421. };
  9422. IRoxieServerActivityFactory *createRoxieServerChooseSetsEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9423. {
  9424. return new CRoxieServerChooseSetsEnthActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9425. }
  9426. class CRoxieServerChooseSetsLastActivityFactory : public CRoxieServerActivityFactory
  9427. {
  9428. public:
  9429. CRoxieServerChooseSetsLastActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9430. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  9431. {
  9432. }
  9433. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9434. {
  9435. return new CRoxieServerChooseSetsLastActivity(_ctx, this, _probeManager);
  9436. }
  9437. };
  9438. IRoxieServerActivityFactory *createRoxieServerChooseSetsLastActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9439. {
  9440. return new CRoxieServerChooseSetsLastActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9441. }
  9442. //=================================================================================
  9443. class CRoxieServerEnthActivity : public CRoxieServerActivity
  9444. {
  9445. IHThorEnthArg &helper;
  9446. unsigned __int64 numerator;
  9447. unsigned __int64 denominator;
  9448. unsigned __int64 counter;
  9449. bool eof;
  9450. public:
  9451. CRoxieServerEnthActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9452. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorEnthArg &)basehelper)
  9453. {
  9454. eof = false;
  9455. numerator = denominator = counter = 0;
  9456. }
  9457. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9458. {
  9459. eof = false;
  9460. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9461. numerator = helper.getProportionNumerator();
  9462. denominator = helper.getProportionDenominator();
  9463. if(denominator == 0) denominator = 1; //MORE: simplest way to avoid disaster in this case
  9464. counter = (helper.getSampleNumber()-1) * greatestCommonDivisor(numerator, denominator);
  9465. if (counter >= denominator)
  9466. counter %= denominator;
  9467. }
  9468. inline bool wanted()
  9469. {
  9470. counter += numerator;
  9471. if(counter >= denominator)
  9472. {
  9473. counter -= denominator;
  9474. return true;
  9475. }
  9476. return false;
  9477. }
  9478. virtual const void * nextRow()
  9479. {
  9480. ActivityTimer t(totalCycles, timeActivities);
  9481. if (eof)
  9482. return NULL;
  9483. const void * ret;
  9484. for (;;)
  9485. {
  9486. ret = inputStream->ungroupedNextRow();
  9487. if (!ret) //eof
  9488. {
  9489. eof = true;
  9490. return ret;
  9491. }
  9492. if (wanted())
  9493. return ret;
  9494. ReleaseRoxieRow(ret);
  9495. }
  9496. }
  9497. };
  9498. class CRoxieServerEnthActivityFactory : public CRoxieServerActivityFactory
  9499. {
  9500. public:
  9501. CRoxieServerEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9502. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  9503. {
  9504. }
  9505. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9506. {
  9507. return new CRoxieServerEnthActivity(_ctx, this, _probeManager);
  9508. }
  9509. };
  9510. IRoxieServerActivityFactory *createRoxieServerEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9511. {
  9512. return new CRoxieServerEnthActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9513. }
  9514. //=================================================================================
  9515. class CRoxieServerAggregateActivity : public CRoxieServerActivity
  9516. {
  9517. IHThorAggregateArg &helper;
  9518. bool eof;
  9519. bool isInputGrouped;
  9520. bool abortEarly;
  9521. public:
  9522. CRoxieServerAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9523. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorAggregateArg &)basehelper)
  9524. {
  9525. eof = false;
  9526. isInputGrouped = false;
  9527. abortEarly = false;
  9528. }
  9529. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9530. {
  9531. eof = false;
  9532. isInputGrouped = input->queryOutputMeta()->isGrouped(); // could be done earlier, in setInput?
  9533. abortEarly = !isInputGrouped && (factory->getKind() == TAKexistsaggregate); // ditto
  9534. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9535. }
  9536. virtual bool needsAllocator() const { return true; }
  9537. virtual const void * nextRow()
  9538. {
  9539. ActivityTimer t(totalCycles, timeActivities);
  9540. if (eof)
  9541. return NULL;
  9542. const void * next = inputStream->nextRow();
  9543. if (!next && isInputGrouped)
  9544. {
  9545. eof = true;
  9546. return NULL;
  9547. }
  9548. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  9549. size32_t finalSize = helper.clearAggregate(rowBuilder);
  9550. if (next)
  9551. {
  9552. finalSize = helper.processFirst(rowBuilder, next);
  9553. ReleaseRoxieRow(next);
  9554. if (!abortEarly)
  9555. {
  9556. for (;;)
  9557. {
  9558. next = inputStream->nextRow();
  9559. if (!next)
  9560. break;
  9561. finalSize = helper.processNext(rowBuilder, next);
  9562. ReleaseRoxieRow(next);
  9563. }
  9564. }
  9565. }
  9566. if (!isInputGrouped) // either read all, or aborted early
  9567. eof = true;
  9568. processed++;
  9569. return rowBuilder.finalizeRowClear(finalSize);
  9570. }
  9571. };
  9572. class CRoxieServerStrandedAggregateActivity : public CRoxieServerStrandedActivity, implements IOrderedCallbackCollection
  9573. {
  9574. class AggregateProcessor : public StrandProcessor, implements IStrandThreaded, implements IOrderedOutputCallback
  9575. {
  9576. protected:
  9577. IHThorAggregateArg &helper;
  9578. OwnedConstRoxieRow result;
  9579. bool eof = false;
  9580. bool isInputGrouped = false;
  9581. bool abortEarly = false;
  9582. public:
  9583. AggregateProcessor(CRoxieServerActivity &_parent, IEngineRowStream *_inputStream, IHThorAggregateArg &_helper, bool _isInputGrouped, bool _abortEarly)
  9584. : StrandProcessor(_parent, _inputStream, true), helper(_helper), isInputGrouped(_isInputGrouped), abortEarly(_abortEarly)
  9585. {
  9586. }
  9587. virtual const void * nextRow() override
  9588. {
  9589. ActivityTimer t(totalCycles, timeActivities);
  9590. if (eof || isAborting())
  9591. return NULL;
  9592. const void * next = inputStream->nextRow();
  9593. if (!next && isInputGrouped)
  9594. {
  9595. eof = true;
  9596. return NULL;
  9597. }
  9598. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  9599. size32_t finalSize = helper.clearAggregate(rowBuilder);
  9600. if (next)
  9601. {
  9602. finalSize = helper.processFirst(rowBuilder, next);
  9603. ReleaseRoxieRow(next);
  9604. if (!abortEarly)
  9605. {
  9606. for (;;)
  9607. {
  9608. next = inputStream->nextRow();
  9609. if (!next)
  9610. break;
  9611. finalSize = helper.processNext(rowBuilder, next);
  9612. ReleaseRoxieRow(next);
  9613. if (isAborting())
  9614. break;
  9615. }
  9616. }
  9617. }
  9618. if (!isInputGrouped) // either read all, or aborted early
  9619. eof = true;
  9620. processed++;
  9621. return rowBuilder.finalizeRowClear(finalSize);
  9622. }
  9623. virtual void main() override
  9624. {
  9625. isInputGrouped = true; // gather no row if there are no input rows.
  9626. result.setown(nextRow());
  9627. queryActivity().noteStrandFinished(inputStream);
  9628. }
  9629. virtual void reset() override
  9630. {
  9631. StrandProcessor::reset();
  9632. result.clear();
  9633. eof = false;
  9634. }
  9635. //interface IOutputOutputCallback
  9636. virtual bool noteEndOfInputChunk() { return true; }
  9637. virtual void noteEndOfInput() {}
  9638. virtual void stopStream()
  9639. {
  9640. inputStream->stop();
  9641. }
  9642. const void * queryResult() const { return result; }
  9643. CRoxieServerStrandedAggregateActivity & queryActivity() { return static_cast<CRoxieServerStrandedAggregateActivity &>(parent); }
  9644. };
  9645. //This class is only used when a single aggregate is being calculated.
  9646. class AggregateCombiner : public CInterfaceOf<IEngineRowStream>
  9647. {
  9648. public:
  9649. explicit AggregateCombiner(CRoxieServerStrandedAggregateActivity & _parent) : parent(_parent)
  9650. {
  9651. }
  9652. virtual const void *nextRow()
  9653. {
  9654. return parent.getCombinedAggregate();
  9655. }
  9656. virtual void stop()
  9657. {
  9658. parent.outputStopped();
  9659. }
  9660. virtual void resetEOF()
  9661. {
  9662. throwUnexpected();
  9663. }
  9664. protected:
  9665. CRoxieServerStrandedAggregateActivity & parent;
  9666. } combiner;
  9667. class NullCallback : implements IOrderedOutputCallback
  9668. {
  9669. public:
  9670. virtual bool noteEndOfInputChunk() { return true; }
  9671. virtual void noteEndOfInput() {}
  9672. } nullCallback;
  9673. public:
  9674. CRoxieServerStrandedAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const StrandOptions &_strandOptions)
  9675. : CRoxieServerStrandedActivity(_ctx, _factory, _probeManager, _strandOptions), helper((IHThorAggregateArg &)basehelper), combiner(*this)
  9676. {
  9677. isInputGrouped = false;
  9678. abortEarly = false;
  9679. }
  9680. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  9681. {
  9682. CRoxieServerStrandedActivity::setInput(idx, _sourceIdx, _in);
  9683. isInputGrouped = input->queryOutputMeta()->isGrouped(); // could be done earlier, in setInput?
  9684. abortEarly = !isInputGrouped && (factory->getKind() == TAKexistsaggregate); // ditto
  9685. //For EXISTS(), and aggregates that rely on the input order, force to execute single threaded
  9686. //MORE: Ordered should be able to process a block at a time and then merge them, similar to disk write processing.
  9687. if (abortEarly || (!isInputGrouped && queryFactory()->isInputOrdered(false, 0)))
  9688. strandOptions.numStrands = 1;
  9689. else if (!isInputGrouped)
  9690. combineStreams = true;
  9691. }
  9692. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  9693. {
  9694. PointerArrayOf<IEngineRowStream> localStreams;
  9695. //If streams are being combined, this class should be notified of end of sections, otherwise grouped aggregates can inform a downstream activity.
  9696. IOrderedCallbackCollection * callbacks = combineStreams ? static_cast<IOrderedCallbackCollection *>(this) : orderedCallbacks;
  9697. Owned<IStrandJunction> outJunction = CRoxieServerStrandedActivity::getOutputStreams(ctx, idx, localStreams, consumerOptions, consumerOrdered, callbacks);
  9698. if (localStreams.ordinality() == 1)
  9699. combineStreams = false; // Select a more efficient/simpler code path
  9700. if (combineStreams)
  9701. {
  9702. assertex(!outJunction); // this needs more thought!
  9703. streams.append(&combiner);
  9704. }
  9705. else
  9706. {
  9707. streams.swapWith(localStreams);
  9708. }
  9709. return outJunction.getClear();
  9710. }
  9711. virtual StrandProcessor *createStrandProcessor(IEngineRowStream *instream)
  9712. {
  9713. if (traceLevel > 4)
  9714. DBGLOG("Create aggregate strand processor %u", strandOptions.numStrands);
  9715. return new AggregateProcessor(*this, instream, (IHThorAggregateArg &) basehelper, isInputGrouped && !combineStreams, abortEarly);
  9716. }
  9717. virtual StrandProcessor *createStrandSourceProcessor(bool inputOrdered) { throwUnexpected(); }
  9718. virtual bool needsAllocator() const { return true; }
  9719. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused) override
  9720. {
  9721. CRoxieServerStrandedActivity::start(parentExtractSize, parentExtract, paused);
  9722. if (combineStreams)
  9723. {
  9724. barrier.setown(createStrandBarrier());
  9725. ForEachItemIn(i, strands)
  9726. barrier->startStrand(queryAggregate(i));
  9727. active.store(1);
  9728. }
  9729. else
  9730. active.store(0);
  9731. }
  9732. virtual void reset() override
  9733. {
  9734. CRoxieServerStrandedActivity::reset();
  9735. barrier.clear();
  9736. calculated = false;
  9737. }
  9738. //Helper functions for the single aggregate case
  9739. const void * getCombinedAggregate()
  9740. {
  9741. if (calculated)
  9742. return NULL;
  9743. calculated= true;
  9744. barrier->waitForStrands();
  9745. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  9746. size32_t finalSize = helper.clearAggregate(rowBuilder);
  9747. bool isFirst = true;
  9748. for (unsigned i=0; i < numStrands(); i++)
  9749. {
  9750. const void * next = queryAggregate(i).queryResult();
  9751. if (next)
  9752. {
  9753. if (isFirst)
  9754. {
  9755. finalSize = cloneRow(rowBuilder, next, helper.queryOutputMeta());
  9756. isFirst = false;
  9757. }
  9758. else
  9759. finalSize = helper.mergeAggregate(rowBuilder, next);
  9760. }
  9761. }
  9762. return rowBuilder.finalizeRowClear(finalSize);
  9763. }
  9764. void outputStopped()
  9765. {
  9766. //only called if generating a single result.
  9767. assertex(combineStreams);
  9768. if (barrier)
  9769. {
  9770. requestAbort(); // if strands are still running, abort them
  9771. barrier->waitForStrands();
  9772. }
  9773. else
  9774. {
  9775. ForEachItemIn(i, strands)
  9776. queryAggregate(i).stopStream();
  9777. }
  9778. CRoxieServerStrandedActivity::stop();
  9779. }
  9780. void noteStrandFinished(IRowStream * stream)
  9781. {
  9782. barrier->noteStrandFinished(stream);
  9783. }
  9784. virtual IOrderedOutputCallback * queryCallback(unsigned i)
  9785. {
  9786. //The non-ordered aggregate does not need to process the ordered call back information.
  9787. //If the ordered single aggregate was implemented then it would need to be processed instead of ignored,
  9788. //however it needs some care since the strands are not yet created. So cannot return strand(i).
  9789. return &nullCallback;
  9790. }
  9791. inline AggregateProcessor & queryAggregate(unsigned i)
  9792. {
  9793. return static_cast<AggregateProcessor &>(strands.item(i));
  9794. }
  9795. protected:
  9796. IHThorAggregateArg &helper;
  9797. Owned<IStrandBarrier> barrier;
  9798. IEngineRowStream * combinedStream = nullptr;
  9799. bool isInputGrouped;
  9800. bool abortEarly;
  9801. bool combineStreams = false;
  9802. bool calculated = false;
  9803. };
  9804. class CRoxieServerAggregateActivityFactory : public CRoxieServerActivityFactory
  9805. {
  9806. StrandOptions strandOptions;
  9807. public:
  9808. CRoxieServerAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9809. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), strandOptions(_graphNode)
  9810. {
  9811. Owned<IHThorAggregateArg> helper = (IHThorAggregateArg *) helperFactory();
  9812. if (!(helper->getAggregateFlags() & TAForderedmerge))
  9813. optStableInput = false;
  9814. }
  9815. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9816. {
  9817. return new CRoxieServerStrandedAggregateActivity(_ctx, this, _probeManager, strandOptions);
  9818. }
  9819. };
  9820. IRoxieServerActivityFactory *createRoxieServerAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9821. {
  9822. return new CRoxieServerAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9823. }
  9824. //=================================================================================
  9825. typedef unsigned t_hashPrefix;
  9826. class CRoxieServerHashAggregateActivity : public CRoxieServerActivity
  9827. {
  9828. IHThorHashAggregateArg &helper;
  9829. RowAggregator aggregated;
  9830. bool eof;
  9831. bool gathered;
  9832. bool isGroupedAggregate;
  9833. public:
  9834. CRoxieServerHashAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, bool _isGroupedAggregate, IProbeManager *_probeManager)
  9835. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorHashAggregateArg &)basehelper),
  9836. isGroupedAggregate(_isGroupedAggregate),
  9837. aggregated(helper, helper)
  9838. {
  9839. eof = false;
  9840. gathered = false;
  9841. }
  9842. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9843. {
  9844. eof = false;
  9845. gathered = false;
  9846. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9847. }
  9848. virtual void reset()
  9849. {
  9850. aggregated.reset();
  9851. CRoxieServerActivity::reset();
  9852. }
  9853. virtual bool needsAllocator() const { return true; }
  9854. virtual const void * nextRow()
  9855. {
  9856. ActivityTimer t(totalCycles, timeActivities);
  9857. if (eof)
  9858. return NULL;
  9859. if (!gathered)
  9860. {
  9861. aggregated.start(rowAllocator);
  9862. bool eog = true;
  9863. for (;;)
  9864. {
  9865. const void * next = inputStream->nextRow();
  9866. if (!next)
  9867. {
  9868. if (isGroupedAggregate)
  9869. {
  9870. if (eog)
  9871. eof = true;
  9872. break;
  9873. }
  9874. next = inputStream->nextRow();
  9875. if (!next)
  9876. break;
  9877. }
  9878. eog = false;
  9879. aggregated.addRow(next);
  9880. ReleaseRoxieRow(next);
  9881. }
  9882. gathered = true;
  9883. }
  9884. Owned<AggregateRowBuilder> next = aggregated.nextResult();
  9885. if (next)
  9886. {
  9887. processed++;
  9888. return next->finalizeRowClear();
  9889. }
  9890. if (!isGroupedAggregate)
  9891. eof = true;
  9892. aggregated.reset();
  9893. gathered = false;
  9894. return NULL;
  9895. }
  9896. };
  9897. class CRoxieServerHashAggregateActivityFactory : public CRoxieServerActivityFactory
  9898. {
  9899. public:
  9900. CRoxieServerHashAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9901. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  9902. {
  9903. isGroupedAggregate = _graphNode.getPropBool("att[@name='grouped']/@value");
  9904. }
  9905. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9906. {
  9907. return new CRoxieServerHashAggregateActivity(_ctx, this, isGroupedAggregate, _probeManager);
  9908. }
  9909. protected:
  9910. bool isGroupedAggregate;
  9911. };
  9912. IRoxieServerActivityFactory *createRoxieServerHashAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9913. {
  9914. return new CRoxieServerHashAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9915. }
  9916. //=================================================================================
  9917. class CRoxieServerDegroupActivity : public CRoxieServerActivity
  9918. {
  9919. IHThorDegroupArg &helper;
  9920. bool eof;
  9921. public:
  9922. CRoxieServerDegroupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9923. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorDegroupArg &)basehelper)
  9924. {
  9925. eof = false;
  9926. }
  9927. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9928. {
  9929. eof = false;
  9930. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9931. }
  9932. virtual const void * nextRow()
  9933. {
  9934. ActivityTimer t(totalCycles, timeActivities);
  9935. if (eof)
  9936. return NULL;
  9937. const void * ret = inputStream->ungroupedNextRow();
  9938. if (ret)
  9939. processed++;
  9940. else
  9941. eof = true;
  9942. return ret;
  9943. }
  9944. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  9945. {
  9946. ActivityTimer t(totalCycles, timeActivities);
  9947. if (eof)
  9948. return NULL;
  9949. const void * ret = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  9950. if (ret)
  9951. processed++;
  9952. else
  9953. eof = true;
  9954. return ret;
  9955. }
  9956. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  9957. {
  9958. return input->gatherConjunctions(collector);
  9959. }
  9960. virtual void resetEOF()
  9961. {
  9962. eof = false;
  9963. inputStream->resetEOF();
  9964. }
  9965. IInputSteppingMeta * querySteppingMeta()
  9966. {
  9967. return input->querySteppingMeta();
  9968. }
  9969. };
  9970. class CRoxieServerDegroupActivityFactory : public CRoxieServerActivityFactory
  9971. {
  9972. public:
  9973. CRoxieServerDegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9974. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  9975. {
  9976. }
  9977. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9978. {
  9979. return new CRoxieServerDegroupActivity(_ctx, this, _probeManager);
  9980. }
  9981. };
  9982. IRoxieServerActivityFactory *createRoxieServerDegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9983. {
  9984. return new CRoxieServerDegroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9985. }
  9986. //=================================================================================
  9987. class CRoxieServerSpillReadActivity : public CRoxieServerActivity
  9988. {
  9989. IHThorDiskReadArg &helper;
  9990. bool needTransform;
  9991. bool eof;
  9992. bool anyThisGroup;
  9993. unsigned __int64 rowLimit;
  9994. unsigned __int64 choosenLimit;
  9995. public:
  9996. CRoxieServerSpillReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9997. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorDiskReadArg &)basehelper)
  9998. {
  9999. needTransform = helper.needTransform();
  10000. rowLimit = (unsigned __int64) -1;
  10001. choosenLimit = 0;
  10002. eof = false;
  10003. anyThisGroup = false;
  10004. }
  10005. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10006. {
  10007. anyThisGroup = false;
  10008. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  10009. if (helper.canMatchAny())
  10010. eof = false;
  10011. else
  10012. eof = true;
  10013. choosenLimit = helper.getChooseNLimit();
  10014. rowLimit = helper.getRowLimit();
  10015. helper.setCallback(NULL); // members should not be called - change if they are
  10016. }
  10017. virtual bool needsAllocator() const { return true; }
  10018. virtual const void * nextRow()
  10019. {
  10020. ActivityTimer t(totalCycles, timeActivities);
  10021. if (eof)
  10022. return NULL;
  10023. if (processed==choosenLimit)
  10024. {
  10025. eof = true;
  10026. return NULL;
  10027. }
  10028. if (needTransform)
  10029. {
  10030. for (;;)
  10031. {
  10032. const void *in = inputStream->nextRow();
  10033. if (!in)
  10034. {
  10035. if (anyThisGroup)
  10036. {
  10037. anyThisGroup = false;
  10038. return NULL;
  10039. }
  10040. in = inputStream->nextRow();
  10041. if (!in)
  10042. {
  10043. eof = true;
  10044. return NULL; // eof...
  10045. }
  10046. }
  10047. unsigned outSize;
  10048. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  10049. try
  10050. {
  10051. outSize = helper.transform(rowBuilder, in);
  10052. ReleaseRoxieRow(in);
  10053. }
  10054. catch (IException *E)
  10055. {
  10056. throw makeWrappedException(E);
  10057. }
  10058. if (outSize)
  10059. {
  10060. anyThisGroup = true;
  10061. processed++;
  10062. if (processed==rowLimit)
  10063. {
  10064. if (traceLevel > 4)
  10065. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  10066. helper.onLimitExceeded();
  10067. }
  10068. return rowBuilder.finalizeRowClear(outSize);
  10069. }
  10070. }
  10071. }
  10072. else
  10073. {
  10074. const void *ret = inputStream->nextRow();
  10075. if (ret)
  10076. {
  10077. processed++;
  10078. if (processed==rowLimit)
  10079. {
  10080. if (traceLevel > 4)
  10081. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  10082. ReleaseClearRoxieRow(ret);
  10083. helper.onLimitExceeded(); // should not return
  10084. throwUnexpected();
  10085. }
  10086. }
  10087. return ret;
  10088. }
  10089. }
  10090. };
  10091. class CRoxieServerSpillReadActivityFactory : public CRoxieServerActivityFactory
  10092. {
  10093. public:
  10094. CRoxieServerSpillReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  10095. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  10096. {
  10097. }
  10098. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  10099. {
  10100. return new CRoxieServerSpillReadActivity(_ctx, this, _probeManager);
  10101. }
  10102. virtual void addDependency(unsigned source, ThorActivityKind sourceKind, unsigned sourceIdx, int controlId, const char *edgeId)
  10103. {
  10104. if (sourceKind==TAKspill || sourceKind==TAKdiskwrite) // Bit of a hack - codegen probably should differentiate
  10105. setInput(0, source, sourceIdx);
  10106. else
  10107. CRoxieServerActivityFactory::addDependency(source, kind, sourceIdx, controlId, edgeId);
  10108. }
  10109. };
  10110. IRoxieServerActivityFactory *createRoxieServerSpillReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  10111. {
  10112. return new CRoxieServerSpillReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  10113. }
  10114. //=================================================================================
  10115. class CRoxieServerSpillWriteActivity : public CRoxieServerActivity
  10116. {
  10117. public:
  10118. CRoxieServerSpillWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  10119. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  10120. {
  10121. }
  10122. ~CRoxieServerSpillWriteActivity()
  10123. {
  10124. }
  10125. virtual const void *nextRow()
  10126. {
  10127. ActivityTimer t(totalCycles, timeActivities);
  10128. return inputStream->nextRow();
  10129. }
  10130. };
  10131. //==================================================================================
  10132. class CRoxieServerDiskWriteActivity : public CRoxieServerInternalSinkActivity, implements IRoxiePublishCallback
  10133. {
  10134. protected:
  10135. Owned<IExtRowWriter> outSeq;
  10136. Owned<IOutputRowSerializer> rowSerializer;
  10137. Linked<IFileIOStream> diskout;
  10138. bool blockcompressed;
  10139. bool extend;
  10140. bool overwrite;
  10141. bool encrypted;
  10142. bool grouped;
  10143. IHThorDiskWriteArg &helper;
  10144. Owned<IRecordSize> diskmeta;
  10145. Owned<IRoxieWriteHandler> writer;
  10146. bool tallycrc;
  10147. unsigned __int64 uncompressedBytesWritten;
  10148. CRC32 crc;
  10149. void updateWorkUnitResult(unsigned __int64 reccount)
  10150. {
  10151. assertex(writer);
  10152. // MORE - a lot of this is common with hthor
  10153. WorkunitUpdate wu = ctx->updateWorkUnit();
  10154. if (wu)
  10155. {
  10156. OwnedRoxieString rawLogicalName = helper.getFileName();
  10157. StringBuffer lfn; // logical filename
  10158. expandLogicalFilename(lfn, rawLogicalName, wu, false, false);
  10159. if (lfn.length())
  10160. {
  10161. unsigned flags = helper.getFlags();
  10162. WUFileKind fileKind;
  10163. if (TDXtemporary & flags)
  10164. fileKind = WUFileTemporary;
  10165. else if(TDXjobtemp & flags)
  10166. fileKind = WUFileJobOwned;
  10167. else if(TDWowned & flags)
  10168. fileKind = WUFileOwned;
  10169. else
  10170. fileKind = WUFileStandard;
  10171. StringArray clusters;
  10172. writer->getClusters(clusters);
  10173. wu->addFile(lfn.str(), &clusters, helper.getTempUsageCount(), fileKind, NULL);
  10174. if (!(flags & TDXtemporary) && helper.getSequence() >= 0)
  10175. {
  10176. Owned<IWUResult> result = wu->updateResultBySequence(helper.getSequence());
  10177. if (result)
  10178. {
  10179. result->setResultTotalRowCount(reccount);
  10180. result->setResultStatus(ResultStatusCalculated);
  10181. if (helper.getFlags() & TDWresult)
  10182. result->setResultFilename(lfn.str());
  10183. else
  10184. result->setResultLogicalName(lfn.str());
  10185. }
  10186. }
  10187. }
  10188. }
  10189. }
  10190. void resolve()
  10191. {
  10192. OwnedRoxieString rawLogicalName = helper.getFileName();
  10193. assertex(rawLogicalName);
  10194. assertex((helper.getFlags() & TDXtemporary) == 0);
  10195. StringArray clusters;
  10196. unsigned clusterIdx = 0;
  10197. while(true)
  10198. {
  10199. OwnedRoxieString cluster(helper.getCluster(clusterIdx));
  10200. if(!cluster)
  10201. break;
  10202. clusters.append(cluster);
  10203. clusterIdx++;
  10204. }
  10205. if (clusters.length())
  10206. {
  10207. if (extend)
  10208. throw MakeStringException(0, "Cannot combine EXTEND and CLUSTER flags on disk write of file %s", rawLogicalName.get());
  10209. }
  10210. else
  10211. {
  10212. if (roxieName.length())
  10213. clusters.append(roxieName.str());
  10214. else
  10215. clusters.append(".");
  10216. }
  10217. writer.setown(ctx->createLFN(rawLogicalName, overwrite, extend, clusters));
  10218. // MORE - need to check somewhere that single part if it's an existing file or an external one...
  10219. }
  10220. public:
  10221. CRoxieServerDiskWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  10222. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, 0), helper((IHThorDiskWriteArg &) basehelper)
  10223. {
  10224. extend = ((helper.getFlags() & TDWextend) != 0);
  10225. overwrite = ((helper.getFlags() & TDWoverwrite) != 0);
  10226. grouped = (helper.getFlags() & TDXgrouped) != 0;
  10227. diskmeta.set(helper.queryDiskRecordSize()->querySerializedDiskMeta());
  10228. if (grouped)
  10229. diskmeta.setown(createDeltaRecordSize(diskmeta, +1));
  10230. blockcompressed = (((helper.getFlags() & TDWnewcompress) != 0) || (((helper.getFlags() & TDXcompress) != 0) && (diskmeta->getFixedSize() >= MIN_ROWCOMPRESS_RECSIZE))); //always use new compression
  10231. encrypted = false; // set later
  10232. tallycrc = true;
  10233. uncompressedBytesWritten = 0;
  10234. }
  10235. ~CRoxieServerDiskWriteActivity()
  10236. {
  10237. }
  10238. virtual bool needsAllocator() const
  10239. {
  10240. return true;
  10241. }
  10242. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10243. {
  10244. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  10245. resolve();
  10246. Owned<IFileIO> io;
  10247. void *ekey;
  10248. size32_t ekeylen;
  10249. helper.getEncryptKey(ekeylen, ekey);
  10250. Owned<ICompressor> ecomp;
  10251. if (ekeylen!=0)
  10252. {
  10253. ecomp.setown(createAESCompressor256(ekeylen,ekey));
  10254. memset(ekey,0,ekeylen);
  10255. rtlFree(ekey);
  10256. encrypted = true;
  10257. blockcompressed = true;
  10258. }
  10259. if (blockcompressed)
  10260. io.setown(createCompressedFileWriter(writer->queryFile(), (diskmeta->isFixedSize() ? diskmeta->getFixedSize() : 0), extend, true, ecomp));
  10261. else
  10262. io.setown(writer->queryFile()->open(extend ? IFOwrite : IFOcreate));
  10263. if (!io)
  10264. throw MakeStringException(errno, "Failed to create%s file %s for writing", (encrypted ? " encrypted" : (blockcompressed ? " compressed" : "")), writer->queryFile()->queryFilename());
  10265. diskout.setown(createBufferedIOStream(io));
  10266. if (extend)
  10267. diskout->seek(0, IFSend);
  10268. tallycrc = !factory->queryQueryFactory().queryOptions().skipFileFormatCrcCheck && !(helper.getFlags() & TDRnocrccheck) && !blockcompressed;
  10269. Owned<IRowInterfaces> rowIf = createRowInterfaces(input->queryOutputMeta(), activityId, factory->getHeapFlags(), ctx->queryCodeContext());
  10270. rowSerializer.set(rowIf->queryRowSerializer());
  10271. unsigned rwFlags = rw_autoflush;
  10272. if(grouped)
  10273. rwFlags |= rw_grouped;
  10274. if(tallycrc)
  10275. rwFlags |= rw_crc;
  10276. outSeq.setown(createRowWriter(diskout, rowIf, rwFlags));
  10277. }
  10278. virtual void stop()
  10279. {
  10280. if (aborted)
  10281. {
  10282. if (writer)
  10283. writer->finish(false, this);
  10284. }
  10285. else
  10286. {
  10287. if (outSeq)
  10288. outSeq->flush(&crc);
  10289. if (outSeq)
  10290. uncompressedBytesWritten = outSeq->getPosition();
  10291. outSeq.clear();
  10292. diskout.clear(); // Make sure file is properly closed or date may not match published info
  10293. if (writer)
  10294. {
  10295. updateWorkUnitResult(processed);
  10296. writer->finish(true, this);
  10297. }
  10298. }
  10299. writer.clear();
  10300. CRoxieServerActivity::stop();
  10301. }
  10302. virtual void reset()
  10303. {
  10304. CRoxieServerActivity::reset();
  10305. diskout.clear();
  10306. outSeq.clear();
  10307. writer.clear();
  10308. uncompressedBytesWritten = 0;
  10309. crc.reset();
  10310. }
  10311. virtual void onExecute()
  10312. {
  10313. for (;;)
  10314. {
  10315. const void *row = inputStream->nextRow();
  10316. if (!row)
  10317. {
  10318. row = inputStream->nextRow();
  10319. if (!row)
  10320. break;
  10321. if (grouped)
  10322. outSeq->putRow(NULL);
  10323. }
  10324. processed++;
  10325. outSeq->putRow(row);
  10326. }
  10327. }
  10328. virtual void setFileProperties(IFileDescriptor *desc) const
  10329. {
  10330. IPropertyTree &partProps = desc->queryPart(0)->queryProperties(); //properties of the first file part.
  10331. IPropertyTree &fileProps = desc->queryProperties(); // properties of the logical file
  10332. if (blockcompressed)
  10333. {
  10334. // caller has already set @size from file size...
  10335. fileProps.setPropBool("@blockCompressed", true);
  10336. fileProps.setPropInt64("@compressedSize", partProps.getPropInt64("@size", 0));
  10337. partProps.setPropInt64("@compressedSize", partProps.getPropInt64("@size", 0));
  10338. fileProps.setPropInt64("@size", uncompressedBytesWritten);
  10339. partProps.setPropInt64("@size", uncompressedBytesWritten);
  10340. }
  10341. else if (tallycrc && crc.get())
  10342. partProps.setPropInt64("@fileCrc", crc.get());
  10343. if (encrypted)
  10344. fileProps.setPropBool("@encrypted", true);
  10345. fileProps.setPropInt64("@recordCount", processed);
  10346. unsigned flags = helper.getFlags();
  10347. if (flags & TDWpersist)
  10348. fileProps.setPropBool("@persistent", true);
  10349. if (grouped)
  10350. fileProps.setPropBool("@grouped", true);
  10351. if (flags & (TDWowned|TDXjobtemp|TDXtemporary))
  10352. fileProps.setPropBool("@owned", true);
  10353. if (flags & TDWresult)
  10354. fileProps.setPropBool("@result", true);
  10355. IConstWorkUnit *workUnit = ctx->queryWorkUnit();
  10356. if (workUnit)
  10357. {
  10358. fileProps.setProp("@owner", workUnit->queryUser());
  10359. fileProps.setProp("@workunit", workUnit->queryWuid());
  10360. fileProps.setProp("@job", workUnit->queryJobName());
  10361. }
  10362. if (flags & TDWexpires)
  10363. setExpiryTime(fileProps, helper.getExpiryDays());
  10364. if (flags & TDWupdate)
  10365. {
  10366. unsigned eclCRC;
  10367. unsigned __int64 totalCRC;
  10368. helper.getUpdateCRCs(eclCRC, totalCRC);
  10369. fileProps.setPropInt("@eclCRC", eclCRC);
  10370. fileProps.setPropInt64("@totalCRC", totalCRC);
  10371. }
  10372. fileProps.setPropInt("@formatCrc", helper.getFormatCrc());
  10373. IRecordSize * inputMeta = input->queryOutputMeta();
  10374. if ((inputMeta->isFixedSize()) && !isOutputTransformed())
  10375. fileProps.setPropInt("@recordSize", inputMeta->getFixedSize() + (grouped ? 1 : 0));
  10376. const char *recordECL = helper.queryRecordECL();
  10377. if (recordECL && *recordECL)
  10378. fileProps.setProp("ECL", recordECL);
  10379. fileProps.setProp("@kind", "flat"); // default, derivitives may override
  10380. }
  10381. virtual IUserDescriptor *queryUserDescriptor() const
  10382. {
  10383. IConstWorkUnit *workUnit = ctx->queryWorkUnit();
  10384. if (workUnit)
  10385. return workUnit->queryUserDescriptor();//ad-hoc mode
  10386. else
  10387. {
  10388. Owned<IRoxieDaliHelper> daliHelper = connectToDali(false);
  10389. if (daliHelper)
  10390. return daliHelper->queryUserDescriptor();//predeployed query mode
  10391. }
  10392. return NULL;
  10393. }
  10394. virtual bool isOutputTransformed() const { return false; }
  10395. };
  10396. //=================================================================================
  10397. class CRoxieServerCsvWriteActivity : public CRoxieServerDiskWriteActivity
  10398. {
  10399. IHThorCsvWriteArg &csvHelper;
  10400. CSVOutputStream csvOutput;
  10401. public:
  10402. CRoxieServerCsvWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  10403. : CRoxieServerDiskWriteActivity(_ctx, _factory, _probeManager), csvHelper(static_cast<IHThorCsvWriteArg &>(helper))
  10404. {
  10405. csvOutput.init(csvHelper.queryCsvParameters(), false);
  10406. }
  10407. virtual void onExecute()
  10408. {
  10409. OwnedRoxieString header(csvHelper.queryCsvParameters()->getHeader());
  10410. if (header)
  10411. {
  10412. csvOutput.beginLine();
  10413. csvOutput.writeHeaderLn(strlen(header), header);
  10414. diskout->write(csvOutput.length(), csvOutput.str());
  10415. }
  10416. for (;;)
  10417. {
  10418. const void *nextrec = inputStream->ungroupedNextRow();
  10419. if (!nextrec)
  10420. break;
  10421. processed++;
  10422. csvOutput.beginLine();
  10423. csvHelper.writeRow((const byte *)nextrec, &csvOutput);
  10424. csvOutput.endLine();
  10425. diskout->write(csvOutput.length(), csvOutput.str());
  10426. ReleaseRoxieRow(nextrec);
  10427. }
  10428. OwnedRoxieString footer(csvHelper.queryCsvParameters()->getFooter());
  10429. if (footer)
  10430. {
  10431. csvOutput.beginLine();
  10432. csvOutput.writeHeaderLn(strlen(footer), footer);
  10433. diskout->write(csvOutput.length(), csvOutput.str());
  10434. }
  10435. }
  10436. virtual void setFileProperties(IFileDescriptor *desc) const
  10437. {
  10438. CRoxieServerDiskWriteActivity::setFileProperties(desc);
  10439. IPropertyTree &props = desc->queryProperties();
  10440. props.setProp("@format","utf8n");
  10441. ICsvParameters *csvParameters = csvHelper.queryCsvParameters();
  10442. StringBuffer separator;
  10443. OwnedRoxieString rs(csvParameters->getSeparator(0));
  10444. const char *s = rs;
  10445. while (s && *s)
  10446. {
  10447. if (',' == *s)
  10448. separator.append("\\,");
  10449. else
  10450. separator.append(*s);
  10451. ++s;
  10452. }
  10453. props.setProp("@csvSeparate", separator.str());
  10454. props.setProp("@csvQuote", rs.setown(csvParameters->getQuote(0)));
  10455. props.setProp("@csvTerminate", rs.setown(csvParameters->getTerminator(0)));
  10456. props.setProp("@csvEscape", rs.setown(csvParameters->getEscape(0)));
  10457. props.setProp("@kind", "csv");
  10458. }
  10459. virtual bool isOutputTransformed() const { return true; }
  10460. };
  10461. class CRoxieServerXmlWriteActivity : public CRoxieServerDiskWriteActivity
  10462. {
  10463. IHThorXmlWriteArg &xmlHelper;
  10464. StringAttr rowTag;
  10465. ThorActivityKind kind;
  10466. unsigned headerLength;
  10467. unsigned footerLength;
  10468. public:
  10469. CRoxieServerXmlWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, ThorActivityKind _kind)
  10470. : CRoxieServerDiskWriteActivity(_ctx, _factory, _probeManager), xmlHelper(static_cast<IHThorXmlWriteArg &>(helper)), kind(_kind), headerLength(0), footerLength(0)
  10471. {
  10472. }
  10473. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10474. {
  10475. CRoxieServerDiskWriteActivity::start(parentExtractSize, parentExtract, paused);
  10476. OwnedRoxieString xmlpath(xmlHelper.getXmlIteratorPath());
  10477. if (!xmlpath)
  10478. rowTag.set(DEFAULTXMLROWTAG);
  10479. else
  10480. {
  10481. const char *path = xmlpath;
  10482. if (*path == '/') path++;
  10483. if (strchr(path, '/')) UNIMPLEMENTED; // more what do we do with /mydata/row
  10484. rowTag.set(path);
  10485. }
  10486. }
  10487. virtual void onExecute()
  10488. {
  10489. StringBuffer header;
  10490. OwnedRoxieString suppliedHeader(xmlHelper.getHeader());
  10491. if (kind==TAKjsonwrite)
  10492. buildJsonHeader(header, suppliedHeader, rowTag);
  10493. else if (suppliedHeader)
  10494. header.set(suppliedHeader);
  10495. else
  10496. header.append(DEFAULTXMLHEADER).newline();
  10497. headerLength = header.length();
  10498. diskout->write(header.length(), header.str());
  10499. Owned<IXmlWriterExt> writer = createIXmlWriterExt(xmlHelper.getXmlFlags(), 0, NULL, (kind==TAKjsonwrite) ? WTJSON : WTStandard);
  10500. writer->outputBeginArray(rowTag); //need to set this
  10501. writer->clear(); //but not output it
  10502. for (;;)
  10503. {
  10504. OwnedConstRoxieRow nextrec = inputStream->ungroupedNextRow();
  10505. if (!nextrec)
  10506. break;
  10507. processed++;
  10508. writer->clear().outputBeginNested(rowTag, false);
  10509. xmlHelper.toXML((const byte *)nextrec.get(), *writer);
  10510. writer->outputEndNested(rowTag);
  10511. diskout->write(writer->length(), writer->str());
  10512. }
  10513. OwnedRoxieString suppliedFooter(xmlHelper.getFooter());
  10514. StringBuffer footer;
  10515. if (kind==TAKjsonwrite)
  10516. buildJsonFooter(footer.newline(), suppliedFooter, rowTag);
  10517. else if (suppliedFooter)
  10518. footer.append(suppliedFooter);
  10519. else
  10520. footer.append(DEFAULTXMLFOOTER);
  10521. footerLength=footer.length();
  10522. diskout->write(footer.length(), footer);
  10523. }
  10524. virtual void reset()
  10525. {
  10526. CRoxieServerDiskWriteActivity::reset();
  10527. rowTag.clear();
  10528. }
  10529. virtual void setFileProperties(IFileDescriptor *desc) const
  10530. {
  10531. CRoxieServerDiskWriteActivity::setFileProperties(desc);
  10532. desc->queryProperties().setProp("@format","utf8n");
  10533. desc->queryProperties().setProp("@rowTag",rowTag.get());
  10534. desc->queryProperties().setProp("@kind", (kind==TAKjsonwrite) ? "json" : "xml");
  10535. desc->queryProperties().setPropInt(FPheaderLength, headerLength);
  10536. desc->queryProperties().setPropInt(FPfooterLength, footerLength);
  10537. }
  10538. virtual bool isOutputTransformed() const { return true; }
  10539. };
  10540. class CRoxieServerDiskWriteActivityFactory : public CRoxieServerMultiOutputFactory
  10541. {
  10542. bool isRoot;
  10543. bool isTemp;
  10544. public:
  10545. CRoxieServerDiskWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  10546. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  10547. {
  10548. Owned<IHThorDiskWriteArg> helper = (IHThorDiskWriteArg *) helperFactory();
  10549. isTemp = (helper->getFlags() & TDXtemporary) != 0;
  10550. setNumOutputs(helper->getTempUsageCount());
  10551. if (_kind!=TAKdiskwrite)
  10552. assertex(numOutputs == 0);
  10553. }
  10554. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  10555. {
  10556. switch (numOutputs)
  10557. {
  10558. case 0:
  10559. switch (kind)
  10560. {
  10561. case TAKdiskwrite: return new CRoxieServerDiskWriteActivity(_ctx, this, _probeManager);
  10562. case TAKcsvwrite: return new CRoxieServerCsvWriteActivity(_ctx, this, _probeManager);
  10563. case TAKxmlwrite:
  10564. case TAKjsonwrite:
  10565. return new CRoxieServerXmlWriteActivity(_ctx, this, _probeManager, kind);
  10566. };
  10567. throwUnexpected();
  10568. case 1:
  10569. return new CRoxieServerSpillWriteActivity(_ctx, this, _probeManager);
  10570. default:
  10571. return new CRoxieServerThroughSpillActivity(_ctx, this, _probeManager, numOutputs);
  10572. }
  10573. }
  10574. virtual bool isSink() const
  10575. {
  10576. return numOutputs == 0 && !isTemp; // MORE - check with Gavin if this is right if not a temp but reread in same job...
  10577. }
  10578. };
  10579. IRoxieServerActivityFactory *createRoxieServerDiskWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  10580. {
  10581. return new CRoxieServerDiskWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  10582. }
  10583. //=================================================================================
  10584. class CRoxieServerIndexWriteActivity : public CRoxieServerInternalSinkActivity, implements IRoxiePublishCallback
  10585. {
  10586. IHThorIndexWriteArg &helper;
  10587. bool overwrite;
  10588. Owned<ClusterWriteHandler> clusterHandler;
  10589. Owned<IRoxieWriteHandler> writer;
  10590. unsigned __int64 reccount;
  10591. unsigned int fileCrc;
  10592. StringBuffer filename;
  10593. void updateWorkUnitResult()
  10594. {
  10595. // MORE - a lot of this is common with hthor
  10596. WorkunitUpdate wu = ctx->updateWorkUnit();
  10597. if (wu)
  10598. {
  10599. OwnedRoxieString rawLogicalName = helper.getFileName();
  10600. StringBuffer lfn; // logical filename
  10601. expandLogicalFilename(lfn, rawLogicalName, wu, false, false);
  10602. if (lfn.length())
  10603. {
  10604. if (helper.getSequence() >= 0)
  10605. {
  10606. Owned<IWUResult> result = wu->updateResultBySequence(helper.getSequence());
  10607. if (result)
  10608. {
  10609. result->setResultTotalRowCount(reccount);
  10610. result->setResultStatus(ResultStatusCalculated);
  10611. result->setResultLogicalName(lfn.str());
  10612. }
  10613. }
  10614. if(clusterHandler)
  10615. clusterHandler->finish(writer->queryFile());
  10616. CTXLOG("Created roxie index file %s", lfn.str());
  10617. }
  10618. }
  10619. }
  10620. virtual void resolve()
  10621. {
  10622. StringArray clusters;
  10623. unsigned clusterIdx = 0;
  10624. while(true)
  10625. {
  10626. OwnedRoxieString cluster(helper.getCluster(clusterIdx));
  10627. if(!cluster)
  10628. break;
  10629. clusters.append(cluster);
  10630. clusterIdx++;
  10631. }
  10632. if (roxieName.length())
  10633. clusters.append(roxieName.str());
  10634. else
  10635. clusters.append(".");
  10636. OwnedRoxieString fname(helper.getFileName());
  10637. writer.setown(ctx->createLFN(fname, overwrite, false, clusters)); // MORE - if there's a workunit, use if for scope.
  10638. filename.set(writer->queryFile()->queryFilename());
  10639. if (writer->queryFile()->exists())
  10640. {
  10641. if (overwrite)
  10642. {
  10643. CTXLOG("Removing existing %s from DFS",filename.str());
  10644. writer->queryFile()->remove();
  10645. }
  10646. else
  10647. throw MakeStringException(99, "Cannot write index file %s, file already exists (missing OVERWRITE attribute?)", filename.str());
  10648. }
  10649. }
  10650. void buildUserMetadata(Owned<IPropertyTree> & metadata)
  10651. {
  10652. size32_t nameLen;
  10653. char * nameBuff;
  10654. size32_t valueLen;
  10655. char * valueBuff;
  10656. unsigned idx = 0;
  10657. while(helper.getIndexMeta(nameLen, nameBuff, valueLen, valueBuff, idx++))
  10658. {
  10659. StringBuffer name(nameLen, nameBuff);
  10660. StringBuffer value(valueLen, valueBuff);
  10661. if(*nameBuff == '_' && strcmp(name, "_nodeSize") != 0)
  10662. {
  10663. OwnedRoxieString fname(helper.getFileName());
  10664. throw MakeStringException(0, "Invalid name %s in user metadata for index %s (names beginning with underscore are reserved)", name.str(), fname.get());
  10665. }
  10666. if(!validateXMLTag(name.str()))
  10667. {
  10668. OwnedRoxieString fname(helper.getFileName());
  10669. throw MakeStringException(0, "Invalid name %s in user metadata for index %s (not legal XML element name)", name.str(), fname.get());
  10670. }
  10671. if(!metadata)
  10672. metadata.setown(createPTree("metadata", ipt_fast));
  10673. metadata->setProp(name.str(), value.str());
  10674. }
  10675. }
  10676. void buildLayoutMetadata(Owned<IPropertyTree> & metadata)
  10677. {
  10678. if(!metadata)
  10679. metadata.setown(createPTree("metadata", ipt_fast));
  10680. metadata->setProp("_record_ECL", helper.queryRecordECL());
  10681. void * layoutMetaBuff;
  10682. size32_t layoutMetaSize;
  10683. if(helper.getIndexLayout(layoutMetaSize, layoutMetaBuff))
  10684. {
  10685. metadata->setPropBin("_record_layout", layoutMetaSize, layoutMetaBuff);
  10686. rtlFree(layoutMetaBuff);
  10687. }
  10688. }
  10689. public:
  10690. CRoxieServerIndexWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  10691. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, 0), helper(static_cast<IHThorIndexWriteArg &>(basehelper))
  10692. {
  10693. overwrite = ((helper.getFlags() & TIWoverwrite) != 0);
  10694. reccount = 0;
  10695. fileCrc = 0;
  10696. }
  10697. ~CRoxieServerIndexWriteActivity()
  10698. {
  10699. }
  10700. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10701. {
  10702. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  10703. resolve();
  10704. }
  10705. virtual void onExecute()
  10706. {
  10707. bool isVariable = helper.queryDiskRecordSize()->isVariableSize();
  10708. size32_t maxDiskRecordSize;
  10709. if (isVariable)
  10710. {
  10711. if (helper.getFlags() & TIWmaxlength)
  10712. maxDiskRecordSize = helper.getMaxKeySize();
  10713. else
  10714. maxDiskRecordSize = KEYBUILD_MAXLENGTH; // Current default behaviour, could be improved in the future
  10715. }
  10716. else
  10717. maxDiskRecordSize = helper.queryDiskRecordSize()->getFixedSize();
  10718. if (maxDiskRecordSize > KEYBUILD_MAXLENGTH)
  10719. throw MakeStringException(99, "Index maximum record length (%d) exceeds 32k internal limit", maxDiskRecordSize);
  10720. OwnedMalloc<char> rowBuffer(maxDiskRecordSize, true);
  10721. fileCrc = -1;
  10722. {
  10723. Owned<IFileIO> io;
  10724. try
  10725. {
  10726. io.setown(writer->queryFile()->open(IFOcreate));
  10727. }
  10728. catch(IException * e)
  10729. {
  10730. e->Release();
  10731. clearKeyStoreCache(false);
  10732. io.setown(writer->queryFile()->open(IFOcreate));
  10733. }
  10734. if(!io)
  10735. throw MakeStringException(errno, "Failed to create file %s for writing", filename.str());
  10736. Owned<IFileIOStream> out = createIOStream(io);
  10737. unsigned flags = COL_PREFIX | HTREE_FULLSORT_KEY;
  10738. if (helper.getFlags() & TIWrowcompress)
  10739. flags |= HTREE_COMPRESSED_KEY|HTREE_QUICK_COMPRESSED_KEY;
  10740. else if (!(helper.getFlags() & TIWnolzwcompress))
  10741. flags |= HTREE_COMPRESSED_KEY;
  10742. if (isVariable)
  10743. flags |= HTREE_VARSIZE;
  10744. Owned<IPropertyTree> metadata;
  10745. buildUserMetadata(metadata);
  10746. buildLayoutMetadata(metadata);
  10747. unsigned nodeSize = metadata ? metadata->getPropInt("_nodeSize", NODESIZE) : NODESIZE;
  10748. Owned<IKeyBuilder> builder = createKeyBuilder(out, flags, maxDiskRecordSize, nodeSize, helper.getKeyedSize(), 0);
  10749. class BcWrapper : implements IBlobCreator
  10750. {
  10751. IKeyBuilder *builder;
  10752. public:
  10753. BcWrapper(IKeyBuilder *_builder) : builder(_builder) {}
  10754. virtual unsigned __int64 createBlob(size32_t size, const void * ptr)
  10755. {
  10756. return builder->createBlob(size, (const char *) ptr);
  10757. }
  10758. } bc(builder);
  10759. // Loop thru the results
  10760. for (;;)
  10761. {
  10762. OwnedConstRoxieRow nextrec(inputStream->ungroupedNextRow());
  10763. if (!nextrec)
  10764. break;
  10765. try
  10766. {
  10767. unsigned __int64 fpos=0;
  10768. RtlStaticRowBuilder rowBuilder(rowBuffer, maxDiskRecordSize);
  10769. size32_t thisSize = helper.transform(rowBuilder, nextrec, &bc, fpos);
  10770. builder->processKeyData(rowBuffer, fpos, thisSize);
  10771. }
  10772. catch(IException * e)
  10773. {
  10774. throw makeWrappedException(e);
  10775. }
  10776. reccount++;
  10777. }
  10778. if(metadata)
  10779. builder->finish(metadata,&fileCrc);
  10780. else
  10781. builder->finish(&fileCrc);
  10782. }
  10783. }
  10784. virtual void stop()
  10785. {
  10786. if (writer)
  10787. {
  10788. if (!aborted)
  10789. updateWorkUnitResult();
  10790. writer->finish(!aborted, this);
  10791. writer.clear();
  10792. }
  10793. CRoxieServerActivity::stop();
  10794. }
  10795. virtual void reset()
  10796. {
  10797. CRoxieServerActivity::reset();
  10798. writer.clear();
  10799. }
  10800. //interface IRoxiePublishCallback
  10801. virtual void setFileProperties(IFileDescriptor *desc) const
  10802. {
  10803. IPropertyTree &partProps = desc->queryPart(0)->queryProperties(); //properties of the first file part.
  10804. IPropertyTree &fileProps = desc->queryProperties(); // properties of the logical file
  10805. // Now publish to name services
  10806. StringBuffer dir,base;
  10807. offset_t indexFileSize = writer->queryFile()->size();
  10808. if(clusterHandler)
  10809. clusterHandler->splitPhysicalFilename(dir, base);
  10810. else
  10811. splitFilename(filename.str(), &dir, &dir, &base, &base);
  10812. desc->setDefaultDir(dir.str());
  10813. //properties of the first file part.
  10814. Owned<IPropertyTree> attrs;
  10815. if(clusterHandler)
  10816. attrs.setown(createPTree("Part", ipt_fast)); // clusterHandler is going to set attributes
  10817. else
  10818. {
  10819. // add cluster
  10820. StringBuffer mygroupname;
  10821. desc->setNumParts(1);
  10822. desc->setPartMask(base.str());
  10823. attrs.set(&desc->queryPart(0)->queryProperties());
  10824. }
  10825. attrs->setPropInt64("@size", indexFileSize);
  10826. CDateTime createTime, modifiedTime, accessedTime;
  10827. writer->queryFile()->getTime(&createTime, &modifiedTime, &accessedTime);
  10828. // round file time down to nearest sec. Nanosec accurancy is not preserved elsewhere and can lead to mismatch later.
  10829. unsigned hour, min, sec, nanosec;
  10830. modifiedTime.getTime(hour, min, sec, nanosec);
  10831. modifiedTime.setTime(hour, min, sec, 0);
  10832. StringBuffer timestr;
  10833. modifiedTime.getString(timestr);
  10834. if(timestr.length())
  10835. attrs->setProp("@modified", timestr.str());
  10836. if(clusterHandler)
  10837. clusterHandler->setDescriptorParts(desc, base.str(), attrs);
  10838. // properties of the logical file
  10839. IPropertyTree & properties = desc->queryProperties();
  10840. properties.setProp("@kind", "key");
  10841. properties.setPropInt64("@size", indexFileSize);
  10842. properties.setPropInt64("@recordCount", reccount);
  10843. WorkunitUpdate workUnit = ctx->updateWorkUnit();
  10844. if (workUnit)
  10845. {
  10846. properties.setProp("@owner", workUnit->queryUser());
  10847. properties.setProp("@workunit", workUnit->queryWuid());
  10848. properties.setProp("@job", workUnit->queryJobName());
  10849. }
  10850. char const * rececl = helper.queryRecordECL();
  10851. if(rececl && *rececl)
  10852. properties.setProp("ECL", rececl);
  10853. if (helper.getFlags() & TIWexpires)
  10854. setExpiryTime(properties, helper.getExpiryDays());
  10855. if (helper.getFlags() & TIWupdate)
  10856. {
  10857. unsigned eclCRC;
  10858. unsigned __int64 totalCRC;
  10859. helper.getUpdateCRCs(eclCRC, totalCRC);
  10860. properties.setPropInt("@eclCRC", eclCRC);
  10861. properties.setPropInt64("@totalCRC", totalCRC);
  10862. }
  10863. properties.setPropInt("@fileCrc", fileCrc);
  10864. properties.setPropInt("@formatCrc", helper.getFormatCrc());
  10865. void * layoutMetaBuff;
  10866. size32_t layoutMetaSize;
  10867. if(helper.getIndexLayout(layoutMetaSize, layoutMetaBuff))
  10868. {
  10869. properties.setPropBin("_record_layout", layoutMetaSize, layoutMetaBuff);
  10870. rtlFree(layoutMetaBuff);
  10871. }
  10872. }
  10873. IUserDescriptor *queryUserDescriptor() const
  10874. {
  10875. IConstWorkUnit *workUnit = ctx->queryWorkUnit();
  10876. if (workUnit)
  10877. return workUnit->queryUserDescriptor();//ad-hoc mode
  10878. else
  10879. {
  10880. Owned<IRoxieDaliHelper> daliHelper = connectToDali(false);
  10881. if (daliHelper)
  10882. return daliHelper->queryUserDescriptor();//predeployed query mode
  10883. }
  10884. return NULL;
  10885. }
  10886. };
  10887. //=================================================================================
  10888. class CRoxieServerIndexWriteActivityFactory : public CRoxieServerMultiOutputFactory
  10889. {
  10890. public:
  10891. CRoxieServerIndexWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  10892. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  10893. {
  10894. setNumOutputs(0);
  10895. }
  10896. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  10897. {
  10898. return new CRoxieServerIndexWriteActivity(_ctx, this, _probeManager);
  10899. }
  10900. virtual bool isSink() const
  10901. {
  10902. return true;
  10903. }
  10904. };
  10905. IRoxieServerActivityFactory *createRoxieServerIndexWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  10906. {
  10907. return new CRoxieServerIndexWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  10908. }
  10909. //=================================================================================
  10910. static inline void getLimitType(unsigned flags, bool & limitFail, bool & limitOnFail)
  10911. {
  10912. if((flags & JFmatchAbortLimitSkips) != 0)
  10913. {
  10914. limitFail = false;
  10915. limitOnFail = false;
  10916. }
  10917. else
  10918. {
  10919. limitOnFail = ((flags & JFonfail) != 0);
  10920. limitFail = !limitOnFail;
  10921. }
  10922. }
  10923. class CRoxieServerJoinActivity : public CRoxieServerTwoInputActivity
  10924. {
  10925. enum { JSfill, JSfillleft, JSfillright, JScollate, JScompare, JSleftonly, JSrightonly } state;
  10926. IHThorJoinArg &helper;
  10927. ICompare * collate;
  10928. ICompare * collateupper;
  10929. ThorActivityKind activityKind;
  10930. bool leftOuterJoin;
  10931. bool rightOuterJoin;
  10932. bool exclude;
  10933. bool limitFail;
  10934. bool limitOnFail;
  10935. bool forceSpill;
  10936. unsigned keepLimit;
  10937. unsigned joinLimit;
  10938. unsigned atmostLimit;
  10939. unsigned abortLimit;
  10940. unsigned atmostsTriggered;
  10941. bool betweenjoin;
  10942. OwnedRowArray right;
  10943. const void * left;
  10944. const void * pendingRight;
  10945. unsigned rightIndex;
  10946. unsigned joinCounter;
  10947. BoolArray matchedRight;
  10948. bool matchedLeft;
  10949. Owned<IException> failingLimit;
  10950. ConstPointerArray filteredRight;
  10951. Owned<IRHLimitedCompareHelper> limitedhelper;
  10952. OwnedConstRoxieRow defaultLeft;
  10953. OwnedConstRoxieRow defaultRight;
  10954. Owned<IEngineRowAllocator> defaultLeftAllocator;
  10955. Owned<IEngineRowAllocator> defaultRightAllocator;
  10956. Owned<IGroupedInput> sortedLeft;
  10957. Owned<IGroupedInput> groupedSortedRight;
  10958. bool cloneLeft;
  10959. void createDefaultLeft()
  10960. {
  10961. if (!defaultLeft)
  10962. {
  10963. if (!defaultLeftAllocator)
  10964. defaultLeftAllocator.setown(createRowAllocator(input->queryOutputMeta()));
  10965. RtlDynamicRowBuilder rowBuilder(defaultLeftAllocator);
  10966. size32_t thisSize = helper.createDefaultLeft(rowBuilder);
  10967. defaultLeft.setown(rowBuilder.finalizeRowClear(thisSize));
  10968. }
  10969. }
  10970. void createDefaultRight()
  10971. {
  10972. if (!defaultRight)
  10973. {
  10974. if (!defaultRightAllocator)
  10975. defaultRightAllocator.setown(createRowAllocator(input1->queryOutputMeta()));
  10976. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  10977. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  10978. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  10979. }
  10980. }
  10981. public:
  10982. CRoxieServerJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _forceSpill)
  10983. : CRoxieServerTwoInputActivity(_ctx, _factory, _probeManager), helper((IHThorJoinArg &)basehelper), forceSpill(_forceSpill)
  10984. {
  10985. // MORE - some of this should be done in factory
  10986. unsigned joinFlags = helper.getJoinFlags();
  10987. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  10988. rightOuterJoin = (joinFlags & JFrightouter) != 0;
  10989. exclude = (joinFlags & JFexclude) != 0;
  10990. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  10991. getLimitType(joinFlags, limitFail, limitOnFail);
  10992. if (joinFlags & JFslidingmatch)
  10993. {
  10994. betweenjoin = true;
  10995. collate = helper.queryCompareLeftRightLower();
  10996. collateupper = helper.queryCompareLeftRightUpper();
  10997. }
  10998. else
  10999. {
  11000. betweenjoin = false;
  11001. collate = collateupper = helper.queryCompareLeftRight();
  11002. }
  11003. rightIndex = 0;
  11004. joinCounter = 0;
  11005. state = JSfill;
  11006. matchedLeft = false;
  11007. joinLimit = 0;
  11008. keepLimit = 0; // wait until ctx available
  11009. atmostLimit = 0; // wait until ctx available
  11010. abortLimit = 0; // wait until ctx available
  11011. atmostsTriggered = 0;
  11012. assertex((joinFlags & (JFfirst | JFfirstleft | JFfirstright)) == 0);
  11013. left = NULL;
  11014. pendingRight = NULL;
  11015. activityKind = _factory->getKind();
  11016. }
  11017. virtual bool needsAllocator() const { return true; }
  11018. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11019. {
  11020. left = NULL;
  11021. rightIndex = 0;
  11022. joinCounter = 0;
  11023. state = JSfill;
  11024. matchedLeft = false;
  11025. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  11026. keepLimit = helper.getKeepLimit();
  11027. if (keepLimit == 0)
  11028. keepLimit = (unsigned)-1;
  11029. atmostsTriggered = 0;
  11030. atmostLimit = helper.getJoinLimit();
  11031. if(atmostLimit == 0)
  11032. atmostLimit = (unsigned)-1;
  11033. else
  11034. assertex(!rightOuterJoin && !betweenjoin);
  11035. abortLimit = helper.getMatchAbortLimit();
  11036. if (abortLimit == 0)
  11037. abortLimit = (unsigned)-1;
  11038. if (rightOuterJoin)
  11039. createDefaultLeft();
  11040. if ((leftOuterJoin && (activityKind==TAKjoin || activityKind==TAKjoinlight || activityKind==TAKdenormalizegroup)) || limitOnFail)
  11041. createDefaultRight();
  11042. bool isStable = (helper.getJoinFlags() & JFunstable) == 0;
  11043. RoxieSortAlgorithm sortAlgorithm;
  11044. if (forceSpill)
  11045. sortAlgorithm = isStable ? stableSpillingQuickSortAlgorithm : spillingQuickSortAlgorithm;
  11046. else
  11047. sortAlgorithm = isStable ? stableQuickSortAlgorithm : quickSortAlgorithm;
  11048. if (helper.isLeftAlreadySorted())
  11049. sortedLeft.setown(createDegroupedInputReader(inputStream));
  11050. else
  11051. sortedLeft.setown(createSortedInputReader(inputStream, createSortAlgorithm(sortAlgorithm, helper.queryCompareLeft(), ctx->queryRowManager(), input->queryOutputMeta(), ctx->queryCodeContext(), tempDirectory, activityId)));
  11052. ICompare *compareRight = helper.queryCompareRight();
  11053. if (helper.isRightAlreadySorted())
  11054. groupedSortedRight.setown(createGroupedInputReader(inputStream1, compareRight));
  11055. else
  11056. groupedSortedRight.setown(createSortedGroupedInputReader(inputStream1, compareRight, createSortAlgorithm(sortAlgorithm, compareRight, ctx->queryRowManager(), input1->queryOutputMeta(), ctx->queryCodeContext(), tempDirectory, activityId)));
  11057. if ((helper.getJoinFlags() & JFlimitedprefixjoin) && helper.getJoinLimit())
  11058. { //limited match join (s[1..n])
  11059. limitedhelper.setown(createRHLimitedCompareHelper());
  11060. limitedhelper->init( helper.getJoinLimit(), groupedSortedRight, collate, helper.queryPrefixCompare() );
  11061. }
  11062. }
  11063. virtual void reset()
  11064. {
  11065. if (atmostsTriggered)
  11066. noteStatistic(StNumAtmostTriggered, atmostsTriggered);
  11067. right.clear();
  11068. ReleaseClearRoxieRow(left);
  11069. ReleaseClearRoxieRow(pendingRight);
  11070. defaultRight.clear();
  11071. defaultLeft.clear();
  11072. sortedLeft.clear();
  11073. groupedSortedRight.clear();
  11074. CRoxieServerTwoInputActivity::reset();
  11075. }
  11076. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  11077. {
  11078. if (!idx && (helper.getJoinFlags() & JFparallel) != 0)
  11079. {
  11080. puller.setown(new CRoxieServerReadAheadInput(ctx, ctx->queryOptions().parallelJoinPreload));
  11081. puller->setInput(0, _sourceIdx, _in);
  11082. _in = puller;
  11083. _sourceIdx = 0;
  11084. }
  11085. CRoxieServerTwoInputActivity::setInput(idx, _sourceIdx, _in);
  11086. }
  11087. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  11088. {
  11089. if (idx==(unsigned)-1)
  11090. idx = 0;
  11091. return idx ? NULL : this;
  11092. }
  11093. void fillLeft()
  11094. {
  11095. matchedLeft = false;
  11096. left = sortedLeft->nextRow(); // NOTE: already degrouped by the IGroupedInput we attached
  11097. if (betweenjoin && left && pendingRight && (collate->docompare(left, pendingRight) >= 0))
  11098. fillRight();
  11099. if (limitedhelper && 0==rightIndex)
  11100. {
  11101. rightIndex = 0;
  11102. joinCounter = 0;
  11103. right.clear();
  11104. matchedRight.kill();
  11105. if (left)
  11106. {
  11107. limitedhelper->getGroup(right,left);
  11108. ForEachItemIn(idx, right)
  11109. matchedRight.append(false);
  11110. }
  11111. }
  11112. }
  11113. void fillRight()
  11114. {
  11115. if (limitedhelper)
  11116. return;
  11117. failingLimit.clear();
  11118. if(betweenjoin && left)
  11119. {
  11120. aindex_t start = 0;
  11121. while(right.isItem(start) && (collateupper->docompare(left, right.item(start)) > 0))
  11122. start++;
  11123. if(start>0)
  11124. right.clearPart(0, start);
  11125. }
  11126. else
  11127. right.clear();
  11128. rightIndex = 0;
  11129. joinCounter = 0;
  11130. unsigned groupCount = 0;
  11131. const void * next;
  11132. while(true)
  11133. {
  11134. if(pendingRight)
  11135. {
  11136. next = pendingRight;
  11137. pendingRight = NULL;
  11138. }
  11139. else
  11140. {
  11141. next = groupedSortedRight->nextRow();
  11142. }
  11143. if(!rightOuterJoin && next && (!left || (collateupper->docompare(left, next) > 0))) // if right is less than left, and not right outer, can skip group
  11144. {
  11145. while(next)
  11146. {
  11147. ReleaseClearRoxieRow(next);
  11148. next = groupedSortedRight->nextRow();
  11149. }
  11150. continue;
  11151. }
  11152. while(next)
  11153. {
  11154. if(groupCount==abortLimit)
  11155. {
  11156. if(limitFail)
  11157. failLimit();
  11158. if (ctx->queryDebugContext())
  11159. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  11160. if(limitOnFail)
  11161. {
  11162. assertex(!failingLimit);
  11163. try
  11164. {
  11165. failLimit();
  11166. }
  11167. catch(IException * except)
  11168. {
  11169. failingLimit.setown(except);
  11170. }
  11171. assertex(failingLimit != NULL);
  11172. }
  11173. right.append(next);
  11174. do
  11175. {
  11176. next = groupedSortedRight->nextRow();
  11177. ReleaseRoxieRow(next);
  11178. } while(next);
  11179. break;
  11180. }
  11181. else if(groupCount==atmostLimit)
  11182. {
  11183. atmostsTriggered++;
  11184. right.clear();
  11185. groupCount = 0;
  11186. while(next)
  11187. {
  11188. ReleaseRoxieRow(next);
  11189. next = groupedSortedRight->nextRow();
  11190. }
  11191. }
  11192. else
  11193. {
  11194. right.append(next);
  11195. groupCount++;
  11196. }
  11197. next = groupedSortedRight->nextRow();
  11198. }
  11199. // 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
  11200. if(betweenjoin && left)
  11201. {
  11202. pendingRight = groupedSortedRight->nextRow();
  11203. if(!pendingRight || (collate->docompare(left, pendingRight) < 0))
  11204. break;
  11205. }
  11206. else
  11207. break;
  11208. }
  11209. matchedRight.kill();
  11210. ForEachItemIn(idx, right)
  11211. matchedRight.append(false);
  11212. }
  11213. const void * joinRecords(const void * curLeft, const void * curRight, unsigned counter)
  11214. {
  11215. if (cloneLeft)
  11216. {
  11217. LinkRoxieRow(curLeft);
  11218. return curLeft;
  11219. }
  11220. try
  11221. {
  11222. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11223. size32_t thisSize = helper.transform(rowBuilder, curLeft, curRight, counter);
  11224. if (thisSize)
  11225. return rowBuilder.finalizeRowClear(thisSize);
  11226. else
  11227. return NULL;
  11228. }
  11229. catch (IException *E)
  11230. {
  11231. throw makeWrappedException(E);
  11232. }
  11233. }
  11234. const void * denormalizeRecords(const void * curLeft, ConstPointerArray & rows)
  11235. {
  11236. try
  11237. {
  11238. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11239. unsigned numRows = rows.ordinality();
  11240. const void * right = numRows ? rows.item(0) : defaultRight.get();
  11241. size32_t thisSize = helper.transform(rowBuilder, curLeft, right, numRows, (const void * *)rows.getArray());
  11242. if (thisSize)
  11243. return rowBuilder.finalizeRowClear(thisSize);
  11244. else
  11245. return NULL;
  11246. }
  11247. catch (IException *E)
  11248. {
  11249. throw makeWrappedException(E);
  11250. }
  11251. }
  11252. const void * joinException(const void * curLeft, IException * except)
  11253. {
  11254. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11255. size32_t thisSize = helper.onFailTransform(rowBuilder, curLeft, defaultRight, except);
  11256. return rowBuilder.finalizeRowClear(thisSize);
  11257. }
  11258. void failLimit()
  11259. {
  11260. helper.onMatchAbortLimitExceeded();
  11261. CommonXmlWriter xmlwrite(0);
  11262. if (input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  11263. {
  11264. input->queryOutputMeta()->toXML((byte *) left, xmlwrite);
  11265. }
  11266. throw MakeStringException(ROXIE_TOO_MANY_RESULTS, "More than %d match candidates in join %d for row %s", abortLimit, queryId(), xmlwrite.str());
  11267. }
  11268. virtual const void * nextRow()
  11269. {
  11270. ActivityTimer t(totalCycles, timeActivities);
  11271. for (;;)
  11272. {
  11273. switch (state)
  11274. {
  11275. case JSfill:
  11276. fillLeft();
  11277. state = JSfillright;
  11278. break;
  11279. case JSfillright:
  11280. fillRight();
  11281. state = JScollate;
  11282. break;
  11283. case JSfillleft:
  11284. fillLeft();
  11285. state = JScollate;
  11286. break;
  11287. case JScollate:
  11288. if (right.ordinality() == 0)
  11289. {
  11290. if (left == NULL)
  11291. return NULL;
  11292. state = JSleftonly;
  11293. }
  11294. else
  11295. {
  11296. if (!left)
  11297. state = JSrightonly;
  11298. else
  11299. {
  11300. int diff;
  11301. if(betweenjoin)
  11302. diff = ((collate->docompare(left, right.item(0)) < 0) ? -1 : ((collateupper->docompare(left, right.item(right.ordinality()-1)) > 0) ? +1 : 0));
  11303. else
  11304. diff = collate->docompare(left, right.item(0));
  11305. bool limitExceeded = right.ordinality()>abortLimit;
  11306. if (diff == 0)
  11307. {
  11308. if (limitExceeded)
  11309. {
  11310. const void * ret = NULL;
  11311. if(failingLimit)
  11312. ret = joinException(left, failingLimit);
  11313. ReleaseRoxieRow(left);
  11314. left = NULL;
  11315. state = JSfillleft;
  11316. ForEachItemIn(idx, right)
  11317. matchedRight.replace(true, idx);
  11318. if(ret)
  11319. {
  11320. processed++;
  11321. return ret;
  11322. }
  11323. }
  11324. else
  11325. {
  11326. state = JScompare;
  11327. joinLimit = keepLimit;
  11328. }
  11329. }
  11330. else if (diff < 0)
  11331. state = JSleftonly;
  11332. else if (limitExceeded)
  11333. {
  11334. // MORE - Roxie code seems to think there should be a destroyRowset(right) here....
  11335. state = JSfillright;
  11336. }
  11337. else
  11338. state = JSrightonly;
  11339. }
  11340. }
  11341. break;
  11342. case JSrightonly:
  11343. if (rightOuterJoin)
  11344. {
  11345. switch (activityKind)
  11346. {
  11347. case TAKjoin:
  11348. {
  11349. while (right.isItem(rightIndex))
  11350. {
  11351. if (!matchedRight.item(rightIndex))
  11352. {
  11353. const void * rhs = right.item(rightIndex++);
  11354. const void *ret = joinRecords(defaultLeft, rhs, 0);
  11355. if (ret)
  11356. {
  11357. processed++;
  11358. return ret;
  11359. }
  11360. }
  11361. else
  11362. rightIndex++;
  11363. }
  11364. break;
  11365. }
  11366. //Probably excessive to implement the following, but possibly useful
  11367. case TAKdenormalize:
  11368. {
  11369. OwnedConstRoxieRow newLeft;
  11370. newLeft.set(defaultLeft);
  11371. unsigned rowSize = 0;
  11372. unsigned leftCount = 0;
  11373. while (right.isItem(rightIndex))
  11374. {
  11375. if (!matchedRight.item(rightIndex))
  11376. {
  11377. const void * rhs = right.item(rightIndex);
  11378. try
  11379. {
  11380. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11381. unsigned thisSize = helper.transform(rowBuilder, newLeft, rhs, ++leftCount);
  11382. if (thisSize)
  11383. {
  11384. rowSize = thisSize;
  11385. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  11386. }
  11387. }
  11388. catch (IException *E)
  11389. {
  11390. throw makeWrappedException(E);
  11391. }
  11392. }
  11393. rightIndex++;
  11394. }
  11395. state = JSfillright;
  11396. if (rowSize)
  11397. {
  11398. processed++;
  11399. return newLeft.getClear();
  11400. }
  11401. break;
  11402. }
  11403. case TAKdenormalizegroup:
  11404. {
  11405. filteredRight.kill();
  11406. while (right.isItem(rightIndex))
  11407. {
  11408. if (!matchedRight.item(rightIndex))
  11409. filteredRight.append(right.item(rightIndex));
  11410. rightIndex++;
  11411. }
  11412. state = JSfillright;
  11413. if (filteredRight.ordinality())
  11414. {
  11415. const void * ret = denormalizeRecords(defaultLeft, filteredRight);
  11416. filteredRight.kill();
  11417. if (ret)
  11418. {
  11419. processed++;
  11420. return ret;
  11421. }
  11422. }
  11423. break;
  11424. }
  11425. }
  11426. }
  11427. state = JSfillright;
  11428. break;
  11429. case JSleftonly:
  11430. {
  11431. const void * ret = NULL;
  11432. if (!matchedLeft && leftOuterJoin)
  11433. {
  11434. switch (activityKind)
  11435. {
  11436. case TAKjoin:
  11437. ret = joinRecords(left, defaultRight, 0);
  11438. break;
  11439. case TAKdenormalize:
  11440. ret = left;
  11441. left = NULL;
  11442. break;
  11443. case TAKdenormalizegroup:
  11444. filteredRight.kill();
  11445. ret = denormalizeRecords(left, filteredRight);
  11446. break;
  11447. }
  11448. }
  11449. ReleaseRoxieRow(left);
  11450. left = NULL;
  11451. state = JSfillleft;
  11452. if (ret)
  11453. {
  11454. processed++;
  11455. return ret;
  11456. }
  11457. break;
  11458. }
  11459. case JScompare:
  11460. if (joinLimit != 0)
  11461. {
  11462. switch (activityKind)
  11463. {
  11464. case TAKjoin:
  11465. {
  11466. while (right.isItem(rightIndex))
  11467. {
  11468. const void * rhs = right.item(rightIndex++);
  11469. if (helper.match(left, rhs))
  11470. {
  11471. matchedRight.replace(true, rightIndex-1);
  11472. matchedLeft = true;
  11473. if (!exclude)
  11474. {
  11475. const void *ret = joinRecords(left, rhs, ++joinCounter);
  11476. if (ret)
  11477. {
  11478. processed++;
  11479. joinLimit--;
  11480. return ret;
  11481. }
  11482. }
  11483. }
  11484. }
  11485. break;
  11486. }
  11487. case TAKdenormalize:
  11488. {
  11489. OwnedConstRoxieRow newLeft;
  11490. newLeft.set(left);
  11491. unsigned rowSize = 0;
  11492. unsigned leftCount = 0;
  11493. while (right.isItem(rightIndex) && joinLimit)
  11494. {
  11495. try
  11496. {
  11497. const void * rhs = right.item(rightIndex++);
  11498. if (helper.match(left, rhs))
  11499. {
  11500. matchedRight.replace(true, rightIndex-1);
  11501. matchedLeft = true;
  11502. if (!exclude)
  11503. {
  11504. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11505. unsigned thisSize = helper.transform(rowBuilder, newLeft, rhs, ++leftCount);
  11506. if (thisSize)
  11507. {
  11508. rowSize = thisSize;
  11509. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  11510. joinLimit--;
  11511. }
  11512. }
  11513. }
  11514. }
  11515. catch (IException *E)
  11516. {
  11517. throw makeWrappedException(E);
  11518. }
  11519. }
  11520. state = JSleftonly;
  11521. rightIndex = 0;
  11522. if (rowSize)
  11523. {
  11524. processed++;
  11525. return newLeft.getClear();
  11526. }
  11527. break;
  11528. }
  11529. case TAKdenormalizegroup:
  11530. {
  11531. filteredRight.kill();
  11532. while (right.isItem(rightIndex))
  11533. {
  11534. const void * rhs = right.item(rightIndex++);
  11535. if (helper.match(left, rhs))
  11536. {
  11537. matchedRight.replace(true, rightIndex-1);
  11538. filteredRight.append(rhs);
  11539. matchedLeft = true;
  11540. if (filteredRight.ordinality()==joinLimit)
  11541. break;
  11542. }
  11543. }
  11544. state = JSleftonly;
  11545. rightIndex = 0;
  11546. if (!exclude && filteredRight.ordinality())
  11547. {
  11548. const void * ret = denormalizeRecords(left, filteredRight);
  11549. filteredRight.kill();
  11550. if (ret)
  11551. {
  11552. processed++;
  11553. return ret;
  11554. }
  11555. }
  11556. break;
  11557. }
  11558. }
  11559. }
  11560. state = JSleftonly;
  11561. rightIndex = 0;
  11562. joinCounter = 0;
  11563. break;
  11564. }
  11565. }
  11566. }
  11567. };
  11568. class CRoxieServerJoinActivityFactory : public CRoxieServerActivityFactory
  11569. {
  11570. unsigned input2;
  11571. unsigned input2idx;
  11572. bool forceSpill;
  11573. public:
  11574. CRoxieServerJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  11575. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  11576. {
  11577. forceSpill = _graphNode.getPropBool("hint[@name='spill']/@value", _queryFactory.queryOptions().allSortsMaySpill);
  11578. input2 = 0;
  11579. input2idx = 0;
  11580. }
  11581. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  11582. {
  11583. return new CRoxieServerJoinActivity(_ctx, this, _probeManager, forceSpill);
  11584. }
  11585. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  11586. {
  11587. if (idx==1)
  11588. {
  11589. input2 = source;
  11590. input2idx = sourceidx;
  11591. }
  11592. else
  11593. CRoxieServerActivityFactory::setInput(idx, source, sourceidx);
  11594. }
  11595. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  11596. {
  11597. switch (idx)
  11598. {
  11599. case 1:
  11600. sourceidx = input2idx;
  11601. return input2;
  11602. case 0:
  11603. return CRoxieServerActivityFactory::getInput(idx, sourceidx);
  11604. default:
  11605. return (unsigned) -1;
  11606. }
  11607. }
  11608. virtual unsigned numInputs() const { return 2; }
  11609. virtual const StatisticsMapping &queryStatsMapping() const
  11610. {
  11611. return joinStatistics;
  11612. }
  11613. };
  11614. IRoxieServerActivityFactory *createRoxieServerJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  11615. {
  11616. return new CRoxieServerJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  11617. }
  11618. //=================================================================================
  11619. #define CONCAT_READAHEAD 1000
  11620. class CRoxieThreadedConcatReader : implements IRecordPullerCallback, public CInterface
  11621. {
  11622. public:
  11623. IMPLEMENT_IINTERFACE;
  11624. CRoxieThreadedConcatReader(InterruptableSemaphore &_ready, bool _grouped)
  11625. : puller(false), grouped(_grouped), atEog(true), ready(_ready), eof(false)
  11626. {
  11627. }
  11628. void start(unsigned parentExtractSize, const byte *parentExtract, bool paused, IRoxieSlaveContext *ctx)
  11629. {
  11630. space.reinit(CONCAT_READAHEAD);
  11631. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().concatPreload, false, ctx);
  11632. }
  11633. void stop()
  11634. {
  11635. space.interrupt();
  11636. puller.stop();
  11637. }
  11638. IFinalRoxieInput *queryInput() const
  11639. {
  11640. return puller.queryInput();
  11641. }
  11642. void reset()
  11643. {
  11644. puller.reset();
  11645. ForEachItemIn(idx, buffer)
  11646. ReleaseRoxieRow(buffer.item(idx));
  11647. buffer.clear();
  11648. eof = false;
  11649. atEog = true;
  11650. }
  11651. void setInput(unsigned _sourceIdx, IFinalRoxieInput *_in)
  11652. {
  11653. puller.setInput(this, _sourceIdx, _in);
  11654. }
  11655. void connectInputStreams(IRoxieSlaveContext *ctx, bool consumerOrdered)
  11656. {
  11657. puller.connectInputStreams(ctx, consumerOrdered);
  11658. }
  11659. virtual void processRow(const void *row)
  11660. {
  11661. buffer.enqueue(row);
  11662. ready.signal();
  11663. space.wait();
  11664. }
  11665. virtual void processGroup(const ConstPointerArray &rows)
  11666. {
  11667. // We use record-by-record input mode of the puller thread even in grouped mode.
  11668. throwUnexpected();
  11669. }
  11670. virtual void processEOG()
  11671. {
  11672. if (grouped)
  11673. processRow(NULL);
  11674. }
  11675. virtual void processDone()
  11676. {
  11677. processRow(NULL);
  11678. }
  11679. virtual bool fireException(IException *e)
  11680. {
  11681. // called from puller thread on failure
  11682. ready.interrupt(LINK(e));
  11683. space.interrupt(e);
  11684. return true;
  11685. }
  11686. bool peek(const void * &row, bool &anyActive)
  11687. {
  11688. if (!eof)
  11689. {
  11690. if (buffer.ordinality())
  11691. {
  11692. space.signal();
  11693. row = buffer.dequeue();
  11694. if (row==NULL)
  11695. {
  11696. if (atEog)
  11697. {
  11698. eof = true;
  11699. return false;
  11700. }
  11701. else
  11702. atEog = true;
  11703. }
  11704. else if (grouped)
  11705. atEog = false;
  11706. return true;
  11707. }
  11708. anyActive = true;
  11709. }
  11710. return false;
  11711. }
  11712. protected:
  11713. RecordPullerThread puller;
  11714. InterruptableSemaphore space;
  11715. InterruptableSemaphore &ready;
  11716. SafeQueueOf<const void, true> buffer;
  11717. bool atEog;
  11718. bool eof;
  11719. bool grouped;
  11720. };
  11721. typedef CopyReferenceArrayOf<CRoxieThreadedConcatReader> ReaderArray;
  11722. class CRoxieServerThreadedConcatActivity : public CRoxieServerActivity
  11723. {
  11724. InterruptableSemaphore ready;
  11725. ReaderArray pullers;
  11726. unsigned numInputs;
  11727. unsigned nextPuller; // for round robin
  11728. unsigned readyPending;
  11729. bool eof;
  11730. bool inGroup;
  11731. bool grouped;
  11732. public:
  11733. CRoxieServerThreadedConcatActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _grouped, unsigned _numInputs)
  11734. : CRoxieServerActivity(_ctx, _factory, _probeManager), grouped(_grouped)
  11735. {
  11736. numInputs = _numInputs;
  11737. eof = (numInputs==0);
  11738. inGroup = false;
  11739. nextPuller = 0;
  11740. readyPending = 0;
  11741. for (unsigned i = 0; i < numInputs; i++)
  11742. pullers.append(*new CRoxieThreadedConcatReader(ready, _grouped));
  11743. }
  11744. ~CRoxieServerThreadedConcatActivity()
  11745. {
  11746. ForEachItemIn(idx, pullers)
  11747. delete &pullers.item(idx);
  11748. }
  11749. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11750. {
  11751. eof = (numInputs==0);
  11752. inGroup = false;
  11753. nextPuller = 0;
  11754. readyPending = 0;
  11755. ready.reinit();
  11756. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  11757. ForEachItemIn(idx, pullers)
  11758. {
  11759. pullers.item(idx).start(parentExtractSize, parentExtract, paused, ctx);
  11760. // NOTE - it is ok to start the thread running while parts of the subgraph are still being started, since everything
  11761. // in the part of the subgraph that the thread uses has been started.
  11762. // Note that splitters are supposed to cope with being used when only some outputs have been started.
  11763. }
  11764. }
  11765. virtual void stop()
  11766. {
  11767. ready.interrupt();
  11768. ForEachItemIn(idx, pullers)
  11769. pullers.item(idx).stop();
  11770. CRoxieServerActivity::stop();
  11771. }
  11772. virtual unsigned __int64 queryLocalCycles() const
  11773. {
  11774. return 0;
  11775. }
  11776. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  11777. {
  11778. if (pullers.isItem(idx))
  11779. return pullers.item(idx).queryInput();
  11780. else
  11781. return NULL;
  11782. }
  11783. virtual void reset()
  11784. {
  11785. CRoxieServerActivity::reset();
  11786. ForEachItemIn(idx, pullers)
  11787. pullers.item(idx).reset();
  11788. eof = false;
  11789. inGroup = false;
  11790. nextPuller = 0;
  11791. readyPending = 0;
  11792. }
  11793. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  11794. {
  11795. if (pullers.isItem(idx))
  11796. pullers.item(idx).setInput(_sourceIdx, _in);
  11797. else
  11798. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
  11799. }
  11800. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  11801. {
  11802. ForEachItemIn(i, pullers)
  11803. pullers.item(i).connectInputStreams(ctx, consumerOrdered);
  11804. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, nullptr, consumerOrdered, nullptr); // No input actually connected
  11805. }
  11806. virtual const void * nextRow()
  11807. {
  11808. ActivityTimer t(totalCycles, timeActivities);
  11809. if (eof)
  11810. return NULL;
  11811. for (;;)
  11812. {
  11813. if (readyPending && !inGroup)
  11814. {
  11815. if (readyPending > 1)
  11816. ready.signal(readyPending-1);
  11817. readyPending = 0;
  11818. }
  11819. else
  11820. ready.wait();
  11821. bool anyActive = false;
  11822. ForEachItemIn(unused_index, pullers)
  11823. {
  11824. // NOTE - we round robin not just because it's more efficient, but because it ensures the preservation of grouping information
  11825. const void *ret;
  11826. bool fetched = pullers.item(nextPuller).peek(ret, anyActive);
  11827. if (fetched)
  11828. {
  11829. inGroup = (ret != NULL);
  11830. return ret;
  11831. }
  11832. if (inGroup && grouped)
  11833. {
  11834. // Some other puller has data, but we can't consume it until the group we are reading is complete.
  11835. readyPending++;
  11836. anyActive = true;
  11837. break;
  11838. }
  11839. nextPuller++;
  11840. if (nextPuller==pullers.ordinality())
  11841. nextPuller = 0;
  11842. }
  11843. if (!anyActive)
  11844. break;
  11845. // A ready signal without anything being ready means someone reached end-of-file.
  11846. }
  11847. eof = true;
  11848. return NULL;
  11849. }
  11850. };
  11851. class CRoxieServerOrderedConcatActivity : public CRoxieServerMultiInputActivity
  11852. {
  11853. IEngineRowStream *curStream;
  11854. bool eogSeen;
  11855. bool anyThisGroup;
  11856. bool grouped;
  11857. unsigned streamIdx;
  11858. public:
  11859. CRoxieServerOrderedConcatActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _grouped, unsigned _numInputs)
  11860. : CRoxieServerMultiInputActivity(_ctx, _factory, _probeManager, _numInputs)
  11861. {
  11862. eogSeen = false;
  11863. anyThisGroup = false;
  11864. grouped = _grouped;
  11865. streamIdx = 0;
  11866. curStream = NULL;
  11867. }
  11868. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11869. {
  11870. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  11871. streamIdx = 0;
  11872. curStream = streamArray[streamIdx];
  11873. eogSeen = false;
  11874. anyThisGroup = false;
  11875. }
  11876. virtual const void * nextRow()
  11877. {
  11878. ActivityTimer t(totalCycles, timeActivities);
  11879. if (!curStream)
  11880. return NULL; // eof
  11881. const void * next = curStream->nextRow();
  11882. if (next)
  11883. {
  11884. anyThisGroup = true;
  11885. eogSeen = false;
  11886. processed++;
  11887. return next;
  11888. }
  11889. else if (!eogSeen)
  11890. {
  11891. eogSeen = true;
  11892. if (grouped)
  11893. {
  11894. if (anyThisGroup)
  11895. {
  11896. anyThisGroup = false;
  11897. return NULL;
  11898. }
  11899. else
  11900. return nextRow();
  11901. }
  11902. else
  11903. return nextRow();
  11904. }
  11905. else if (streamIdx < numStreams-1)
  11906. {
  11907. streamIdx++;
  11908. curStream = streamArray[streamIdx];
  11909. eogSeen = false;
  11910. return nextRow();
  11911. }
  11912. else
  11913. {
  11914. curStream = NULL;
  11915. return NULL;
  11916. }
  11917. }
  11918. };
  11919. class CRoxieServerConcatActivityFactory : public CRoxieServerMultiInputFactory
  11920. {
  11921. bool ordered;
  11922. bool grouped;
  11923. public:
  11924. CRoxieServerConcatActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  11925. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  11926. {
  11927. Owned <IHThorFunnelArg> helper = (IHThorFunnelArg *) helperFactory();
  11928. ordered = helper->isOrdered();
  11929. grouped = helper->queryOutputMeta()->isGrouped();
  11930. }
  11931. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  11932. {
  11933. if (ordered || (_probeManager && _probeManager->queryDebugManager()))
  11934. return new CRoxieServerOrderedConcatActivity(_ctx, this, _probeManager, grouped, numInputs());
  11935. else
  11936. return new CRoxieServerThreadedConcatActivity(_ctx, this, _probeManager, grouped, numInputs());
  11937. }
  11938. };
  11939. IRoxieServerActivityFactory *createRoxieServerConcatActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  11940. {
  11941. return new CRoxieServerConcatActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  11942. }
  11943. //=================================================================================
  11944. class CRoxieServerNonEmptyActivity : public CRoxieServerMultiInputBaseActivity
  11945. {
  11946. IEngineRowStream* selectedStream;
  11947. unsigned savedParentExtractSize;
  11948. const byte * savedParentExtract;
  11949. bool foundInput;
  11950. bool unusedStopped;
  11951. public:
  11952. CRoxieServerNonEmptyActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  11953. : CRoxieServerMultiInputBaseActivity(_ctx, _factory, _probeManager, _numInputs)
  11954. {
  11955. foundInput = false;
  11956. unusedStopped = false;
  11957. selectedStream = NULL;
  11958. savedParentExtractSize = 0;;
  11959. savedParentExtract = NULL;
  11960. }
  11961. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11962. {
  11963. //Don't start the inputs yet so we can short-circuit...
  11964. CRoxieServerMultiInputBaseActivity::start(parentExtractSize, parentExtract, paused);
  11965. savedParentExtractSize = parentExtractSize;
  11966. savedParentExtract = parentExtract;
  11967. }
  11968. virtual void stop()
  11969. {
  11970. if (unusedStopped)
  11971. {
  11972. if (selectedStream)
  11973. selectedStream->stop();
  11974. }
  11975. else
  11976. {
  11977. //May possibly call stop too many times if input->start() throws an exception (e.g. due to a dependency)
  11978. for (unsigned i = 0; i < numStreams; i++)
  11979. streamArray[i]->stop();
  11980. }
  11981. CRoxieServerMultiInputBaseActivity::stop();
  11982. }
  11983. virtual void reset()
  11984. {
  11985. CRoxieServerMultiInputBaseActivity::reset();
  11986. foundInput = false;
  11987. unusedStopped = false;
  11988. selectedStream = NULL;
  11989. }
  11990. virtual unsigned __int64 queryLocalCycles() const
  11991. {
  11992. return 0; // Can't easily calculate anything reliable but local processing is negligible
  11993. }
  11994. virtual const void * nextRow()
  11995. {
  11996. ActivityTimer t(totalCycles, timeActivities);
  11997. if (!foundInput)
  11998. {
  11999. foundInput = true;
  12000. assertex(numInputs == numStreams); // If this ceases to be true we will need to rethink some of this
  12001. //If we get an exception in this loop then stop() will stop any started inputs
  12002. for (unsigned i=0; i < numStreams; i++)
  12003. {
  12004. selectedStream = streamArray[i];
  12005. inputArray[i]->start(savedParentExtractSize, savedParentExtract, false); // Assumes 1:1 mapping streams to inputs
  12006. startJunction(junctionArray[i]);
  12007. const void * next = selectedStream->nextRow();
  12008. if (next)
  12009. {
  12010. //Found a row so stop remaining
  12011. for (unsigned j=i+1; j < numInputs; j++)
  12012. streamArray[j]->stop();
  12013. unusedStopped = true;
  12014. processed++;
  12015. return next;
  12016. }
  12017. selectedStream->stop();
  12018. }
  12019. unusedStopped = true;
  12020. selectedStream = NULL;
  12021. return NULL;
  12022. }
  12023. if (!selectedStream)
  12024. return NULL;
  12025. const void * next = selectedStream->nextRow();
  12026. if (next)
  12027. processed++;
  12028. return next;
  12029. }
  12030. };
  12031. class CRoxieServerNonEmptyActivityFactory : public CRoxieServerMultiInputFactory
  12032. {
  12033. public:
  12034. CRoxieServerNonEmptyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12035. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12036. {
  12037. }
  12038. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12039. {
  12040. return new CRoxieServerNonEmptyActivity(_ctx, this, _probeManager, numInputs());
  12041. }
  12042. };
  12043. IRoxieServerActivityFactory *createRoxieServerNonEmptyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12044. {
  12045. return new CRoxieServerNonEmptyActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12046. }
  12047. //=================================================================================
  12048. class CRoxieServerMergeActivity : public CRoxieServerMultiInputActivity
  12049. {
  12050. IHThorMergeArg &helper;
  12051. unsigned *mergeheap;
  12052. unsigned activeInputs;
  12053. const void **pending;
  12054. bool first;
  12055. ICompare *compare;
  12056. bool dedup;
  12057. void permute()
  12058. {
  12059. assertex(activeInputs == 0);
  12060. for(unsigned i = 0; i < numStreams; i++)
  12061. if(pullInput(i))
  12062. mergeheap[activeInputs++] = i;
  12063. // the tree structure: element p has children p*2+1 and p*2+2, or element c has parent (unsigned)(c-1)/2
  12064. // the heap property: no element should be smaller than its parent
  12065. // the dedup variant: if(dedup), the top of the heap should also not be equal to either child
  12066. // 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
  12067. if (activeInputs >= 2)
  12068. for(unsigned p = (activeInputs-2)/2; p > 0; --p)
  12069. siftDown(p);
  12070. if(dedup)
  12071. siftDownDedupTop();
  12072. else
  12073. siftDown(0);
  12074. }
  12075. void readNext()
  12076. {
  12077. if(!pullInput(mergeheap[0]))
  12078. if(!promote(0))
  12079. return;
  12080. // we have changed the element at the top of the heap, so need to sift it down to maintain the heap property
  12081. if(dedup)
  12082. siftDownDedupTop();
  12083. else
  12084. siftDown(0);
  12085. }
  12086. bool pullInput(unsigned i)
  12087. {
  12088. const void *next = streamArray[i]->ungroupedNextRow();
  12089. pending[i] = next;
  12090. return (next != NULL);
  12091. }
  12092. bool promote(unsigned p)
  12093. {
  12094. activeInputs--;
  12095. if(activeInputs == p)
  12096. return false;
  12097. mergeheap[p] = mergeheap[activeInputs];
  12098. return true;
  12099. }
  12100. bool siftDown(unsigned p)
  12101. {
  12102. // assuming that all descendants of p form a heap, sift p down to its correct position, and so include it in the heap
  12103. bool nochange = true;
  12104. while(1)
  12105. {
  12106. unsigned c = p*2 + 1;
  12107. if(c >= activeInputs)
  12108. return nochange;
  12109. if(c+1 < activeInputs)
  12110. {
  12111. int childcmp = BuffCompare(c+1, c);
  12112. if((childcmp < 0) || ((childcmp == 0) && (mergeheap[c+1] < mergeheap[c])))
  12113. ++c;
  12114. }
  12115. int cmp = BuffCompare(c, p);
  12116. if((cmp > 0) || ((cmp == 0) && (mergeheap[c] > mergeheap[p])))
  12117. return nochange;
  12118. nochange = false;
  12119. unsigned r = mergeheap[c];
  12120. mergeheap[c] = mergeheap[p];
  12121. mergeheap[p] = r;
  12122. p = c;
  12123. }
  12124. }
  12125. void siftDownDedupTop()
  12126. {
  12127. // same as siftDown(0), except that it also ensures that the top of the heap is not equal to either of its children
  12128. if(activeInputs < 2)
  12129. return;
  12130. unsigned c = 1;
  12131. int childcmp = 1;
  12132. if(activeInputs >= 3)
  12133. {
  12134. childcmp = BuffCompare(2, 1);
  12135. if(childcmp < 0)
  12136. c = 2;
  12137. }
  12138. int cmp = BuffCompare(c, 0);
  12139. if(cmp > 0)
  12140. return;
  12141. // the following loop ensures the correct property holds on the smaller branch, and that childcmp==0 iff the top matches the other branch
  12142. while(cmp <= 0)
  12143. {
  12144. if(cmp == 0)
  12145. {
  12146. if(mergeheap[c] < mergeheap[0])
  12147. {
  12148. unsigned r = mergeheap[c];
  12149. mergeheap[c] = mergeheap[0];
  12150. mergeheap[0] = r;
  12151. }
  12152. ReleaseClearRoxieRow(pending[mergeheap[c]]);
  12153. if(!pullInput(mergeheap[c]))
  12154. if(!promote(c))
  12155. break;
  12156. siftDown(c);
  12157. }
  12158. else
  12159. {
  12160. unsigned r = mergeheap[c];
  12161. mergeheap[c] = mergeheap[0];
  12162. mergeheap[0] = r;
  12163. if(siftDown(c))
  12164. break;
  12165. }
  12166. cmp = BuffCompare(c, 0);
  12167. }
  12168. // the following loop ensures the uniqueness property holds on the other branch too
  12169. c = 3-c;
  12170. if(activeInputs <= c)
  12171. return;
  12172. while(childcmp == 0)
  12173. {
  12174. if(mergeheap[c] < mergeheap[0])
  12175. {
  12176. unsigned r = mergeheap[c];
  12177. mergeheap[c] = mergeheap[0];
  12178. mergeheap[0] = r;
  12179. }
  12180. ReleaseClearRoxieRow(pending[mergeheap[c]]);
  12181. if(!pullInput(mergeheap[c]))
  12182. if(!promote(c))
  12183. break;
  12184. siftDown(c);
  12185. childcmp = BuffCompare(c, 0);
  12186. }
  12187. }
  12188. inline int BuffCompare(unsigned a, unsigned b)
  12189. {
  12190. return compare->docompare(pending[mergeheap[a]], pending[mergeheap[b]]);
  12191. }
  12192. public:
  12193. CRoxieServerMergeActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  12194. : CRoxieServerMultiInputActivity(_ctx, _factory, _probeManager, _numInputs), helper((IHThorMergeArg &)basehelper)
  12195. {
  12196. activeInputs = 0;
  12197. first = true;
  12198. mergeheap = new unsigned[numInputs];
  12199. pending = new const void *[numStreams];
  12200. compare = helper.queryCompare();
  12201. dedup = helper.dedup();
  12202. for (unsigned i = 0; i < numStreams; i++)
  12203. pending[i] = NULL;
  12204. }
  12205. ~CRoxieServerMergeActivity()
  12206. {
  12207. delete [] mergeheap;
  12208. delete [] pending;
  12209. }
  12210. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12211. {
  12212. activeInputs = 0;
  12213. first = true;
  12214. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  12215. }
  12216. virtual void reset()
  12217. {
  12218. for (unsigned i = 0; i < numStreams; i++)
  12219. ReleaseClearRoxieRow(pending[i]);
  12220. CRoxieServerMultiInputActivity::reset();
  12221. }
  12222. virtual const void * nextRow()
  12223. {
  12224. ActivityTimer t(totalCycles, timeActivities);
  12225. if (first)
  12226. {
  12227. permute();
  12228. first = false;
  12229. }
  12230. if (activeInputs)
  12231. {
  12232. const void *next = pending[mergeheap[0]];
  12233. readNext();
  12234. if (next)
  12235. processed++;
  12236. return next;
  12237. }
  12238. else
  12239. return NULL;
  12240. }
  12241. };
  12242. class CRoxieServerMergeActivityFactory : public CRoxieServerMultiInputFactory
  12243. {
  12244. public:
  12245. CRoxieServerMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12246. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12247. {
  12248. }
  12249. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12250. {
  12251. return new CRoxieServerMergeActivity(_ctx, this, _probeManager, numInputs());
  12252. }
  12253. };
  12254. IRoxieServerActivityFactory *createRoxieServerMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12255. {
  12256. return new CRoxieServerMergeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12257. }
  12258. //=================================================================================
  12259. class CRoxieServerRegroupActivity : public CRoxieServerMultiInputActivity
  12260. {
  12261. IHThorRegroupArg &helper;
  12262. unsigned streamIndex;
  12263. bool eof;
  12264. unsigned __int64 numProcessedLastGroup;
  12265. public:
  12266. CRoxieServerRegroupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  12267. : CRoxieServerMultiInputActivity(_ctx, _factory, _probeManager, _numInputs), helper((IHThorRegroupArg &)basehelper)
  12268. {
  12269. streamIndex = 0;
  12270. eof = false;
  12271. numProcessedLastGroup = 0;
  12272. }
  12273. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12274. {
  12275. streamIndex = 0;
  12276. eof = false;
  12277. numProcessedLastGroup = processed;
  12278. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  12279. }
  12280. const void * nextFromInputs()
  12281. {
  12282. unsigned initialStream = streamIndex;
  12283. while (streamIndex < numStreams)
  12284. {
  12285. const void * next = streamArray[streamIndex]->nextRow();
  12286. if (next)
  12287. {
  12288. if ((streamIndex != initialStream) && (streamIndex != initialStream+1))
  12289. {
  12290. ReleaseRoxieRow(next);
  12291. throw MakeStringException(ROXIE_MISMATCH_GROUP_ERROR, "Mismatched groups supplied to Regroup (%d)", factory->queryId());
  12292. }
  12293. return next;
  12294. }
  12295. streamIndex++;
  12296. }
  12297. if ((initialStream != 0) && (initialStream+1 != numStreams))
  12298. throw MakeStringException(ROXIE_MISMATCH_GROUP_ERROR, "Mismatched groups supplied to Regroup (%d)", factory->queryId());
  12299. streamIndex = 0;
  12300. return NULL;
  12301. }
  12302. virtual const void * nextRow()
  12303. {
  12304. ActivityTimer t(totalCycles, timeActivities);
  12305. if (eof)
  12306. return NULL;
  12307. const void * ret = nextFromInputs();
  12308. if (ret)
  12309. {
  12310. processed++;
  12311. return ret;
  12312. }
  12313. if (numProcessedLastGroup != processed)
  12314. {
  12315. numProcessedLastGroup = processed;
  12316. return NULL;
  12317. }
  12318. eof = true;
  12319. return NULL;
  12320. }
  12321. };
  12322. class CRoxieServerRegroupActivityFactory : public CRoxieServerMultiInputFactory
  12323. {
  12324. public:
  12325. CRoxieServerRegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12326. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12327. {
  12328. }
  12329. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12330. {
  12331. return new CRoxieServerRegroupActivity(_ctx, this, _probeManager, numInputs());
  12332. }
  12333. };
  12334. IRoxieServerActivityFactory *createRoxieServerRegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12335. {
  12336. return new CRoxieServerRegroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12337. }
  12338. //=================================================================================
  12339. class CRoxieServerCombineActivity : public CRoxieServerMultiInputActivity
  12340. {
  12341. IHThorCombineArg &helper;
  12342. unsigned __int64 numProcessedLastGroup;
  12343. public:
  12344. CRoxieServerCombineActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  12345. : CRoxieServerMultiInputActivity(_ctx, _factory, _probeManager, _numInputs), helper((IHThorCombineArg &)basehelper)
  12346. {
  12347. numProcessedLastGroup = 0;
  12348. }
  12349. ~CRoxieServerCombineActivity()
  12350. {
  12351. }
  12352. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12353. {
  12354. numProcessedLastGroup = processed;
  12355. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  12356. }
  12357. void nextInputs(ConstPointerArray & out)
  12358. {
  12359. for (unsigned i=0; i < numStreams; i++)
  12360. {
  12361. const void * next = streamArray[i]->nextRow();
  12362. if (next)
  12363. out.append(next);
  12364. }
  12365. }
  12366. virtual bool needsAllocator() const { return true; }
  12367. virtual const void * nextRow()
  12368. {
  12369. ActivityTimer t(totalCycles, timeActivities);
  12370. for (;;)
  12371. {
  12372. ConstPointerArray group;
  12373. nextInputs(group);
  12374. if ((group.ordinality() == 0) && (numProcessedLastGroup == processed))
  12375. nextInputs(group);
  12376. if (group.ordinality() == 0)
  12377. {
  12378. numProcessedLastGroup = processed;
  12379. return NULL;
  12380. }
  12381. else if (group.ordinality() != numInputs)
  12382. {
  12383. ReleaseRoxieRows(group);
  12384. throw MakeStringException(ROXIE_MISMATCH_GROUP_ERROR, "Mismatched group input for Combine Activity(%d)", factory->queryId());
  12385. }
  12386. try
  12387. {
  12388. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12389. size32_t outSize = helper.transform(rowBuilder, group.ordinality(), group.getArray());
  12390. ReleaseRoxieRows(group);
  12391. if (outSize)
  12392. {
  12393. processed++;
  12394. return rowBuilder.finalizeRowClear(outSize);
  12395. }
  12396. }
  12397. catch (IException *E)
  12398. {
  12399. ReleaseRoxieRows(group);
  12400. throw makeWrappedException(E);
  12401. }
  12402. }
  12403. }
  12404. };
  12405. class CRoxieServerCombineActivityFactory : public CRoxieServerMultiInputFactory
  12406. {
  12407. public:
  12408. CRoxieServerCombineActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12409. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12410. {
  12411. }
  12412. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12413. {
  12414. return new CRoxieServerCombineActivity(_ctx, this, _probeManager, numInputs());
  12415. }
  12416. };
  12417. IRoxieServerActivityFactory *createRoxieServerCombineActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12418. {
  12419. return new CRoxieServerCombineActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12420. }
  12421. //=================================================================================
  12422. class CRoxieServerCombineGroupActivity : public CRoxieServerTwoInputActivity
  12423. {
  12424. IHThorCombineGroupArg &helper;
  12425. unsigned __int64 numProcessedLastGroup;
  12426. public:
  12427. CRoxieServerCombineGroupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  12428. : CRoxieServerTwoInputActivity(_ctx, _factory, _probeManager), helper((IHThorCombineGroupArg &)basehelper)
  12429. {
  12430. numProcessedLastGroup = 0;
  12431. }
  12432. ~CRoxieServerCombineGroupActivity()
  12433. {
  12434. }
  12435. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12436. {
  12437. numProcessedLastGroup = processed;
  12438. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  12439. }
  12440. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  12441. {
  12442. if (idx==(unsigned)-1)
  12443. idx = 0;
  12444. return idx ? NULL : this;
  12445. }
  12446. virtual bool needsAllocator() const { return true; }
  12447. virtual const void * nextRow()
  12448. {
  12449. ActivityTimer t(totalCycles, timeActivities);
  12450. for (;;)
  12451. {
  12452. const void * left = inputStream->nextRow();
  12453. if (!left && (numProcessedLastGroup == processed))
  12454. left = inputStream->nextRow();
  12455. if (!left)
  12456. {
  12457. if (numProcessedLastGroup == processed)
  12458. {
  12459. const void * nextRight = inputStream1->nextRow();
  12460. if (nextRight)
  12461. {
  12462. ReleaseRoxieRow(nextRight);
  12463. throw MakeStringException(ROXIE_MISSING_GROUP_ERROR, "Missing LEFT record for Combine Group (%d)", factory->queryId());
  12464. }
  12465. }
  12466. else
  12467. numProcessedLastGroup = processed;
  12468. return NULL;
  12469. }
  12470. ConstPointerArray group;
  12471. for (;;)
  12472. {
  12473. const void * in = inputStream1->nextRow();
  12474. if (!in)
  12475. break;
  12476. group.append(in);
  12477. }
  12478. if (group.ordinality() == 0)
  12479. {
  12480. ReleaseRoxieRow(left);
  12481. ReleaseRoxieRows(group);
  12482. throw MakeStringException(ROXIE_MISSING_GROUP_ERROR, "Missing RIGHT group for Combine Group (%d)", factory->queryId());
  12483. }
  12484. try
  12485. {
  12486. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12487. size32_t outSize = helper.transform(rowBuilder, left, group.ordinality(), (const void * *)group.getArray());
  12488. ReleaseRoxieRow(left);
  12489. ReleaseRoxieRows(group);
  12490. if (outSize)
  12491. {
  12492. processed++;
  12493. return rowBuilder.finalizeRowClear(outSize);
  12494. }
  12495. }
  12496. catch (IException *E)
  12497. {
  12498. ReleaseRoxieRow(left);
  12499. ReleaseRoxieRows(group);
  12500. throw makeWrappedException(E);
  12501. }
  12502. }
  12503. }
  12504. };
  12505. class CRoxieServerCombineGroupActivityFactory : public CRoxieServerActivityFactory
  12506. {
  12507. unsigned input2;
  12508. unsigned input2idx;
  12509. public:
  12510. CRoxieServerCombineGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12511. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12512. {
  12513. input2 = 0;
  12514. input2idx = 0;
  12515. }
  12516. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12517. {
  12518. return new CRoxieServerCombineGroupActivity(_ctx, this, _probeManager);
  12519. }
  12520. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  12521. {
  12522. if (idx==1)
  12523. {
  12524. input2 = source;
  12525. input2idx = sourceidx;
  12526. }
  12527. else
  12528. CRoxieServerActivityFactory::setInput(idx, source, sourceidx);
  12529. }
  12530. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  12531. {
  12532. switch (idx)
  12533. {
  12534. case 1:
  12535. sourceidx = input2idx;
  12536. return input2;
  12537. case 0:
  12538. return CRoxieServerActivityFactory::getInput(idx, sourceidx);
  12539. default:
  12540. return (unsigned) -1;
  12541. }
  12542. }
  12543. virtual unsigned numInputs() const { return 2; }
  12544. };
  12545. IRoxieServerActivityFactory *createRoxieServerCombineGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12546. {
  12547. return new CRoxieServerCombineGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12548. }
  12549. //=================================================================================
  12550. class CRoxieServerRollupGroupActivity : public CRoxieServerActivity
  12551. {
  12552. IHThorRollupGroupArg &helper;
  12553. bool eof;
  12554. public:
  12555. CRoxieServerRollupGroupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  12556. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  12557. helper((IHThorRollupGroupArg &)basehelper)
  12558. {
  12559. eof = false;
  12560. }
  12561. ~CRoxieServerRollupGroupActivity()
  12562. {
  12563. }
  12564. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12565. {
  12566. eof = false;
  12567. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  12568. }
  12569. virtual bool needsAllocator() const { return true; }
  12570. virtual const void * nextRow()
  12571. {
  12572. ActivityTimer t(totalCycles, timeActivities);
  12573. if (eof)
  12574. return NULL;
  12575. for (;;)
  12576. {
  12577. ConstPointerArray group;
  12578. for (;;)
  12579. {
  12580. const void * in = inputStream->nextRow();
  12581. if (!in)
  12582. break;
  12583. group.append(in);
  12584. }
  12585. if (group.ordinality() == 0)
  12586. {
  12587. eof = true;
  12588. return NULL;
  12589. }
  12590. try
  12591. {
  12592. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12593. size32_t outSize = helper.transform(rowBuilder, group.ordinality(), (const void * *)group.getArray());
  12594. ReleaseRoxieRows(group);
  12595. if (outSize)
  12596. {
  12597. processed++;
  12598. return rowBuilder.finalizeRowClear(outSize);
  12599. }
  12600. }
  12601. catch (IException * E)
  12602. {
  12603. ReleaseRoxieRows(group);
  12604. throw makeWrappedException(E);
  12605. }
  12606. }
  12607. }
  12608. };
  12609. class CRoxieServerRollupGroupActivityFactory : public CRoxieServerActivityFactory
  12610. {
  12611. public:
  12612. CRoxieServerRollupGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12613. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12614. {
  12615. }
  12616. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12617. {
  12618. return new CRoxieServerRollupGroupActivity(_ctx, this, _probeManager);
  12619. }
  12620. };
  12621. IRoxieServerActivityFactory *createRoxieServerRollupGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12622. {
  12623. return new CRoxieServerRollupGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12624. }
  12625. //=================================================================================
  12626. class CRoxieServerFilterProjectActivity : public CRoxieServerLateStartActivity
  12627. {
  12628. IHThorFilterProjectArg &helper;
  12629. unsigned numProcessedLastGroup;
  12630. unsigned __int64 recordCount;
  12631. public:
  12632. CRoxieServerFilterProjectActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  12633. : CRoxieServerLateStartActivity(_ctx, _factory, _probeManager), helper((IHThorFilterProjectArg &)basehelper)
  12634. {
  12635. numProcessedLastGroup = 0;
  12636. recordCount = 0;
  12637. }
  12638. ~CRoxieServerFilterProjectActivity()
  12639. {
  12640. }
  12641. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12642. {
  12643. numProcessedLastGroup = 0;
  12644. recordCount = 0;
  12645. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  12646. lateStart(parentExtractSize, parentExtract, helper.canMatchAny()); //sets eof
  12647. }
  12648. virtual bool needsAllocator() const { return true; }
  12649. virtual const void * nextRow()
  12650. {
  12651. ActivityTimer t(totalCycles, timeActivities);
  12652. if (eof)
  12653. return NULL;
  12654. for (;;)
  12655. {
  12656. const void * in = inputStream->nextRow();
  12657. if (!in)
  12658. {
  12659. recordCount = 0;
  12660. if (numProcessedLastGroup == processed)
  12661. in = inputStream->nextRow();
  12662. if (!in)
  12663. {
  12664. numProcessedLastGroup = processed;
  12665. return NULL;
  12666. }
  12667. }
  12668. try
  12669. {
  12670. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12671. size32_t outSize = helper.transform(rowBuilder, in, ++recordCount);
  12672. ReleaseRoxieRow(in);
  12673. if (outSize)
  12674. {
  12675. processed++;
  12676. return rowBuilder.finalizeRowClear(outSize);
  12677. }
  12678. }
  12679. catch (IException *E)
  12680. {
  12681. throw makeWrappedException(E);
  12682. }
  12683. }
  12684. }
  12685. };
  12686. class CRoxieServerFilterProjectActivityFactory : public CRoxieServerActivityFactory
  12687. {
  12688. public:
  12689. CRoxieServerFilterProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12690. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12691. {
  12692. //MORE: Code generator needs to indicate if the count is used.
  12693. //optStableInput = false;
  12694. }
  12695. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12696. {
  12697. return new CRoxieServerFilterProjectActivity(_ctx, this, _probeManager);
  12698. }
  12699. };
  12700. IRoxieServerActivityFactory *createRoxieServerFilterProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12701. {
  12702. return new CRoxieServerFilterProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12703. }
  12704. //=====================================================
  12705. class CRoxieServerStrandedProjectActivity : public CRoxieServerStrandedActivity
  12706. {
  12707. class ProjectProcessor : public StrandProcessor
  12708. {
  12709. protected:
  12710. IHThorProjectArg &helper;
  12711. public:
  12712. ProjectProcessor(CRoxieServerActivity &_parent, IEngineRowStream *_inputStream, IHThorProjectArg &_helper)
  12713. : StrandProcessor(_parent, _inputStream, true), helper(_helper)
  12714. {
  12715. }
  12716. virtual const void * nextRow()
  12717. {
  12718. ActivityTimer t(totalCycles, timeActivities);
  12719. for (;;)
  12720. {
  12721. OwnedConstRoxieRow in = inputStream->nextRow();
  12722. if (!in)
  12723. {
  12724. if (numProcessedLastGroup == processed)
  12725. in.setown(inputStream->nextRow());
  12726. if (!in)
  12727. {
  12728. numProcessedLastGroup = processed;
  12729. return NULL;
  12730. }
  12731. }
  12732. try
  12733. {
  12734. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12735. size32_t outSize;
  12736. outSize = helper.transform(rowBuilder, in);
  12737. if (outSize)
  12738. {
  12739. processed++;
  12740. return rowBuilder.finalizeRowClear(outSize);
  12741. }
  12742. }
  12743. catch (IException *E)
  12744. {
  12745. throw parent.makeWrappedException(E);
  12746. }
  12747. }
  12748. }
  12749. };
  12750. public:
  12751. CRoxieServerStrandedProjectActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const StrandOptions &_strandOptions)
  12752. : CRoxieServerStrandedActivity(_ctx, _factory, _probeManager, _strandOptions)
  12753. {
  12754. }
  12755. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12756. {
  12757. CRoxieServerStrandedActivity::start(parentExtractSize, parentExtract, paused);
  12758. onStartStrands();
  12759. }
  12760. virtual StrandProcessor *createStrandProcessor(IEngineRowStream *instream)
  12761. {
  12762. return new ProjectProcessor(*this, instream, (IHThorProjectArg &) basehelper);
  12763. }
  12764. virtual StrandProcessor *createStrandSourceProcessor(bool inputOrdered) { throwUnexpected(); }
  12765. };
  12766. class CRoxieServerProjectActivity : public CRoxieServerActivity
  12767. {
  12768. unsigned numProcessedLastGroup;
  12769. unsigned __int64 recordCount;
  12770. bool count;
  12771. public:
  12772. CRoxieServerProjectActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _count)
  12773. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  12774. count(_count)
  12775. {
  12776. numProcessedLastGroup = 0;
  12777. recordCount = 0;
  12778. }
  12779. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12780. {
  12781. numProcessedLastGroup = 0;
  12782. recordCount = 0;
  12783. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  12784. }
  12785. virtual bool needsAllocator() const { return true; }
  12786. virtual const void * nextRow()
  12787. {
  12788. ActivityTimer t(totalCycles, timeActivities);
  12789. for (;;)
  12790. {
  12791. OwnedConstRoxieRow in = inputStream->nextRow();
  12792. if (!in)
  12793. {
  12794. recordCount = 0;
  12795. if (numProcessedLastGroup == processed)
  12796. in.setown(inputStream->nextRow());
  12797. if (!in)
  12798. {
  12799. numProcessedLastGroup = processed;
  12800. return NULL;
  12801. }
  12802. }
  12803. try
  12804. {
  12805. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12806. size32_t outSize;
  12807. if (count)
  12808. outSize = ((IHThorCountProjectArg &) basehelper).transform(rowBuilder, in, ++recordCount);
  12809. else
  12810. outSize = ((IHThorProjectArg &) basehelper).transform(rowBuilder, in);
  12811. if (outSize)
  12812. {
  12813. processed++;
  12814. return rowBuilder.finalizeRowClear(outSize);
  12815. }
  12816. }
  12817. catch (IException *E)
  12818. {
  12819. throw makeWrappedException(E);
  12820. }
  12821. }
  12822. }
  12823. };
  12824. class CRoxieServerProjectActivityFactory : public CRoxieServerActivityFactory
  12825. {
  12826. protected:
  12827. StrandOptions strandOptions;
  12828. bool count;
  12829. public:
  12830. CRoxieServerProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12831. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), strandOptions(_graphNode)
  12832. {
  12833. count = (kind==TAKcountproject || kind==TAKprefetchcountproject);
  12834. optStableInput = count;
  12835. }
  12836. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12837. {
  12838. // 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.
  12839. if (kind == TAKproject) // Not supported on prefetch or count projects
  12840. return new CRoxieServerStrandedProjectActivity(_ctx, this, _probeManager, strandOptions);
  12841. else
  12842. return new CRoxieServerProjectActivity(_ctx, this, _probeManager, count);
  12843. }
  12844. };
  12845. IRoxieServerActivityFactory *createRoxieServerProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12846. {
  12847. return new CRoxieServerProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12848. }
  12849. //=================================================================================
  12850. class CRoxieServerPrefetchProjectActivity : public CRoxieServerActivity, implements IRecordPullerCallback
  12851. {
  12852. unsigned numProcessedLastGroup;
  12853. bool count;
  12854. bool eof;
  12855. bool allPulled;
  12856. bool isThreaded;
  12857. unsigned preload;
  12858. unsigned __int64 recordCount;
  12859. IHThorPrefetchProjectArg &helper;
  12860. RecordPullerThread puller;
  12861. InterruptableSemaphore ready;
  12862. InterruptableSemaphore space;
  12863. class PrefetchInfo : public CInterface
  12864. {
  12865. public:
  12866. inline PrefetchInfo(IHThorPrefetchProjectArg &helper, const void *_in, unsigned __int64 _recordCount)
  12867. {
  12868. if (helper.preTransform(extract, _in, _recordCount))
  12869. {
  12870. in.setown(_in);
  12871. recordCount = _recordCount;
  12872. }
  12873. else
  12874. {
  12875. ReleaseRoxieRow(_in);
  12876. recordCount = 0;
  12877. }
  12878. }
  12879. OwnedConstRoxieRow in;
  12880. unsigned __int64 recordCount;
  12881. rtlRowBuilder extract;
  12882. };
  12883. QueueOf<PrefetchInfo, true> pulled;
  12884. CriticalSection pulledCrit;
  12885. public:
  12886. CRoxieServerPrefetchProjectActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _count)
  12887. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  12888. helper((IHThorPrefetchProjectArg &) basehelper),
  12889. puller(false),
  12890. count(_count)
  12891. {
  12892. numProcessedLastGroup = 0;
  12893. recordCount = 0;
  12894. eof = false;
  12895. allPulled = false;
  12896. isThreaded = (helper.getFlags() & PPFparallel) != 0;
  12897. preload = 0;
  12898. }
  12899. ~CRoxieServerPrefetchProjectActivity()
  12900. {
  12901. while (pulled.ordinality())
  12902. ::Release(pulled.dequeue());
  12903. }
  12904. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  12905. {
  12906. if (idx)
  12907. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
  12908. puller.setInput(this, _sourceIdx, _in);
  12909. }
  12910. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  12911. {
  12912. puller.connectInputStreams(ctx, consumerOrdered);
  12913. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
  12914. }
  12915. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  12916. {
  12917. if (idx==0)
  12918. return puller.queryInput();
  12919. else
  12920. return NULL;
  12921. }
  12922. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12923. {
  12924. numProcessedLastGroup = 0;
  12925. recordCount = 0;
  12926. eof = false;
  12927. allPulled = false;
  12928. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  12929. preload = helper.getLookahead();
  12930. if (!preload)
  12931. preload = ctx->queryOptions().prefetchProjectPreload;
  12932. space.reinit(preload);
  12933. ready.reinit();
  12934. puller.start(parentExtractSize, parentExtract, paused, preload, !isThreaded, ctx);
  12935. }
  12936. virtual void stop()
  12937. {
  12938. space.interrupt();
  12939. ready.interrupt();
  12940. CRoxieServerActivity::stop();
  12941. puller.stop();
  12942. }
  12943. virtual void reset()
  12944. {
  12945. CRoxieServerActivity::reset();
  12946. puller.reset();
  12947. allPulled = false;
  12948. while (pulled.ordinality())
  12949. ::Release(pulled.dequeue());
  12950. }
  12951. virtual PrefetchInfo *readNextRecord()
  12952. {
  12953. if (!isThreaded)
  12954. {
  12955. if (!allPulled) // This looks like it's thread unsafe but we are inside the if(!isThreaded) so should be ok
  12956. puller.pullRecords(1);
  12957. }
  12958. else
  12959. ready.wait();
  12960. CriticalBlock b(pulledCrit);
  12961. PrefetchInfo *ret = pulled.ordinality() ? pulled.dequeue() : NULL;
  12962. space.signal();
  12963. return ret;
  12964. }
  12965. virtual bool needsAllocator() const { return true; }
  12966. virtual const void * nextRow()
  12967. {
  12968. ActivityTimer t(totalCycles, timeActivities);
  12969. if (eof)
  12970. return NULL;
  12971. for (;;)
  12972. {
  12973. Owned<PrefetchInfo> in = readNextRecord();
  12974. if (!in)
  12975. {
  12976. recordCount = 0;
  12977. if (numProcessedLastGroup == processed)
  12978. in.setown(readNextRecord());
  12979. if (!in)
  12980. {
  12981. numProcessedLastGroup = processed;
  12982. eof = true;
  12983. return NULL;
  12984. }
  12985. }
  12986. try
  12987. {
  12988. if (in->in)
  12989. {
  12990. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12991. size32_t outSize;
  12992. IThorChildGraph *child = helper.queryChild();
  12993. Owned<IEclGraphResults> results;
  12994. if (child)
  12995. results.setown(child->evaluate(in->extract.size(), in->extract.getbytes()));
  12996. outSize = helper.transform(rowBuilder, in->in, results, in->recordCount);
  12997. if (outSize)
  12998. {
  12999. processed++;
  13000. return rowBuilder.finalizeRowClear(outSize);
  13001. }
  13002. }
  13003. }
  13004. catch (IException *E)
  13005. {
  13006. throw makeWrappedException(E);
  13007. }
  13008. }
  13009. }
  13010. // interface IExceptionHandler
  13011. virtual bool fireException(IException *e)
  13012. {
  13013. // called from puller thread on failure
  13014. ready.interrupt(LINK(e));
  13015. space.interrupt(e);
  13016. return true;
  13017. }
  13018. // interface IRecordPullerCallback
  13019. virtual void processRow(const void *row)
  13020. {
  13021. {
  13022. CriticalBlock b(pulledCrit);
  13023. pulled.enqueue(new PrefetchInfo(helper, row, ++recordCount));
  13024. }
  13025. if (isThreaded)
  13026. {
  13027. ready.signal();
  13028. space.wait();
  13029. }
  13030. }
  13031. virtual void processEOG()
  13032. {
  13033. {
  13034. CriticalBlock b(pulledCrit);
  13035. pulled.enqueue(NULL);
  13036. }
  13037. if (isThreaded)
  13038. {
  13039. ready.signal();
  13040. space.wait();
  13041. }
  13042. }
  13043. virtual void processGroup(const ConstPointerArray &rows)
  13044. {
  13045. throwUnexpected();
  13046. }
  13047. virtual void processDone()
  13048. {
  13049. CriticalBlock b(pulledCrit);
  13050. allPulled = true;
  13051. if (isThreaded)
  13052. ready.signal();
  13053. }
  13054. };
  13055. class CRoxieServerPrefetchProjectActivityFactory : public CRoxieServerProjectActivityFactory
  13056. {
  13057. public:
  13058. CRoxieServerPrefetchProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  13059. : CRoxieServerProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  13060. {
  13061. }
  13062. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  13063. {
  13064. return new CRoxieServerPrefetchProjectActivity(_ctx, this, _probeManager, count);
  13065. }
  13066. };
  13067. extern IRoxieServerActivityFactory *createRoxieServerPrefetchProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  13068. {
  13069. return new CRoxieServerPrefetchProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  13070. }
  13071. //=================================================================================
  13072. class CPointerArrayRoxieInput : public CPseudoRoxieInput
  13073. {
  13074. public:
  13075. CPointerArrayRoxieInput()
  13076. {
  13077. rowset = NULL;
  13078. rowcount = 0;
  13079. curRow = 0;
  13080. }
  13081. void init(size32_t _rowcount, byte **_rowset)
  13082. {
  13083. rowset = _rowset;
  13084. rowcount = _rowcount;
  13085. curRow = 0;
  13086. }
  13087. virtual const void * nextRow()
  13088. {
  13089. if (curRow < rowcount)
  13090. {
  13091. const void * ret = rowset[curRow];
  13092. if (ret)
  13093. LinkRoxieRow(ret);
  13094. curRow++;
  13095. return ret;
  13096. }
  13097. return NULL;
  13098. }
  13099. protected:
  13100. byte **rowset;
  13101. size32_t rowcount;
  13102. size32_t curRow;
  13103. };
  13104. class CRoxieServerLoopActivity : public CRoxieServerActivity
  13105. {
  13106. protected:
  13107. IHThorLoopArg &helper;
  13108. ThorActivityKind activityKind;
  13109. unsigned maxIterations;
  13110. bool finishedLooping;
  13111. unsigned flags;
  13112. bool eof;
  13113. rtlRowBuilder loopExtractBuilder;
  13114. unsigned loopGraphId;
  13115. Linked<IOutputMetaData> counterMeta;
  13116. public:
  13117. CRoxieServerLoopActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _loopGraphId, IOutputMetaData * _counterMeta)
  13118. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  13119. helper((IHThorLoopArg &)basehelper), loopGraphId(_loopGraphId), counterMeta(_counterMeta)
  13120. {
  13121. eof = false;
  13122. finishedLooping = false;
  13123. activityKind = factory->getKind();
  13124. flags = helper.getFlags();
  13125. maxIterations = 0;
  13126. }
  13127. virtual bool needsAllocator() const { return true; }
  13128. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13129. {
  13130. eof = false;
  13131. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  13132. int iterations = (int) helper.numIterations();
  13133. maxIterations = (iterations >= 0) ? iterations : 0;
  13134. finishedLooping = ((activityKind == TAKloopcount) && (maxIterations == 0));
  13135. if ((flags & IHThorLoopArg::LFnewloopagain) && !helper.loopFirstTime())
  13136. finishedLooping = true;
  13137. loopExtractBuilder.clear();
  13138. helper.createParentExtract(loopExtractBuilder); // could possibly delay this until execution actually happens
  13139. }
  13140. virtual void stop()
  13141. {
  13142. CRoxieServerActivity::stop();
  13143. loopExtractBuilder.clear();
  13144. }
  13145. void createCounterResult(IRoxieServerChildGraph * graph, unsigned counter)
  13146. {
  13147. if (flags & IHThorLoopArg::LFcounter)
  13148. {
  13149. void * counterRow = ctx->queryRowManager().allocate(sizeof(thor_loop_counter_t), activityId);
  13150. *((thor_loop_counter_t *)counterRow) = counter;
  13151. RtlLinkedDatasetBuilder builder(rowAllocator);
  13152. builder.appendOwn(counterRow);
  13153. Owned<CGraphResult> counterResult = new CGraphResult(builder.getcount(), builder.linkrows());
  13154. graph->setInputResult(2, counterResult);
  13155. }
  13156. }
  13157. };
  13158. //=================================================================================
  13159. class CRoxieServerSequentialLoopActivity : public CRoxieServerLoopActivity
  13160. {
  13161. Owned<IActivityGraph> loopQuery;
  13162. Owned<IRoxieServerChildGraph> loopGraph;
  13163. IEngineRowStream * curStream;
  13164. RtlLinkedDatasetBuilder *loopInputBuilder;
  13165. CPointerArrayRoxieInput arrayInput;
  13166. Linked<IEngineRowStream> resultStream;
  13167. unsigned loopCounter;
  13168. public:
  13169. CRoxieServerSequentialLoopActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _loopGraphId, IOutputMetaData * _counterMeta)
  13170. : CRoxieServerLoopActivity(_ctx, _factory, _probeManager, _loopGraphId, _counterMeta)
  13171. {
  13172. curStream = NULL;
  13173. loopCounter = 0;
  13174. loopInputBuilder = NULL;
  13175. }
  13176. virtual bool needsAllocator() const { return true; }
  13177. virtual void onCreate(IHThorArg *_colocalParent)
  13178. {
  13179. CRoxieServerLoopActivity::onCreate(_colocalParent);
  13180. loopQuery.set(ctx->queryChildGraph(loopGraphId));
  13181. }
  13182. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13183. {
  13184. curStream = inputStream;
  13185. loopCounter = 1;
  13186. CRoxieServerLoopActivity::start(parentExtractSize, parentExtract, paused);
  13187. //MORE: Not sure about this, should IRoxieServerChildGraph be combined with IActivityGraph?
  13188. loopGraph.set(loopQuery->queryLoopGraph());
  13189. loopInputBuilder = new RtlLinkedDatasetBuilder(rowAllocator);
  13190. }
  13191. virtual void stop()
  13192. {
  13193. delete loopInputBuilder;
  13194. loopInputBuilder = NULL;
  13195. CRoxieServerLoopActivity::stop();
  13196. }
  13197. virtual const void * nextRow()
  13198. {
  13199. ActivityTimer t(totalCycles, timeActivities);
  13200. if (eof)
  13201. return NULL;
  13202. unsigned emptyIterations = 0;
  13203. for (;;)
  13204. {
  13205. for (;;)
  13206. {
  13207. const void * ret = curStream->nextRow();
  13208. if (!ret)
  13209. {
  13210. ret = curStream->nextRow(); // more cope with groups somehow....
  13211. if (!ret)
  13212. {
  13213. if (finishedLooping)
  13214. {
  13215. eof = true;
  13216. return NULL;
  13217. }
  13218. break;
  13219. }
  13220. }
  13221. if (finishedLooping ||
  13222. ((flags & IHThorLoopArg::LFfiltered) && !helper.sendToLoop(loopCounter, ret)))
  13223. {
  13224. processed++;
  13225. return ret;
  13226. }
  13227. loopInputBuilder->appendOwn(ret);
  13228. }
  13229. switch (activityKind)
  13230. {
  13231. case TAKloopdataset:
  13232. {
  13233. if (!(flags & IHThorLoopArg::LFnewloopagain))
  13234. {
  13235. if (!helper.loopAgain(loopCounter, loopInputBuilder->getcount(), (const void**) loopInputBuilder->queryrows()))
  13236. {
  13237. if (loopInputBuilder->getcount() == 0)
  13238. {
  13239. eof = true;
  13240. return NULL;
  13241. }
  13242. arrayInput.init(loopInputBuilder->getcount(), loopInputBuilder->linkrows());
  13243. // MORE - should builder be cleared here?
  13244. curStream = &arrayInput;
  13245. finishedLooping = true;
  13246. continue; // back to the input loop again
  13247. }
  13248. }
  13249. break;
  13250. }
  13251. case TAKlooprow:
  13252. if (!loopInputBuilder->getcount())
  13253. {
  13254. finishedLooping = true;
  13255. eof = true;
  13256. return NULL;
  13257. }
  13258. break;
  13259. }
  13260. if (loopInputBuilder->getcount())
  13261. emptyIterations = 0;
  13262. else
  13263. {
  13264. //note: any outputs which didn't go around the loop again, would return the record, reinitializing emptyIterations
  13265. emptyIterations++;
  13266. if (emptyIterations > maxEmptyLoopIterations)
  13267. throw MakeStringException(ROXIE_TOO_MANY_EMPTY_LOOP, "Executed LOOP with empty input and output %u times", emptyIterations);
  13268. if (emptyIterations % 32 == 0)
  13269. CTXLOG("Executing LOOP with empty input and output %u times", emptyIterations);
  13270. }
  13271. checkAbort();
  13272. try
  13273. {
  13274. Owned<IRoxieGraphResults> results = executeIteration(loopExtractBuilder.size(), loopExtractBuilder.getbytes(), loopCounter);
  13275. resultStream.setown(results->createIterator(0));
  13276. if (flags & IHThorLoopArg::LFnewloopagain)
  13277. {
  13278. Owned<IEngineRowStream> againResult = results->createIterator(helper.loopAgainResult());
  13279. OwnedConstRoxieRow row = againResult->nextRow();
  13280. assertex(row);
  13281. //Result is a row which contains a single boolean field.
  13282. if (!((const bool *)row.get())[0])
  13283. finishedLooping = true;
  13284. }
  13285. }
  13286. catch (IException *E)
  13287. {
  13288. throw makeWrappedException(E);
  13289. }
  13290. curStream = resultStream.get();
  13291. loopCounter++;
  13292. if ((activityKind == TAKloopcount) && (loopCounter > maxIterations))
  13293. finishedLooping = true;
  13294. }
  13295. }
  13296. IRoxieGraphResults * executeIteration(unsigned parentExtractSize, const byte *parentExtract, unsigned counter)
  13297. {
  13298. try
  13299. {
  13300. loopGraph->beforeExecute();
  13301. Owned<IGraphResult> inputRowsResult = new CGraphResult(loopInputBuilder->getcount(), loopInputBuilder->linkrows());
  13302. loopInputBuilder->clear();
  13303. loopGraph->setInputResult(1, inputRowsResult);
  13304. createCounterResult(loopGraph, counter);
  13305. Owned<IRoxieGraphResults> ret = loopGraph->execute(parentExtractSize, parentExtract);
  13306. loopGraph->afterExecute();
  13307. return ret.getClear();
  13308. }
  13309. catch (...)
  13310. {
  13311. CTXLOG("Exception thrown in loop body - cleaning up");
  13312. loopGraph->afterExecute();
  13313. throw;
  13314. }
  13315. }
  13316. };
  13317. //=================================================================================
  13318. typedef SafeQueueOf<const void, true> SafeRowQueue;
  13319. class CRowQueuePseudoInput : public CPseudoRoxieInput
  13320. {
  13321. public:
  13322. CRowQueuePseudoInput(SafeRowQueue & _input, IOutputMetaData * _meta)
  13323. : meta(_meta), input(_input)
  13324. {
  13325. eof = false;
  13326. }
  13327. virtual const void * nextRow()
  13328. {
  13329. if (eof)
  13330. return NULL;
  13331. const void * ret = input.dequeue();
  13332. if (!ret)
  13333. eof = true;
  13334. return ret;
  13335. }
  13336. virtual IOutputMetaData * queryOutputMeta() const { return meta; }
  13337. protected:
  13338. SafeRowQueue & input;
  13339. IOutputMetaData * meta;
  13340. bool eof;
  13341. };
  13342. class CRoxieServerParallelLoopActivity;
  13343. class LoopFilterPseudoInput : public CIndirectRoxieInput
  13344. {
  13345. public:
  13346. LoopFilterPseudoInput(CRoxieServerParallelLoopActivity * _activity, unsigned _counter) :
  13347. activity(_activity), counter(_counter)
  13348. {
  13349. }
  13350. virtual const void * nextRow();
  13351. protected:
  13352. CRoxieServerParallelLoopActivity * activity;
  13353. unsigned counter;
  13354. };
  13355. class LoopExecutorThread : public RestartableThread
  13356. {
  13357. protected:
  13358. Owned<CSafeRoxieInput> safeInput;
  13359. CRoxieServerParallelLoopActivity * activity;
  13360. bool eof;
  13361. CriticalSection crit;
  13362. unsigned flags;
  13363. SafeRowQueue tempResults[2];
  13364. unsigned savedParentExtractSize;
  13365. const byte * savedParentExtract;
  13366. IArrayOf<IActivityGraph> cachedGraphs;
  13367. IRoxieSlaveContext *ctx;
  13368. public:
  13369. LoopExecutorThread()
  13370. : RestartableThread("LoopExecutorThread")
  13371. {
  13372. activity = NULL;
  13373. eof = false;
  13374. flags = 0;
  13375. ctx = NULL;
  13376. savedParentExtract = NULL;
  13377. savedParentExtractSize = 0;
  13378. }
  13379. void setInput(CRoxieServerParallelLoopActivity * _activity, unsigned _sourceIdx, IFinalRoxieInput *_input, unsigned _flags)
  13380. {
  13381. activity = _activity;
  13382. flags = _flags;
  13383. // 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.
  13384. safeInput.setown(new CSafeRoxieInput(_sourceIdx, _input));
  13385. }
  13386. void connectInputStreams(bool consumerOrdered)
  13387. {
  13388. safeInput->connectInputStreams(ctx, consumerOrdered);
  13389. }
  13390. IFinalRoxieInput *queryInput() const
  13391. {
  13392. return safeInput;
  13393. }
  13394. void onCreate(IRoxieSlaveContext * _ctx);
  13395. void start(unsigned parentExtractSize, const byte *parentExtract, bool paused);
  13396. void stop();
  13397. void reset();
  13398. virtual int run();
  13399. protected:
  13400. void executeLoop();
  13401. void executeLoopInstance(unsigned counter, unsigned numIterations, unsigned inputIdx, IFinalRoxieInput * input, SafeRowQueue * spillOutput);
  13402. IFinalRoxieInput * createLoopIterationGraph(unsigned i, unsigned inputIdx, IFinalRoxieInput * input, unsigned counter);
  13403. };
  13404. class CRoxieServerParallelLoopActivity : public CRoxieServerLoopActivity
  13405. {
  13406. friend class LoopFilterPseudoInput;
  13407. friend class LoopExecutorThread;
  13408. QueueOf<const void, true> ready;
  13409. CriticalSection helperCS;
  13410. CriticalSection cs;
  13411. unsigned defaultNumParallel;
  13412. LoopExecutorThread executor;
  13413. IProbeManager* probeManager;
  13414. CriticalSection canAccess;
  13415. CriticalSection scrit;
  13416. InterruptableSemaphore readySpace;
  13417. InterruptableSemaphore recordsReady;
  13418. protected:
  13419. bool includeInLoop(unsigned counter, const void * row)
  13420. {
  13421. CriticalBlock b(helperCS);
  13422. return helper.sendToLoop(counter, row);
  13423. }
  13424. public:
  13425. CRoxieServerParallelLoopActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _loopGraphId, IOutputMetaData * _counterMeta)
  13426. : CRoxieServerLoopActivity(_ctx, _factory, _probeManager, _loopGraphId, _counterMeta),
  13427. readySpace(parallelLoopFlowLimit)
  13428. {
  13429. probeManager = _probeManager;
  13430. defaultNumParallel = 0;
  13431. }
  13432. virtual void onCreate(IHThorArg *_colocalParent)
  13433. {
  13434. CRoxieServerActivity::onCreate(_colocalParent);
  13435. executor.onCreate(ctx);
  13436. }
  13437. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13438. {
  13439. CriticalBlock b(scrit); // can stop while still starting, if unlucky...
  13440. readySpace.reinit(parallelLoopFlowLimit);
  13441. recordsReady.reinit();
  13442. CRoxieServerLoopActivity::start(parentExtractSize, parentExtract, paused);
  13443. defaultNumParallel = helper.defaultParallelIterations();
  13444. if (!defaultNumParallel)
  13445. defaultNumParallel = DEFAULT_PARALLEL_LOOP_THREADS;
  13446. //MORE: If numIterations <= number of parallel iterations[1],
  13447. //then we don't need to create a separate thread to do the processing, and the results will also avoid
  13448. //being transferred via a queue
  13449. executor.start(parentExtractSize, parentExtract, paused);
  13450. }
  13451. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  13452. {
  13453. if (idx)
  13454. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
  13455. executor.setInput(this, _sourceIdx, _in, flags);
  13456. }
  13457. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  13458. {
  13459. executor.connectInputStreams(consumerOrdered);
  13460. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, nullptr, consumerOrdered, nullptr);
  13461. }
  13462. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  13463. {
  13464. if (idx==0)
  13465. return executor.queryInput();
  13466. else
  13467. return NULL;
  13468. }
  13469. virtual void stop()
  13470. {
  13471. CriticalBlock b(scrit); // can stop while still starting, if unlucky...
  13472. readySpace.interrupt();
  13473. recordsReady.interrupt();
  13474. executor.join(); // MORE - may not be needed given stop/reset split
  13475. CRoxieServerLoopActivity::stop();
  13476. }
  13477. virtual void reset()
  13478. {
  13479. while (ready.ordinality())
  13480. ReleaseRoxieRow(ready.dequeue());
  13481. executor.reset();
  13482. CRoxieServerActivity::reset();
  13483. }
  13484. virtual const void * nextRow()
  13485. {
  13486. ActivityTimer t(totalCycles, timeActivities);
  13487. for (;;)
  13488. {
  13489. if (eof)
  13490. return NULL;
  13491. recordsReady.wait();
  13492. CriticalBlock procedure(canAccess);
  13493. if (ready.ordinality())
  13494. {
  13495. const void *result = ready.dequeue();
  13496. readySpace.signal();
  13497. if (result)
  13498. processed++;
  13499. return result;
  13500. }
  13501. else
  13502. eof = true;
  13503. }
  13504. }
  13505. unsigned getNumParallel(unsigned iter)
  13506. {
  13507. return defaultNumParallel;
  13508. }
  13509. inline void enqueueResult(const void * row)
  13510. {
  13511. try
  13512. {
  13513. while(!readySpace.wait(1000))
  13514. {
  13515. CTXLOG("Blocked waiting for space in loop %p activity id: %d output queue: %d records in queue", this, queryId(), ready.ordinality());
  13516. }
  13517. }
  13518. catch (...)
  13519. {
  13520. ReleaseRoxieRow(row);
  13521. throw;
  13522. }
  13523. CriticalBlock b2(canAccess);
  13524. ready.enqueue(row);
  13525. recordsReady.signal();
  13526. }
  13527. inline void finishResults()
  13528. {
  13529. recordsReady.signal();
  13530. }
  13531. virtual bool fireException(IException *e)
  13532. {
  13533. readySpace.interrupt(LINK(e));
  13534. recordsReady.interrupt(e);
  13535. return true;
  13536. }
  13537. IActivityGraph * createChildGraphInstance()
  13538. {
  13539. return factory->createChildGraph(ctx, &helper, loopGraphId, this, probeManager, *this);
  13540. }
  13541. IActivityGraph * queryChildGraph()
  13542. {
  13543. return ctx->queryChildGraph(loopGraphId);
  13544. }
  13545. };
  13546. //=================================================================================
  13547. const void * LoopFilterPseudoInput::nextRow()
  13548. {
  13549. for (;;)
  13550. {
  13551. const void * next = stream->nextRow();
  13552. if (!next || activity->includeInLoop(counter, next))
  13553. return next;
  13554. activity->enqueueResult(next);
  13555. }
  13556. }
  13557. void LoopExecutorThread::onCreate(IRoxieSlaveContext * _ctx)
  13558. {
  13559. //Initialise the cached graph list with the child instance that will always be created. Other iterations will be created on demand.
  13560. ctx = _ctx;
  13561. cachedGraphs.append(*LINK(activity->queryChildGraph()));
  13562. }
  13563. void LoopExecutorThread::start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13564. {
  13565. savedParentExtractSize = parentExtractSize;
  13566. savedParentExtract = parentExtract;
  13567. eof = false;
  13568. StringBuffer logPrefix("[");
  13569. ctx->getLogPrefix(logPrefix).append("] ");
  13570. RestartableThread::start(logPrefix);
  13571. }
  13572. int LoopExecutorThread::run()
  13573. {
  13574. try
  13575. {
  13576. executeLoop();
  13577. }
  13578. catch (IException *e)
  13579. {
  13580. activity->fireException(e);
  13581. }
  13582. catch (...)
  13583. {
  13584. activity->fireException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unexpected exception caught in LoopExecutorThread::run"));
  13585. }
  13586. return 0;
  13587. }
  13588. void LoopExecutorThread::stop()
  13589. {
  13590. safeInput->stop();
  13591. RestartableThread::join();
  13592. }
  13593. void LoopExecutorThread::reset()
  13594. {
  13595. safeInput->reset();
  13596. }
  13597. void LoopExecutorThread::executeLoop()
  13598. {
  13599. unsigned iterations = 0;
  13600. unsigned counter = 0;
  13601. unsigned outputIndex = 0;
  13602. //Note, activities don't link inputs, so need to be careful that special inputs remain linked while the activity is executing.
  13603. for (;;)
  13604. {
  13605. if (activity->activityKind == TAKloopcount)
  13606. {
  13607. if (counter == activity->maxIterations)
  13608. break;
  13609. }
  13610. else
  13611. {
  13612. //This condition isn't quite right because it needs to be whether the filtered
  13613. //input is empty. May be ok if we include that in the semantics,
  13614. if (tempResults[1-outputIndex].ordinality() == 0)
  13615. break;
  13616. }
  13617. unsigned numParallel = activity->getNumParallel(iterations);
  13618. Linked<IFinalRoxieInput> curInput;
  13619. if (iterations == 0)
  13620. curInput.set(safeInput);
  13621. else
  13622. {
  13623. SafeRowQueue & inputQueue = tempResults[1-outputIndex];
  13624. inputQueue.enqueue(NULL);
  13625. curInput.setown(new CRowQueuePseudoInput(inputQueue, activity->queryOutputMeta()));
  13626. }
  13627. SafeRowQueue * curOutput = NULL;
  13628. if (counter+numParallel > activity->maxIterations)
  13629. numParallel = activity->maxIterations - counter;
  13630. else if (counter+numParallel < activity->maxIterations)
  13631. curOutput = &tempResults[outputIndex];
  13632. executeLoopInstance(counter, numParallel, 0, curInput, curOutput); // CurInput is always SOME sort of proxy so idx always 0
  13633. outputIndex = 1-outputIndex;
  13634. counter += numParallel;
  13635. iterations++;
  13636. }
  13637. //Check for TAKlooprow, where end of loop couldn't be determined ahead of time
  13638. SafeRowQueue & inputQueue = tempResults[1-outputIndex];
  13639. while (inputQueue.ordinality())
  13640. {
  13641. const void * next = inputQueue.dequeue();
  13642. activity->enqueueResult(next);
  13643. }
  13644. activity->finishResults();
  13645. }
  13646. void LoopExecutorThread::executeLoopInstance(unsigned counter, unsigned numIterations, unsigned inputIdx, IFinalRoxieInput * input, SafeRowQueue * spillOutput)
  13647. {
  13648. IArrayOf<IFinalRoxieInput> savedInputs; // activities don't link their inputs, so this list keeps filters alive.
  13649. Linked<IFinalRoxieInput> curInput = input;
  13650. unsigned i;
  13651. for (i= 0; i != numIterations; i++)
  13652. {
  13653. unsigned thisCounter = counter+i+1;
  13654. IFinalRoxieInput * filtered = curInput;
  13655. if (flags & IHThorLoopArg::LFfiltered)
  13656. {
  13657. LoopFilterPseudoInput *newFiltered = new LoopFilterPseudoInput(activity, thisCounter);
  13658. newFiltered->setInput(inputIdx, curInput);
  13659. filtered = newFiltered;
  13660. savedInputs.append(*filtered);
  13661. inputIdx = 0;
  13662. }
  13663. //graph is kept, so new curInput will be guaranteed to exist
  13664. curInput.setown(createLoopIterationGraph(i, inputIdx, filtered, thisCounter));
  13665. inputIdx = 0;
  13666. }
  13667. Owned<IStrandJunction> curJunction;
  13668. IEngineRowStream *curStream = connectSingleStream(ctx, curInput, inputIdx, curJunction, true);
  13669. try
  13670. {
  13671. curInput->start(savedParentExtractSize, savedParentExtract, false);
  13672. if (spillOutput)
  13673. {
  13674. for (;;)
  13675. {
  13676. const void * next = curStream->nextRow();
  13677. if (!next)
  13678. break;
  13679. spillOutput->enqueue(next);
  13680. }
  13681. }
  13682. else
  13683. {
  13684. for (;;)
  13685. {
  13686. const void * next = curStream->nextRow();
  13687. if (!next)
  13688. break;
  13689. activity->enqueueResult(next);
  13690. }
  13691. }
  13692. }
  13693. catch (IException *E)
  13694. {
  13695. ctx->notifyAbort(E);
  13696. for (i= 0; i != numIterations; i++)
  13697. {
  13698. cachedGraphs.item(i).queryLoopGraph()->afterExecute();
  13699. }
  13700. curStream->stop();
  13701. curInput->reset();
  13702. throw;
  13703. }
  13704. for (i= 0; i != numIterations; i++)
  13705. {
  13706. cachedGraphs.item(i).queryLoopGraph()->afterExecute();
  13707. }
  13708. curStream->stop();
  13709. curInput->reset();
  13710. }
  13711. IFinalRoxieInput * LoopExecutorThread::createLoopIterationGraph(unsigned i, unsigned inputIdx, IFinalRoxieInput * input, unsigned counter)
  13712. {
  13713. if (!cachedGraphs.isItem(i))
  13714. cachedGraphs.append(*activity->createChildGraphInstance());
  13715. Linked<IRoxieServerChildGraph> loopGraph = cachedGraphs.item(i).queryLoopGraph();
  13716. loopGraph->beforeExecute();
  13717. if (!loopGraph->querySetInputResult(1, inputIdx, input))
  13718. throwUnexpected(); // a loop which doesn't use the value from the previous iteration. Should probably handle even if daft.
  13719. activity->createCounterResult(loopGraph, counter);
  13720. return loopGraph->selectOutput(0);
  13721. }
  13722. //=================================================================================
  13723. class CCounterRowMetaData : implements IOutputMetaData, public CInterface
  13724. {
  13725. public:
  13726. IMPLEMENT_IINTERFACE
  13727. virtual size32_t getRecordSize(const void *) { return sizeof(thor_loop_counter_t); }
  13728. virtual size32_t getMinRecordSize() const { return sizeof(thor_loop_counter_t); }
  13729. virtual size32_t getFixedSize() const { return sizeof(thor_loop_counter_t); }
  13730. virtual void toXML(const byte * self, IXmlWriter & out) { }
  13731. virtual unsigned getVersion() const { return OUTPUTMETADATA_VERSION; }
  13732. virtual unsigned getMetaFlags() { return 0; }
  13733. virtual void destruct(byte * self) {}
  13734. virtual IOutputRowSerializer * createDiskSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  13735. virtual IOutputRowDeserializer * createDiskDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  13736. virtual ISourceRowPrefetcher * createDiskPrefetcher(ICodeContext * ctx, unsigned activityId) { return NULL; }
  13737. virtual IOutputMetaData * querySerializedDiskMeta() { return this; }
  13738. virtual IOutputRowSerializer * createInternalSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  13739. virtual IOutputRowDeserializer * createInternalDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  13740. virtual void walkIndirectMembers(const byte * self, IIndirectMemberVisitor & visitor) {}
  13741. virtual IOutputMetaData * queryChildMeta(unsigned i) { return NULL; }
  13742. };
  13743. class CRoxieServerLoopActivityFactory : public CRoxieServerActivityFactory
  13744. {
  13745. unsigned loopGraphId;
  13746. unsigned flags;
  13747. Linked<IOutputMetaData> counterMeta;
  13748. public:
  13749. CRoxieServerLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _loopGraphId)
  13750. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), loopGraphId(_loopGraphId)
  13751. {
  13752. Owned<IHThorLoopArg> helper = (IHThorLoopArg *) helperFactory();
  13753. flags = helper->getFlags();
  13754. counterMeta.setown(new CCounterRowMetaData);
  13755. }
  13756. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  13757. {
  13758. if (flags & IHThorLoopArg::LFparallel)
  13759. return new CRoxieServerParallelLoopActivity(_ctx, this, _probeManager, loopGraphId, counterMeta);
  13760. else
  13761. return new CRoxieServerSequentialLoopActivity(_ctx, this, _probeManager, loopGraphId, counterMeta);
  13762. }
  13763. };
  13764. IRoxieServerActivityFactory *createRoxieServerLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _loopGraphId)
  13765. {
  13766. return new CRoxieServerLoopActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _loopGraphId);
  13767. }
  13768. //=================================================================================
  13769. class CRoxieServerGraphLoopActivity : public CRoxieServerActivity
  13770. {
  13771. protected:
  13772. IHThorGraphLoopArg &helper;
  13773. unsigned maxIterations;
  13774. unsigned flags;
  13775. rtlRowBuilder GraphExtractBuilder;
  13776. unsigned loopGraphId;
  13777. Linked<IOutputMetaData> counterMeta;
  13778. public:
  13779. CRoxieServerGraphLoopActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _GraphGraphId, IOutputMetaData * _counterMeta)
  13780. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  13781. helper((IHThorGraphLoopArg &)basehelper), loopGraphId(_GraphGraphId), counterMeta(_counterMeta)
  13782. {
  13783. flags = helper.getFlags();
  13784. maxIterations = 0;
  13785. }
  13786. virtual bool needsAllocator() const { return true; }
  13787. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13788. {
  13789. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  13790. int iterations = (int) helper.numIterations();
  13791. maxIterations = (iterations >= 0) ? iterations : 0;
  13792. if (maxIterations > maxGraphLoopIterations)
  13793. throw MakeStringException(ROXIE_TOO_MANY_GRAPH_LOOP, "Attempt to execute graph %u times", maxIterations);
  13794. if (maxIterations != 0)
  13795. {
  13796. GraphExtractBuilder.clear();
  13797. helper.createParentExtract(GraphExtractBuilder);
  13798. }
  13799. }
  13800. virtual void stop()
  13801. {
  13802. CRoxieServerActivity::stop();
  13803. GraphExtractBuilder.clear();
  13804. }
  13805. void createCounterResult(IRoxieServerChildGraph * graph, unsigned counter)
  13806. {
  13807. if (flags & IHThorGraphLoopArg::GLFcounter)
  13808. {
  13809. void * counterRow = ctx->queryRowManager().allocate(sizeof(thor_loop_counter_t), activityId);
  13810. *((thor_loop_counter_t *)counterRow) = counter;
  13811. RtlLinkedDatasetBuilder builder(rowAllocator);
  13812. builder.appendOwn(counterRow);
  13813. Owned<CGraphResult> counterResult = new CGraphResult(builder.getcount(), builder.linkrows());
  13814. graph->setInputResult(0, counterResult);
  13815. }
  13816. }
  13817. };
  13818. //=================================================================================
  13819. class CRoxieServerSequentialGraphLoopActivity : public CRoxieServerGraphLoopActivity
  13820. {
  13821. Owned<IActivityGraph> GraphQuery;
  13822. Owned<IRoxieServerChildGraph> loopGraph;
  13823. Linked<IEngineRowStream> resultStream;
  13824. bool evaluated;
  13825. public:
  13826. CRoxieServerSequentialGraphLoopActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _GraphGraphId, IOutputMetaData * _counterMeta)
  13827. : CRoxieServerGraphLoopActivity(_ctx, _factory, _probeManager, _GraphGraphId, _counterMeta)
  13828. {
  13829. evaluated = false;
  13830. }
  13831. virtual void onCreate(IHThorArg *_colocalParent)
  13832. {
  13833. CRoxieServerGraphLoopActivity::onCreate(_colocalParent);
  13834. GraphQuery.set(ctx->queryChildGraph(loopGraphId));
  13835. }
  13836. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13837. {
  13838. CRoxieServerGraphLoopActivity::start(parentExtractSize, parentExtract, paused);
  13839. //MORE: Not sure about this, should IRoxieServerChildGraph be combined with IActivityGraph?
  13840. loopGraph.set(GraphQuery->queryLoopGraph());
  13841. evaluated = false;
  13842. }
  13843. virtual void stop()
  13844. {
  13845. if (loopGraph)
  13846. loopGraph->clearGraphLoopResults();
  13847. CRoxieServerGraphLoopActivity::stop();
  13848. }
  13849. virtual const void * nextRow()
  13850. {
  13851. ActivityTimer t(totalCycles, timeActivities);
  13852. if (!evaluated)
  13853. {
  13854. executeEntireGraph();
  13855. evaluated = true;
  13856. }
  13857. const void * ret = resultStream->nextRow();
  13858. if (ret)
  13859. processed++;
  13860. return ret;
  13861. }
  13862. void executeIteration(unsigned parentExtractSize, const byte *parentExtract, unsigned counter)
  13863. {
  13864. try
  13865. {
  13866. loopGraph->beforeExecute();
  13867. createCounterResult(loopGraph, counter);
  13868. loopGraph->executeGraphLoop(parentExtractSize, parentExtract);
  13869. loopGraph->afterExecute();
  13870. }
  13871. catch (...)
  13872. {
  13873. CTXLOG("Exception thrown in graph body - cleaning up");
  13874. loopGraph->afterExecute();
  13875. throw;
  13876. }
  13877. }
  13878. void createInitialGraphInput()
  13879. {
  13880. loopGraph->clearGraphLoopResults();
  13881. RtlLinkedDatasetBuilder builder(rowAllocator);
  13882. inputStream->readAll(builder);
  13883. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  13884. loopGraph->setGraphLoopResult(0, result);
  13885. }
  13886. void executeEntireGraph()
  13887. {
  13888. createInitialGraphInput();
  13889. for (unsigned loopCounter=1; loopCounter <= maxIterations; loopCounter++)
  13890. {
  13891. executeIteration(GraphExtractBuilder.size(), GraphExtractBuilder.getbytes(), loopCounter);
  13892. }
  13893. resultStream.setown(loopGraph->getGraphLoopResult(maxIterations));
  13894. }
  13895. };
  13896. //=================================================================================
  13897. struct GraphOutputSplitterArg : public ccdserver_hqlhelper::CThorSplitArg
  13898. {
  13899. public:
  13900. virtual unsigned numBranches()
  13901. {
  13902. return 0;
  13903. }
  13904. virtual IOutputMetaData * queryOutputMeta()
  13905. {
  13906. return NULL;// get it from the parent..
  13907. }
  13908. };
  13909. extern "C" IHThorArg * createGraphOutputSplitter() { return new GraphOutputSplitterArg; }
  13910. class CGraphIterationInfo : public CInterface
  13911. {
  13912. private:
  13913. Owned<IRoxieServerActivityFactory> factory; // Note - before sourceAct, so destroyed last
  13914. unsigned sourceIdx;
  13915. Linked<IRoxieServerActivity> sourceAct;
  13916. Linked<IFinalRoxieInput> sourceInput;
  13917. unsigned numUses;
  13918. unsigned iteration;
  13919. public:
  13920. CGraphIterationInfo(IRoxieServerActivity * _sourceAct, IFinalRoxieInput *_input, unsigned _sourceIdx, unsigned _iteration)
  13921. : sourceAct(_sourceAct), sourceInput(_input), sourceIdx(_sourceIdx), iteration(_iteration)
  13922. {
  13923. numUses = 0;
  13924. }
  13925. inline void noteUsed()
  13926. {
  13927. numUses++;
  13928. }
  13929. void createSplitter(IRoxieSlaveContext *ctx, IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes)
  13930. {
  13931. if (numUses > 1)
  13932. {
  13933. Owned<IPropertyTree> splitterNode = createPTree(ipt_fast);
  13934. factory.setown(createRoxieServerThroughSpillActivityFactory(sourceAct->queryFactory()->queryQueryFactory(), createGraphOutputSplitter, numUses, *splitterNode));
  13935. IRoxieServerActivity *splitter = factory->createActivity(ctx, NULL);
  13936. splitter->onCreate(NULL);
  13937. IFinalRoxieInput *input = sourceAct->queryOutput(sourceIdx);
  13938. if (probeManager)
  13939. {
  13940. IRoxieProbe * inputProbe = probeManager->createProbe(static_cast<IInputBase*>(input), sourceAct, splitter, sourceIdx, 0, iteration);
  13941. probes.append(*LINK(inputProbe));
  13942. input = &dynamic_cast<IFinalRoxieInput &>(inputProbe->queryInput());
  13943. sourceIdx = 0;
  13944. }
  13945. sourceAct.setown(splitter);
  13946. sourceAct->setInput(0, sourceIdx, input);
  13947. sourceIdx = 0;
  13948. sourceInput.clear();
  13949. }
  13950. }
  13951. IFinalRoxieInput *connectOutput(IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes, IRoxieServerActivity *targetAct, unsigned targetIdx)
  13952. {
  13953. // MORE - not really necessary to create splitters in separate pass, is it?
  13954. if (factory) // we created a splitter....
  13955. sourceInput.set(sourceAct->queryOutput(sourceIdx));
  13956. IFinalRoxieInput *ret = sourceInput;
  13957. if (probeManager)
  13958. {
  13959. IRoxieProbe * inputProbe = probeManager->createProbe(sourceInput, sourceAct, targetAct, sourceIdx, targetIdx, iteration);
  13960. probes.append(*LINK(inputProbe));
  13961. ret = &dynamic_cast<IFinalRoxieInput &>(inputProbe->queryInput());
  13962. // MORE - do we need to connect the stream in the probe?
  13963. }
  13964. if (factory) // we created a splitter....
  13965. sourceIdx++;
  13966. return ret;
  13967. }
  13968. };
  13969. class CRoxieServerParallelGraphLoopActivity : public CRoxieServerGraphLoopActivity, implements IRoxieServerLoopResultProcessor
  13970. {
  13971. Owned<IActivityGraph> childGraph;
  13972. IFinalRoxieInput * resultInput;
  13973. IEngineRowStream * resultStream;
  13974. Owned<IStrandJunction> resultJunction;
  13975. CIArrayOf<CGraphIterationInfo> outputs;
  13976. IArrayOf<IRoxieServerChildGraph> iterationGraphs;
  13977. Owned<CExtractMapperInput> inputExtractMapper;
  13978. IProbeManager *probeManager;
  13979. unsigned createLoopCounter;
  13980. IArrayOf<IRoxieProbe> probes;
  13981. public:
  13982. CRoxieServerParallelGraphLoopActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _GraphGraphId, IOutputMetaData * _counterMeta)
  13983. : CRoxieServerGraphLoopActivity(_ctx, _factory, _probeManager, _GraphGraphId, _counterMeta), probeManager(_probeManager)
  13984. {
  13985. inputExtractMapper.setown(new CExtractMapperInput);
  13986. resultInput = NULL;
  13987. resultStream = NULL;
  13988. createLoopCounter = 0;
  13989. }
  13990. virtual void onCreate(IHThorArg *_colocalParent)
  13991. {
  13992. CRoxieServerGraphLoopActivity::onCreate(_colocalParent);
  13993. childGraph.set(ctx->queryChildGraph(loopGraphId));
  13994. }
  13995. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  13996. {
  13997. //Input needs to be handled very carefully.....
  13998. //We don't want to call onStart on the input unless it is actually used, so don't use the base CRoxieServerActivity implementation.
  13999. //This activity's input needs to be started with (parentExtractSize, parentExtract), but the elements in the graph need to be started with the
  14000. //GraphExtractBuilder parent extract. So we need to wrap the input in a pseudo-input (inputExtractMapper) that passes through a different
  14001. //parentExtract. Something very similar will be needed for query library calls with streaming inputs when they are implemented.
  14002. assertex(idx == 0);
  14003. inputExtractMapper->setInput(_sourceIdx, _in);
  14004. }
  14005. virtual void connectInputStreams(bool consumerOrdered)
  14006. {
  14007. //NB: inputExtractMapper is not connected at this point - only if/when it is used from within the graph
  14008. CRoxieServerActivity::connectInputStreams(consumerOrdered);
  14009. }
  14010. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  14011. {
  14012. if (idx==0)
  14013. return inputExtractMapper->queryInput();
  14014. else
  14015. return NULL;
  14016. }
  14017. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14018. {
  14019. CRoxieServerGraphLoopActivity::start(parentExtractSize, parentExtract, paused); // initialises GraphExtractBuilder
  14020. inputExtractMapper->setParentExtract(parentExtractSize, parentExtract);
  14021. createExpandedGraph(GraphExtractBuilder.size(), GraphExtractBuilder.getbytes(), probeManager);
  14022. resultInput->start(GraphExtractBuilder.size(), GraphExtractBuilder.getbytes(), paused);
  14023. startJunction(resultJunction);
  14024. }
  14025. virtual void stop()
  14026. {
  14027. if (resultStream)
  14028. resultStream->stop();
  14029. CRoxieServerGraphLoopActivity::stop();
  14030. }
  14031. virtual void reset()
  14032. {
  14033. if (resultInput)
  14034. resultInput->reset();
  14035. resetJunction(resultJunction);
  14036. resultInput = NULL;
  14037. resultStream = NULL;
  14038. resultJunction.clear();
  14039. outputs.kill();
  14040. iterationGraphs.kill(); // must be done after all activities killed
  14041. if (probeManager)
  14042. {
  14043. probeManager->deleteGraph(NULL, (IArrayOf<IInputBase>*)&probes);
  14044. probes.kill();
  14045. }
  14046. CRoxieServerGraphLoopActivity::reset();
  14047. }
  14048. virtual const void * nextRow()
  14049. {
  14050. ActivityTimer t(totalCycles, timeActivities);
  14051. const void * ret = resultStream->nextRow();
  14052. if (ret)
  14053. processed++;
  14054. return ret;
  14055. }
  14056. void createExpandedGraph(unsigned parentExtractSize, const byte *parentExtract, IProbeManager *probeManager)
  14057. {
  14058. //result(0) is the input to the graph.
  14059. resultInput = inputExtractMapper;
  14060. outputs.append(* new CGraphIterationInfo(resultInput->queryActivity(), resultInput, 0, 1));
  14061. for (createLoopCounter=1; createLoopCounter <= maxIterations; createLoopCounter++)
  14062. {
  14063. IRoxieServerChildGraph * graph = childGraph->createGraphLoopInstance(ctx, createLoopCounter, parentExtractSize, parentExtract, *this);
  14064. graph->beforeExecute();
  14065. iterationGraphs.append(*graph);
  14066. graph->gatherIterationUsage(*this);
  14067. CGraphIterationInfo *iteration = graph->selectGraphLoopOutput();
  14068. outputs.append(*iteration);
  14069. }
  14070. createLoopCounter = 0;
  14071. createSplitters(probeManager, probes);
  14072. ForEachItemIn(i2, iterationGraphs)
  14073. iterationGraphs.item(i2).associateIterationOutputs(*this);
  14074. resultInput = outputs.tos().connectOutput(probeManager, probes, this, 0);
  14075. resultStream = connectSingleStream(ctx, resultInput, 0, resultJunction, true);
  14076. }
  14077. void createSplitters(IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes)
  14078. {
  14079. ForEachItemIn(i, outputs)
  14080. {
  14081. CGraphIterationInfo & next = outputs.item(i);
  14082. next.createSplitter(ctx, probeManager, probes);
  14083. }
  14084. }
  14085. //IRoxieServerLoopResultProcessor
  14086. virtual void noteUseIteration(unsigned _whichIteration)
  14087. {
  14088. int whichIteration = (int) _whichIteration; // May go negative - API is unsigned for historical reasons
  14089. if (whichIteration >= 0)
  14090. {
  14091. if (!outputs.isItem(whichIteration))
  14092. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Error reading graph result %d from iteration %d", whichIteration, createLoopCounter);
  14093. outputs.item(whichIteration).noteUsed();
  14094. }
  14095. }
  14096. virtual IFinalRoxieInput* connectIterationOutput(unsigned whichIteration, IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes, IRoxieServerActivity *targetAct, unsigned targetIdx)
  14097. {
  14098. if (outputs.isItem(whichIteration))
  14099. {
  14100. CGraphIterationInfo & next = outputs.item(whichIteration);
  14101. return next.connectOutput(probeManager, probes, targetAct, targetIdx);
  14102. }
  14103. return NULL;
  14104. }
  14105. };
  14106. //=================================================================================
  14107. class CRoxieServerGraphLoopActivityFactory : public CRoxieServerActivityFactory
  14108. {
  14109. unsigned loopGraphId;
  14110. unsigned flags;
  14111. Linked<IOutputMetaData> counterMeta;
  14112. public:
  14113. CRoxieServerGraphLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _loopGraphId)
  14114. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), loopGraphId(_loopGraphId)
  14115. {
  14116. Owned<IHThorGraphLoopArg> helper = (IHThorGraphLoopArg *) helperFactory();
  14117. flags = helper->getFlags();
  14118. counterMeta.setown(new CCounterRowMetaData);
  14119. }
  14120. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  14121. {
  14122. if (kind == TAKparallelgraphloop)
  14123. return new CRoxieServerParallelGraphLoopActivity(_ctx, this, _probeManager, loopGraphId, counterMeta);
  14124. else
  14125. return new CRoxieServerSequentialGraphLoopActivity(_ctx, this, _probeManager, loopGraphId, counterMeta);
  14126. }
  14127. };
  14128. IRoxieServerActivityFactory *createRoxieServerGraphLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _loopGraphId)
  14129. {
  14130. return new CRoxieServerGraphLoopActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _loopGraphId);
  14131. }
  14132. //=====================================================================================================
  14133. class CRoxieServerLibraryCallActivity : public CRoxieServerActivity
  14134. {
  14135. class OutputAdaptor : public CExtractMapperInput
  14136. {
  14137. bool stopped;
  14138. public:
  14139. CRoxieServerLibraryCallActivity *parent;
  14140. IOutputMetaData * meta = nullptr;
  14141. unsigned oid;
  14142. unsigned processed;
  14143. public:
  14144. OutputAdaptor()
  14145. {
  14146. parent = NULL;
  14147. oid = 0;
  14148. init();
  14149. }
  14150. ~OutputAdaptor()
  14151. {
  14152. if (traceStartStop)
  14153. DBGLOG("%p ~OutputAdaptor %d", this, oid);
  14154. if (processed && parent && parent->factory)
  14155. {
  14156. parent->factory->noteProcessed(oid, processed);
  14157. if (parent->ctx)
  14158. parent->ctx->noteProcessed(parent->querySubgraphId(), parent->activityId, oid, processed, 0);
  14159. }
  14160. }
  14161. void setParent(CRoxieServerLibraryCallActivity * _parent, IOutputMetaData * _meta, unsigned _oid)
  14162. {
  14163. parent = _parent;
  14164. meta = _meta;
  14165. oid = _oid;
  14166. }
  14167. void init()
  14168. {
  14169. processed = 0;
  14170. stopped = false;
  14171. }
  14172. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14173. {
  14174. parent->start(oid, parentExtractSize, parentExtract, paused);
  14175. CExtractMapperInput::start(parentExtractSize, parentExtract, paused);
  14176. }
  14177. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  14178. {
  14179. //MORE value of consumerOrdered depends on whether this activity is marked as ordered.
  14180. if (!oid) // Only need to set up once
  14181. {
  14182. parent->connectInputStreams(true); // To handle dependencies etc
  14183. }
  14184. return CExtractMapperInput::getOutputStreams(ctx, 0, streams, nullptr, true, nullptr);
  14185. }
  14186. //This override should not really be needed, but input is set up too late for the call to connect strands
  14187. virtual IOutputMetaData * queryOutputMeta() const
  14188. {
  14189. return meta;
  14190. }
  14191. virtual void stop()
  14192. {
  14193. if (!stopped)
  14194. {
  14195. stopped = true;
  14196. parent->stop(oid); // parent code relies on stop being called exactly once per adaptor, so make sure it is!
  14197. CExtractMapperInput::stop();
  14198. }
  14199. };
  14200. virtual void reset()
  14201. {
  14202. parent->reset(oid);
  14203. CExtractMapperInput::reset();
  14204. init();
  14205. };
  14206. virtual void checkAbort()
  14207. {
  14208. parent->checkAbort();
  14209. }
  14210. };
  14211. IHThorLibraryCallArg &helper;
  14212. unsigned numInputs;
  14213. unsigned numOutputs;
  14214. unsigned numActiveOutputs;
  14215. bool started;
  14216. OutputAdaptor* outputAdaptors;
  14217. CExtractMapperInput * * inputAdaptors;
  14218. bool * inputUsed;
  14219. bool * outputUsed;
  14220. Owned<IException> error;
  14221. CriticalSection crit;
  14222. rtlRowBuilder libraryExtractBuilder;
  14223. Owned<IActivityGraph> libraryGraph;
  14224. const LibraryCallFactoryExtra & extra;
  14225. public:
  14226. CRoxieServerLibraryCallActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs, unsigned _numOutputs, const LibraryCallFactoryExtra & _extra)
  14227. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  14228. helper((IHThorLibraryCallArg &)basehelper), extra(_extra)
  14229. {
  14230. numInputs = _numInputs;
  14231. numOutputs = _numOutputs;
  14232. numActiveOutputs = numOutputs;
  14233. inputAdaptors = new CExtractMapperInput*[numInputs];
  14234. inputUsed = new bool[numInputs];
  14235. for (unsigned i1 = 0; i1 < numInputs; i1++)
  14236. {
  14237. inputAdaptors[i1] = new CExtractMapperInput;
  14238. inputUsed[i1] = false;
  14239. }
  14240. outputAdaptors = new OutputAdaptor[numOutputs];
  14241. outputUsed = new bool[numOutputs];
  14242. for (unsigned i2 = 0; i2 < numOutputs; i2++)
  14243. {
  14244. outputAdaptors[i2].setParent(this, helper.queryOutputMeta(i2), i2);
  14245. outputUsed[i2] = false;
  14246. }
  14247. started = false;
  14248. }
  14249. ~CRoxieServerLibraryCallActivity()
  14250. {
  14251. for (unsigned i1 = 0; i1 < numInputs; i1++)
  14252. ::Release(inputAdaptors[i1]);
  14253. delete [] inputAdaptors;
  14254. delete [] inputUsed;
  14255. delete [] outputAdaptors;
  14256. delete [] outputUsed;
  14257. }
  14258. virtual void onCreate(IHThorArg *_colocalParent)
  14259. {
  14260. CRoxieServerActivity::onCreate(_colocalParent);
  14261. libraryGraph.setown(ctx->getLibraryGraph(extra, this));
  14262. libraryGraph->onCreate(_colocalParent);
  14263. //Now map the inputs and outputs to the adapters
  14264. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  14265. for (unsigned i1=0; i1<numInputs; i1++)
  14266. inputUsed[i1] = graph->querySetInputResult(i1, 0, inputAdaptors[i1]);
  14267. for (unsigned i2=0; i2<numOutputs; i2++)
  14268. {
  14269. unsigned outputIndex = extra.outputs.item(i2);
  14270. Owned<IFinalRoxieInput> output = graph->selectOutput(numInputs+outputIndex);
  14271. outputAdaptors[i2].setInput(0, output); // MORE - no idea if this 0 is right??
  14272. outputAdaptors[i2].connectInputStreams(ctx, true);
  14273. }
  14274. }
  14275. virtual void start(unsigned oid, unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14276. {
  14277. CriticalBlock b(crit);
  14278. if (error)
  14279. throw error.getLink();
  14280. if (factory)
  14281. factory->noteStarted(oid);
  14282. if (!started)
  14283. {
  14284. // even though it is not complete, we don't want to run this again if it fails.
  14285. started = true;
  14286. //see notes on splitter above
  14287. try
  14288. {
  14289. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14290. }
  14291. catch (IException *E)
  14292. {
  14293. #ifdef TRACE_SPLIT
  14294. CTXLOG("spill %d caught exception in start", activityId);
  14295. #endif
  14296. error.set(E);
  14297. throw;
  14298. }
  14299. catch (...)
  14300. {
  14301. IException *E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught in CRoxieServerLibraryCallActivity::start");
  14302. error.set(E);
  14303. throw E;
  14304. }
  14305. //recreate the parent extract, and use it to reinitialize the graphs...
  14306. libraryExtractBuilder.clear();
  14307. helper.createParentExtract(libraryExtractBuilder);
  14308. // 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
  14309. // some inputs before we see start on others.
  14310. for (unsigned i1 = 0; i1 < numInputs; i1++)
  14311. {
  14312. if (inputUsed[i1])
  14313. inputAdaptors[i1]->setParentExtract(parentExtractSize, parentExtract);
  14314. else
  14315. inputAdaptors[i1]->queryInput()->stopall();
  14316. }
  14317. for (unsigned i2 = 0; i2 < numOutputs; i2++)
  14318. outputAdaptors[i2].setParentExtract(libraryExtractBuilder.size(), libraryExtractBuilder.getbytes());
  14319. //call stop on all the unused inputs.
  14320. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  14321. graph->beforeExecute();
  14322. ForEachItemIn(i3, extra.unusedOutputs)
  14323. {
  14324. Owned<IFinalRoxieInput> output = graph->selectOutput(numInputs+extra.unusedOutputs.item(i3));
  14325. output->stopall();
  14326. }
  14327. }
  14328. }
  14329. virtual void stop(unsigned oid)
  14330. {
  14331. CriticalBlock b(crit);
  14332. if (--numActiveOutputs == 0)
  14333. {
  14334. //call stop on all the unused inputs.
  14335. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  14336. graph->beforeExecute();
  14337. ForEachItemIn(i3, extra.unusedOutputs)
  14338. {
  14339. Owned<IFinalRoxieInput> output = graph->selectOutput(numInputs+extra.unusedOutputs.item(i3));
  14340. output->stopall();
  14341. }
  14342. CRoxieServerActivity::stop();
  14343. }
  14344. }
  14345. void reset(unsigned oid)
  14346. {
  14347. started = false;
  14348. error.clear();
  14349. numActiveOutputs = numOutputs;
  14350. if (state != STATEreset) // make sure input is only reset once
  14351. {
  14352. CRoxieServerActivity::reset();
  14353. libraryGraph->reset();
  14354. //Call reset on all unused inputs/outputs from the graph - no one else will.
  14355. for (unsigned i1 = 0; i1 < numInputs; i1++)
  14356. {
  14357. if (!inputUsed[i1])
  14358. inputAdaptors[i1]->reset();
  14359. }
  14360. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  14361. ForEachItemIn(i3, extra.unusedOutputs)
  14362. {
  14363. Owned<IFinalRoxieInput> output = graph->selectOutput(numInputs+extra.unusedOutputs.item(i3));
  14364. output->reset();
  14365. }
  14366. }
  14367. };
  14368. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  14369. {
  14370. inputAdaptors[idx]->setInput(_sourceIdx, _in);
  14371. }
  14372. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  14373. {
  14374. if (idx < numInputs && inputAdaptors[idx])
  14375. return inputAdaptors[idx]->queryInput();
  14376. else
  14377. return NULL;
  14378. }
  14379. public:
  14380. virtual const void *nextRow()
  14381. {
  14382. throwUnexpected(); // Internal logic error - we are not anybody's input
  14383. }
  14384. virtual IOutputMetaData * queryOutputMeta() const
  14385. {
  14386. throwUnexpected(); // should be called on outputs instead
  14387. }
  14388. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  14389. {
  14390. assertex(idx!=(unsigned)-1);
  14391. assertex(!outputUsed[idx]);
  14392. outputUsed[idx] = true;
  14393. return &outputAdaptors[idx];
  14394. }
  14395. };
  14396. void LibraryCallFactoryExtra::set(const LibraryCallFactoryExtra & _other)
  14397. {
  14398. ForEachItemIn(i1, _other.outputs)
  14399. outputs.append(_other.outputs.item(i1));
  14400. ForEachItemIn(i2, _other.unusedOutputs)
  14401. unusedOutputs.append(_other.unusedOutputs.item(i2));
  14402. maxOutputs = _other.maxOutputs;
  14403. graphid = _other.graphid;
  14404. libraryName.set(_other.libraryName);
  14405. embeddedGraphName.set(_other.embeddedGraphName);
  14406. interfaceHash = _other.interfaceHash;
  14407. embedded = _other.embedded;
  14408. }
  14409. void LibraryCallFactoryExtra::calcUnused()
  14410. {
  14411. for (unsigned i=0; i < maxOutputs; i++)
  14412. if (!outputs.contains(i))
  14413. unusedOutputs.append(i);
  14414. }
  14415. class CRoxieServerLibraryCallActivityFactory : public CRoxieServerMultiOutputFactory
  14416. {
  14417. private:
  14418. CRoxieServerMultiInputInfo inputs;
  14419. LibraryCallFactoryExtra extra;
  14420. public:
  14421. CRoxieServerLibraryCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, LibraryCallFactoryExtra & _extra)
  14422. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  14423. {
  14424. extra.set(_extra);
  14425. extra.calcUnused();
  14426. setNumOutputs(extra.outputs.ordinality());
  14427. }
  14428. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  14429. {
  14430. return new CRoxieServerLibraryCallActivity(_ctx, this, _probeManager, numInputs(), numOutputs, extra);
  14431. }
  14432. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  14433. {
  14434. inputs.set(idx, source, sourceidx);
  14435. }
  14436. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  14437. {
  14438. return inputs.get(idx, sourceidx);
  14439. }
  14440. virtual unsigned numInputs() const { return inputs.ordinality(); }
  14441. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  14442. {
  14443. addXrefLibraryInfo(reply, extra.libraryName);
  14444. }
  14445. };
  14446. IRoxieServerActivityFactory *createRoxieServerLibraryCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, LibraryCallFactoryExtra & _extra)
  14447. {
  14448. return new CRoxieServerLibraryCallActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _extra);
  14449. }
  14450. //=====================================================================================================
  14451. // CRoxieServerNWayInputActivity is a multi-input, multi-output activity, where the outputs are a subset of the inputs
  14452. // Used to implement RANGE(<rowset-expression>, [set-of-indices])
  14453. class CRoxieServerNWayInputBaseActivity : public CRoxieServerMultiInputBaseActivity
  14454. {
  14455. protected:
  14456. PointerArrayOf<IFinalRoxieInput> selectedInputs;
  14457. PointerArrayOf<IEngineRowStream> selectedStreams;
  14458. PointerArrayOf<IStrandJunction> selectedJunctions;
  14459. public:
  14460. CRoxieServerNWayInputBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14461. : CRoxieServerMultiInputBaseActivity(_ctx, _factory, _probeManager, _numInputs)
  14462. {
  14463. }
  14464. virtual unsigned __int64 queryLocalCycles() const
  14465. {
  14466. __int64 localCycles = totalCycles.totalCycles;
  14467. ForEachItemIn(i, selectedInputs)
  14468. {
  14469. localCycles -= selectedInputs.item(i)->queryTotalCycles();
  14470. }
  14471. if (localCycles < 0)
  14472. localCycles = 0;
  14473. return localCycles;
  14474. }
  14475. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  14476. {
  14477. if (selectedInputs.isItem(idx))
  14478. return selectedInputs.item(idx);
  14479. else
  14480. return NULL;
  14481. }
  14482. virtual void reset()
  14483. {
  14484. ForEachItemIn(i, selectedInputs)
  14485. selectedInputs.item(i)->reset();
  14486. selectedInputs.kill();
  14487. selectedStreams.kill();
  14488. selectedJunctions.kill();
  14489. CRoxieServerMultiInputBaseActivity::reset();
  14490. }
  14491. virtual const void * nextRow()
  14492. {
  14493. throwUnexpected();
  14494. }
  14495. virtual unsigned numConcreteOutputs() const
  14496. {
  14497. return selectedInputs.ordinality();
  14498. }
  14499. virtual IFinalRoxieInput * queryConcreteInput(unsigned idx)
  14500. {
  14501. return queryInput(idx);
  14502. }
  14503. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput)
  14504. {
  14505. if (selectedStreams.isItem(whichInput))
  14506. return selectedStreams.item(whichInput);
  14507. return NULL;
  14508. }
  14509. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const
  14510. {
  14511. if (selectedJunctions.isItem(idx))
  14512. return selectedJunctions.item(idx);
  14513. return NULL;
  14514. }
  14515. };
  14516. class CRoxieServerNWayInputActivity : public CRoxieServerNWayInputBaseActivity
  14517. {
  14518. IHThorNWayInputArg & helper;
  14519. public:
  14520. CRoxieServerNWayInputActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14521. : CRoxieServerNWayInputBaseActivity(_ctx, _factory, _probeManager, _numInputs), helper((IHThorNWayInputArg &)basehelper)
  14522. {
  14523. }
  14524. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14525. {
  14526. CRoxieServerNWayInputBaseActivity::start(parentExtractSize, parentExtract, paused);
  14527. bool selectionIsAll;
  14528. size32_t selectionLen;
  14529. rtlDataAttr selection;
  14530. helper.getInputSelection(selectionIsAll, selectionLen, selection.refdata());
  14531. selectedInputs.kill();
  14532. selectedStreams.kill();
  14533. selectedJunctions.kill();
  14534. assertex(numInputs==numStreams); // Will need refactoring when that ceases to be true
  14535. if (selectionIsAll)
  14536. {
  14537. for (unsigned i=0; i < numInputs; i++)
  14538. {
  14539. selectedInputs.append(inputArray[i]);
  14540. selectedStreams.append(streamArray[i]); // Assumes 1:1 relationship - is that good?
  14541. selectedJunctions.append(junctionArray[i]);
  14542. }
  14543. }
  14544. else
  14545. {
  14546. const size32_t * selections = (const size32_t *)selection.getdata();
  14547. unsigned max = selectionLen/sizeof(size32_t);
  14548. for (unsigned i = 0; i < max; i++)
  14549. {
  14550. unsigned nextIndex = selections[i];
  14551. //Check there are no duplicates..... Assumes there are a fairly small number of inputs, so n^2 search is ok.
  14552. for (unsigned j=i+1; j < max; j++)
  14553. {
  14554. if (nextIndex == selections[j])
  14555. throw MakeStringException(ROXIE_NWAY_INPUT_ERROR, "Selection list for nway input can not contain duplicates");
  14556. }
  14557. if (nextIndex > numInputs || nextIndex > numStreams)
  14558. throw MakeStringException(ROXIE_NWAY_INPUT_ERROR, "Index %d in RANGE selection list is out of range", nextIndex);
  14559. selectedInputs.append(inputArray[nextIndex-1]);
  14560. selectedStreams.append(streamArray[nextIndex-1]); // Assumes 1:1 relationship - is that good?
  14561. selectedJunctions.append(junctionArray[nextIndex-1]);
  14562. }
  14563. }
  14564. // NB: Whatever pulls this nwayinput activity, starts and stops the selectedInputs and selectedJunctions
  14565. // But the N-Way input itself is now done with processing, and can stop itself/dependencies.
  14566. stop();
  14567. }
  14568. };
  14569. class CRoxieServerNWayInputActivityFactory : public CRoxieServerMultiInputFactory
  14570. {
  14571. public:
  14572. CRoxieServerNWayInputActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  14573. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  14574. {
  14575. }
  14576. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  14577. {
  14578. return new CRoxieServerNWayInputActivity(_ctx, this, _probeManager, numInputs());
  14579. }
  14580. };
  14581. IRoxieServerActivityFactory *createRoxieServerNWayInputActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  14582. {
  14583. return new CRoxieServerNWayInputActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  14584. }
  14585. //=====================================================================================================
  14586. class CRoxieServerNWayGraphLoopResultReadActivity : public CRoxieServerNWayInputBaseActivity
  14587. {
  14588. IHThorNWayGraphLoopResultReadArg & helper;
  14589. IArrayOf<IRoxieServerActivity> resultReaders;
  14590. Owned<IStrandJunction> *resultJunctions;
  14591. unsigned graphId;
  14592. bool grouped;
  14593. bool selectionIsAll;
  14594. size32_t selectionLen;
  14595. rtlDataAttr selection;
  14596. public:
  14597. CRoxieServerNWayGraphLoopResultReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId)
  14598. : CRoxieServerNWayInputBaseActivity(_ctx, _factory, _probeManager, 0), helper((IHThorNWayGraphLoopResultReadArg &)basehelper)
  14599. {
  14600. grouped = helper.isGrouped();
  14601. graphId = _graphId;
  14602. selectionIsAll = false;
  14603. selectionLen = 0;
  14604. resultJunctions = NULL;
  14605. }
  14606. ~CRoxieServerNWayGraphLoopResultReadActivity()
  14607. {
  14608. delete [] resultJunctions;
  14609. }
  14610. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14611. {
  14612. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14613. if (selectedInputs.ordinality() == 0)
  14614. {
  14615. initInputSelection();
  14616. unsigned max = selectionLen / sizeof(size32_t);
  14617. const size32_t * selections = (const size32_t *)selection.getdata();
  14618. IProbeManager * probeManager = NULL; // MORE!!
  14619. for (unsigned i = 0; i < max; i++)
  14620. {
  14621. CRoxieServerActivity * resultInput = new CRoxieServerInternalGraphLoopResultReadActivity(ctx, factory, probeManager, graphId, selections[i]);
  14622. resultReaders.append(*resultInput);
  14623. selectedInputs.append(resultInput);
  14624. resultInput->onCreate(colocalParent);
  14625. resultInput->start(parentExtractSize, parentExtract, paused);
  14626. selectedStreams.append(connectSingleStream(ctx, resultInput, 0, resultJunctions[i], true));
  14627. selectedJunctions.append(resultJunctions[i]);
  14628. }
  14629. }
  14630. // I have done with my processing - note that this won't stop my inputs
  14631. stop();
  14632. }
  14633. virtual void reset()
  14634. {
  14635. resultReaders.kill();
  14636. CRoxieServerNWayInputBaseActivity::reset();
  14637. ForEachItemIn(i, selectedStreams)
  14638. resetJunction(resultJunctions[i]);
  14639. }
  14640. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract)
  14641. {
  14642. ensureCreated();
  14643. basehelper.onStart(parentExtract, NULL);
  14644. initInputSelection();
  14645. unsigned max = selectionLen / sizeof(size32_t);
  14646. const size32_t * selections = (const size32_t *)selection.getdata();
  14647. for (unsigned i = 0; i < max; i++)
  14648. processor.noteUseIteration(selections[i]);
  14649. }
  14650. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract, IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes)
  14651. {
  14652. //selection etc. already initialised from the gatherIterationUsage() call.
  14653. unsigned max = selectionLen / sizeof(size32_t);
  14654. const size32_t * selections = (const size32_t *)selection.getdata();
  14655. resultJunctions = new Owned<IStrandJunction> [max];
  14656. for (unsigned i = 0; i < max; i++)
  14657. {
  14658. IFinalRoxieInput *in = processor.connectIterationOutput(selections[i], probeManager, probes, this, i);
  14659. selectedInputs.append(in);
  14660. selectedStreams.append(connectSingleStream(ctx, in, 0, resultJunctions[i], true));
  14661. selectedJunctions.append(resultJunctions[i]);
  14662. }
  14663. }
  14664. protected:
  14665. void initInputSelection()
  14666. {
  14667. helper.getInputSelection(selectionIsAll, selectionLen, selection.refdata());
  14668. if (selectionIsAll)
  14669. throw MakeStringException(ROXIE_NWAY_INPUT_ERROR, "ALL not yet supported for NWay graph inputs");
  14670. }
  14671. };
  14672. class CRoxieServerNWayGraphLoopResultReadActivityFactory : public CRoxieServerActivityFactory
  14673. {
  14674. unsigned graphId;
  14675. public:
  14676. CRoxieServerNWayGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _graphId)
  14677. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), graphId(_graphId)
  14678. {
  14679. }
  14680. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  14681. {
  14682. return new CRoxieServerNWayGraphLoopResultReadActivity(_ctx, this, _probeManager, graphId);
  14683. }
  14684. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  14685. {
  14686. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for NWay GraphLoopResultRead activity");
  14687. }
  14688. };
  14689. IRoxieServerActivityFactory *createRoxieServerNWayGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned graphId)
  14690. {
  14691. return new CRoxieServerNWayGraphLoopResultReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, graphId);
  14692. }
  14693. //=================================================================================
  14694. class RoxieSteppedInput : implements ISteppedInput, public CInterface
  14695. {
  14696. public:
  14697. RoxieSteppedInput(IFinalRoxieInput * _input, IEngineRowStream *_stream) { input = _input; inputStream = _stream; }
  14698. IMPLEMENT_IINTERFACE
  14699. protected:
  14700. virtual const void * nextInputRow()
  14701. {
  14702. #ifdef TRACE_SEEK_REQUESTS
  14703. IRoxieContextLogger * logger = input->queryActivity();
  14704. const void * ret = doNextInputRow();
  14705. {
  14706. CommonXmlWriter xmlwrite(XWFtrim|XWFopt|XWFnoindent);
  14707. if (!ret)
  14708. xmlwrite.outputBool(true,"eof");
  14709. else if (input->queryOutputMeta()->hasXML())
  14710. input->queryOutputMeta()->toXML((byte *) ret, xmlwrite);
  14711. logger->CTXLOG("next() returns (%s)", xmlwrite.str());
  14712. }
  14713. return ret;
  14714. #else
  14715. return inputStream->ungroupedNextRow();
  14716. #endif
  14717. }
  14718. virtual const void * nextInputRowGE(const void * seek, unsigned numFields, bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  14719. {
  14720. #ifdef TRACE_SEEK_REQUESTS
  14721. IRoxieContextLogger * logger = input->queryActivity();
  14722. {
  14723. CommonXmlWriter xmlwrite(XWFtrim|XWFopt|XWFnoindent);
  14724. if (input->queryOutputMeta()->hasXML())
  14725. input->queryOutputMeta()->toXML((byte *) seek, xmlwrite);
  14726. logger->CTXLOG("nextInputRowGE(%d, %s%s%s, %s) seek(%s)",
  14727. numFields,
  14728. stepExtra.readAheadManyResults() ? "readahead " : "",
  14729. stepExtra.returnMismatches() ? "mismatch" : "exact",
  14730. stepExtra.onlyReturnFirstSeekMatch() ? " single-match" : "",
  14731. stepExtra.queryExtraSeeks() ? "multi-seek":"",
  14732. xmlwrite.str());
  14733. }
  14734. const void * ret = doNextInputRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  14735. {
  14736. CommonXmlWriter xmlwrite(XWFtrim|XWFopt|XWFnoindent);
  14737. if (!ret)
  14738. xmlwrite.outputBool(true,"eof");
  14739. else if (input->queryOutputMeta()->hasXML())
  14740. input->queryOutputMeta()->toXML((byte *) ret, xmlwrite);
  14741. logger->CTXLOG("nextInputRowGE(%d, %s%s%s, %s) result(%s)",
  14742. numFields,
  14743. stepExtra.readAheadManyResults() ? "readahead " : "",
  14744. stepExtra.returnMismatches() ? "mismatch" : "exact",
  14745. stepExtra.onlyReturnFirstSeekMatch() ? " single-match" : "",
  14746. stepExtra.queryExtraSeeks() ? "multi-seek":"",
  14747. xmlwrite.str());
  14748. }
  14749. return ret;
  14750. #else
  14751. return doNextInputRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  14752. #endif
  14753. }
  14754. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  14755. {
  14756. return input->gatherConjunctions(collector);
  14757. }
  14758. virtual void resetEOF()
  14759. {
  14760. inputStream->resetEOF();
  14761. }
  14762. virtual IInputSteppingMeta * queryInputSteppingMeta()
  14763. {
  14764. return input->querySteppingMeta();
  14765. }
  14766. inline const void * doNextInputRowGE(const void * seek, unsigned numFields, bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  14767. {
  14768. assertex(wasCompleteMatch);
  14769. return inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  14770. }
  14771. protected:
  14772. IFinalRoxieInput * input;
  14773. IEngineRowStream * inputStream;
  14774. };
  14775. //=================================================================================
  14776. class CRoxieServerNWayBaseActivity : public CRoxieServerMultiInputBaseActivity
  14777. {
  14778. public:
  14779. CRoxieServerNWayBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14780. : CRoxieServerMultiInputBaseActivity(_ctx, _factory, _probeManager, _numInputs)
  14781. {
  14782. }
  14783. void startExpandedInputs(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14784. {
  14785. ForEachItemIn(ei, expandedInputs)
  14786. expandedInputs.item(ei)->start(parentExtractSize, parentExtract, paused);
  14787. ForEachItemIn(idx, expandedInputs)
  14788. startJunction(expandedJunctions.item(idx));
  14789. }
  14790. virtual void stop()
  14791. {
  14792. ForEachItemIn(i, expandedStreams)
  14793. expandedStreams.item(i)->stop();
  14794. CRoxieServerMultiInputBaseActivity::stop();
  14795. }
  14796. virtual void reset()
  14797. {
  14798. ForEachItemIn(idx, expandedInputs)
  14799. resetJunction(expandedJunctions.item(idx));
  14800. expandedInputs.kill();
  14801. expandedStreams.kill();
  14802. expandedJunctions.kill();
  14803. CRoxieServerMultiInputBaseActivity::reset();
  14804. }
  14805. protected:
  14806. PointerArrayOf<IFinalRoxieInput> expandedInputs;
  14807. PointerArrayOf<IEngineRowStream> expandedStreams;
  14808. PointerArrayOf<IStrandJunction> expandedJunctions;
  14809. };
  14810. //=================================================================================
  14811. class CRoxieServerNaryActivity : public CRoxieServerNWayBaseActivity
  14812. {
  14813. public:
  14814. CRoxieServerNaryActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14815. : CRoxieServerNWayBaseActivity(_ctx, _factory, _probeManager, _numInputs)
  14816. {
  14817. }
  14818. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14819. {
  14820. CRoxieServerNWayBaseActivity::start(parentExtractSize, parentExtract, paused);
  14821. for (unsigned i=0; i < numInputs; i++)
  14822. {
  14823. IFinalRoxieInput * cur = inputArray[i];
  14824. CRoxieServerNWayInputBaseActivity *nWayInput = dynamic_cast<CRoxieServerNWayInputBaseActivity *>(cur);
  14825. if (nWayInput)
  14826. {
  14827. nWayInput->start(parentExtractSize, parentExtract, paused);
  14828. unsigned numRealInputs = cur->numConcreteOutputs();
  14829. for (unsigned j = 0; j < numRealInputs; j++)
  14830. {
  14831. expandedInputs.append(cur->queryConcreteInput(j));
  14832. expandedStreams.append(cur->queryConcreteOutputStream(j));
  14833. expandedJunctions.append(cur->queryConcreteOutputJunction(j));
  14834. }
  14835. }
  14836. else
  14837. {
  14838. expandedInputs.append(cur);
  14839. // NB: this activities input streams + junction have been setup and held in CRoxieServerMultiInputActivity base
  14840. expandedStreams.append(queryConcreteOutputStream(i));
  14841. expandedJunctions.append(queryConcreteOutputJunction(i));
  14842. }
  14843. }
  14844. startExpandedInputs(parentExtractSize, parentExtract, paused);
  14845. }
  14846. };
  14847. //=================================================================================
  14848. class CRoxieStreamMerger : public CStreamMerger
  14849. {
  14850. public:
  14851. CRoxieStreamMerger() : CStreamMerger(true)
  14852. {
  14853. streamArray = NULL;
  14854. }
  14855. void initInputs(unsigned _numInputs, IEngineRowStream ** _streamArray)
  14856. {
  14857. CStreamMerger::initInputs(_numInputs);
  14858. streamArray = _streamArray;
  14859. }
  14860. virtual bool pullInput(unsigned i, const void * seek, unsigned numFields, const SmartStepExtra * stepExtra)
  14861. {
  14862. const void * next;
  14863. bool matches = true;
  14864. if (seek)
  14865. next = streamArray[i]->nextRowGE(seek, numFields, matches, *stepExtra);
  14866. else
  14867. next = streamArray[i]->ungroupedNextRow();
  14868. pending[i] = next;
  14869. pendingMatches[i] = matches;
  14870. return (next != NULL);
  14871. }
  14872. virtual void releaseRow(const void * row)
  14873. {
  14874. ReleaseRoxieRow(row);
  14875. }
  14876. protected:
  14877. IEngineRowStream **streamArray;
  14878. };
  14879. class CRoxieServerNWayMergeActivity : public CRoxieServerNaryActivity
  14880. {
  14881. public:
  14882. CRoxieServerNWayMergeActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14883. : CRoxieServerNaryActivity(_ctx, _factory, _probeManager, _numInputs),
  14884. helper((IHThorNWayMergeArg &)basehelper)
  14885. {
  14886. initializedMeta = false;
  14887. }
  14888. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14889. {
  14890. CRoxieServerNaryActivity::start(parentExtractSize, parentExtract, paused);
  14891. merger.init(helper.queryCompare(), helper.dedup(), helper.querySteppingMeta()->queryCompare());
  14892. merger.initInputs(expandedStreams.length(), expandedStreams.getArray());
  14893. }
  14894. virtual void stop()
  14895. {
  14896. merger.done();
  14897. CRoxieServerNaryActivity::stop();
  14898. }
  14899. virtual void reset()
  14900. {
  14901. merger.cleanup();
  14902. CRoxieServerNaryActivity::reset();
  14903. initializedMeta = false;
  14904. }
  14905. virtual const void * nextRow()
  14906. {
  14907. ActivityTimer t(totalCycles, timeActivities);
  14908. const void * next = merger.nextRow();
  14909. if (next)
  14910. processed++;
  14911. return next;
  14912. }
  14913. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  14914. {
  14915. ActivityTimer t(totalCycles, timeActivities);
  14916. const void * next = merger.nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  14917. if (next)
  14918. processed++;
  14919. return next;
  14920. }
  14921. virtual IInputSteppingMeta * querySteppingMeta()
  14922. {
  14923. if (expandedStreams.ordinality() == 0)
  14924. return NULL;
  14925. if (!initializedMeta)
  14926. {
  14927. meta.init(helper.querySteppingMeta(), false);
  14928. ForEachItemIn(i, expandedStreams)
  14929. {
  14930. if (meta.getNumFields() == 0)
  14931. break;
  14932. IInputSteppingMeta * inputMeta = expandedInputs.item(i)->querySteppingMeta();
  14933. meta.intersect(inputMeta);
  14934. }
  14935. initializedMeta = true;
  14936. }
  14937. if (meta.getNumFields() == 0)
  14938. return NULL;
  14939. return &meta;
  14940. }
  14941. protected:
  14942. IHThorNWayMergeArg &helper;
  14943. CRoxieStreamMerger merger;
  14944. CSteppingMeta meta;
  14945. bool initializedMeta;
  14946. };
  14947. class CRoxieServerNWayMergeActivityFactory : public CRoxieServerMultiInputFactory
  14948. {
  14949. public:
  14950. CRoxieServerNWayMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  14951. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  14952. {
  14953. }
  14954. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  14955. {
  14956. return new CRoxieServerNWayMergeActivity(_ctx, this, _probeManager, numInputs());
  14957. }
  14958. };
  14959. IRoxieServerActivityFactory *createRoxieServerNWayMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  14960. {
  14961. return new CRoxieServerNWayMergeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  14962. }
  14963. //=================================================================================
  14964. class CRoxieServerNWayMergeJoinActivity : public CRoxieServerNaryActivity
  14965. {
  14966. public:
  14967. CRoxieServerNWayMergeJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs, CMergeJoinProcessor & _processor)
  14968. : CRoxieServerNaryActivity(_ctx, _factory, _probeManager, _numInputs),processor(_processor),
  14969. helper((IHThorNWayMergeJoinArg &)basehelper)
  14970. {
  14971. }
  14972. virtual void onCreate(IHThorArg *_colocalParent)
  14973. {
  14974. CRoxieServerNaryActivity::onCreate(_colocalParent);
  14975. ICodeContext * codectx = ctx->queryCodeContext();
  14976. inputAllocator.setown(createRowAllocator(helper.queryInputMeta()));
  14977. outputAllocator.setown(createRowAllocator(helper.queryOutputMeta()));
  14978. }
  14979. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14980. {
  14981. CRoxieServerNaryActivity::start(parentExtractSize, parentExtract, paused);
  14982. ForEachItemIn(i1, expandedInputs)
  14983. {
  14984. Owned<RoxieSteppedInput> stepInput = new RoxieSteppedInput(expandedInputs.item(i1), expandedStreams.item(i1));
  14985. processor.addInput(stepInput);
  14986. }
  14987. processor.beforeProcessing(inputAllocator, outputAllocator);
  14988. }
  14989. virtual void stop()
  14990. {
  14991. processor.afterProcessing();
  14992. CRoxieServerNaryActivity::stop();
  14993. }
  14994. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  14995. {
  14996. return processor.gatherConjunctions(collector);
  14997. }
  14998. virtual void resetEOF()
  14999. {
  15000. processor.queryResetEOF();
  15001. }
  15002. virtual const void * nextRow()
  15003. {
  15004. ActivityTimer t(totalCycles, timeActivities);
  15005. const void * next = processor.nextRow();
  15006. if (next)
  15007. processed++;
  15008. return next;
  15009. }
  15010. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  15011. {
  15012. ActivityTimer t(totalCycles, timeActivities);
  15013. const void * next = processor.nextGE(seek, numFields, wasCompleteMatch, stepExtra);
  15014. if (next)
  15015. processed++;
  15016. return next;
  15017. }
  15018. virtual IInputSteppingMeta * querySteppingMeta()
  15019. {
  15020. return processor.queryInputSteppingMeta();
  15021. }
  15022. protected:
  15023. IHThorNWayMergeJoinArg & helper;
  15024. CMergeJoinProcessor & processor;
  15025. Owned<IEngineRowAllocator> inputAllocator;
  15026. Owned<IEngineRowAllocator> outputAllocator;
  15027. };
  15028. class CRoxieServerAndMergeJoinActivity : public CRoxieServerNWayMergeJoinActivity
  15029. {
  15030. public:
  15031. CRoxieServerAndMergeJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  15032. : CRoxieServerNWayMergeJoinActivity(_ctx, _factory, _probeManager, _numInputs, andProcessor), andProcessor(helper)
  15033. {
  15034. }
  15035. protected:
  15036. CAndMergeJoinProcessor andProcessor;
  15037. };
  15038. class CRoxieServerAndLeftMergeJoinActivity : public CRoxieServerNWayMergeJoinActivity
  15039. {
  15040. public:
  15041. CRoxieServerAndLeftMergeJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  15042. : CRoxieServerNWayMergeJoinActivity(_ctx, _factory, _probeManager, _numInputs, andLeftProcessor), andLeftProcessor(helper)
  15043. {
  15044. }
  15045. protected:
  15046. CAndLeftMergeJoinProcessor andLeftProcessor;
  15047. };
  15048. class CRoxieServerMofNMergeJoinActivity : public CRoxieServerNWayMergeJoinActivity
  15049. {
  15050. public:
  15051. CRoxieServerMofNMergeJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  15052. : CRoxieServerNWayMergeJoinActivity(_ctx, _factory, _probeManager, _numInputs, mofnProcessor), mofnProcessor(helper)
  15053. {
  15054. }
  15055. protected:
  15056. CMofNMergeJoinProcessor mofnProcessor;
  15057. };
  15058. class CRoxieServerProximityJoinActivity : public CRoxieServerNWayMergeJoinActivity
  15059. {
  15060. public:
  15061. CRoxieServerProximityJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  15062. : CRoxieServerNWayMergeJoinActivity(_ctx, _factory, _probeManager, _numInputs, proximityProcessor), proximityProcessor(helper)
  15063. {
  15064. }
  15065. protected:
  15066. CProximityJoinProcessor proximityProcessor;
  15067. };
  15068. class CRoxieServerNWayMergeJoinActivityFactory : public CRoxieServerMultiInputFactory
  15069. {
  15070. unsigned flags;
  15071. public:
  15072. CRoxieServerNWayMergeJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15073. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15074. {
  15075. Owned<IHThorNWayMergeJoinArg> helper = (IHThorNWayMergeJoinArg *) helperFactory();
  15076. flags = helper->getJoinFlags();
  15077. }
  15078. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15079. {
  15080. if (flags & IHThorNWayMergeJoinArg::MJFhasrange)
  15081. return new CRoxieServerProximityJoinActivity(_ctx, this, _probeManager, numInputs());
  15082. switch (flags & IHThorNWayMergeJoinArg::MJFkindmask)
  15083. {
  15084. case IHThorNWayMergeJoinArg::MJFinner:
  15085. return new CRoxieServerAndMergeJoinActivity(_ctx, this, _probeManager, numInputs());
  15086. case IHThorNWayMergeJoinArg::MJFleftonly:
  15087. case IHThorNWayMergeJoinArg::MJFleftouter:
  15088. return new CRoxieServerAndLeftMergeJoinActivity(_ctx, this, _probeManager, numInputs());
  15089. case IHThorNWayMergeJoinArg::MJFmofn:
  15090. return new CRoxieServerMofNMergeJoinActivity(_ctx, this, _probeManager, numInputs());
  15091. default:
  15092. throwUnexpected();
  15093. }
  15094. }
  15095. };
  15096. IRoxieServerActivityFactory *createRoxieServerNWayMergeJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15097. {
  15098. return new CRoxieServerNWayMergeJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15099. }
  15100. //=================================================================================
  15101. class CRoxieServerNWaySelectActivity : public CRoxieServerNWayBaseActivity
  15102. {
  15103. IHThorNWaySelectArg &helper;
  15104. public:
  15105. CRoxieServerNWaySelectActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  15106. : CRoxieServerNWayBaseActivity(_ctx, _factory, _probeManager, _numInputs),
  15107. helper((IHThorNWaySelectArg &)basehelper)
  15108. {
  15109. }
  15110. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15111. {
  15112. CRoxieServerNWayBaseActivity::start(parentExtractSize, parentExtract, paused);
  15113. unsigned whichInput = helper.getInputIndex();
  15114. selectedInput = nullptr;
  15115. selectedStream = nullptr;
  15116. if (whichInput--)
  15117. {
  15118. for (unsigned i=0; i < numInputs; i++)
  15119. {
  15120. IFinalRoxieInput * cur = inputArray[i];
  15121. CRoxieServerNWayInputBaseActivity *nWayInput = dynamic_cast<CRoxieServerNWayInputBaseActivity *>(cur);
  15122. if (nWayInput)
  15123. {
  15124. nWayInput->start(parentExtractSize, parentExtract, paused);
  15125. unsigned numRealInputs = cur->numConcreteOutputs();
  15126. if (whichInput < numRealInputs)
  15127. {
  15128. expandedInputs.append(cur->queryConcreteInput(whichInput));
  15129. expandedStreams.append(cur->queryConcreteOutputStream(whichInput));
  15130. expandedJunctions.append(cur->queryConcreteOutputJunction(whichInput));
  15131. break;
  15132. }
  15133. whichInput -= numRealInputs;
  15134. }
  15135. else
  15136. {
  15137. if (whichInput == 0)
  15138. {
  15139. expandedInputs.append(cur);
  15140. // NB: this activities input streams + junction have been setup and held in CRoxieServerMultiInputActivity base
  15141. expandedStreams.append(queryConcreteOutputStream(i));
  15142. expandedJunctions.append(queryConcreteOutputJunction(i));
  15143. break;
  15144. }
  15145. whichInput -= 1;
  15146. }
  15147. }
  15148. }
  15149. if (expandedInputs.ordinality())
  15150. {
  15151. startExpandedInputs(parentExtractSize, parentExtract, paused);
  15152. selectedInput = expandedInputs.item(0);
  15153. selectedStream = expandedStreams.item(0);
  15154. }
  15155. }
  15156. const void * nextRow()
  15157. {
  15158. ActivityTimer t(totalCycles, timeActivities);
  15159. if (!selectedStream)
  15160. return NULL;
  15161. return selectedStream->nextRow();
  15162. }
  15163. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  15164. {
  15165. if (!selectedInput)
  15166. return false;
  15167. return selectedInput->gatherConjunctions(collector);
  15168. }
  15169. virtual void resetEOF()
  15170. {
  15171. if (selectedStream)
  15172. selectedStream->resetEOF();
  15173. }
  15174. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  15175. {
  15176. ActivityTimer t(totalCycles, timeActivities);
  15177. if (!selectedStream)
  15178. return NULL;
  15179. return selectedStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  15180. }
  15181. IInputSteppingMeta * querySteppingMeta()
  15182. {
  15183. if (selectedInput)
  15184. return selectedInput->querySteppingMeta();
  15185. return NULL;
  15186. }
  15187. protected:
  15188. IFinalRoxieInput * selectedInput = nullptr;
  15189. IEngineRowStream * selectedStream = nullptr;
  15190. Owned<IStrandJunction> selectedJunction;
  15191. };
  15192. class CRoxieServerNWaySelectActivityFactory : public CRoxieServerMultiInputFactory
  15193. {
  15194. public:
  15195. CRoxieServerNWaySelectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15196. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15197. {
  15198. }
  15199. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15200. {
  15201. return new CRoxieServerNWaySelectActivity(_ctx, this, _probeManager, numInputs());
  15202. }
  15203. };
  15204. IRoxieServerActivityFactory *createRoxieServerNWaySelectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15205. {
  15206. return new CRoxieServerNWaySelectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15207. }
  15208. //=================================================================================
  15209. class CRoxieServerRemoteActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler
  15210. {
  15211. protected:
  15212. IHThorRemoteArg &helper;
  15213. CRemoteResultAdaptor remote;
  15214. public:
  15215. CRoxieServerRemoteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteID)
  15216. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  15217. helper((IHThorRemoteArg &)basehelper),
  15218. remote(_ctx, this, _remoteID, meta.queryOriginal(), helper, *this, false, false) // MORE - if they need it stable we'll have to think!
  15219. {
  15220. }
  15221. virtual const IResolvedFile *queryVarFileInfo() const
  15222. {
  15223. return NULL;
  15224. }
  15225. virtual void onCreate(IHThorArg *_colocalParent)
  15226. {
  15227. CRoxieServerActivity::onCreate(_colocalParent);
  15228. remote.onCreate(_colocalParent);
  15229. }
  15230. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15231. {
  15232. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  15233. remote.onStart(parentExtractSize, parentExtract);
  15234. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  15235. unsigned fileNo = 0; // MORE - superfiles require us to do this per file part... maybe (needs thought)
  15236. remote.getMem(0, fileNo, 0); // the cached context is all we need to send
  15237. remote.flush();
  15238. remote.senddone();
  15239. }
  15240. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  15241. {
  15242. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  15243. }
  15244. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  15245. {
  15246. if (idx==(unsigned)-1)
  15247. idx = 0;
  15248. return idx ? NULL: &remote;
  15249. }
  15250. virtual void reset()
  15251. {
  15252. processed = remote.processed;
  15253. remote.processed = 0;
  15254. CRoxieServerActivity::reset();
  15255. }
  15256. virtual void onLimitExceeded(bool isKeyed)
  15257. {
  15258. if (traceLevel > 4)
  15259. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  15260. helper.onLimitExceeded();
  15261. }
  15262. virtual const void *createLimitFailRow(bool isKeyed)
  15263. {
  15264. UNIMPLEMENTED; // MORE - is there an ONFAIL for a limit folded into a remote?
  15265. }
  15266. virtual const void *nextRow()
  15267. {
  15268. throwUnexpected(); // I am nobody's input
  15269. }
  15270. };
  15271. class CRoxieServerRemoteActivityFactory : public CRoxieServerActivityFactory
  15272. {
  15273. public:
  15274. RemoteActivityId remoteId;
  15275. bool isRoot;
  15276. CRoxieServerRemoteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId, bool _isRoot)
  15277. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), remoteId(_remoteId), isRoot(_isRoot)
  15278. {
  15279. }
  15280. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15281. {
  15282. return new CRoxieServerRemoteActivity(_ctx, this, _probeManager, remoteId);
  15283. }
  15284. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  15285. {
  15286. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  15287. }
  15288. virtual bool isSink() const
  15289. {
  15290. //I don't think the action version of this is implemented - but this would be the code
  15291. return isRoot && !meta.queryOriginal();
  15292. }
  15293. virtual const StatisticsMapping &queryStatsMapping() const
  15294. {
  15295. return allStatistics; // Child queries...
  15296. }
  15297. };
  15298. IRoxieServerActivityFactory *createRoxieServerRemoteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId, bool _isRoot)
  15299. {
  15300. return new CRoxieServerRemoteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId, _isRoot);
  15301. }
  15302. //=================================================================================
  15303. class CRoxieServerIterateActivity : public CRoxieServerActivity
  15304. {
  15305. IHThorIterateArg &helper;
  15306. OwnedConstRoxieRow defaultRecord;
  15307. OwnedConstRoxieRow left;
  15308. OwnedConstRoxieRow right;
  15309. unsigned counter;
  15310. public:
  15311. CRoxieServerIterateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  15312. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  15313. helper((IHThorIterateArg &)basehelper)
  15314. {
  15315. counter = 0;
  15316. }
  15317. virtual bool needsAllocator() const { return true; }
  15318. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15319. {
  15320. counter = 0;
  15321. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  15322. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15323. size32_t thisSize = helper.createDefault(rowBuilder);
  15324. defaultRecord.setown(rowBuilder.finalizeRowClear(thisSize));
  15325. }
  15326. virtual void reset()
  15327. {
  15328. defaultRecord.clear();
  15329. right.clear();
  15330. left.clear();
  15331. CRoxieServerActivity::reset();
  15332. }
  15333. virtual const void * nextRow()
  15334. {
  15335. ActivityTimer t(totalCycles, timeActivities);
  15336. for (;;)
  15337. {
  15338. right.setown(inputStream->nextRow());
  15339. if (!right)
  15340. {
  15341. bool skippedGroup = (left == NULL) && (counter > 0); //we have just skipped entire group, but shouldn't output a double null
  15342. left.clear();
  15343. counter = 0;
  15344. if (skippedGroup) continue;
  15345. return NULL;
  15346. }
  15347. try
  15348. {
  15349. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15350. unsigned outSize = helper.transform(rowBuilder, left ? left : defaultRecord, right, ++counter);
  15351. if (outSize)
  15352. {
  15353. left.setown(rowBuilder.finalizeRowClear(outSize));
  15354. processed++;
  15355. return left.getLink();
  15356. }
  15357. }
  15358. catch (IException *E)
  15359. {
  15360. throw makeWrappedException(E);
  15361. }
  15362. }
  15363. }
  15364. };
  15365. class CRoxieServerIterateActivityFactory : public CRoxieServerActivityFactory
  15366. {
  15367. public:
  15368. CRoxieServerIterateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15369. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15370. {
  15371. }
  15372. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15373. {
  15374. return new CRoxieServerIterateActivity(_ctx, this, _probeManager);
  15375. }
  15376. };
  15377. IRoxieServerActivityFactory *createRoxieServerIterateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15378. {
  15379. return new CRoxieServerIterateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15380. }
  15381. //=================================================================================
  15382. class CRoxieServerProcessActivity : public CRoxieServerActivity
  15383. {
  15384. IHThorProcessArg &helper;
  15385. OwnedConstRoxieRow curRight;
  15386. OwnedConstRoxieRow initialRight;
  15387. unsigned counter;
  15388. Owned<IEngineRowAllocator> rightRowAllocator;
  15389. public:
  15390. CRoxieServerProcessActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  15391. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorProcessArg &)basehelper)
  15392. {
  15393. counter = 0;
  15394. }
  15395. virtual bool needsAllocator() const { return true; }
  15396. virtual void onCreate(IHThorArg *_colocalParent)
  15397. {
  15398. CRoxieServerActivity::onCreate(_colocalParent);
  15399. rightRowAllocator.setown(createRowAllocator(helper.queryRightRecordSize()));
  15400. }
  15401. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15402. {
  15403. counter = 0;
  15404. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  15405. RtlDynamicRowBuilder rowBuilder(rightRowAllocator);
  15406. size32_t thisSize = helper.createInitialRight(rowBuilder);
  15407. initialRight.setown(rowBuilder.finalizeRowClear(thisSize));
  15408. curRight.set(initialRight);
  15409. }
  15410. virtual const void * nextRow()
  15411. {
  15412. ActivityTimer t(totalCycles, timeActivities);
  15413. try
  15414. {
  15415. for (;;)
  15416. {
  15417. const void * in = inputStream->nextRow();
  15418. if (!in)
  15419. {
  15420. bool eog = (curRight != initialRight); // processed any records?
  15421. counter = 0;
  15422. curRight.set(initialRight);
  15423. if (eog)
  15424. return NULL;
  15425. in = inputStream->nextRow();
  15426. if (!in)
  15427. return NULL;
  15428. }
  15429. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15430. RtlDynamicRowBuilder rightRowBuilder(rightRowAllocator);
  15431. size32_t outSize = helper.transform(rowBuilder, rightRowBuilder, in, curRight, ++counter);
  15432. ReleaseRoxieRow(in);
  15433. if (outSize)
  15434. {
  15435. //MORE: This should be returned...
  15436. size32_t rightSize = rightRowAllocator->queryOutputMeta()->getRecordSize(rightRowBuilder.getSelf());
  15437. curRight.setown(rightRowBuilder.finalizeRowClear(rightSize));
  15438. processed++;
  15439. return rowBuilder.finalizeRowClear(outSize);
  15440. }
  15441. }
  15442. }
  15443. catch (IException *E)
  15444. {
  15445. throw makeWrappedException(E);
  15446. }
  15447. }
  15448. };
  15449. class CRoxieServerProcessActivityFactory : public CRoxieServerActivityFactory
  15450. {
  15451. public:
  15452. CRoxieServerProcessActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15453. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15454. {
  15455. }
  15456. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15457. {
  15458. return new CRoxieServerProcessActivity(_ctx, this, _probeManager);
  15459. }
  15460. };
  15461. IRoxieServerActivityFactory *createRoxieServerProcessActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15462. {
  15463. return new CRoxieServerProcessActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15464. }
  15465. //=================================================================================
  15466. class CRoxieServerGroupActivity : public CRoxieServerActivity
  15467. {
  15468. IHThorGroupArg &helper;
  15469. bool endPending;
  15470. bool eof;
  15471. bool first;
  15472. unsigned numGroups;
  15473. unsigned numGroupMax;
  15474. unsigned numProcessedLastGroup;
  15475. const void *next;
  15476. public:
  15477. CRoxieServerGroupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  15478. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorGroupArg &)basehelper)
  15479. {
  15480. next = NULL;
  15481. endPending = false;
  15482. eof = false;
  15483. first = true;
  15484. numGroups = 0;
  15485. numGroupMax = 0;
  15486. numProcessedLastGroup = 0;
  15487. }
  15488. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15489. {
  15490. endPending = false;
  15491. eof = false;
  15492. first = true;
  15493. numGroups = 0;
  15494. numGroupMax = 0;
  15495. numProcessedLastGroup = processed;
  15496. assertex(next == NULL);
  15497. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  15498. }
  15499. virtual void reset()
  15500. {
  15501. noteStatistic(StNumGroups, numGroups);
  15502. noteStatistic(StNumGroupMax, numGroupMax);
  15503. ReleaseClearRoxieRow(next);
  15504. CRoxieServerActivity::reset();
  15505. }
  15506. virtual const void * nextRow()
  15507. {
  15508. ActivityTimer t(totalCycles, timeActivities);
  15509. if (first)
  15510. {
  15511. next = inputStream->nextRow();
  15512. first = false;
  15513. }
  15514. if (eof || endPending)
  15515. {
  15516. endPending = false;
  15517. return NULL;
  15518. }
  15519. const void * prev = next;
  15520. next = inputStream->ungroupedNextRow();
  15521. if (next)
  15522. {
  15523. assertex(prev);
  15524. if (!helper.isSameGroup(prev, next))
  15525. {
  15526. noteEndOfGroup();
  15527. endPending = true;
  15528. }
  15529. }
  15530. else
  15531. {
  15532. noteEndOfGroup();
  15533. eof = true;
  15534. }
  15535. if (prev)
  15536. processed++;
  15537. return prev;
  15538. }
  15539. inline void noteEndOfGroup()
  15540. {
  15541. unsigned numThisGroup = processed - numProcessedLastGroup;
  15542. if (numThisGroup == 0)
  15543. return;
  15544. numProcessedLastGroup = processed;
  15545. if (numThisGroup > numGroupMax)
  15546. numGroupMax = numThisGroup;
  15547. numGroups++;
  15548. }
  15549. };
  15550. class CRoxieServerGroupActivityFactory : public CRoxieServerActivityFactory
  15551. {
  15552. public:
  15553. CRoxieServerGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15554. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15555. {
  15556. }
  15557. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15558. {
  15559. return new CRoxieServerGroupActivity(_ctx, this, _probeManager);
  15560. }
  15561. virtual const StatisticsMapping &queryStatsMapping() const
  15562. {
  15563. return groupStatistics;
  15564. }
  15565. };
  15566. IRoxieServerActivityFactory *createRoxieServerGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15567. {
  15568. return new CRoxieServerGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15569. }
  15570. //=================================================================================
  15571. class CRoxieServerFirstNActivity : public CRoxieServerLateStartActivity
  15572. {
  15573. unsigned __int64 limit;
  15574. unsigned __int64 skip;
  15575. unsigned doneThisGroup;
  15576. IHThorFirstNArg &helper;
  15577. public:
  15578. CRoxieServerFirstNActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  15579. : CRoxieServerLateStartActivity(_ctx, _factory, _probeManager), helper((IHThorFirstNArg &)basehelper)
  15580. {
  15581. doneThisGroup = 0;
  15582. limit = 0;
  15583. skip = 0;
  15584. }
  15585. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15586. {
  15587. doneThisGroup = 0;
  15588. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  15589. limit = helper.getLimit();
  15590. skip = helper.numToSkip();
  15591. lateStart(parentExtractSize, parentExtract, limit > 0);
  15592. if (limit + skip >= limit)
  15593. limit += skip;
  15594. }
  15595. const void * nextRow()
  15596. {
  15597. ActivityTimer t(totalCycles, timeActivities);
  15598. if (eof)
  15599. return NULL;
  15600. const void *ret;
  15601. for (;;)
  15602. {
  15603. ret = inputStream->nextRow();
  15604. if (!ret)
  15605. {
  15606. if (meta.isGrouped())
  15607. {
  15608. if (doneThisGroup > skip)
  15609. {
  15610. doneThisGroup = 0;
  15611. return NULL;
  15612. }
  15613. doneThisGroup = 0;
  15614. }
  15615. ret = inputStream->nextRow();
  15616. if (!ret)
  15617. {
  15618. eof = true;
  15619. return NULL;
  15620. }
  15621. }
  15622. doneThisGroup++;
  15623. if (doneThisGroup > skip)
  15624. break;
  15625. ReleaseRoxieRow(ret);
  15626. }
  15627. if (doneThisGroup <= limit)
  15628. {
  15629. processed++;
  15630. return ret;
  15631. }
  15632. ReleaseRoxieRow(ret);
  15633. if (meta.isGrouped())
  15634. {
  15635. while ((ret = inputStream->nextRow()) != NULL)
  15636. ReleaseRoxieRow(ret);
  15637. doneThisGroup = 0;
  15638. }
  15639. else
  15640. eof = true;
  15641. return NULL;
  15642. }
  15643. };
  15644. class CRoxieServerFirstNActivityFactory : public CRoxieServerActivityFactory
  15645. {
  15646. public:
  15647. CRoxieServerFirstNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15648. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15649. {
  15650. }
  15651. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15652. {
  15653. return new CRoxieServerFirstNActivity(_ctx, this, _probeManager);
  15654. }
  15655. };
  15656. IRoxieServerActivityFactory *createRoxieServerFirstNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15657. {
  15658. return new CRoxieServerFirstNActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15659. }
  15660. //=================================================================================
  15661. class CRoxieServerSelectNActivity : public CRoxieServerActivity
  15662. {
  15663. bool done;
  15664. IHThorSelectNArg &helper;
  15665. public:
  15666. CRoxieServerSelectNActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  15667. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorSelectNArg &)basehelper)
  15668. {
  15669. done = false;
  15670. }
  15671. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15672. {
  15673. done = false;
  15674. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  15675. }
  15676. const void *defaultRow()
  15677. {
  15678. if (!rowAllocator)
  15679. ensureRowAllocator(); // We delay as often not needed...
  15680. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15681. size32_t thisSize = helper.createDefault(rowBuilder);
  15682. return rowBuilder.finalizeRowClear(thisSize);
  15683. }
  15684. virtual const void * nextRow()
  15685. {
  15686. ActivityTimer t(totalCycles, timeActivities);
  15687. if (done)
  15688. return NULL;
  15689. done = true;
  15690. processed++; // always going to return a row!
  15691. unsigned __int64 index = helper.getRowToSelect();
  15692. while (--index)
  15693. {
  15694. const void * next = inputStream->ungroupedNextRow();
  15695. if (!next)
  15696. return defaultRow();
  15697. ReleaseRoxieRow(next);
  15698. }
  15699. const void * next = inputStream->ungroupedNextRow();
  15700. if (!next)
  15701. next = defaultRow();
  15702. return next;
  15703. }
  15704. };
  15705. class CRoxieServerSelectNActivityFactory : public CRoxieServerActivityFactory
  15706. {
  15707. public:
  15708. CRoxieServerSelectNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15709. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15710. {
  15711. }
  15712. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15713. {
  15714. return new CRoxieServerSelectNActivity(_ctx, this, _probeManager);
  15715. }
  15716. };
  15717. IRoxieServerActivityFactory *createRoxieServerSelectNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15718. {
  15719. return new CRoxieServerSelectNActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15720. }
  15721. //=================================================================================
  15722. class CRoxieServerSelfJoinActivity : public CRoxieServerActivity
  15723. {
  15724. IHThorJoinArg &helper;
  15725. ICompare *collate;
  15726. OwnedRowArray group;
  15727. bool matchedLeft;
  15728. BoolArray matchedRight;
  15729. bool eof;
  15730. bool first;
  15731. unsigned leftIndex;
  15732. unsigned rightIndex;
  15733. unsigned rightOuterIndex;
  15734. unsigned joinLimit;
  15735. unsigned atmostLimit;
  15736. unsigned atmostsTriggered;
  15737. unsigned abortLimit;
  15738. unsigned keepLimit;
  15739. unsigned joinCounter;
  15740. bool leftOuterJoin;
  15741. bool rightOuterJoin;
  15742. bool exclude;
  15743. bool limitFail;
  15744. bool limitOnFail;
  15745. bool cloneLeft;
  15746. bool forceSpill;
  15747. OwnedConstRoxieRow defaultLeft;
  15748. OwnedConstRoxieRow defaultRight;
  15749. OwnedConstRoxieRow lhs;
  15750. Owned<IException> failingLimit;
  15751. bool failingOuterAtmost;
  15752. Owned<IEngineRowAllocator> defaultAllocator;
  15753. Owned<IRHLimitedCompareHelper> limitedhelper;
  15754. Owned<CRHDualCache> dualcache;
  15755. Owned<IGroupedInput> groupedInput;
  15756. IRowStream *dualCacheInput;
  15757. bool fillGroup()
  15758. {
  15759. group.clear();
  15760. matchedLeft = false;
  15761. matchedRight.kill();
  15762. failingOuterAtmost = false;
  15763. const void * next;
  15764. unsigned groupCount = 0;
  15765. while((next = groupedInput->nextRow()) != NULL)
  15766. {
  15767. if(groupCount==abortLimit)
  15768. {
  15769. if(limitFail)
  15770. failLimit(next);
  15771. if (ctx->queryDebugContext())
  15772. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  15773. if(limitOnFail)
  15774. {
  15775. assertex(!failingLimit);
  15776. try
  15777. {
  15778. failLimit(next);
  15779. }
  15780. catch(IException * except)
  15781. {
  15782. failingLimit.setown(except);
  15783. }
  15784. assertex(failingLimit != NULL);
  15785. group.append(next);
  15786. groupCount++;
  15787. break;
  15788. }
  15789. group.clear();
  15790. groupCount = 0;
  15791. while(next)
  15792. {
  15793. ReleaseRoxieRow(next);
  15794. next = groupedInput->nextRow();
  15795. }
  15796. }
  15797. else if(groupCount==atmostLimit)
  15798. {
  15799. atmostsTriggered++;
  15800. if(leftOuterJoin)
  15801. {
  15802. group.append(next);
  15803. groupCount++;
  15804. failingOuterAtmost = true;
  15805. break;
  15806. }
  15807. else
  15808. {
  15809. group.clear();
  15810. groupCount = 0;
  15811. while (next)
  15812. {
  15813. ReleaseRoxieRow(next);
  15814. next = groupedInput->nextRow();
  15815. }
  15816. }
  15817. }
  15818. else
  15819. {
  15820. group.append(next);
  15821. groupCount++;
  15822. }
  15823. }
  15824. if(group.ordinality()==0)
  15825. {
  15826. eof = true;
  15827. return false;
  15828. }
  15829. leftIndex = 0;
  15830. rightIndex = 0;
  15831. rightOuterIndex = 0;
  15832. joinCounter = 0;
  15833. joinLimit = keepLimit;
  15834. ForEachItemIn(idx, group)
  15835. matchedRight.append(false);
  15836. return true;
  15837. }
  15838. void failLimit(const void * next)
  15839. {
  15840. helper.onMatchAbortLimitExceeded();
  15841. CommonXmlWriter xmlwrite(XWFtrim|XWFopt );
  15842. if (!ctx->isBlind() && input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  15843. {
  15844. input->queryOutputMeta()->toXML((byte *) next, xmlwrite);
  15845. }
  15846. throw MakeStringException(ROXIE_TOO_MANY_RESULTS, "More than %d match candidates in self-join %d for row %s", abortLimit, queryId(), xmlwrite.str());
  15847. }
  15848. virtual bool needsAllocator() const { return true; }
  15849. const void *joinRecords(const void * curLeft, const void * curRight, unsigned counter, IException * except)
  15850. {
  15851. try
  15852. {
  15853. if (cloneLeft && !except)
  15854. {
  15855. LinkRoxieRow(curLeft);
  15856. return curLeft;
  15857. }
  15858. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15859. size32_t outsize = except ? helper.onFailTransform(rowBuilder, curLeft, curRight, except) : helper.transform(rowBuilder, curLeft, curRight, counter);
  15860. if (outsize)
  15861. return rowBuilder.finalizeRowClear(outsize);
  15862. else
  15863. return NULL;
  15864. }
  15865. catch (IException *E)
  15866. {
  15867. throw makeWrappedException(E);
  15868. }
  15869. }
  15870. void createDefaultLeft()
  15871. {
  15872. if (!defaultLeft)
  15873. {
  15874. if (!defaultAllocator)
  15875. defaultAllocator.setown(createRowAllocator(input->queryOutputMeta()));
  15876. RtlDynamicRowBuilder rowBuilder(defaultAllocator);
  15877. size32_t thisSize = helper.createDefaultLeft(rowBuilder);
  15878. defaultLeft.setown(rowBuilder.finalizeRowClear(thisSize));
  15879. }
  15880. }
  15881. void createDefaultRight()
  15882. {
  15883. if (!defaultRight)
  15884. {
  15885. if (!defaultAllocator)
  15886. defaultAllocator.setown(createRowAllocator(input->queryOutputMeta()));
  15887. RtlDynamicRowBuilder rowBuilder(defaultAllocator);
  15888. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  15889. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  15890. }
  15891. }
  15892. public:
  15893. CRoxieServerSelfJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _forceSpill)
  15894. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorJoinArg &)basehelper), forceSpill(_forceSpill)
  15895. {
  15896. collate = helper.queryCompareLeftRight();
  15897. eof = false;
  15898. first = true;
  15899. keepLimit = 0;
  15900. atmostLimit = 0;
  15901. atmostsTriggered = 0;
  15902. unsigned joinFlags = helper.getJoinFlags();
  15903. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  15904. rightOuterJoin = (joinFlags & JFrightouter) != 0;
  15905. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  15906. exclude = (joinFlags & JFexclude) != 0;
  15907. abortLimit = 0;
  15908. joinLimit = 0;
  15909. assertex((joinFlags & (JFfirst | JFfirstleft | JFfirstright)) == 0); // no longer supported
  15910. getLimitType(joinFlags, limitFail, limitOnFail);
  15911. if((joinFlags & JFslidingmatch) != 0)
  15912. throw MakeStringException(ROXIE_UNIMPLEMENTED_ERROR, "Internal Error: Sliding self join not supported");
  15913. failingOuterAtmost = false;
  15914. matchedLeft = false;
  15915. leftIndex = 0;
  15916. rightIndex = 0;
  15917. rightOuterIndex = 0;
  15918. joinCounter = 0;
  15919. dualCacheInput = NULL;
  15920. }
  15921. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15922. {
  15923. eof = false;
  15924. first = true;
  15925. failingLimit.clear();
  15926. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  15927. keepLimit = helper.getKeepLimit();
  15928. if(keepLimit == 0)
  15929. keepLimit = (unsigned)-1;
  15930. atmostsTriggered = 0;
  15931. atmostLimit = helper.getJoinLimit();
  15932. if(atmostLimit == 0)
  15933. atmostLimit = (unsigned)-1;
  15934. else
  15935. assertex(!rightOuterJoin);
  15936. abortLimit = helper.getMatchAbortLimit();
  15937. if (abortLimit == 0)
  15938. abortLimit = (unsigned)-1;
  15939. if (rightOuterJoin)
  15940. createDefaultLeft();
  15941. if (leftOuterJoin || limitOnFail)
  15942. createDefaultRight();
  15943. ICompare *compareLeft = helper.queryCompareLeft();
  15944. if (helper.isLeftAlreadySorted())
  15945. groupedInput.setown(createGroupedInputReader(inputStream, compareLeft));
  15946. else
  15947. {
  15948. bool isStable = (helper.getJoinFlags() & JFunstable) == 0;
  15949. RoxieSortAlgorithm sortAlgorithm;
  15950. if (forceSpill)
  15951. sortAlgorithm = isStable ? stableSpillingQuickSortAlgorithm : spillingQuickSortAlgorithm;
  15952. else
  15953. sortAlgorithm = isStable ? stableQuickSortAlgorithm : quickSortAlgorithm;
  15954. groupedInput.setown(createSortedGroupedInputReader(inputStream, compareLeft, createSortAlgorithm(sortAlgorithm, compareLeft, ctx->queryRowManager(), input->queryOutputMeta(), ctx->queryCodeContext(), tempDirectory, activityId)));
  15955. }
  15956. if ((helper.getJoinFlags() & JFlimitedprefixjoin) && helper.getJoinLimit())
  15957. { //limited match join (s[1..n])
  15958. dualcache.setown(new CRHDualCache());
  15959. dualcache->init(groupedInput);
  15960. dualCacheInput = dualcache->queryOut1();
  15961. failingOuterAtmost = false;
  15962. matchedLeft = false;
  15963. leftIndex = 0;
  15964. rightOuterIndex = 0;
  15965. joinCounter = 0;
  15966. limitedhelper.setown(createRHLimitedCompareHelper());
  15967. limitedhelper->init( helper.getJoinLimit(), dualcache->queryOut2(), collate, helper.queryPrefixCompare() );
  15968. }
  15969. }
  15970. virtual void reset()
  15971. {
  15972. if (atmostsTriggered)
  15973. noteStatistic(StNumAtmostTriggered, atmostsTriggered);
  15974. group.clear();
  15975. groupedInput.clear();
  15976. CRoxieServerActivity::reset();
  15977. defaultLeft.clear();
  15978. defaultRight.clear();
  15979. }
  15980. virtual const void * nextRow()
  15981. {
  15982. ActivityTimer t(totalCycles, timeActivities);
  15983. if (limitedhelper)
  15984. {
  15985. while(!eof) //limited match join
  15986. {
  15987. if (!group.isItem(rightIndex))
  15988. {
  15989. lhs.setown(dualCacheInput->nextRow());
  15990. if (lhs)
  15991. {
  15992. rightIndex = 0;
  15993. joinCounter = 0;
  15994. group.clear();
  15995. limitedhelper->getGroup(group,lhs);
  15996. }
  15997. else
  15998. {
  15999. eof = true;
  16000. }
  16001. }
  16002. if (group.isItem(rightIndex))
  16003. {
  16004. const void * rhs = group.item(rightIndex++);
  16005. if(helper.match(lhs, rhs))
  16006. {
  16007. const void * ret = joinRecords(lhs, rhs, ++joinCounter, NULL);
  16008. if(ret)
  16009. {
  16010. processed++;
  16011. return ret;
  16012. }
  16013. }
  16014. }
  16015. }
  16016. return NULL;
  16017. }
  16018. else
  16019. {
  16020. if (first)
  16021. {
  16022. first = false;
  16023. fillGroup();
  16024. }
  16025. while(!eof)
  16026. {
  16027. if(failingOuterAtmost)
  16028. while(group.isItem(leftIndex))
  16029. {
  16030. const void * ret = joinRecords(group.item(leftIndex++), defaultRight, 0, NULL);
  16031. if(ret)
  16032. {
  16033. processed++;
  16034. return ret;
  16035. }
  16036. }
  16037. if((joinLimit == 0) || !group.isItem(rightIndex))
  16038. {
  16039. if(leftOuterJoin && !matchedLeft && !failingLimit)
  16040. {
  16041. const void * ret = joinRecords(group.item(leftIndex), defaultRight, 0, NULL);
  16042. if(ret)
  16043. {
  16044. matchedLeft = true;
  16045. processed++;
  16046. return ret;
  16047. }
  16048. }
  16049. leftIndex++;
  16050. matchedLeft = false;
  16051. rightIndex = 0;
  16052. joinCounter = 0;
  16053. joinLimit = keepLimit;
  16054. }
  16055. if(!group.isItem(leftIndex))
  16056. {
  16057. if(failingLimit || failingOuterAtmost)
  16058. {
  16059. const void * lhs;
  16060. while((lhs = groupedInput->nextRow()) != NULL) // dualCache never active here
  16061. {
  16062. const void * ret = joinRecords(lhs, defaultRight, 0, failingLimit);
  16063. ReleaseRoxieRow(lhs);
  16064. if(ret)
  16065. {
  16066. processed++;
  16067. return ret;
  16068. }
  16069. }
  16070. failingLimit.clear();
  16071. }
  16072. if(rightOuterJoin && !failingLimit)
  16073. while(group.isItem(rightOuterIndex))
  16074. if(!matchedRight.item(rightOuterIndex++))
  16075. {
  16076. const void * ret = joinRecords(defaultLeft, group.item(rightOuterIndex-1), 0, NULL);
  16077. if(ret)
  16078. {
  16079. processed++;
  16080. return ret;
  16081. }
  16082. }
  16083. if(!fillGroup())
  16084. return NULL;
  16085. continue;
  16086. }
  16087. const void * lhs = group.item(leftIndex);
  16088. if(failingLimit)
  16089. {
  16090. leftIndex++;
  16091. const void * ret = joinRecords(lhs, defaultRight, 0, failingLimit);
  16092. if(ret)
  16093. {
  16094. processed++;
  16095. return ret;
  16096. }
  16097. }
  16098. else
  16099. {
  16100. const void * rhs = group.item(rightIndex++);
  16101. if(helper.match(lhs, rhs))
  16102. {
  16103. matchedLeft = true;
  16104. matchedRight.replace(true, rightIndex-1);
  16105. if(!exclude)
  16106. {
  16107. const void * ret = joinRecords(lhs, rhs, ++joinCounter, NULL);
  16108. if(ret)
  16109. {
  16110. processed++;
  16111. joinLimit--;
  16112. return ret;
  16113. }
  16114. }
  16115. }
  16116. }
  16117. }
  16118. return NULL;
  16119. }
  16120. }
  16121. };
  16122. class CRoxieServerSelfJoinActivityFactory : public CRoxieServerActivityFactory
  16123. {
  16124. bool forceSpill;
  16125. public:
  16126. CRoxieServerSelfJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  16127. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  16128. {
  16129. forceSpill = queryFactory.queryOptions().allSortsMaySpill || _graphNode.getPropBool("hint[@name='spill']/@value", false);;
  16130. }
  16131. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  16132. {
  16133. return new CRoxieServerSelfJoinActivity(_ctx, this, _probeManager, forceSpill);
  16134. }
  16135. virtual const StatisticsMapping &queryStatsMapping() const
  16136. {
  16137. return joinStatistics;
  16138. }
  16139. };
  16140. IRoxieServerActivityFactory *createRoxieServerSelfJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  16141. {
  16142. return new CRoxieServerSelfJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  16143. }
  16144. //=====================================================================================================
  16145. class CRoxieServerLookupJoinActivity : public CRoxieServerTwoInputActivity
  16146. {
  16147. private:
  16148. class LookupTable : public CInterface
  16149. {
  16150. public:
  16151. LookupTable(IHThorHashJoinArg &helper)
  16152. : leftRightCompare(helper.queryCompareLeftRight()), rightCompare(helper.queryCompareRight()),
  16153. leftHash(helper.queryHashLeft()), rightHash(helper.queryHashRight())
  16154. {
  16155. size = 0;
  16156. }
  16157. virtual const void *find(const void * left) const = 0;
  16158. virtual const void *findNext(const void * left) const = 0;
  16159. protected:
  16160. ICompare * leftRightCompare;
  16161. ICompare * rightCompare;
  16162. IHash * leftHash;
  16163. IHash * rightHash;
  16164. unsigned size;
  16165. };
  16166. class DedupLookupTable : public LookupTable
  16167. {
  16168. public:
  16169. DedupLookupTable(ConstPointerArray &rightRows, IHThorHashJoinArg &helper)
  16170. : LookupTable(helper)
  16171. {
  16172. size = (4*rightRows.length())/3 + 1;
  16173. table = (const void * *)calloc(size, sizeof(void *)); // This should probably be allocated from roxiemem (and size rounded up to actual available size)
  16174. ForEachItemIn(idx, rightRows)
  16175. add(rightRows.item(idx));
  16176. }
  16177. ~DedupLookupTable()
  16178. {
  16179. roxiemem::ReleaseRoxieRowArray(size, table);
  16180. free(table);
  16181. }
  16182. virtual const void *find(const void * left) const
  16183. {
  16184. unsigned index = leftHash->hash(left) % size;
  16185. unsigned start = index;
  16186. while (table[index])
  16187. {
  16188. if(leftRightCompare->docompare(left, table[index]) == 0)
  16189. return table[index];
  16190. index++;
  16191. if (index==size)
  16192. index = 0;
  16193. if (index==start)
  16194. throw MakeStringException(ROXIE_JOIN_ERROR, "Internal error in lookup join activity (hash table full on lookup)");
  16195. }
  16196. return NULL;
  16197. }
  16198. virtual const void *findNext(const void * left) const
  16199. {
  16200. return NULL;
  16201. }
  16202. protected:
  16203. void add(const void * right)
  16204. {
  16205. unsigned index = rightHash->hash(right) % size;
  16206. unsigned start = index;
  16207. while (table[index])
  16208. {
  16209. if (rightCompare->docompare(table[index], right) == 0)
  16210. {
  16211. ReleaseRoxieRow(right);
  16212. return;
  16213. }
  16214. index++;
  16215. if (index==size)
  16216. index = 0;
  16217. if (index==start)
  16218. throw MakeStringException(ROXIE_JOIN_ERROR, "Internal error in lookup join activity (hash table full on add)");
  16219. }
  16220. table[index] = right;
  16221. }
  16222. const void * * table;
  16223. };
  16224. class FewLookupTable : public LookupTable
  16225. {
  16226. public:
  16227. FewLookupTable(ConstPointerArray &rightRows, IHThorHashJoinArg &helper)
  16228. : LookupTable(helper)
  16229. {
  16230. size = (4*rightRows.length())/3 + 1;
  16231. table = (const void * *)calloc(size, sizeof(void *)); // This should probably be allocated from roxiemem
  16232. findex = fstart = BadIndex;
  16233. ForEachItemIn(idx, rightRows)
  16234. add(rightRows.item(idx));
  16235. }
  16236. ~FewLookupTable()
  16237. {
  16238. roxiemem::ReleaseRoxieRowArray(size, table);
  16239. free(table);
  16240. }
  16241. virtual const void *find(const void * left) const
  16242. {
  16243. fstart = leftHash->hash(left) % size;
  16244. findex = fstart;
  16245. return doFind(left);
  16246. }
  16247. virtual const void *findNext(const void * left) const
  16248. {
  16249. if (findex == BadIndex)
  16250. return NULL;
  16251. advance();
  16252. return doFind(left);
  16253. }
  16254. protected:
  16255. void add(const void * right)
  16256. {
  16257. unsigned start = rightHash->hash(right) % size;
  16258. unsigned index = start;
  16259. while (table[index])
  16260. {
  16261. index++;
  16262. if (index==size)
  16263. index = 0;
  16264. if (index==start)
  16265. throwUnexpected(); //table is full, should never happen
  16266. }
  16267. table[index] = right;
  16268. }
  16269. void advance() const
  16270. {
  16271. findex++;
  16272. if(findex==size)
  16273. findex = 0;
  16274. if(findex==fstart)
  16275. throw MakeStringException(ROXIE_JOIN_ERROR, "Internal error in lookup join activity (hash table full on lookup)");
  16276. }
  16277. const void *doFind(const void * left) const
  16278. {
  16279. while(table[findex])
  16280. {
  16281. if (leftRightCompare->docompare(left, table[findex]) == 0)
  16282. return table[findex];
  16283. advance();
  16284. }
  16285. findex = BadIndex;
  16286. return NULL;
  16287. }
  16288. const void * * table;
  16289. unsigned mutable fstart;
  16290. unsigned mutable findex;
  16291. static unsigned const BadIndex;
  16292. };
  16293. class ManyLookupTable : public LookupTable
  16294. {
  16295. public:
  16296. ManyLookupTable(ConstPointerArray &rightRows, IHThorHashJoinArg &helper)
  16297. : LookupTable(helper)
  16298. {
  16299. rightRows.swapWith(rowtable);
  16300. UInt64Array groups;
  16301. unsigned numRows = rowtable.length();
  16302. if (numRows)
  16303. {
  16304. unsigned groupStart = 0;
  16305. const void *groupStartRow = rowtable.item(0);
  16306. for (unsigned i=1; i < numRows; i++)
  16307. {
  16308. const void *thisRow = rowtable.item(i);
  16309. if (rightCompare->docompare(groupStartRow, thisRow))
  16310. {
  16311. groups.append(makeint64(groupStart, i-groupStart));
  16312. groupStart = i;
  16313. groupStartRow = thisRow;
  16314. }
  16315. }
  16316. groups.append(makeint64(groupStart, numRows-groupStart));
  16317. }
  16318. size = (4*groups.length())/3 + 1;
  16319. table = (__uint64 *) calloc(size, sizeof(__uint64)); // This should probably be allocated from roxiemem
  16320. ForEachItemIn(idx, groups)
  16321. {
  16322. unsigned __int64 group = groups.item(idx);
  16323. unsigned groupstart = high(group);
  16324. const void *row = rowtable.item(groupstart);
  16325. add(row, group);
  16326. }
  16327. }
  16328. ~ManyLookupTable()
  16329. {
  16330. roxiemem::ReleaseRoxieRows(rowtable);
  16331. free(table);
  16332. }
  16333. void add(const void *row, unsigned __int64 group)
  16334. {
  16335. unsigned start = rightHash->hash(row) % size;
  16336. unsigned index = start;
  16337. while (table[index])
  16338. {
  16339. index++;
  16340. if (index==size)
  16341. index = 0;
  16342. if (index==start)
  16343. throwUnexpected(); //table is full, should never happen
  16344. }
  16345. table[index] = group;
  16346. }
  16347. virtual const void *find(const void * left) const
  16348. {
  16349. unsigned index = leftHash->hash(left) % size;
  16350. unsigned start = index;
  16351. while (table[index])
  16352. {
  16353. __uint64 group = table[index];
  16354. currentMatch = high(group);
  16355. const void *right = rowtable.item(currentMatch);
  16356. if (leftRightCompare->docompare(left, right) == 0)
  16357. {
  16358. currentMatch++;
  16359. matchCount = low(group) - 1;
  16360. return right;
  16361. }
  16362. index++;
  16363. if (index==size)
  16364. index = 0;
  16365. if (index==start)
  16366. throw MakeStringException(ROXIE_JOIN_ERROR, "Internal error in lookup join activity (hash table full on lookup)");
  16367. }
  16368. matchCount = 0;
  16369. return NULL;
  16370. }
  16371. virtual const void *findNext(const void * left) const
  16372. {
  16373. if (!matchCount)
  16374. return NULL;
  16375. matchCount--;
  16376. return rowtable.item(currentMatch++);
  16377. }
  16378. protected:
  16379. __uint64 *table;
  16380. ConstPointerArray rowtable;
  16381. mutable unsigned currentMatch = 0;
  16382. mutable unsigned matchCount = 0;
  16383. };
  16384. IHThorHashJoinArg &helper;
  16385. bool leftOuterJoin;
  16386. bool exclude;
  16387. bool eog;
  16388. bool many;
  16389. bool dedupRHS;
  16390. bool useFewTable;
  16391. bool matchedGroup;
  16392. const void *left;
  16393. OwnedConstRoxieRow defaultRight;
  16394. Owned<LookupTable> table;
  16395. unsigned keepLimit;
  16396. unsigned atmostLimit;
  16397. unsigned atmostsTriggered;
  16398. unsigned limitLimit;
  16399. unsigned joinCounter;
  16400. bool limitFail;
  16401. bool limitOnFail;
  16402. bool hasGroupLimit;
  16403. bool isSmartJoin;
  16404. unsigned keepCount;
  16405. bool gotMatch;
  16406. bool cloneLeft;
  16407. ConstPointerArray rightGroup;
  16408. aindex_t rightGroupIndex;
  16409. Owned<IException> failingLimit;
  16410. ConstPointerArray filteredRight;
  16411. ThorActivityKind activityKind;
  16412. Owned<IEngineRowAllocator> defaultRightAllocator;
  16413. void createDefaultRight()
  16414. {
  16415. if (!defaultRight)
  16416. {
  16417. if (!defaultRightAllocator)
  16418. defaultRightAllocator.setown(createRowAllocator(input1->queryOutputMeta()));
  16419. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  16420. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  16421. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  16422. }
  16423. }
  16424. public:
  16425. CRoxieServerLookupJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _useFewTable)
  16426. : CRoxieServerTwoInputActivity(_ctx, _factory, _probeManager), helper((IHThorHashJoinArg &)basehelper), useFewTable(_useFewTable)
  16427. {
  16428. unsigned joinFlags = helper.getJoinFlags();
  16429. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  16430. assertex((joinFlags & JFrightouter) == 0);
  16431. exclude = (joinFlags & JFexclude) != 0;
  16432. many = (joinFlags & JFmanylookup) != 0;
  16433. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  16434. dedupRHS = (joinFlags & (JFmanylookup | JFmatchrequired | JFtransformMaySkip)) == 0; // optimisation: can implicitly dedup RHS unless is many lookup, or match required, or transform may skip
  16435. left = NULL;
  16436. activityKind = factory->getKind();
  16437. eog = false;
  16438. matchedGroup = false;
  16439. gotMatch = false;
  16440. keepLimit = 0;
  16441. keepCount = 0;
  16442. joinCounter = 0;
  16443. atmostLimit = 0;
  16444. atmostsTriggered = 0;
  16445. limitLimit = 0;
  16446. rightGroupIndex = 0;
  16447. hasGroupLimit = false;
  16448. isSmartJoin = (joinFlags & JFsmart) != 0;
  16449. getLimitType(joinFlags, limitFail, limitOnFail);
  16450. }
  16451. void loadRight()
  16452. {
  16453. ConstPointerArray rightset;
  16454. try
  16455. {
  16456. const void * next;
  16457. while(true)
  16458. {
  16459. next = inputStream1->ungroupedNextRow();
  16460. if(!next)
  16461. break;
  16462. rightset.append(next);
  16463. }
  16464. if (!dedupRHS)
  16465. {
  16466. if (useFewTable)
  16467. {
  16468. table.setown(new FewLookupTable(rightset, helper)); // NOTE - takes ownership of rightset
  16469. }
  16470. else
  16471. {
  16472. if (!helper.isRightAlreadySorted())
  16473. {
  16474. if (helper.getJoinFlags() & JFunstable)
  16475. {
  16476. qsortvec(const_cast<void * *>(rightset.getArray()), rightset.ordinality(), *helper.queryCompareRight());
  16477. }
  16478. else
  16479. {
  16480. unsigned rightord = rightset.ordinality();
  16481. MemoryAttr tempAttr(rightord*sizeof(void **)); // Temp storage for stable sort. This should probably be allocated from roxiemem
  16482. void **temp = (void **) tempAttr.bufferBase();
  16483. void **_rows = const_cast<void * *>(rightset.getArray());
  16484. msortvecstableinplace(_rows, rightord, *helper.queryCompareRight(), temp);
  16485. }
  16486. }
  16487. table.setown(new ManyLookupTable(rightset, helper)); // NOTE - takes ownership of rightset
  16488. }
  16489. }
  16490. else
  16491. {
  16492. table.setown(new DedupLookupTable(rightset, helper)); // NOTE - takes ownership of rightset
  16493. }
  16494. }
  16495. catch (...)
  16496. {
  16497. roxiemem::ReleaseRoxieRows(rightset);
  16498. throw;
  16499. }
  16500. };
  16501. virtual void reset()
  16502. {
  16503. if (atmostsTriggered)
  16504. noteStatistic(StNumAtmostTriggered, atmostsTriggered);
  16505. CRoxieServerTwoInputActivity::reset();
  16506. ReleaseClearRoxieRow(left);
  16507. defaultRight.clear();
  16508. table.clear();
  16509. }
  16510. virtual bool needsAllocator() const { return true; }
  16511. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16512. {
  16513. eog = false;
  16514. matchedGroup = false;
  16515. left = NULL;
  16516. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  16517. keepLimit = helper.getKeepLimit();
  16518. if(keepLimit==0) keepLimit = static_cast<unsigned>(-1);
  16519. atmostsTriggered = 0;
  16520. atmostLimit = helper.getJoinLimit();
  16521. limitLimit = helper.getMatchAbortLimit();
  16522. hasGroupLimit = ((atmostLimit > 0) || (limitLimit > 0));
  16523. if(atmostLimit==0) atmostLimit = static_cast<unsigned>(-1);
  16524. if(limitLimit==0) limitLimit = static_cast<unsigned>(-1);
  16525. getLimitType(helper.getJoinFlags(), limitFail, limitOnFail);
  16526. switch (activityKind)
  16527. {
  16528. case TAKlookupjoin:
  16529. case TAKlookupdenormalizegroup:
  16530. case TAKsmartjoin:
  16531. case TAKsmartdenormalizegroup:
  16532. if (leftOuterJoin)
  16533. createDefaultRight();
  16534. break;
  16535. }
  16536. if (limitOnFail)
  16537. createDefaultRight();
  16538. }
  16539. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  16540. {
  16541. if (!idx && (helper.getJoinFlags() & JFparallel) != 0)
  16542. {
  16543. puller.setown(new CRoxieServerReadAheadInput(ctx, ctx->queryOptions().parallelJoinPreload));
  16544. puller->setInput(0, _sourceIdx, _in);
  16545. _in = puller;
  16546. _sourceIdx = 0;
  16547. }
  16548. CRoxieServerTwoInputActivity::setInput(idx, _sourceIdx, _in);
  16549. }
  16550. virtual const void * nextRow()
  16551. {
  16552. ActivityTimer t(totalCycles, timeActivities);
  16553. if(!table)
  16554. loadRight();
  16555. switch (activityKind)
  16556. {
  16557. case TAKlookupjoin:
  16558. case TAKsmartjoin:
  16559. return nextRowJoin();
  16560. case TAKlookupdenormalize:
  16561. case TAKlookupdenormalizegroup:
  16562. case TAKsmartdenormalize:
  16563. case TAKsmartdenormalizegroup:
  16564. return nextRowDenormalize();
  16565. }
  16566. throwUnexpected();
  16567. }
  16568. private:
  16569. const void * nextRowJoin()
  16570. {
  16571. if(!table)
  16572. loadRight();
  16573. while(true)
  16574. {
  16575. const void * right = NULL;
  16576. if(!left)
  16577. {
  16578. left = inputStream->nextRow();
  16579. keepCount = keepLimit;
  16580. joinCounter = 0;
  16581. if(!left)
  16582. {
  16583. if (isSmartJoin)
  16584. left = inputStream->nextRow();
  16585. if (!left)
  16586. {
  16587. if(matchedGroup || eog)
  16588. {
  16589. matchedGroup = false;
  16590. eog = true;
  16591. return NULL;
  16592. }
  16593. eog = true;
  16594. continue;
  16595. }
  16596. }
  16597. eog = false;
  16598. gotMatch = false;
  16599. right = getRightFirst();
  16600. }
  16601. else
  16602. right = getRightNext();
  16603. const void * ret = NULL;
  16604. if(failingLimit)
  16605. {
  16606. ret = joinException(left, failingLimit);
  16607. }
  16608. else
  16609. {
  16610. while(right)
  16611. {
  16612. if(helper.match(left, right))
  16613. {
  16614. gotMatch = true;
  16615. if(exclude)
  16616. break;
  16617. ret = joinRecords(left, right, ++joinCounter);
  16618. if(ret)
  16619. {
  16620. processed++;
  16621. break;
  16622. }
  16623. }
  16624. right = getRightNext();
  16625. ret = NULL;
  16626. }
  16627. if(leftOuterJoin && !gotMatch)
  16628. {
  16629. ret = joinRecords(left, defaultRight, 0);
  16630. gotMatch = true;
  16631. }
  16632. }
  16633. if(ret)
  16634. {
  16635. matchedGroup = true;
  16636. processed++;
  16637. if(!many || (--keepCount == 0) || failingLimit)
  16638. {
  16639. ReleaseClearRoxieRow(left);
  16640. failingLimit.clear();
  16641. }
  16642. return ret;
  16643. }
  16644. ReleaseClearRoxieRow(left);
  16645. }
  16646. }
  16647. const void * nextRowDenormalize()
  16648. {
  16649. while(true)
  16650. {
  16651. left = inputStream->nextRow();
  16652. if(!left)
  16653. {
  16654. if (!matchedGroup || isSmartJoin)
  16655. left = inputStream->nextRow();
  16656. if (!left)
  16657. {
  16658. matchedGroup = false;
  16659. return NULL;
  16660. }
  16661. }
  16662. gotMatch = false;
  16663. const void * right = getRightFirst();
  16664. const void * ret = NULL;
  16665. if (failingLimit)
  16666. ret = joinException(left, failingLimit);
  16667. else if (activityKind == TAKlookupdenormalize || activityKind == TAKsmartdenormalize)
  16668. {
  16669. OwnedConstRoxieRow newLeft;
  16670. newLeft.set(left);
  16671. unsigned rowSize = 0;
  16672. unsigned leftCount = 0;
  16673. keepCount = keepLimit;
  16674. while (right)
  16675. {
  16676. try
  16677. {
  16678. if (helper.match(left, right))
  16679. {
  16680. gotMatch = true;
  16681. if (exclude)
  16682. break;
  16683. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16684. unsigned thisSize = helper.transform(rowBuilder, newLeft, right, ++leftCount);
  16685. if (thisSize)
  16686. {
  16687. rowSize = thisSize;
  16688. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  16689. }
  16690. if(!many || (--keepCount == 0))
  16691. break;
  16692. }
  16693. right = getRightNext();
  16694. }
  16695. catch (IException *E)
  16696. {
  16697. throw makeWrappedException(E);
  16698. }
  16699. }
  16700. if (rowSize)
  16701. ret = newLeft.getClear();
  16702. else if (leftOuterJoin && !gotMatch)
  16703. {
  16704. ret = left;
  16705. left = NULL;
  16706. }
  16707. }
  16708. else
  16709. {
  16710. filteredRight.kill();
  16711. keepCount = keepLimit;
  16712. while (right)
  16713. {
  16714. if (helper.match(left, right))
  16715. {
  16716. gotMatch = true;
  16717. if(exclude)
  16718. break;
  16719. filteredRight.append(right);
  16720. if(!many || (--keepCount == 0))
  16721. break;
  16722. }
  16723. right = getRightNext();
  16724. }
  16725. if((filteredRight.ordinality() > 0) || (leftOuterJoin && !gotMatch))
  16726. ret = denormalizeRecords(left, filteredRight);
  16727. filteredRight.kill();
  16728. }
  16729. ReleaseRoxieRow(left);
  16730. left = NULL;
  16731. failingLimit.clear();
  16732. if(ret)
  16733. {
  16734. matchedGroup = true;
  16735. processed++;
  16736. return ret;
  16737. }
  16738. }
  16739. }
  16740. const void * joinRecords(const void * left, const void * right, unsigned counter)
  16741. {
  16742. if (cloneLeft)
  16743. {
  16744. LinkRoxieRow(left);
  16745. return left;
  16746. }
  16747. try
  16748. {
  16749. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16750. unsigned outSize = helper.transform(rowBuilder, left, right, counter);
  16751. if (outSize)
  16752. return rowBuilder.finalizeRowClear(outSize);
  16753. else
  16754. return NULL;
  16755. }
  16756. catch (IException *E)
  16757. {
  16758. throw makeWrappedException(E);
  16759. }
  16760. }
  16761. const void * joinException(const void * left, IException * except)
  16762. {
  16763. try
  16764. {
  16765. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16766. unsigned outSize = helper.onFailTransform(rowBuilder, left, defaultRight, except);
  16767. if (outSize)
  16768. return rowBuilder.finalizeRowClear(outSize);
  16769. else
  16770. return NULL;
  16771. }
  16772. catch (IException *E)
  16773. {
  16774. throw makeWrappedException(E);
  16775. }
  16776. }
  16777. const void * denormalizeRecords(const void * left, ConstPointerArray & rows)
  16778. {
  16779. try
  16780. {
  16781. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16782. unsigned numRows = rows.ordinality();
  16783. const void * right = numRows ? rows.item(0) : defaultRight.get();
  16784. unsigned outSize = helper.transform(rowBuilder, left, right, numRows, (const void * *)rows.getArray());
  16785. if (outSize)
  16786. return rowBuilder.finalizeRowClear(outSize);
  16787. else
  16788. return NULL;
  16789. }
  16790. catch (IException *E)
  16791. {
  16792. throw makeWrappedException(E);
  16793. }
  16794. }
  16795. const void * getRightFirst() { if(hasGroupLimit) return fillRightGroup(); else return table->find(left); }
  16796. const void * getRightNext() { if(hasGroupLimit) return readRightGroup(); else return table->findNext(left); }
  16797. const void * readRightGroup() { if(rightGroup.isItem(rightGroupIndex)) return rightGroup.item(rightGroupIndex++); else return NULL; }
  16798. const void *fillRightGroup()
  16799. {
  16800. rightGroup.kill();
  16801. for(const void * right = table->find(left); right; right = table->findNext(left))
  16802. {
  16803. rightGroup.append(right);
  16804. if(rightGroup.ordinality() > limitLimit)
  16805. {
  16806. if(limitFail)
  16807. failLimit();
  16808. gotMatch = true;
  16809. if (ctx->queryDebugContext())
  16810. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  16811. if(limitOnFail)
  16812. {
  16813. assertex(!failingLimit);
  16814. try
  16815. {
  16816. failLimit();
  16817. }
  16818. catch(IException * e)
  16819. {
  16820. failingLimit.setown(e);
  16821. }
  16822. assertex(failingLimit != NULL);
  16823. }
  16824. else
  16825. {
  16826. rightGroup.kill();
  16827. }
  16828. break;
  16829. }
  16830. if(rightGroup.ordinality() > atmostLimit)
  16831. {
  16832. atmostsTriggered++;
  16833. rightGroup.kill();
  16834. break;
  16835. }
  16836. }
  16837. rightGroupIndex = 0;
  16838. return readRightGroup();
  16839. }
  16840. void failLimit()
  16841. {
  16842. helper.onMatchAbortLimitExceeded();
  16843. CommonXmlWriter xmlwrite(XWFtrim|XWFopt );
  16844. if(!ctx->isBlind() && input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  16845. {
  16846. input->queryOutputMeta()->toXML(static_cast<const unsigned char *>(left), xmlwrite);
  16847. }
  16848. throw MakeStringException(ROXIE_TOO_MANY_RESULTS, "More than %u match candidates in join %d for row %s", limitLimit, queryId(), xmlwrite.str());
  16849. }
  16850. };
  16851. unsigned const CRoxieServerLookupJoinActivity::FewLookupTable::BadIndex(static_cast<unsigned>(-1));
  16852. class CRoxieServerLookupJoinActivityFactory : public CRoxieServerJoinActivityFactory
  16853. {
  16854. public:
  16855. CRoxieServerLookupJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  16856. : CRoxieServerJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  16857. {
  16858. Owned<IHThorHashJoinArg> helper = (IHThorHashJoinArg *) helperFactory();
  16859. useFewTable = _graphNode.getPropBool("hint[@name='usefewtable']/@value", false);
  16860. if((helper->getJoinFlags() & (JFfirst | JFfirstleft | JFfirstright | JFslidingmatch)) != 0)
  16861. throw MakeStringException(ROXIE_INVALID_FLAGS, "Invalid flags for lookup join activity"); // code generator should never create such an activity
  16862. }
  16863. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  16864. {
  16865. return new CRoxieServerLookupJoinActivity(_ctx, this, _probeManager, useFewTable);
  16866. }
  16867. virtual const StatisticsMapping &queryStatsMapping() const
  16868. {
  16869. return joinStatistics;
  16870. }
  16871. protected:
  16872. bool useFewTable;
  16873. };
  16874. IRoxieServerActivityFactory *createRoxieServerLookupJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  16875. {
  16876. return new CRoxieServerLookupJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  16877. }
  16878. //=====================================================================================================
  16879. class CRoxieServerAllJoinActivity : public CRoxieServerTwoInputActivity
  16880. {
  16881. private:
  16882. IHThorAllJoinArg &helper;
  16883. bool leftOuterJoin;
  16884. bool rightOuterJoin;
  16885. bool exclude;
  16886. OwnedConstRoxieRow defaultRight;
  16887. OwnedConstRoxieRow defaultLeft;
  16888. Owned<IEngineRowAllocator> defaultRightAllocator;
  16889. Owned<IEngineRowAllocator> defaultLeftAllocator;
  16890. const void *left;
  16891. unsigned countForLeft;
  16892. ConstPointerArray rightset;
  16893. BoolArray matchedRight; // MORE - could use a bitset...
  16894. unsigned keepLimit;
  16895. bool started;
  16896. bool eog;
  16897. bool eos;
  16898. bool matchedLeft;
  16899. bool matchedGroup;
  16900. bool leftIsGrouped;
  16901. bool cloneLeft;
  16902. unsigned rightIndex;
  16903. unsigned joinCounter;
  16904. unsigned rightOrdinality;
  16905. ThorActivityKind activityKind;
  16906. ConstPointerArray filteredRight;
  16907. void createDefaultLeft()
  16908. {
  16909. if (!defaultLeft)
  16910. {
  16911. if (!defaultLeftAllocator)
  16912. defaultLeftAllocator.setown(createRowAllocator(input->queryOutputMeta()));
  16913. RtlDynamicRowBuilder rowBuilder(defaultLeftAllocator);
  16914. size32_t thisSize = helper.createDefaultLeft(rowBuilder);
  16915. defaultLeft.setown(rowBuilder.finalizeRowClear(thisSize));
  16916. }
  16917. }
  16918. void createDefaultRight()
  16919. {
  16920. if (!defaultRight)
  16921. {
  16922. if (!defaultRightAllocator)
  16923. defaultRightAllocator.setown(createRowAllocator(input1->queryOutputMeta()));
  16924. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  16925. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  16926. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  16927. }
  16928. }
  16929. public:
  16930. CRoxieServerAllJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  16931. : CRoxieServerTwoInputActivity(_ctx, _factory, _probeManager), helper((IHThorAllJoinArg &)basehelper)
  16932. {
  16933. unsigned joinFlags = helper.getJoinFlags();
  16934. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  16935. rightOuterJoin = (joinFlags & JFrightouter) != 0;
  16936. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  16937. keepLimit = (unsigned) -1;
  16938. exclude = (joinFlags & JFexclude) != 0;
  16939. left = NULL;
  16940. started = true;
  16941. eog = false;
  16942. eos = false;
  16943. matchedLeft = false;
  16944. matchedGroup = false;
  16945. activityKind = factory->getKind();
  16946. rightIndex = 0;
  16947. rightOrdinality = 0;
  16948. leftIsGrouped = false;
  16949. countForLeft = 0;
  16950. joinCounter = 0;
  16951. }
  16952. virtual void reset()
  16953. {
  16954. defaultRight.clear();
  16955. defaultLeft.clear();
  16956. ReleaseRoxieRows(rightset);
  16957. matchedRight.kill();
  16958. CRoxieServerTwoInputActivity::reset();
  16959. }
  16960. virtual bool needsAllocator() const { return true; }
  16961. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16962. {
  16963. eog = false;
  16964. eos = false;
  16965. matchedLeft = false;
  16966. matchedGroup = false;
  16967. started = false;
  16968. left = NULL;
  16969. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  16970. keepLimit = helper.getKeepLimit();
  16971. if(keepLimit==0)
  16972. keepLimit = (unsigned) -1;
  16973. countForLeft = keepLimit;
  16974. joinCounter = 0;
  16975. leftIsGrouped = input->queryOutputMeta()->isGrouped();
  16976. if((activityKind==TAKalljoin || activityKind==TAKalldenormalizegroup) && leftOuterJoin)
  16977. createDefaultRight();
  16978. if(rightOuterJoin)
  16979. createDefaultLeft();
  16980. }
  16981. void loadRight()
  16982. {
  16983. const void * next;
  16984. while(true)
  16985. {
  16986. next = inputStream1->ungroupedNextRow();
  16987. if(!next)
  16988. break;
  16989. rightset.append(next);
  16990. matchedRight.append(false);
  16991. }
  16992. rightIndex = 0;
  16993. joinCounter = 0;
  16994. rightOrdinality = rightset.ordinality();
  16995. }
  16996. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  16997. {
  16998. if (!idx && (helper.getJoinFlags() & JFparallel) != 0)
  16999. {
  17000. puller.setown(new CRoxieServerReadAheadInput(ctx, ctx->queryOptions().parallelJoinPreload));
  17001. puller->setInput(0, _sourceIdx, _in);
  17002. _in = puller;
  17003. _sourceIdx = 0;
  17004. }
  17005. CRoxieServerTwoInputActivity::setInput(idx, _sourceIdx, _in);
  17006. }
  17007. const void * joinRecords(const void * left, const void * right, unsigned counter)
  17008. {
  17009. // MORE - could share some code with lookup join
  17010. if (cloneLeft)
  17011. {
  17012. LinkRoxieRow(left);
  17013. return left;
  17014. }
  17015. try
  17016. {
  17017. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17018. unsigned outSize = helper.transform(rowBuilder, left, right, counter);
  17019. if (outSize)
  17020. return rowBuilder.finalizeRowClear(outSize);
  17021. else
  17022. return NULL;
  17023. }
  17024. catch (IException *E)
  17025. {
  17026. throw makeWrappedException(E);
  17027. }
  17028. }
  17029. const void * denormalizeRecords(const void * curLeft, ConstPointerArray & rows)
  17030. {
  17031. try
  17032. {
  17033. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17034. unsigned numRows = rows.ordinality();
  17035. const void * right = numRows ? rows.item(0) : defaultRight.get();
  17036. unsigned outSize = helper.transform(rowBuilder, curLeft, right, numRows, rows.getArray());
  17037. if (outSize)
  17038. return rowBuilder.finalizeRowClear(outSize);
  17039. else
  17040. return NULL;
  17041. }
  17042. catch (IException *E)
  17043. {
  17044. throw makeWrappedException(E);
  17045. }
  17046. }
  17047. virtual const void *nextRow()
  17048. {
  17049. ActivityTimer t(totalCycles, timeActivities);
  17050. if(!started)
  17051. {
  17052. started = true;
  17053. left = inputStream->nextRow();
  17054. matchedLeft = false;
  17055. countForLeft = keepLimit;
  17056. joinCounter = 0;
  17057. if(left == NULL)
  17058. {
  17059. eos = true;
  17060. return NULL;
  17061. }
  17062. loadRight();
  17063. }
  17064. const void * ret;
  17065. const void * right;
  17066. if(eos)
  17067. return NULL;
  17068. while(true)
  17069. {
  17070. ret = NULL;
  17071. if((rightIndex == rightOrdinality) || (countForLeft==0))
  17072. {
  17073. if(leftOuterJoin && left && !matchedLeft)
  17074. {
  17075. switch(activityKind)
  17076. {
  17077. case TAKalljoin:
  17078. ret = joinRecords(left, defaultRight, 0);
  17079. break;
  17080. case TAKalldenormalize:
  17081. ret = left;
  17082. left = NULL;
  17083. break;
  17084. case TAKalldenormalizegroup:
  17085. filteredRight.kill();
  17086. ret = denormalizeRecords(left, filteredRight);
  17087. break;
  17088. default:
  17089. throwUnexpected();
  17090. }
  17091. }
  17092. rightIndex = 0;
  17093. joinCounter = 0;
  17094. ReleaseRoxieRow(left);
  17095. left = NULL;
  17096. if(ret)
  17097. {
  17098. matchedGroup = true;
  17099. processed++;
  17100. return ret;
  17101. }
  17102. }
  17103. if(!left)
  17104. {
  17105. left = inputStream->nextRow();
  17106. matchedLeft = false;
  17107. countForLeft = keepLimit;
  17108. joinCounter = 0;
  17109. }
  17110. if(!left)
  17111. {
  17112. if(eog)
  17113. {
  17114. eos = true;
  17115. matchedGroup = false;
  17116. return NULL;
  17117. }
  17118. eog = true;
  17119. if (matchedGroup && leftIsGrouped)
  17120. {
  17121. matchedGroup = false;
  17122. return NULL;
  17123. }
  17124. matchedGroup = false;
  17125. continue;
  17126. }
  17127. eog = false;
  17128. switch(activityKind)
  17129. {
  17130. case TAKalljoin:
  17131. while(rightIndex < rightOrdinality)
  17132. {
  17133. right = rightset.item(rightIndex);
  17134. if(helper.match(left, right))
  17135. {
  17136. matchedLeft = true;
  17137. matchedRight.replace(true, rightIndex);
  17138. if(!exclude)
  17139. ret = joinRecords(left, right, ++joinCounter);
  17140. }
  17141. rightIndex++;
  17142. if(ret)
  17143. {
  17144. countForLeft--;
  17145. matchedGroup = true;
  17146. processed++;
  17147. return ret;
  17148. }
  17149. }
  17150. break;
  17151. case TAKalldenormalize:
  17152. {
  17153. OwnedConstRoxieRow newLeft;
  17154. newLeft.set(left);
  17155. unsigned rowSize = 0;
  17156. unsigned leftCount = 0;
  17157. while((rightIndex < rightOrdinality) && countForLeft)
  17158. {
  17159. right = rightset.item(rightIndex);
  17160. if(helper.match(left, right))
  17161. {
  17162. matchedLeft = true;
  17163. matchedRight.replace(true, rightIndex);
  17164. if(!exclude)
  17165. {
  17166. try
  17167. {
  17168. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17169. unsigned thisSize = helper.transform(rowBuilder, newLeft, right, ++leftCount);
  17170. if(thisSize)
  17171. {
  17172. rowSize = thisSize;
  17173. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  17174. --countForLeft;
  17175. }
  17176. }
  17177. catch (IException *e)
  17178. {
  17179. throw makeWrappedException(e);
  17180. }
  17181. }
  17182. }
  17183. rightIndex++;
  17184. }
  17185. if(rowSize)
  17186. {
  17187. processed++;
  17188. return newLeft.getClear();
  17189. }
  17190. }
  17191. break;
  17192. case TAKalldenormalizegroup:
  17193. filteredRight.kill();
  17194. while((rightIndex < rightOrdinality) && countForLeft)
  17195. {
  17196. right = rightset.item(rightIndex);
  17197. if(helper.match(left, right))
  17198. {
  17199. matchedLeft = true;
  17200. matchedRight.replace(true, rightIndex);
  17201. filteredRight.append(right);
  17202. --countForLeft;
  17203. }
  17204. ++rightIndex;
  17205. }
  17206. if(!exclude && filteredRight.ordinality())
  17207. {
  17208. ret = denormalizeRecords(left, filteredRight);
  17209. filteredRight.kill();
  17210. if(ret)
  17211. {
  17212. processed++;
  17213. return ret;
  17214. }
  17215. }
  17216. break;
  17217. default:
  17218. throwUnexpected();
  17219. }
  17220. }
  17221. }
  17222. };
  17223. class CRoxieServerAllJoinActivityFactory : public CRoxieServerJoinActivityFactory
  17224. {
  17225. public:
  17226. CRoxieServerAllJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17227. : CRoxieServerJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  17228. {
  17229. Owned<IHThorAllJoinArg> helper = (IHThorAllJoinArg *) helperFactory();
  17230. if((helper->getJoinFlags() & (JFfirst | JFfirstleft | JFfirstright)) != 0)
  17231. throw MakeStringException(ROXIE_INVALID_FLAGS, "Invalid flags for join all activity"); // code generator should never create such an activity
  17232. }
  17233. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  17234. {
  17235. return new CRoxieServerAllJoinActivity(_ctx, this, _probeManager);
  17236. }
  17237. virtual const StatisticsMapping &queryStatsMapping() const
  17238. {
  17239. return joinStatistics;
  17240. }
  17241. };
  17242. IRoxieServerActivityFactory *createRoxieServerAllJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17243. {
  17244. return new CRoxieServerAllJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  17245. }
  17246. //=====================================================================================================
  17247. class CRoxieServerTopNActivity : public CRoxieServerLateStartActivity
  17248. {
  17249. unsigned limit;
  17250. bool hasBest;
  17251. bool eoi;
  17252. const void **sorted;
  17253. unsigned sortedCount;
  17254. unsigned curIndex;
  17255. IHThorTopNArg &helper;
  17256. ICompare &compare;
  17257. public:
  17258. CRoxieServerTopNActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17259. : CRoxieServerLateStartActivity(_ctx, _factory, _probeManager), helper((IHThorTopNArg &)basehelper), compare(*helper.queryCompare())
  17260. {
  17261. sorted = NULL;
  17262. sortedCount = 0;
  17263. curIndex = 0;
  17264. limit = 0;
  17265. eoi = false;
  17266. hasBest = false;
  17267. }
  17268. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17269. {
  17270. assertex(sorted == NULL);
  17271. sortedCount = 0;
  17272. curIndex = 0;
  17273. eoi = false;
  17274. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  17275. limit = (unsigned) helper.getLimit();
  17276. hasBest = helper.hasBest();
  17277. lateStart(parentExtractSize, parentExtract, limit > 0);
  17278. // MORE - should we use an expanding array instead?
  17279. if (limit > 0)
  17280. sorted = (const void **) ctx->queryRowManager().allocate((limit+1) * sizeof(const void *), activityId);
  17281. }
  17282. virtual void reset()
  17283. {
  17284. if (sorted)
  17285. {
  17286. roxiemem::ReleaseRoxieRowRange(sorted, curIndex, sortedCount);
  17287. curIndex = 0;
  17288. sortedCount = 0;
  17289. ReleaseRoxieRow(sorted);
  17290. sorted = NULL;
  17291. }
  17292. CRoxieServerLateStartActivity::reset();
  17293. }
  17294. bool abortEarly()
  17295. {
  17296. if (hasBest && (sortedCount == limit))
  17297. {
  17298. int compare = helper.compareBest(sorted[sortedCount-1]);
  17299. if (compare == 0)
  17300. {
  17301. if (meta.isGrouped())
  17302. {
  17303. //MORE: This would be more efficient if we had a away of skipping to the end of the incoming group.
  17304. const void * next;
  17305. while ((next = inputStream->nextRow()) != NULL)
  17306. ReleaseRoxieRow(next);
  17307. }
  17308. else
  17309. eoi = true;
  17310. return true;
  17311. }
  17312. //This only checks the lowest element - we could check all elements inserted, but it would increase the number of compares
  17313. if (compare < 0)
  17314. throw MakeStringException(ROXIE_TOPN_ROW_ERROR, "TOPN: row found that exceeds the best value");
  17315. }
  17316. return false;
  17317. }
  17318. void getSorted()
  17319. {
  17320. curIndex = 0;
  17321. sortedCount = 0;
  17322. if(eoi)
  17323. return;
  17324. const void * next;
  17325. while ((next = inputStream->nextRow()) != NULL)
  17326. {
  17327. if (sortedCount < limit)
  17328. {
  17329. binary_vec_insert_stable(next, sorted, sortedCount, compare);
  17330. sortedCount++;
  17331. if(abortEarly())
  17332. return;
  17333. }
  17334. else
  17335. {
  17336. if(limit && compare.docompare(sorted[sortedCount-1], next) > 0) // MORE - if stability is an issue, need to consider whether this should be > or >=
  17337. {
  17338. binary_vec_insert_stable(next, sorted, sortedCount, compare); // MORE - not sure this is stable!
  17339. ReleaseRoxieRow(sorted[sortedCount]);
  17340. if(abortEarly())
  17341. return;
  17342. }
  17343. else
  17344. {
  17345. ReleaseRoxieRow(next); // do not bother with insertion sort if we know next will fall off the end
  17346. }
  17347. }
  17348. }
  17349. }
  17350. virtual const void * nextRow()
  17351. {
  17352. ActivityTimer t(totalCycles, timeActivities);
  17353. if (eof)
  17354. return NULL;
  17355. if (curIndex >= sortedCount)
  17356. {
  17357. bool eog = sortedCount != 0;
  17358. getSorted();
  17359. if(sortedCount == 0)
  17360. {
  17361. eof = true;
  17362. return NULL;
  17363. }
  17364. if (eog)
  17365. return NULL;
  17366. }
  17367. processed++;
  17368. return sorted[curIndex++];
  17369. }
  17370. };
  17371. class CRoxieServerTopNActivityFactory : public CRoxieServerActivityFactory
  17372. {
  17373. public:
  17374. CRoxieServerTopNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17375. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  17376. {
  17377. }
  17378. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  17379. {
  17380. return new CRoxieServerTopNActivity(_ctx, this, _probeManager);
  17381. }
  17382. };
  17383. IRoxieServerActivityFactory *createRoxieServerTopNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17384. {
  17385. return new CRoxieServerTopNActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  17386. }
  17387. //=================================================================================
  17388. class CRoxieServerLimitActivity : public CRoxieServerActivity
  17389. {
  17390. protected:
  17391. unsigned __int64 rowLimit;
  17392. IHThorLimitArg &helper;
  17393. public:
  17394. CRoxieServerLimitActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17395. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorLimitArg &)basehelper)
  17396. {
  17397. rowLimit = 0;
  17398. }
  17399. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17400. {
  17401. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  17402. rowLimit = helper.getRowLimit(); // could conceivably depend on context so should not compute any earlier than this
  17403. }
  17404. virtual const void *nextRow()
  17405. {
  17406. ActivityTimer t(totalCycles, timeActivities);
  17407. const void * ret = inputStream->nextRow();
  17408. if (ret)
  17409. {
  17410. processed++;
  17411. if (processed > rowLimit)
  17412. {
  17413. ReleaseRoxieRow(ret);
  17414. if (traceLevel > 4)
  17415. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  17416. helper.onLimitExceeded();
  17417. }
  17418. }
  17419. return ret;
  17420. }
  17421. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  17422. {
  17423. ActivityTimer t(totalCycles, timeActivities);
  17424. const void * ret = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  17425. if (ret)
  17426. {
  17427. if (wasCompleteMatch)
  17428. processed++;
  17429. if (processed > rowLimit)
  17430. {
  17431. ReleaseRoxieRow(ret);
  17432. if (traceLevel > 4)
  17433. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  17434. helper.onLimitExceeded();
  17435. }
  17436. }
  17437. return ret;
  17438. }
  17439. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  17440. {
  17441. return input->gatherConjunctions(collector);
  17442. }
  17443. virtual void resetEOF()
  17444. {
  17445. //Do not reset the rowLimit
  17446. inputStream->resetEOF();
  17447. }
  17448. IInputSteppingMeta * querySteppingMeta()
  17449. {
  17450. return input->querySteppingMeta();
  17451. }
  17452. };
  17453. class CRoxieServerLimitActivityFactory : public CRoxieServerActivityFactory
  17454. {
  17455. public:
  17456. CRoxieServerLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17457. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  17458. {
  17459. }
  17460. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  17461. {
  17462. return new CRoxieServerLimitActivity(_ctx, this, _probeManager);
  17463. }
  17464. };
  17465. IRoxieServerActivityFactory *createRoxieServerLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17466. {
  17467. return new CRoxieServerLimitActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  17468. }
  17469. //=====================================================================================================
  17470. class CRoxieServerSkipLimitActivity : public CRoxieServerLimitActivity
  17471. {
  17472. ConstPointerArray buff;
  17473. bool started;
  17474. unsigned index;
  17475. IHThorLimitTransformExtra * transformExtra;
  17476. public:
  17477. CRoxieServerSkipLimitActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _onFail)
  17478. : CRoxieServerLimitActivity(_ctx, _factory, _probeManager)
  17479. {
  17480. transformExtra = NULL;
  17481. started = false;
  17482. index = 0;
  17483. if (_onFail)
  17484. transformExtra = static_cast<IHThorLimitTransformExtra *>(helper.selectInterface(TAIlimittransformextra_1));
  17485. }
  17486. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17487. {
  17488. started = false;
  17489. index = 0;
  17490. CRoxieServerLimitActivity::start(parentExtractSize, parentExtract, paused);
  17491. }
  17492. virtual void reset()
  17493. {
  17494. roxiemem::ReleaseRoxieRowRange(buff.getArray(), index, buff.ordinality());
  17495. buff.kill();
  17496. index = 0;
  17497. started = false;
  17498. CRoxieServerLimitActivity::reset();
  17499. }
  17500. virtual const void *nextRow()
  17501. {
  17502. ActivityTimer t(totalCycles, timeActivities);
  17503. if (!started)
  17504. pullInput();
  17505. if (buff.isItem(index))
  17506. {
  17507. const void * next = buff.item(index++);
  17508. if(next)
  17509. processed++;
  17510. return next;
  17511. }
  17512. return NULL;
  17513. }
  17514. protected:
  17515. void pullInput()
  17516. {
  17517. unsigned count = 0;
  17518. for (;;)
  17519. {
  17520. const void * next = inputStream->nextRow();
  17521. if (next == NULL)
  17522. {
  17523. next = inputStream->nextRow();
  17524. if(next == NULL)
  17525. break;
  17526. buff.append(NULL);
  17527. }
  17528. count++;
  17529. if (count > rowLimit)
  17530. {
  17531. ReleaseRoxieRow(next);
  17532. ReleaseRoxieRows(buff);
  17533. if (ctx->queryDebugContext())
  17534. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  17535. if (transformExtra)
  17536. {
  17537. ensureRowAllocator();
  17538. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17539. size32_t outSize = transformExtra->transformOnLimitExceeded(rowBuilder);
  17540. if (outSize)
  17541. buff.append(rowBuilder.finalizeRowClear(outSize));
  17542. }
  17543. break;
  17544. }
  17545. buff.append(next);
  17546. }
  17547. started = true;
  17548. }
  17549. };
  17550. class CRoxieServerSkipLimitActivityFactory : public CRoxieServerActivityFactory
  17551. {
  17552. public:
  17553. CRoxieServerSkipLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17554. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  17555. {
  17556. }
  17557. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  17558. {
  17559. return new CRoxieServerSkipLimitActivity(_ctx, this, _probeManager, kind==TAKcreaterowlimit);
  17560. }
  17561. };
  17562. IRoxieServerActivityFactory *createRoxieServerSkipLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17563. {
  17564. return new CRoxieServerSkipLimitActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  17565. }
  17566. //=================================================================================
  17567. class CRoxieServerCatchActivity : public CRoxieServerActivity
  17568. {
  17569. IHThorCatchArg &helper;
  17570. public:
  17571. CRoxieServerCatchActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17572. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorCatchArg &)basehelper)
  17573. {
  17574. }
  17575. virtual const void *nextRow()
  17576. {
  17577. ActivityTimer t(totalCycles, timeActivities);
  17578. try
  17579. {
  17580. const void *ret = inputStream->nextRow();
  17581. if (ret)
  17582. processed++;
  17583. return ret;
  17584. }
  17585. catch (IException *E)
  17586. {
  17587. E->Release();
  17588. helper.onExceptionCaught();
  17589. }
  17590. catch (...)
  17591. {
  17592. helper.onExceptionCaught();
  17593. }
  17594. throwUnexpected(); // onExceptionCaught should have thrown something
  17595. }
  17596. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  17597. {
  17598. try
  17599. {
  17600. ActivityTimer t(totalCycles, timeActivities);
  17601. const void * ret = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  17602. if (ret && wasCompleteMatch)
  17603. processed++;
  17604. return ret;
  17605. }
  17606. catch (IException *E)
  17607. {
  17608. E->Release();
  17609. helper.onExceptionCaught();
  17610. }
  17611. catch (...)
  17612. {
  17613. helper.onExceptionCaught();
  17614. }
  17615. throwUnexpected(); // onExceptionCaught should have thrown something
  17616. }
  17617. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  17618. {
  17619. return input->gatherConjunctions(collector);
  17620. }
  17621. virtual void resetEOF()
  17622. {
  17623. inputStream->resetEOF(); // MORE - why not in base class?
  17624. }
  17625. IInputSteppingMeta * querySteppingMeta()
  17626. {
  17627. return input->querySteppingMeta();
  17628. }
  17629. };
  17630. class CRoxieServerSkipCatchActivity : public CRoxieServerActivity
  17631. {
  17632. ConstPointerArray buff;
  17633. bool started;
  17634. unsigned index;
  17635. IHThorCatchArg &helper;
  17636. bool createRow;
  17637. public:
  17638. CRoxieServerSkipCatchActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _createRow)
  17639. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorCatchArg &)basehelper), createRow(_createRow)
  17640. {
  17641. started = false;
  17642. index = 0;
  17643. }
  17644. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17645. {
  17646. started = false;
  17647. index = 0;
  17648. try
  17649. {
  17650. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  17651. }
  17652. catch (IException *E)
  17653. {
  17654. onException(E);
  17655. started = true;
  17656. }
  17657. catch (...)
  17658. {
  17659. onException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught"));
  17660. started = true;
  17661. }
  17662. }
  17663. virtual void reset()
  17664. {
  17665. roxiemem::ReleaseRoxieRowRange(buff.getArray(), index, buff.ordinality());
  17666. buff.kill();
  17667. index = 0;
  17668. started = false;
  17669. CRoxieServerActivity::reset();
  17670. }
  17671. virtual const void *nextRow()
  17672. {
  17673. ActivityTimer t(totalCycles, timeActivities);
  17674. if (!started)
  17675. pullInput();
  17676. if (buff.isItem(index))
  17677. {
  17678. const void * next = buff.item(index++);
  17679. if(next)
  17680. processed++;
  17681. return next;
  17682. }
  17683. return NULL;
  17684. }
  17685. protected:
  17686. void onException(IException *E)
  17687. {
  17688. inputStream->stop();
  17689. ReleaseRoxieRows(buff);
  17690. if (createRow)
  17691. {
  17692. ensureRowAllocator();
  17693. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17694. size32_t outSize = helper.transformOnExceptionCaught(rowBuilder, E);
  17695. if (outSize)
  17696. buff.append(rowBuilder.finalizeRowClear(outSize));
  17697. }
  17698. E->Release();
  17699. }
  17700. void pullInput()
  17701. {
  17702. try
  17703. {
  17704. bool EOGseen = false;
  17705. for (;;)
  17706. {
  17707. const void * next = inputStream->nextRow();
  17708. buff.append(next);
  17709. if (next == NULL)
  17710. {
  17711. if (EOGseen)
  17712. break;
  17713. EOGseen = true;
  17714. }
  17715. else
  17716. EOGseen = false;
  17717. }
  17718. }
  17719. catch (IException *E)
  17720. {
  17721. onException(E);
  17722. }
  17723. catch (...)
  17724. {
  17725. onException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught"));
  17726. }
  17727. started = true;
  17728. }
  17729. };
  17730. class CRoxieServerCatchActivityFactory : public CRoxieServerActivityFactory
  17731. {
  17732. public:
  17733. CRoxieServerCatchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17734. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  17735. {
  17736. }
  17737. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  17738. {
  17739. switch (kind)
  17740. {
  17741. case TAKcatch:
  17742. return new CRoxieServerCatchActivity(_ctx, this, _probeManager);
  17743. case TAKskipcatch:
  17744. return new CRoxieServerSkipCatchActivity(_ctx, this, _probeManager, false);
  17745. case TAKcreaterowcatch:
  17746. return new CRoxieServerSkipCatchActivity(_ctx, this, _probeManager, true);
  17747. default:
  17748. throwUnexpected();
  17749. }
  17750. }
  17751. };
  17752. IRoxieServerActivityFactory *createRoxieServerCatchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17753. {
  17754. return new CRoxieServerCatchActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  17755. }
  17756. //=================================================================================
  17757. class CRoxieServerPullActivity : public CRoxieServerActivity
  17758. {
  17759. ConstPointerArray buff;
  17760. bool started;
  17761. unsigned index;
  17762. public:
  17763. CRoxieServerPullActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17764. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  17765. {
  17766. started = false;
  17767. index = 0;
  17768. }
  17769. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17770. {
  17771. started = false;
  17772. index = 0;
  17773. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  17774. }
  17775. virtual void reset()
  17776. {
  17777. while (buff.isItem(index))
  17778. ReleaseRoxieRow(buff.item(index++));
  17779. buff.kill();
  17780. started = false;
  17781. index = 0;
  17782. CRoxieServerActivity::reset();
  17783. }
  17784. virtual const void *nextRow()
  17785. {
  17786. ActivityTimer t(totalCycles, timeActivities);
  17787. if (!started)
  17788. pullInput();
  17789. if (buff.isItem(index))
  17790. {
  17791. const void * next = buff.item(index++);
  17792. if (next)
  17793. processed++;
  17794. return next;
  17795. }
  17796. return NULL;
  17797. }
  17798. protected:
  17799. void pullInput()
  17800. {
  17801. bool EOGseen = false;
  17802. for (;;)
  17803. {
  17804. const void * next = inputStream->nextRow();
  17805. buff.append(next);
  17806. if (next == NULL)
  17807. {
  17808. if (EOGseen)
  17809. break;
  17810. EOGseen = true;
  17811. }
  17812. else
  17813. EOGseen = false;
  17814. }
  17815. started = true;
  17816. }
  17817. };
  17818. class CRoxieServerPullActivityFactory : public CRoxieServerActivityFactory
  17819. {
  17820. public:
  17821. CRoxieServerPullActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17822. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  17823. {
  17824. }
  17825. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  17826. {
  17827. return new CRoxieServerPullActivity(_ctx, this, _probeManager);
  17828. }
  17829. };
  17830. IRoxieServerActivityFactory *createRoxieServerPullActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17831. {
  17832. return new CRoxieServerPullActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  17833. }
  17834. //=================================================================================
  17835. class CRoxieServerTraceActivity : public CRoxieServerActivity
  17836. {
  17837. public:
  17838. CRoxieServerTraceActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17839. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorTraceArg &) basehelper),
  17840. keepLimit(0), skip(0), sample(0)
  17841. {
  17842. assertex(meta.hasXML());
  17843. traceEnabled = defaultTraceEnabled && !isBlind();
  17844. }
  17845. virtual void onCreate(IHThorArg *_colocalParent)
  17846. {
  17847. CRoxieServerActivity::onCreate(_colocalParent);
  17848. if (ctx)
  17849. traceEnabled = ctx->queryOptions().traceEnabled && !isBlind();
  17850. }
  17851. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17852. {
  17853. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  17854. if (traceEnabled && helper.canMatchAny())
  17855. {
  17856. keepLimit = helper.getKeepLimit();
  17857. if (keepLimit==(unsigned) -1)
  17858. keepLimit = ctx->queryOptions().traceLimit;
  17859. skip = helper.getSkip();
  17860. sample = helper.getSample();
  17861. if (sample)
  17862. sample--;
  17863. name.setown(helper.getName());
  17864. if (!name)
  17865. name.set("Row");
  17866. }
  17867. else
  17868. keepLimit = 0;
  17869. }
  17870. virtual void stop()
  17871. {
  17872. name.clear();
  17873. CRoxieServerActivity::stop();
  17874. }
  17875. virtual bool isPassThrough()
  17876. {
  17877. return true;
  17878. }
  17879. virtual const void *nextRow()
  17880. {
  17881. ActivityTimer t(totalCycles, timeActivities);
  17882. const void *row = inputStream->nextRow();
  17883. if (row)
  17884. {
  17885. onTrace(row);
  17886. processed++;
  17887. }
  17888. return row;
  17889. }
  17890. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  17891. {
  17892. // MORE - will need rethinking once we rethink the nextRowGE interface for global smart-stepping.
  17893. ActivityTimer t(totalCycles, timeActivities);
  17894. const void * row = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  17895. if (row)
  17896. {
  17897. onTrace(row);
  17898. processed++;
  17899. }
  17900. return row;
  17901. }
  17902. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  17903. {
  17904. return input->gatherConjunctions(collector);
  17905. }
  17906. virtual void resetEOF()
  17907. {
  17908. inputStream->resetEOF();
  17909. }
  17910. IInputSteppingMeta * querySteppingMeta()
  17911. {
  17912. return input->querySteppingMeta();
  17913. }
  17914. protected:
  17915. void onTrace(const void *row)
  17916. {
  17917. if (keepLimit && helper.isValid(row))
  17918. {
  17919. if (skip)
  17920. skip--;
  17921. else if (sample)
  17922. sample--;
  17923. else
  17924. {
  17925. CommonXmlWriter xmlwrite(XWFnoindent);
  17926. meta.toXML((const byte *) row, xmlwrite);
  17927. CTXLOG("TRACE: <%s>%s<%s>", name.get(), xmlwrite.str(), name.get());
  17928. keepLimit--;
  17929. sample = helper.getSample();
  17930. if (sample)
  17931. sample--;
  17932. }
  17933. }
  17934. }
  17935. OwnedRoxieString name;
  17936. IHThorTraceArg &helper;
  17937. unsigned keepLimit;
  17938. unsigned skip;
  17939. unsigned sample;
  17940. bool traceEnabled;
  17941. };
  17942. class CRoxieServerTraceActivityFactory : public CRoxieServerActivityFactory
  17943. {
  17944. public:
  17945. CRoxieServerTraceActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17946. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  17947. {
  17948. }
  17949. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  17950. {
  17951. return new CRoxieServerTraceActivity(_ctx, this, _probeManager);
  17952. }
  17953. };
  17954. IRoxieServerActivityFactory *createRoxieServerTraceActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17955. {
  17956. return new CRoxieServerTraceActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  17957. }
  17958. //=================================================================================
  17959. class CRoxieServerCaseActivity : public CRoxieServerMultiInputBaseActivity
  17960. {
  17961. IHThorCaseArg &helper;
  17962. unsigned cond;
  17963. bool unusedStopped;
  17964. IEngineRowStream *active;
  17965. public:
  17966. CRoxieServerCaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  17967. : CRoxieServerMultiInputBaseActivity(_ctx, _factory, _probeManager, _numInputs), helper((IHThorCaseArg &)basehelper)
  17968. {
  17969. unusedStopped = false;
  17970. cond = 0;
  17971. active = NULL;
  17972. }
  17973. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17974. {
  17975. CRoxieServerMultiInputBaseActivity::start(parentExtractSize, parentExtract, paused);
  17976. cond = helper.getBranch();
  17977. //CHOOSE defaults to the last argument if out of range.
  17978. if (cond >= numInputs)
  17979. cond = numInputs - 1;
  17980. inputArray[cond]->start(parentExtractSize, parentExtract, paused);
  17981. startJunction(junctionArray[cond]);
  17982. assertex(numInputs==numStreams);
  17983. for (unsigned idx = 0; idx < numStreams; idx++)
  17984. {
  17985. if (idx!=cond)
  17986. streamArray[idx]->stop(); // Note: stopping unused branches early helps us avoid buffering splits too long.
  17987. }
  17988. active = streamArray[cond];
  17989. unusedStopped = true;
  17990. }
  17991. virtual void stop()
  17992. {
  17993. for (unsigned idx = 0; idx < numStreams; idx++)
  17994. {
  17995. if (idx==cond || !unusedStopped)
  17996. streamArray[idx]->stop();
  17997. }
  17998. CRoxieServerMultiInputBaseActivity::stop();
  17999. }
  18000. virtual void reset()
  18001. {
  18002. unusedStopped = false;
  18003. active = NULL;
  18004. CRoxieServerMultiInputBaseActivity::reset();
  18005. }
  18006. virtual const void *nextRow()
  18007. {
  18008. ActivityTimer t(totalCycles, timeActivities);
  18009. if (active)
  18010. {
  18011. const void *ret = active->nextRow();
  18012. if (ret)
  18013. processed++;
  18014. return ret;
  18015. }
  18016. return NULL;
  18017. }
  18018. };
  18019. class CRoxieServerCaseActivityFactory : public CRoxieServerMultiInputFactory
  18020. {
  18021. bool graphInvariant;
  18022. public:
  18023. CRoxieServerCaseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _graphInvariant)
  18024. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  18025. {
  18026. graphInvariant = _graphInvariant;
  18027. }
  18028. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18029. {
  18030. return new CRoxieServerCaseActivity(_ctx, this, _probeManager, numInputs());
  18031. }
  18032. virtual bool isGraphInvariant() const
  18033. {
  18034. return graphInvariant;
  18035. }
  18036. };
  18037. IRoxieServerActivityFactory *createRoxieServerCaseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _graphInvariant)
  18038. {
  18039. return new CRoxieServerCaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _graphInvariant);
  18040. }
  18041. //=================================================================================
  18042. class CRoxieServerIfActivity : public CRoxieServerActivity
  18043. {
  18044. IHThorIfArg &helper;
  18045. IFinalRoxieInput *inputTrue;
  18046. IFinalRoxieInput *inputFalse;
  18047. IEngineRowStream *streamTrue;
  18048. IEngineRowStream *streamFalse;
  18049. unsigned sourceIdxFalse = 0;
  18050. unsigned sourceIdxTrue = 0;
  18051. Owned<IStrandJunction> junctionTrue;
  18052. Owned<IStrandJunction> junctionFalse;
  18053. bool cond;
  18054. bool unusedStopped;
  18055. public:
  18056. CRoxieServerIfActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18057. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorIfArg &)basehelper)
  18058. {
  18059. inputFalse = NULL;
  18060. inputTrue = NULL;
  18061. streamTrue = NULL;
  18062. streamFalse = NULL;
  18063. unusedStopped = false;
  18064. cond = false;
  18065. }
  18066. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18067. {
  18068. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  18069. cond = helper.getCondition();
  18070. if (cond)
  18071. {
  18072. inputTrue->start(parentExtractSize, parentExtract, paused);
  18073. startJunction(junctionTrue);
  18074. if (streamFalse)
  18075. streamFalse->stop(); // Note: stopping unused branches early helps us avoid buffering splits too long.
  18076. }
  18077. else
  18078. {
  18079. if (inputFalse)
  18080. {
  18081. inputFalse->start(parentExtractSize, parentExtract, paused);
  18082. startJunction(junctionFalse);
  18083. }
  18084. streamTrue->stop();
  18085. }
  18086. unusedStopped = true;
  18087. }
  18088. virtual void stop()
  18089. {
  18090. if (!unusedStopped || cond)
  18091. streamTrue->stop();
  18092. if (streamFalse && (!unusedStopped || !cond))
  18093. streamFalse->stop();
  18094. CRoxieServerActivity::stop();
  18095. }
  18096. virtual unsigned __int64 queryLocalCycles() const
  18097. {
  18098. __int64 localCycles = totalCycles.totalCycles;
  18099. localCycles -= inputTrue->queryTotalCycles();
  18100. if (inputFalse)
  18101. localCycles -= inputFalse->queryTotalCycles();
  18102. if (localCycles < 0)
  18103. localCycles = 0;
  18104. return localCycles;
  18105. }
  18106. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  18107. {
  18108. switch (idx)
  18109. {
  18110. case 0:
  18111. return inputTrue;
  18112. case 1:
  18113. return inputFalse;
  18114. default:
  18115. return NULL;
  18116. }
  18117. }
  18118. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { return this; }
  18119. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { return nullptr; }
  18120. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  18121. {
  18122. IFinalRoxieInput *in = cond ? inputTrue : inputFalse;
  18123. if (in)
  18124. return in->queryIndexReadActivity();
  18125. return NULL;
  18126. }
  18127. virtual void reset()
  18128. {
  18129. CRoxieServerActivity::reset();
  18130. inputTrue->reset();
  18131. if (inputFalse)
  18132. inputFalse->reset();
  18133. resetJunction(junctionTrue);
  18134. resetJunction(junctionFalse);
  18135. unusedStopped = false;
  18136. }
  18137. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  18138. {
  18139. if (idx==1)
  18140. {
  18141. inputFalse = _in;
  18142. sourceIdxFalse = _sourceIdx;
  18143. }
  18144. else
  18145. {
  18146. assertex(!idx);
  18147. inputTrue = _in;
  18148. sourceIdxTrue = _sourceIdx;
  18149. }
  18150. }
  18151. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  18152. {
  18153. //It should be possible to stream IF(), but the number of strands would need to match on the two branches.
  18154. streamTrue = connectSingleStream(ctx, inputTrue, sourceIdxTrue, junctionTrue, consumerOrdered);
  18155. streamFalse = connectSingleStream(ctx, inputFalse, sourceIdxFalse, junctionFalse, consumerOrdered);
  18156. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, nullptr, consumerOrdered, nullptr);
  18157. }
  18158. virtual const void *nextRow()
  18159. {
  18160. ActivityTimer t(totalCycles, timeActivities);
  18161. IEngineRowStream *in = cond ? streamTrue : streamFalse;
  18162. if (in)
  18163. {
  18164. const void * ret;
  18165. if ((ret = in->nextRow()) != NULL)
  18166. processed++;
  18167. return ret;
  18168. }
  18169. return NULL;
  18170. }
  18171. };
  18172. class CRoxieServerIfActivityFactory : public CRoxieServerActivityFactory
  18173. {
  18174. unsigned input2;
  18175. unsigned input2idx;
  18176. bool graphInvariant;
  18177. public:
  18178. CRoxieServerIfActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _graphInvariant)
  18179. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  18180. {
  18181. graphInvariant = _graphInvariant;
  18182. input2 = (unsigned)-1;
  18183. input2idx = (unsigned)-1;
  18184. }
  18185. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18186. {
  18187. return new CRoxieServerIfActivity(_ctx, this, _probeManager);
  18188. }
  18189. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  18190. {
  18191. if (idx==1)
  18192. {
  18193. input2 = source;
  18194. input2idx = sourceidx;
  18195. }
  18196. else
  18197. CRoxieServerActivityFactory::setInput(idx, source, sourceidx);
  18198. }
  18199. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  18200. {
  18201. switch (idx)
  18202. {
  18203. case 1:
  18204. sourceidx = input2idx;
  18205. return input2;
  18206. case 0:
  18207. return CRoxieServerActivityFactory::getInput(idx, sourceidx);
  18208. default:
  18209. return (unsigned) -1;
  18210. }
  18211. }
  18212. virtual unsigned numInputs() const { return (input2 == (unsigned)-1) ? 1 : 2; }
  18213. virtual bool isGraphInvariant() const
  18214. {
  18215. return graphInvariant;
  18216. }
  18217. };
  18218. IRoxieServerActivityFactory *createRoxieServerIfActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _graphInvariant)
  18219. {
  18220. return new CRoxieServerIfActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _graphInvariant);
  18221. }
  18222. //=================================================================================
  18223. class CRoxieServerActionBaseActivity : public CRoxieServerActivity
  18224. {
  18225. CriticalSection ecrit;
  18226. Owned<IException> exception;
  18227. bool executed;
  18228. public:
  18229. CRoxieServerActionBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18230. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  18231. {
  18232. executed = false;
  18233. }
  18234. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract) = 0;
  18235. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  18236. {
  18237. CriticalBlock b(ecrit);
  18238. if (exception)
  18239. throw(exception.getLink());
  18240. if (!executed)
  18241. {
  18242. try
  18243. {
  18244. executed = true;
  18245. start(parentExtractSize, parentExtract, false);
  18246. doExecuteAction(parentExtractSize, parentExtract);
  18247. stop();
  18248. }
  18249. catch (IException * E)
  18250. {
  18251. ctx->notifyAbort(E);
  18252. abort();
  18253. exception.set(E);
  18254. throw;
  18255. }
  18256. }
  18257. }
  18258. virtual void reset()
  18259. {
  18260. executed = false;
  18261. exception.clear();
  18262. CRoxieServerActivity::reset();
  18263. }
  18264. virtual const void *nextRow()
  18265. {
  18266. throwUnexpected(); // I am nobody's input
  18267. }
  18268. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  18269. {
  18270. return NULL;
  18271. }
  18272. };
  18273. class CRoxieServerIfActionActivity : public CRoxieServerActionBaseActivity
  18274. {
  18275. IHThorIfArg &helper;
  18276. public:
  18277. CRoxieServerIfActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18278. : CRoxieServerActionBaseActivity(_ctx, _factory, _probeManager), helper((IHThorIfArg &)basehelper)
  18279. {
  18280. }
  18281. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  18282. {
  18283. bool cond;
  18284. {
  18285. ActivityTimer t(totalCycles, timeActivities);
  18286. cond = helper.getCondition();
  18287. }
  18288. stopDependencies(parentExtractSize, parentExtract, cond ? 2 : 1);
  18289. executeDependencies(parentExtractSize, parentExtract, cond ? 1 : 2);
  18290. }
  18291. };
  18292. class CRoxieServerIfActionActivityFactory : public CRoxieServerActivityFactory
  18293. {
  18294. bool isRoot;
  18295. public:
  18296. CRoxieServerIfActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18297. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  18298. {
  18299. }
  18300. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18301. {
  18302. return new CRoxieServerIfActionActivity(_ctx, this, _probeManager);
  18303. }
  18304. virtual bool isSink() const
  18305. {
  18306. return isRoot;
  18307. }
  18308. };
  18309. IRoxieServerActivityFactory *createRoxieServerIfActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18310. {
  18311. return new CRoxieServerIfActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  18312. }
  18313. //=================================================================================
  18314. class CRoxieServerParallelActionActivity : public CRoxieServerActionBaseActivity
  18315. {
  18316. public:
  18317. CRoxieServerParallelActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18318. : CRoxieServerActionBaseActivity(_ctx, _factory, _probeManager)
  18319. {
  18320. }
  18321. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  18322. {
  18323. #ifdef PARALLEL_EXECUTE
  18324. CParallelActivityExecutor afor(dependencies, parentExtractSize, parentExtract);
  18325. afor.For(dependencies.ordinality(), dependencies.ordinality(), true);
  18326. #else
  18327. ForEachItemIn(idx, dependencies)
  18328. {
  18329. dependencies.item(idx).execute(parentExtractSize, parentExtract);
  18330. }
  18331. #endif
  18332. }
  18333. };
  18334. class CRoxieServerParallelActionActivityFactory : public CRoxieServerActivityFactory
  18335. {
  18336. bool isRoot;
  18337. public:
  18338. CRoxieServerParallelActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18339. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  18340. {
  18341. assertex(!isRoot); // non-internal should be expanded out..
  18342. }
  18343. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18344. {
  18345. return new CRoxieServerParallelActionActivity(_ctx, this, _probeManager);
  18346. }
  18347. virtual bool isSink() const
  18348. {
  18349. return isRoot;
  18350. }
  18351. };
  18352. IRoxieServerActivityFactory *createRoxieServerParallelActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18353. {
  18354. return new CRoxieServerParallelActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  18355. }
  18356. //=================================================================================
  18357. class CRoxieServerSequentialActionActivity : public CRoxieServerActionBaseActivity
  18358. {
  18359. IHThorSequentialArg &helper;
  18360. public:
  18361. CRoxieServerSequentialActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18362. : CRoxieServerActionBaseActivity(_ctx, _factory, _probeManager), helper((IHThorSequentialArg &)basehelper)
  18363. {
  18364. }
  18365. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  18366. {
  18367. unsigned numBranches = helper.numBranches();
  18368. for (unsigned branch=1; branch <= numBranches; branch++)
  18369. executeDependencies(parentExtractSize, parentExtract, branch);
  18370. }
  18371. };
  18372. class CRoxieServerSequentialActionActivityFactory : public CRoxieServerActivityFactory
  18373. {
  18374. bool isRoot;
  18375. public:
  18376. CRoxieServerSequentialActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18377. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  18378. {
  18379. }
  18380. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18381. {
  18382. return new CRoxieServerSequentialActionActivity(_ctx, this, _probeManager);
  18383. }
  18384. virtual bool isSink() const
  18385. {
  18386. return isRoot;
  18387. }
  18388. };
  18389. IRoxieServerActivityFactory *createRoxieServerSequentialActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18390. {
  18391. return new CRoxieServerSequentialActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  18392. }
  18393. //=================================================================================
  18394. class CRoxieServerWhenActivity : public CRoxieServerActivity
  18395. {
  18396. public:
  18397. CRoxieServerWhenActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18398. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  18399. {
  18400. savedExtractSize = 0;
  18401. savedExtract = NULL;
  18402. eofseen = false;
  18403. eogseen = false;
  18404. }
  18405. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18406. {
  18407. savedExtractSize = parentExtractSize;
  18408. savedExtract = parentExtract;
  18409. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  18410. executeDependencies(parentExtractSize, parentExtract, WhenBeforeId);
  18411. executeDependencies(parentExtractSize, parentExtract, WhenParallelId); // MORE: This should probably be done in parallel!
  18412. eofseen = false;
  18413. eogseen = false;
  18414. }
  18415. virtual void stop()
  18416. {
  18417. if (state == STATEreset || (!aborted && !eofseen)) // If someone else aborted, then WHEN clauses don't trigger, whatever
  18418. {
  18419. stopDependencies(savedExtractSize, savedExtract, WhenSuccessId);
  18420. stopDependencies(savedExtractSize, savedExtract, WhenFailureId);
  18421. }
  18422. else if (state != STATEstopped)
  18423. {
  18424. stopDependencies(savedExtractSize, savedExtract, aborted ? WhenSuccessId : WhenFailureId); // These ones don't get executed
  18425. executeDependencies(savedExtractSize, savedExtract, aborted ? WhenFailureId : WhenSuccessId); // These ones do
  18426. }
  18427. CRoxieServerActivity::stop();
  18428. }
  18429. virtual const void *nextRow()
  18430. {
  18431. try
  18432. {
  18433. ActivityTimer t(totalCycles, timeActivities); // bit of a waste of time....
  18434. const void *ret = inputStream->nextRow();
  18435. if (!ret)
  18436. {
  18437. if (eogseen)
  18438. eofseen = true;
  18439. else
  18440. eogseen = true;
  18441. }
  18442. else
  18443. eogseen = false;
  18444. return ret;
  18445. }
  18446. catch (...)
  18447. {
  18448. aborted = true;
  18449. throw;
  18450. }
  18451. }
  18452. protected:
  18453. const byte *savedExtract;
  18454. unsigned savedExtractSize;
  18455. bool eofseen;
  18456. bool eogseen;
  18457. };
  18458. class CRoxieServerWhenActivityFactory : public CRoxieServerActivityFactory
  18459. {
  18460. public:
  18461. CRoxieServerWhenActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  18462. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  18463. {
  18464. }
  18465. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18466. {
  18467. return new CRoxieServerWhenActivity(_ctx, this, _probeManager);
  18468. }
  18469. };
  18470. extern IRoxieServerActivityFactory *createRoxieServerWhenActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  18471. {
  18472. return new CRoxieServerWhenActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  18473. }
  18474. //=================================================================================
  18475. class CRoxieServerWhenActionActivity : public CRoxieServerActionBaseActivity
  18476. {
  18477. public:
  18478. CRoxieServerWhenActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18479. : CRoxieServerActionBaseActivity(_ctx, _factory, _probeManager)
  18480. {
  18481. savedExtractSize = 0;
  18482. savedExtract = NULL;
  18483. }
  18484. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18485. {
  18486. savedExtractSize = parentExtractSize;
  18487. savedExtract = parentExtract;
  18488. CRoxieServerActionBaseActivity::start(parentExtractSize, parentExtract, paused);
  18489. executeDependencies(parentExtractSize, parentExtract, WhenBeforeId);
  18490. executeDependencies(parentExtractSize, parentExtract, WhenParallelId); // MORE: This should probably be done in parallel!
  18491. }
  18492. virtual void stop()
  18493. {
  18494. if (state != STATEstopped)
  18495. {
  18496. stopDependencies(savedExtractSize, savedExtract, aborted ? WhenSuccessId : WhenFailureId); // these are NOT going to execute
  18497. executeDependencies(savedExtractSize, savedExtract, aborted ? WhenFailureId : WhenSuccessId);
  18498. }
  18499. CRoxieServerActionBaseActivity::stop();
  18500. }
  18501. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  18502. {
  18503. executeDependencies(parentExtractSize, parentExtract, 1);
  18504. }
  18505. protected:
  18506. unsigned savedExtractSize;
  18507. const byte *savedExtract;
  18508. };
  18509. class CRoxieServerWhenActionActivityFactory : public CRoxieServerActivityFactory
  18510. {
  18511. public:
  18512. CRoxieServerWhenActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18513. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  18514. {
  18515. }
  18516. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18517. {
  18518. return new CRoxieServerWhenActionActivity(_ctx, this, _probeManager);
  18519. }
  18520. virtual bool isSink() const
  18521. {
  18522. return isRoot;
  18523. }
  18524. private:
  18525. bool isRoot;
  18526. };
  18527. extern IRoxieServerActivityFactory *createRoxieServerWhenActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18528. {
  18529. return new CRoxieServerWhenActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  18530. }
  18531. //=================================================================================
  18532. class CRoxieServerStrandedParseActivity : public CRoxieServerStrandedActivity
  18533. {
  18534. INlpParseAlgorithm * algorithm;
  18535. class ParseProcessor : public StrandProcessor, implements IMatchedAction
  18536. {
  18537. protected:
  18538. IHThorParseArg &helper;
  18539. INlpParser * parser;
  18540. INlpResultIterator * rowIter;
  18541. const void * in;
  18542. char * curSearchText;
  18543. size32_t curSearchTextLen;
  18544. bool processRecord(const void * inRec)
  18545. {
  18546. if (helper.searchTextNeedsFree())
  18547. rtlFree(curSearchText);
  18548. curSearchTextLen = 0;
  18549. curSearchText = NULL;
  18550. helper.getSearchText(curSearchTextLen, curSearchText, inRec);
  18551. return parser->performMatch(*this, in, curSearchTextLen, curSearchText);
  18552. }
  18553. public:
  18554. ParseProcessor(CRoxieServerActivity &_parent, IEngineRowStream *_inputStream, IHThorParseArg &_helper, INlpParseAlgorithm * _algorithm)
  18555. : StrandProcessor(_parent, _inputStream, false), helper(_helper)
  18556. {
  18557. parser = _algorithm->createParser(parent.queryCodeContext(), parent.queryId(), helper.queryHelper(), &helper);
  18558. rowIter = parser->queryResultIter();
  18559. in = NULL;
  18560. curSearchText = NULL;
  18561. curSearchTextLen = 0;
  18562. }
  18563. ~ParseProcessor()
  18564. {
  18565. ::Release(parser);
  18566. }
  18567. virtual void start()
  18568. {
  18569. StrandProcessor::start();
  18570. numProcessedLastGroup = 0;
  18571. curSearchTextLen = 0;
  18572. curSearchText = NULL;
  18573. in = NULL;
  18574. parser->reset();
  18575. }
  18576. virtual void reset()
  18577. {
  18578. if (helper.searchTextNeedsFree())
  18579. rtlFree(curSearchText);
  18580. curSearchText = NULL;
  18581. ReleaseClearRoxieRow(in);
  18582. StrandProcessor::reset();
  18583. }
  18584. virtual const void * nextRow()
  18585. {
  18586. ActivityTimer t(totalCycles, timeActivities);
  18587. for (;;)
  18588. {
  18589. if (rowIter->isValid())
  18590. {
  18591. OwnedConstRoxieRow out = rowIter->getRow();
  18592. rowIter->next();
  18593. processed++;
  18594. return out.getClear();
  18595. }
  18596. ReleaseClearRoxieRow(in);
  18597. in = inputStream->nextRow();
  18598. if (!in)
  18599. {
  18600. if (processed == numProcessedLastGroup)
  18601. in = inputStream->nextRow();
  18602. if (!in)
  18603. {
  18604. processed = numProcessedLastGroup;
  18605. return NULL;
  18606. }
  18607. in = inputStream->nextRow();
  18608. if (!in)
  18609. return NULL;
  18610. }
  18611. processRecord(in);
  18612. rowIter->first();
  18613. }
  18614. }
  18615. virtual unsigned onMatch(ARowBuilder & self, const void * curRecord, IMatchedResults * results, IMatchWalker * walker)
  18616. {
  18617. try
  18618. {
  18619. return helper.transform(self, curRecord, results, walker);
  18620. }
  18621. catch (IException *E)
  18622. {
  18623. throw parent.makeWrappedException(E);
  18624. }
  18625. }
  18626. };
  18627. public:
  18628. CRoxieServerStrandedParseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, INlpParseAlgorithm * _algorithm, const StrandOptions &_strandOptions)
  18629. : CRoxieServerStrandedActivity(_ctx, _factory, _probeManager, _strandOptions), algorithm(_algorithm)
  18630. {
  18631. }
  18632. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18633. {
  18634. CRoxieServerStrandedActivity::start(parentExtractSize, parentExtract, paused);
  18635. onStartStrands();
  18636. }
  18637. virtual StrandProcessor *createStrandProcessor(IEngineRowStream *instream)
  18638. {
  18639. return new ParseProcessor(*this, instream, (IHThorParseArg &) basehelper, algorithm);
  18640. }
  18641. virtual StrandProcessor *createStrandSourceProcessor(bool inputOrdered) { throwUnexpected(); }
  18642. };
  18643. class CRoxieServerParseActivityFactory : public CRoxieServerActivityFactory
  18644. {
  18645. Owned<INlpParseAlgorithm> algorithm;
  18646. Owned<IHThorParseArg> helper;
  18647. StrandOptions strandOptions;
  18648. public:
  18649. CRoxieServerParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, IResourceContext *rc)
  18650. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), strandOptions(_graphNode)
  18651. {
  18652. helper.setown((IHThorParseArg *) helperFactory());
  18653. algorithm.setown(createThorParser(rc, *helper));
  18654. optStableInput = false;
  18655. }
  18656. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18657. {
  18658. return new CRoxieServerStrandedParseActivity(_ctx, this, _probeManager, algorithm, strandOptions);
  18659. }
  18660. };
  18661. IRoxieServerActivityFactory *createRoxieServerParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, IResourceContext *rc)
  18662. {
  18663. return new CRoxieServerParseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, rc);
  18664. }
  18665. //=====================================================================================================
  18666. class CRoxieServerWorkUnitWriteActivity : public CRoxieServerInternalSinkActivity
  18667. {
  18668. IHThorWorkUnitWriteArg &helper;
  18669. bool isReread;
  18670. bool grouped;
  18671. IRoxieServerContext *serverContext;
  18672. public:
  18673. CRoxieServerWorkUnitWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _isReread, unsigned _numOutputs)
  18674. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _numOutputs), helper((IHThorWorkUnitWriteArg &)basehelper), isReread(_isReread)
  18675. {
  18676. grouped = (helper.getFlags() & POFgrouped) != 0;
  18677. serverContext = NULL;
  18678. }
  18679. virtual void onCreate(IHThorArg *_colocalParent)
  18680. {
  18681. CRoxieServerInternalSinkActivity::onCreate(_colocalParent);
  18682. serverContext = ctx->queryServerContext();
  18683. if (!serverContext)
  18684. {
  18685. throw MakeStringException(ROXIE_PIPE_ERROR, "Pipe output activity cannot be executed in slave context");
  18686. }
  18687. }
  18688. virtual bool needsAllocator() const { return true; }
  18689. virtual void onExecute()
  18690. {
  18691. int sequence = helper.getSequence();
  18692. const char *storedName = helper.queryName();
  18693. if (!storedName)
  18694. storedName = "Dataset";
  18695. MemoryBuffer result;
  18696. bool saveInContext = (int) sequence < 0 || isReread;
  18697. if (!meta.queryOriginal()) // this is a bit of a hack - don't know why no meta on an output....
  18698. meta.set(input->queryOutputMeta());
  18699. Owned<IOutputRowSerializer> rowSerializer;
  18700. Owned<IXmlWriter> xmlwriter;
  18701. bool appendRaw = false;
  18702. IHpccProtocolResultsWriter *results = NULL;
  18703. IHpccNativeProtocolResultsWriter *nativeResults = NULL;
  18704. IHpccProtocolResponse *protocol = serverContext->queryProtocol();
  18705. unsigned protocolFlags = (protocol) ? protocol->getFlags() : 0;
  18706. if ((int) sequence >= 0)
  18707. {
  18708. results = (protocol) ? protocol->queryHpccResultsSection() : NULL;
  18709. if (results)
  18710. {
  18711. nativeResults = dynamic_cast<IHpccNativeProtocolResultsWriter*>(results);
  18712. xmlwriter.setown(results->addDataset(helper.queryName(), sequence, "Dataset", appendRaw, serverContext->getXmlFlags(), (helper.getFlags() & POFextend) != 0, serverContext->queryXmlns(sequence))); //xmlwriter only returned if needed
  18713. }
  18714. }
  18715. size32_t outputLimitBytes = 0;
  18716. IConstWorkUnit *workunit = serverContext->queryWorkUnit();
  18717. if (workunit)
  18718. {
  18719. size32_t outputLimit;
  18720. if (helper.getFlags() & POFmaxsize)
  18721. outputLimit = helper.getMaxSize();
  18722. else
  18723. {
  18724. // In absense of OPT_OUTPUTLIMIT check pre 5.2 legacy name OPT_OUTPUTLIMIT_LEGACY
  18725. outputLimit = workunit->getDebugValueInt(OPT_OUTPUTLIMIT, workunit->getDebugValueInt(OPT_OUTPUTLIMIT_LEGACY, defaultDaliResultLimit));
  18726. }
  18727. if (outputLimit>defaultDaliResultOutputMax)
  18728. 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);
  18729. assertex(outputLimit<=0x1000); // 32bit limit because MemoryBuffer/CMessageBuffers involved etc.
  18730. outputLimitBytes = outputLimit * 0x100000;
  18731. }
  18732. if (workunit != NULL || (results && protocol->getFlags() & HPCC_PROTOCOL_NATIVE_RAW))
  18733. {
  18734. ensureRowAllocator();
  18735. rowSerializer.setown(rowAllocator->createDiskSerializer(ctx->queryCodeContext()));
  18736. }
  18737. __int64 initialProcessed = processed;
  18738. RtlLinkedDatasetBuilder builder(rowAllocator);
  18739. for (;;)
  18740. {
  18741. const void *row = inputStream->nextRow();
  18742. if (saveInContext)
  18743. {
  18744. if (row || grouped)
  18745. builder.append(row);
  18746. }
  18747. if (grouped && (processed != initialProcessed))
  18748. {
  18749. if (workunit)
  18750. result.append(row == NULL);
  18751. if (results)
  18752. {
  18753. if (protocolFlags & HPCC_PROTOCOL_NATIVE_RAW && nativeResults)
  18754. {
  18755. char val = (char)(row == NULL);
  18756. nativeResults->appendRaw(sequence, 1, &val);
  18757. }
  18758. else if (xmlwriter)
  18759. {
  18760. xmlwriter->outputBeginNested("Row", false);
  18761. xmlwriter->outputCString("1", "@__GroupBreak__");
  18762. xmlwriter->outputEndNested("Row");
  18763. }
  18764. }
  18765. }
  18766. if (!row)
  18767. {
  18768. row = inputStream->nextRow();
  18769. if (!row)
  18770. break;
  18771. if (saveInContext)
  18772. builder.append(row);
  18773. }
  18774. processed++;
  18775. if (workunit)
  18776. {
  18777. CThorDemoRowSerializer serializerTarget(result);
  18778. rowSerializer->serialize(serializerTarget, (const byte *) row);
  18779. }
  18780. if ((int) sequence >= 0)
  18781. {
  18782. if (appendRaw && nativeResults)
  18783. {
  18784. // MORE - should be able to serialize straight to the response...
  18785. MemoryBuffer rowbuff;
  18786. CThorDemoRowSerializer serializerTarget(rowbuff);
  18787. rowSerializer->serialize(serializerTarget, (const byte *) row);
  18788. nativeResults->appendRawRow(sequence, rowbuff.length(), rowbuff.toByteArray());
  18789. }
  18790. else if (xmlwriter)
  18791. {
  18792. xmlwriter->outputBeginNested(DEFAULTXMLROWTAG, false);
  18793. helper.serializeXml((byte *) row, *xmlwriter);
  18794. xmlwriter->outputEndNested(DEFAULTXMLROWTAG);
  18795. results->finalizeXmlRow(sequence);
  18796. }
  18797. else if (nativeResults)
  18798. {
  18799. SimpleOutputWriter x;
  18800. helper.serializeXml((byte *) row, x);
  18801. x.newline();
  18802. nativeResults->appendSimpleRow(sequence, x.str());
  18803. }
  18804. }
  18805. ReleaseRoxieRow(row);
  18806. if (outputLimitBytes && result.length() > outputLimitBytes)
  18807. {
  18808. StringBuffer errMsg("Dataset too large to output to workunit (limit ");
  18809. errMsg.append(outputLimitBytes/0x100000).append(" megabytes), in result (");
  18810. const char *name = helper.queryName();
  18811. if (name)
  18812. errMsg.append("name=").append(name);
  18813. else
  18814. errMsg.append("sequence=").append(helper.getSequence());
  18815. errMsg.append(")");
  18816. throw MakeStringExceptionDirect(0, errMsg.str());
  18817. }
  18818. }
  18819. if (xmlwriter)
  18820. xmlwriter->outputEndArray(DEFAULTXMLROWTAG);
  18821. if (saveInContext)
  18822. serverContext->appendResultDeserialized(storedName, sequence, builder.getcount(), builder.linkrows(), (helper.getFlags() & POFextend) != 0, LINK(meta.queryOriginal()));
  18823. if (workunit)
  18824. serverContext->appendResultRawContext(storedName, sequence, result.length(), result.toByteArray(), processed, (helper.getFlags() & POFextend) != 0, false); // MORE - shame to do extra copy...
  18825. }
  18826. };
  18827. class CRoxieServerWorkUnitWriteActivityFactory : public CRoxieServerInternalSinkFactory
  18828. {
  18829. bool isReread;
  18830. public:
  18831. CRoxieServerWorkUnitWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  18832. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot)
  18833. {
  18834. isReread = usageCount > 0;
  18835. Owned<IHThorWorkUnitWriteArg> helper = (IHThorWorkUnitWriteArg *) helperFactory();
  18836. isInternal = (helper->getSequence()==ResultSequenceInternal);
  18837. }
  18838. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18839. {
  18840. return new CRoxieServerWorkUnitWriteActivity(_ctx, this, _probeManager, isReread, usageCount);
  18841. }
  18842. };
  18843. IRoxieServerActivityFactory *createRoxieServerWorkUnitWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  18844. {
  18845. return new CRoxieServerWorkUnitWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot);
  18846. }
  18847. //=====================================================================================================
  18848. class CRoxieServerWorkUnitWriteDictActivity : public CRoxieServerInternalSinkActivity
  18849. {
  18850. IHThorDictionaryWorkUnitWriteArg &helper;
  18851. IRoxieServerContext *serverContext;
  18852. public:
  18853. CRoxieServerWorkUnitWriteDictActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _usageCount)
  18854. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _usageCount), helper((IHThorDictionaryWorkUnitWriteArg &)basehelper)
  18855. {
  18856. serverContext = NULL;
  18857. }
  18858. virtual void onCreate(IHThorArg *_colocalParent)
  18859. {
  18860. CRoxieServerInternalSinkActivity::onCreate(_colocalParent);
  18861. serverContext = ctx->queryServerContext();
  18862. if (!serverContext)
  18863. {
  18864. throw MakeStringException(ROXIE_PIPE_ERROR, "Write Dictionary activity cannot be executed in slave context");
  18865. }
  18866. }
  18867. virtual bool needsAllocator() const { return true; }
  18868. virtual void onExecute()
  18869. {
  18870. int sequence = helper.getSequence();
  18871. const char *storedName = helper.queryName();
  18872. assertex(storedName && *storedName);
  18873. assertex(sequence < 0);
  18874. RtlLinkedDictionaryBuilder builder(rowAllocator, helper.queryHashLookupInfo());
  18875. for (;;)
  18876. {
  18877. const void *row = inputStream->ungroupedNextRow();
  18878. if (!row)
  18879. break;
  18880. builder.appendOwn(row);
  18881. processed++;
  18882. }
  18883. serverContext->appendResultDeserialized(storedName, sequence, builder.getcount(), builder.linkrows(), (helper.getFlags() & POFextend) != 0, LINK(meta.queryOriginal()));
  18884. }
  18885. };
  18886. class CRoxieServerWorkUnitWriteDictActivityFactory : public CRoxieServerInternalSinkFactory
  18887. {
  18888. public:
  18889. CRoxieServerWorkUnitWriteDictActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  18890. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot)
  18891. {
  18892. Owned<IHThorDictionaryWorkUnitWriteArg> helper = (IHThorDictionaryWorkUnitWriteArg *) helperFactory();
  18893. isInternal = (helper->getSequence()==ResultSequenceInternal);
  18894. }
  18895. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18896. {
  18897. return new CRoxieServerWorkUnitWriteDictActivity(_ctx, this, _probeManager, usageCount);
  18898. }
  18899. };
  18900. IRoxieServerActivityFactory *createRoxieServerWorkUnitWriteDictActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  18901. {
  18902. return new CRoxieServerWorkUnitWriteDictActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot);
  18903. }
  18904. //=================================================================================
  18905. class CRoxieServerRemoteResultActivity : public CRoxieServerInternalSinkActivity
  18906. {
  18907. IHThorRemoteResultArg &helper;
  18908. public:
  18909. CRoxieServerRemoteResultActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  18910. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _numOutputs), helper((IHThorRemoteResultArg &)basehelper)
  18911. {
  18912. }
  18913. virtual void onExecute()
  18914. {
  18915. OwnedConstRoxieRow row = inputStream->nextRow();
  18916. helper.sendResult(row); // should be only one row or something has gone wrong!
  18917. }
  18918. };
  18919. class CRoxieServerRemoteResultActivityFactory : public CRoxieServerInternalSinkFactory
  18920. {
  18921. public:
  18922. CRoxieServerRemoteResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  18923. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot)
  18924. {
  18925. Owned<IHThorRemoteResultArg> helper = (IHThorRemoteResultArg *) helperFactory();
  18926. isInternal = (helper->getSequence()==ResultSequenceInternal);
  18927. }
  18928. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18929. {
  18930. return new CRoxieServerRemoteResultActivity(_ctx, this, _probeManager, usageCount);
  18931. }
  18932. };
  18933. IRoxieServerActivityFactory *createRoxieServerRemoteResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  18934. {
  18935. return new CRoxieServerRemoteResultActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot);
  18936. }
  18937. //=================================================================================
  18938. class CRoxieServerXmlParseActivity : public CRoxieServerActivity, implements IXMLSelect
  18939. {
  18940. IHThorXmlParseArg &helper;
  18941. Owned<IXMLParse> xmlParser;
  18942. const void * in;
  18943. char * srchStr;
  18944. unsigned numProcessedLastGroup;
  18945. bool srchStrNeedsFree;
  18946. Owned<IColumnProvider> lastMatch;
  18947. public:
  18948. IMPLEMENT_IINTERFACE_USING(CRoxieServerActivity)
  18949. CRoxieServerXmlParseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18950. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  18951. helper((IHThorXmlParseArg &)basehelper)
  18952. {
  18953. srchStrNeedsFree = helper.searchTextNeedsFree();
  18954. numProcessedLastGroup = 0;
  18955. srchStr = NULL;
  18956. in = NULL;
  18957. }
  18958. ~CRoxieServerXmlParseActivity()
  18959. {
  18960. }
  18961. virtual bool needsAllocator() const { return true; }
  18962. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18963. {
  18964. numProcessedLastGroup = 0;
  18965. srchStr = NULL;
  18966. in = NULL;
  18967. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  18968. }
  18969. virtual void reset()
  18970. {
  18971. if (helper.searchTextNeedsFree())
  18972. rtlFree(srchStr);
  18973. srchStr = NULL;
  18974. ReleaseClearRoxieRow(in);
  18975. xmlParser.clear();
  18976. CRoxieServerActivity::reset();
  18977. }
  18978. virtual void match(IColumnProvider &entry, offset_t startOffset, offset_t endOffset)
  18979. {
  18980. lastMatch.set(&entry);
  18981. }
  18982. virtual const void *nextRow()
  18983. {
  18984. ActivityTimer t(totalCycles, timeActivities);
  18985. for (;;)
  18986. {
  18987. if(xmlParser)
  18988. {
  18989. for (;;)
  18990. {
  18991. if(!xmlParser->next())
  18992. {
  18993. if (srchStrNeedsFree)
  18994. {
  18995. rtlFree(srchStr);
  18996. srchStr = NULL;
  18997. }
  18998. xmlParser.clear();
  18999. break;
  19000. }
  19001. if(lastMatch)
  19002. {
  19003. try
  19004. {
  19005. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  19006. size32_t outSize = helper.transform(rowBuilder, in, lastMatch);
  19007. lastMatch.clear();
  19008. if (outSize)
  19009. {
  19010. processed++;
  19011. return rowBuilder.finalizeRowClear(outSize);
  19012. }
  19013. }
  19014. catch (IException *E)
  19015. {
  19016. throw makeWrappedException(E);
  19017. }
  19018. }
  19019. }
  19020. }
  19021. ReleaseClearRoxieRow(in);
  19022. in = inputStream->nextRow();
  19023. if(!in)
  19024. {
  19025. if(numProcessedLastGroup == processed)
  19026. in = inputStream->nextRow();
  19027. if(!in)
  19028. {
  19029. numProcessedLastGroup = processed;
  19030. return NULL;
  19031. }
  19032. }
  19033. size32_t srchLen;
  19034. helper.getSearchText(srchLen, srchStr, in);
  19035. OwnedRoxieString xmlIteratorPath(helper.getXmlIteratorPath());
  19036. xmlParser.setown(createXMLParse(srchStr, srchLen, xmlIteratorPath, *this));
  19037. }
  19038. }
  19039. };
  19040. class CRoxieServerXmlParseActivityFactory : public CRoxieServerActivityFactory
  19041. {
  19042. public:
  19043. CRoxieServerXmlParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  19044. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  19045. {
  19046. }
  19047. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  19048. {
  19049. return new CRoxieServerXmlParseActivity(_ctx, this, _probeManager);
  19050. }
  19051. };
  19052. IRoxieServerActivityFactory *createRoxieServerXmlParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  19053. {
  19054. return new CRoxieServerXmlParseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  19055. }
  19056. //=====================================================================================================
  19057. class CRoxieServerDiskReadBaseActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler, implements IIndexReadContext
  19058. {
  19059. protected:
  19060. IHThorDiskReadBaseArg &helper;
  19061. IHThorCompoundExtra * compoundHelper;
  19062. RemoteActivityId remoteId; // Note we copy it rather than reference
  19063. Owned<CSkippableRemoteResultAdaptor> remote;
  19064. unsigned numParts;
  19065. unsigned __int64 rowLimit;
  19066. unsigned __int64 stopAfter;
  19067. Linked<IInMemoryIndexManager> manager;
  19068. Owned<IInMemoryIndexCursor> cursor;
  19069. Owned<IDirectReader> reader;
  19070. CThorContiguousRowBuffer deserializeSource;
  19071. Owned<ISourceRowPrefetcher> prefetcher;
  19072. bool eof;
  19073. bool isKeyed;
  19074. bool variableFileName;
  19075. bool isOpt;
  19076. bool sorted;
  19077. bool maySkip;
  19078. bool isLocal;
  19079. bool forceRemote;
  19080. bool isGrouped = false;
  19081. CachedOutputMetaData diskSize;
  19082. Owned<const IResolvedFile> varFileInfo;
  19083. Owned<IFileIOArray> varFiles;
  19084. inline bool useRemote()
  19085. {
  19086. return remote != NULL && (forceRemote || numParts > 1);
  19087. }
  19088. public:
  19089. IMPLEMENT_IINTERFACE_USING(CRoxieServerActivity)
  19090. CRoxieServerDiskReadBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager)
  19091. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  19092. helper((IHThorDiskReadBaseArg &)basehelper),
  19093. numParts(_numParts),
  19094. remoteId(_remoteId),
  19095. manager(_manager),
  19096. isLocal(_isLocal),
  19097. sorted(_sorted),
  19098. maySkip(_maySkip),
  19099. deserializeSource(NULL)
  19100. {
  19101. forceRemote = factory->queryQueryFactory().queryOptions().disableLocalOptimizations;
  19102. if ((forceRemote || numParts != 1) && !isLocal) // NOTE : when numParts == 0 (variable case) we create, even though we may not use
  19103. remote.setown(new CSkippableRemoteResultAdaptor(_ctx, this, remoteId, meta.queryOriginal(), helper, *this, sorted, false, _maySkip));
  19104. compoundHelper = NULL;
  19105. eof = false;
  19106. rowLimit = (unsigned __int64) -1;
  19107. isKeyed = false;
  19108. stopAfter = I64C(0x7FFFFFFFFFFFFFFF);
  19109. Linked<IOutputMetaData> diskMeta(helper.queryDiskRecordSize()->querySerializedDiskMeta());
  19110. if (diskMeta->isGrouped())
  19111. {
  19112. diskMeta.setown(new CSuffixedOutputMeta(+1, diskMeta.getClear()));
  19113. isGrouped = true;
  19114. }
  19115. diskSize.set(diskMeta);
  19116. variableFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getFlags() & (TDXvarfilename|TDXdynamicfilename)) != 0);
  19117. isOpt = (helper.getFlags() & TDRoptional) != 0;
  19118. }
  19119. virtual const IResolvedFile *queryVarFileInfo() const
  19120. {
  19121. return varFileInfo;
  19122. }
  19123. virtual void onCreate(IHThorArg *_colocalParent)
  19124. {
  19125. CRoxieServerActivity::onCreate(_colocalParent);
  19126. if (remote)
  19127. remote->onCreate(_colocalParent);
  19128. }
  19129. virtual bool needsAllocator() const { return true; }
  19130. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19131. {
  19132. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  19133. if (compoundHelper)
  19134. {
  19135. rowLimit = compoundHelper->getRowLimit();
  19136. stopAfter = compoundHelper->getChooseNLimit();
  19137. }
  19138. if (!helper.canMatchAny())
  19139. eof = true;
  19140. else
  19141. {
  19142. if (variableFileName)
  19143. {
  19144. OwnedRoxieString fileName(helper.getFileName());
  19145. varFileInfo.setown(resolveLFN(fileName, isOpt));
  19146. numParts = 0;
  19147. if (varFileInfo)
  19148. {
  19149. numParts = varFileInfo->getNumParts();
  19150. const IPropertyTree *options = varFileInfo->queryProperties();
  19151. if (options)
  19152. {
  19153. isGrouped = options->getPropBool("@grouped");
  19154. if (isGrouped && !diskSize.isGrouped())
  19155. {
  19156. // We are prepared to read contents of a grouped persist ungrouped... But not vice versa
  19157. VStringBuffer msg("Published group information for file %s does not match coded information - assuming grouped", fileName.get());
  19158. WARNLOG("%s", msg.str());
  19159. ctx->queryCodeContext()->addWuException(msg.str(), ROXIE_LAYOUT_MISMATCH, SeverityError, "roxie");
  19160. Owned<IOutputMetaData> diskMeta(new CSuffixedOutputMeta(+1, LINK(diskSize.queryOriginal())));
  19161. diskSize.set(diskMeta);
  19162. }
  19163. size32_t dfsSize = options->getPropInt("@recordSize");
  19164. if (dfsSize && diskSize.isFixedSize() && dfsSize != diskSize.getFixedSize())
  19165. throw MakeStringException(ROXIE_LAYOUT_MISMATCH, "Published record size %d for file %s (%s) does not match coded record size %d", dfsSize, fileName.get(), isGrouped ? "grouped" : "ungrouped", diskSize.getFixedSize());
  19166. }
  19167. }
  19168. }
  19169. if (!numParts)
  19170. {
  19171. eof = true;
  19172. }
  19173. else if (useRemote())
  19174. {
  19175. remote->onStart(parentExtractSize, parentExtract);
  19176. remote->setLimits(rowLimit, (unsigned __int64) -1, stopAfter);
  19177. unsigned fileNo = 0;
  19178. // Translation into a message per channel done elsewhere....
  19179. remote->getMem(0, fileNo, 0);
  19180. remote->flush();
  19181. remote->senddone();
  19182. }
  19183. else
  19184. {
  19185. if (variableFileName)
  19186. {
  19187. unsigned channel = isLocal ? factory->queryQueryFactory().queryChannel() : 0;
  19188. varFiles.setown(varFileInfo->getIFileIOArray(isOpt, channel));
  19189. manager.setown(varFileInfo->getIndexManager(isOpt, channel, varFiles, diskSize, false, 0));
  19190. }
  19191. assertex(manager != NULL);
  19192. helper.createSegmentMonitors(this);
  19193. if (cursor)
  19194. {
  19195. isKeyed = cursor->selectKey();
  19196. cursor->reset();
  19197. }
  19198. if (!isKeyed)
  19199. {
  19200. reader.setown(manager->createReader(0, 0, 1));
  19201. deserializeSource.setStream(reader);
  19202. prefetcher.setown(diskSize.queryOriginal()->createDiskPrefetcher(ctx->queryCodeContext(), activityId));
  19203. }
  19204. helper.setCallback(reader ? reader->queryThorDiskCallback() : cursor);
  19205. }
  19206. }
  19207. }
  19208. virtual void append(IKeySegmentMonitor *segment)
  19209. {
  19210. if (!segment->isWild())
  19211. {
  19212. if (!cursor)
  19213. cursor.setown(manager->createCursor());
  19214. cursor->append(segment);
  19215. }
  19216. }
  19217. virtual unsigned ordinality() const
  19218. {
  19219. return cursor ? cursor->ordinality() : 0;
  19220. }
  19221. virtual IKeySegmentMonitor *item(unsigned idx) const
  19222. {
  19223. return cursor ? cursor->item(idx) : 0;
  19224. }
  19225. virtual void setMergeBarrier(unsigned barrierOffset)
  19226. {
  19227. // no merging so no issue...
  19228. }
  19229. virtual void stop()
  19230. {
  19231. if (useRemote())
  19232. remote->onStop();
  19233. CRoxieServerActivity::stop();
  19234. }
  19235. virtual void reset()
  19236. {
  19237. if (useRemote())
  19238. {
  19239. processed = remote->processed;
  19240. remote->processed = 0;
  19241. remote->onReset();
  19242. }
  19243. varFileInfo.clear();
  19244. eof = false;
  19245. if (cursor)
  19246. cursor->reset();
  19247. deserializeSource.clearStream();
  19248. CRoxieServerActivity::reset();
  19249. }
  19250. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  19251. {
  19252. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  19253. }
  19254. virtual void onLimitExceeded(bool isKeyed)
  19255. {
  19256. if (traceLevel > 4)
  19257. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  19258. assertex(compoundHelper);
  19259. if (isKeyed) // MORE does this exist for diskread? should it?
  19260. {
  19261. if (helper.getFlags() & (TDRkeyedlimitskips|TDRkeyedlimitcreates))
  19262. {
  19263. if (ctx->queryDebugContext())
  19264. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  19265. throw makeLimitSkipException(true);
  19266. }
  19267. else
  19268. {
  19269. UNIMPLEMENTED;
  19270. //compoundHelper->onKeyedLimitExceeded(); Doesn't exist - though the flags do... interesting...
  19271. }
  19272. }
  19273. else
  19274. {
  19275. if (helper.getFlags() & (TDRlimitskips|TDRlimitcreates))
  19276. {
  19277. if (ctx->queryDebugContext())
  19278. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  19279. throw makeLimitSkipException(false);
  19280. }
  19281. else
  19282. compoundHelper->onLimitExceeded();
  19283. }
  19284. }
  19285. virtual const void * createLimitFailRow(bool isKeyed)
  19286. {
  19287. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  19288. IHThorSourceLimitTransformExtra *limitTransformExtra = static_cast<IHThorSourceLimitTransformExtra *>(helper.selectInterface(TAIsourcelimittransformextra_1));
  19289. assertex(limitTransformExtra);
  19290. size32_t outSize = isKeyed ? limitTransformExtra->transformOnKeyedLimitExceeded(rowBuilder) : limitTransformExtra->transformOnLimitExceeded(rowBuilder);
  19291. if (outSize)
  19292. return rowBuilder.finalizeRowClear(outSize);
  19293. return NULL;
  19294. }
  19295. };
  19296. class CRoxieServerDiskReadActivity : public CRoxieServerDiskReadBaseActivity
  19297. {
  19298. IHThorCompoundReadExtra * readHelper;
  19299. ConstPointerArray readrows;
  19300. bool readAheadDone;
  19301. bool eogPending;
  19302. unsigned readIndex;
  19303. unsigned lastGroupProcessed;
  19304. public:
  19305. CRoxieServerDiskReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager)
  19306. : CRoxieServerDiskReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, _maySkip, _manager)
  19307. {
  19308. compoundHelper = (IHThorDiskReadArg *)&helper;
  19309. readHelper = (IHThorDiskReadArg *)&helper;
  19310. readAheadDone = false;
  19311. readIndex = 0;
  19312. eogPending = false;
  19313. lastGroupProcessed = processed;
  19314. }
  19315. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19316. {
  19317. rowLimit = compoundHelper->getRowLimit();
  19318. stopAfter = compoundHelper->getChooseNLimit();
  19319. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  19320. readAheadDone = false;
  19321. readIndex = 0;
  19322. eogPending = false;
  19323. lastGroupProcessed = processed;
  19324. }
  19325. virtual void reset()
  19326. {
  19327. roxiemem::ReleaseRoxieRowRange(readrows.getArray(), readIndex, readrows.ordinality());
  19328. readrows.kill();
  19329. readAheadDone = false;
  19330. readIndex = 0;
  19331. eogPending = false;
  19332. lastGroupProcessed = processed;
  19333. CRoxieServerDiskReadBaseActivity::reset();
  19334. }
  19335. virtual const void *nextRow()
  19336. {
  19337. ActivityTimer t(totalCycles, timeActivities);
  19338. if (eof)
  19339. return NULL;
  19340. else if (useRemote())
  19341. return remote->nextRow();
  19342. else if (maySkip)
  19343. {
  19344. if (!readAheadDone)
  19345. {
  19346. unsigned preprocessed = 0;
  19347. while (!eof)
  19348. {
  19349. const void *row = _nextRow();
  19350. if (row)
  19351. preprocessed++;
  19352. if (preprocessed > rowLimit)
  19353. {
  19354. ReleaseRoxieRow(row);
  19355. roxiemem::ReleaseRoxieRowRange(readrows.getArray(), readIndex, readrows.ordinality());
  19356. readrows.kill();
  19357. readIndex = 0;
  19358. eof = true;
  19359. if (ctx->queryDebugContext())
  19360. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  19361. if (helper.getFlags() & TDRlimitskips)
  19362. return NULL;
  19363. else if (helper.getFlags() & TDRlimitcreates)
  19364. return createLimitFailRow(false);
  19365. else
  19366. throwUnexpected();
  19367. }
  19368. if (preprocessed > stopAfter) // MORE - bit of a strange place to check
  19369. {
  19370. eof = true;
  19371. ReleaseRoxieRow(row);
  19372. break;
  19373. }
  19374. readrows.append(row);
  19375. }
  19376. readAheadDone = true;
  19377. }
  19378. if (readrows.isItem(readIndex))
  19379. {
  19380. const void *ret = readrows.item(readIndex++);
  19381. if (ret)
  19382. processed++;
  19383. return ret;
  19384. }
  19385. else
  19386. {
  19387. eof = true;
  19388. return NULL;
  19389. }
  19390. }
  19391. else
  19392. {
  19393. const void *ret = _nextRow();
  19394. if (ret)
  19395. {
  19396. processed++;
  19397. if (processed > rowLimit)
  19398. {
  19399. if (traceLevel > 4)
  19400. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  19401. ReleaseRoxieRow(ret);
  19402. compoundHelper->onLimitExceeded();
  19403. throwUnexpected(); // onLimitExceeded is not supposed to return
  19404. }
  19405. if (processed > stopAfter) // MORE - bit of a strange place to check
  19406. {
  19407. eof = true;
  19408. ReleaseRoxieRow(ret);
  19409. return NULL;
  19410. }
  19411. }
  19412. return ret;
  19413. }
  19414. }
  19415. const void *_nextRow()
  19416. {
  19417. if (eogPending && (lastGroupProcessed != processed))
  19418. {
  19419. eogPending = false;
  19420. lastGroupProcessed = processed;
  19421. return NULL;
  19422. }
  19423. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  19424. unsigned transformedSize = 0;
  19425. if (isKeyed)
  19426. {
  19427. for (;;)
  19428. {
  19429. const void *nextCandidate = cursor->nextMatch();
  19430. if (!nextCandidate)
  19431. {
  19432. eof = true;
  19433. return NULL;
  19434. }
  19435. transformedSize = readHelper->transform(rowBuilder, nextCandidate);
  19436. if (transformedSize)
  19437. break;
  19438. }
  19439. }
  19440. else // use reader...
  19441. {
  19442. assertex(reader != NULL);
  19443. for (;;)
  19444. {
  19445. if (deserializeSource.eos())
  19446. {
  19447. eof = true;
  19448. return NULL;
  19449. }
  19450. prefetcher->readAhead(deserializeSource);
  19451. const byte *nextRec = deserializeSource.queryRow();
  19452. if (cursor && cursor->isFiltered(nextRec))
  19453. transformedSize = 0;
  19454. else
  19455. transformedSize = readHelper->transform(rowBuilder, nextRec);
  19456. bool eog;
  19457. if (isGrouped)
  19458. {
  19459. size32_t sizeRead = diskSize.getRecordSize(nextRec);
  19460. eog = nextRec[sizeRead-1];
  19461. }
  19462. else
  19463. eog = false;
  19464. deserializeSource.finishedRow();
  19465. if (transformedSize)
  19466. {
  19467. if (isGrouped)
  19468. eogPending = eog;
  19469. break;
  19470. }
  19471. else
  19472. {
  19473. if (eog && (lastGroupProcessed != processed))
  19474. {
  19475. lastGroupProcessed = processed;
  19476. return NULL;
  19477. }
  19478. }
  19479. }
  19480. }
  19481. return rowBuilder.finalizeRowClear(transformedSize);
  19482. }
  19483. };
  19484. class CRoxieServerXmlReadActivity : public CRoxieServerDiskReadBaseActivity, implements IXMLSelect, implements IThorDiskCallback
  19485. {
  19486. IHThorXmlReadArg * readHelper;
  19487. Owned<IXmlToRowTransformer> rowTransformer;
  19488. Owned<IXMLParse> xmlParser;
  19489. Owned<IColumnProvider> lastMatch;
  19490. unsigned __int64 fileoffset;
  19491. public:
  19492. IMPLEMENT_IINTERFACE_USING(CRoxieServerDiskReadBaseActivity)
  19493. CRoxieServerXmlReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager)
  19494. : CRoxieServerDiskReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, _maySkip, _manager)
  19495. {
  19496. compoundHelper = NULL;
  19497. readHelper = (IHThorXmlReadArg *)&helper;
  19498. fileoffset = 0;
  19499. }
  19500. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19501. {
  19502. rowLimit = readHelper->getRowLimit();
  19503. stopAfter = readHelper->getChooseNLimit();
  19504. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  19505. if (!useRemote())
  19506. {
  19507. rowTransformer.set(readHelper->queryTransformer());
  19508. assertex(reader != NULL);
  19509. OwnedRoxieString xmlIterator(readHelper->getXmlIteratorPath());
  19510. if (factory->getKind()==TAKjsonread)
  19511. xmlParser.setown(createJSONParse(*reader->querySimpleStream(), xmlIterator, *this, (0 != (TDRxmlnoroot & readHelper->getFlags()))?ptr_noRoot:ptr_none, (readHelper->getFlags() & TDRusexmlcontents) != 0));
  19512. else
  19513. xmlParser.setown(createXMLParse(*reader->querySimpleStream(), xmlIterator, *this, (0 != (TDRxmlnoroot & readHelper->getFlags()))?ptr_noRoot:ptr_none, (readHelper->getFlags() & TDRusexmlcontents) != 0));
  19514. }
  19515. }
  19516. virtual void reset()
  19517. {
  19518. CRoxieServerDiskReadBaseActivity::reset();
  19519. rowTransformer.clear();
  19520. xmlParser.clear();
  19521. }
  19522. virtual void match(IColumnProvider &entry, offset_t startOffset, offset_t endOffset)
  19523. {
  19524. fileoffset = startOffset;
  19525. lastMatch.set(&entry);
  19526. }
  19527. //interface IThorDiskCallback
  19528. virtual unsigned __int64 getFilePosition(const void * row)
  19529. {
  19530. return fileoffset;
  19531. }
  19532. virtual unsigned __int64 getLocalFilePosition(const void * row)
  19533. {
  19534. return reader->makeFilePositionLocal(fileoffset);
  19535. }
  19536. virtual const char * queryLogicalFilename(const void * row)
  19537. {
  19538. return reader->queryThorDiskCallback()->queryLogicalFilename(row);
  19539. }
  19540. virtual const void *nextRow()
  19541. {
  19542. ActivityTimer t(totalCycles, timeActivities);
  19543. if (eof)
  19544. return NULL;
  19545. else if (useRemote())
  19546. return remote->nextRow();
  19547. assertex(xmlParser != NULL);
  19548. try
  19549. {
  19550. while (!eof)
  19551. {
  19552. //call to next() will callback on the IXmlSelect interface
  19553. bool gotNext = false;
  19554. gotNext = xmlParser->next();
  19555. if(!gotNext)
  19556. eof = true;
  19557. else if (lastMatch)
  19558. {
  19559. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  19560. unsigned sizeGot = rowTransformer->transform(rowBuilder, lastMatch, this);
  19561. lastMatch.clear();
  19562. fileoffset = 0;
  19563. if (sizeGot)
  19564. {
  19565. OwnedConstRoxieRow ret = rowBuilder.finalizeRowClear(sizeGot);
  19566. if (processed > rowLimit)
  19567. {
  19568. if (traceLevel > 4)
  19569. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  19570. readHelper->onLimitExceeded();
  19571. throwUnexpected(); // onLimitExceeded is not supposed to return
  19572. }
  19573. processed++;
  19574. if (processed > stopAfter) // MORE - bit of a strange place to check
  19575. {
  19576. eof = true;
  19577. return NULL;
  19578. }
  19579. return ret.getClear();
  19580. }
  19581. }
  19582. }
  19583. return NULL;
  19584. }
  19585. catch(IException *E)
  19586. {
  19587. throw makeWrappedException(E);
  19588. }
  19589. }
  19590. };
  19591. class CRoxieServerCsvReadActivity : public CRoxieServerDiskReadBaseActivity
  19592. {
  19593. IHThorCsvReadArg *readHelper;
  19594. ICsvParameters * csvInfo;
  19595. unsigned headerLines;
  19596. unsigned maxDiskSize;
  19597. CSVSplitter csvSplitter;
  19598. unsigned __int64 localOffset;
  19599. const char *quotes;
  19600. const char *separators;
  19601. const char *terminators;
  19602. const char *escapes;
  19603. size32_t maxRowSize;
  19604. public:
  19605. CRoxieServerCsvReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  19606. unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager,
  19607. const char *_quotes, const char *_separators, const char *_terminators, const char *_escapes, size32_t _maxRowSize)
  19608. : CRoxieServerDiskReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, _maySkip, _manager),
  19609. quotes(_quotes), separators(_separators), terminators(_terminators), escapes(_escapes), maxRowSize(_maxRowSize)
  19610. {
  19611. compoundHelper = NULL;
  19612. readHelper = (IHThorCsvReadArg *)&helper;
  19613. rowLimit = readHelper->getRowLimit();
  19614. stopAfter = readHelper->getChooseNLimit();
  19615. csvInfo = readHelper->queryCsvParameters();
  19616. maxDiskSize = csvInfo->queryMaxSize();
  19617. localOffset = 0;
  19618. headerLines = 0;
  19619. }
  19620. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19621. {
  19622. rowLimit = readHelper->getRowLimit();
  19623. stopAfter = readHelper->getChooseNLimit();
  19624. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  19625. if (!useRemote())
  19626. {
  19627. headerLines = csvInfo->queryHeaderLen();
  19628. if (headerLines && isLocal && reader->queryFilePart() != 1)
  19629. 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...
  19630. if (!eof)
  19631. {
  19632. if (varFileInfo)
  19633. {
  19634. const IPropertyTree *options = varFileInfo->queryProperties();
  19635. if (options)
  19636. {
  19637. quotes = options->queryProp("@csvQuote");
  19638. separators = options->queryProp("@csvSeparate");
  19639. terminators = options->queryProp("@csvTerminate");
  19640. escapes = options->queryProp("@csvEscape");
  19641. }
  19642. }
  19643. csvSplitter.init(readHelper->getMaxColumns(), csvInfo, quotes, separators, terminators, escapes);
  19644. }
  19645. }
  19646. }
  19647. virtual const void *nextRow()
  19648. {
  19649. ActivityTimer t(totalCycles, timeActivities);
  19650. if (eof)
  19651. return NULL;
  19652. else if (useRemote())
  19653. return remote->nextRow();
  19654. try
  19655. {
  19656. while (!eof)
  19657. {
  19658. if (reader->eos())
  19659. {
  19660. eof = true;
  19661. break;
  19662. }
  19663. // MORE - there are rumours of a csvSplitter that operates on a stream... if/when it exists, this should use it
  19664. size32_t rowSize = 4096; // MORE - make configurable
  19665. size32_t thisLineLength;
  19666. for (;;)
  19667. {
  19668. size32_t avail;
  19669. const void *peek = reader->peek(rowSize, avail);
  19670. thisLineLength = csvSplitter.splitLine(avail, (const byte *)peek);
  19671. if (thisLineLength < rowSize || avail < rowSize)
  19672. break;
  19673. if (rowSize == maxRowSize)
  19674. throw MakeStringException(0, "File contained a line of length greater than %d bytes.", maxRowSize);
  19675. if (rowSize >= maxRowSize/2)
  19676. rowSize = maxRowSize;
  19677. else
  19678. rowSize += rowSize;
  19679. }
  19680. if (headerLines)
  19681. {
  19682. headerLines--;
  19683. reader->skip(thisLineLength);
  19684. }
  19685. else
  19686. {
  19687. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  19688. unsigned transformedSize = readHelper->transform(rowBuilder, csvSplitter.queryLengths(), (const char * *)csvSplitter.queryData());
  19689. reader->skip(thisLineLength);
  19690. if (transformedSize)
  19691. {
  19692. OwnedConstRoxieRow ret = rowBuilder.finalizeRowClear(transformedSize);
  19693. if (processed > rowLimit)
  19694. {
  19695. readHelper->onLimitExceeded();
  19696. throwUnexpected(); // onLimitExceeded is not supposed to return
  19697. }
  19698. processed++;
  19699. if (processed > stopAfter) // MORE - bit of a strange place to check
  19700. {
  19701. eof = true;
  19702. return NULL;
  19703. }
  19704. return ret.getClear();
  19705. }
  19706. }
  19707. }
  19708. return NULL;
  19709. }
  19710. catch(IException *E)
  19711. {
  19712. throw makeWrappedException(E);
  19713. }
  19714. }
  19715. virtual void reset()
  19716. {
  19717. CRoxieServerDiskReadBaseActivity::reset();
  19718. csvSplitter.reset();
  19719. localOffset = 0;
  19720. }
  19721. virtual unsigned __int64 getFilePosition(const void * row)
  19722. {
  19723. UNIMPLEMENTED; // we know offset in the reader but not sure it helps us much
  19724. }
  19725. virtual unsigned __int64 getLocalFilePosition(const void * row)
  19726. {
  19727. UNIMPLEMENTED;
  19728. }
  19729. };
  19730. class CRoxieServerDiskNormalizeActivity : public CRoxieServerDiskReadBaseActivity
  19731. {
  19732. IHThorDiskNormalizeArg *normalizeHelper;
  19733. bool firstPending;
  19734. public:
  19735. CRoxieServerDiskNormalizeActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, IInMemoryIndexManager *_manager)
  19736. : CRoxieServerDiskReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, false, _manager)
  19737. {
  19738. compoundHelper = (IHThorDiskNormalizeArg *)&helper;
  19739. normalizeHelper = (IHThorDiskNormalizeArg *)&helper;
  19740. firstPending = true;
  19741. }
  19742. virtual void reset()
  19743. {
  19744. firstPending = true;
  19745. CRoxieServerDiskReadBaseActivity::reset();
  19746. }
  19747. virtual const void *nextRow()
  19748. {
  19749. ActivityTimer t(totalCycles, timeActivities);
  19750. if (eof)
  19751. return NULL;
  19752. else if (useRemote())
  19753. return remote->nextRow();
  19754. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  19755. unsigned transformedSize = 0;
  19756. if (isKeyed)
  19757. {
  19758. for (;;)
  19759. {
  19760. while (firstPending)
  19761. {
  19762. const void *nextCandidate = cursor->nextMatch();
  19763. if (!nextCandidate)
  19764. {
  19765. eof = true;
  19766. return NULL;
  19767. }
  19768. if (normalizeHelper->first(nextCandidate))
  19769. {
  19770. firstPending = false;
  19771. break;
  19772. }
  19773. }
  19774. transformedSize = normalizeHelper->transform(rowBuilder);
  19775. firstPending = !normalizeHelper->next();
  19776. if (transformedSize)
  19777. break;
  19778. }
  19779. }
  19780. else
  19781. {
  19782. assertex(reader != NULL);
  19783. for (;;)
  19784. {
  19785. while (firstPending)
  19786. {
  19787. if (deserializeSource.eos())
  19788. {
  19789. eof = true;
  19790. return NULL;
  19791. }
  19792. prefetcher->readAhead(deserializeSource);
  19793. const byte *nextRec = deserializeSource.queryRow();
  19794. if (!cursor || !cursor->isFiltered(nextRec))
  19795. {
  19796. if (normalizeHelper->first(nextRec))
  19797. firstPending = false;
  19798. }
  19799. deserializeSource.finishedRow();
  19800. }
  19801. transformedSize = normalizeHelper->transform(rowBuilder);
  19802. firstPending = !normalizeHelper->next();
  19803. if (transformedSize)
  19804. break;
  19805. }
  19806. }
  19807. OwnedConstRoxieRow recBuffer = rowBuilder.finalizeRowClear(transformedSize);
  19808. processed++;
  19809. if (processed > rowLimit)
  19810. {
  19811. compoundHelper->onLimitExceeded();
  19812. throwUnexpected(); // onLimitExceeded is not supposed to return
  19813. }
  19814. if (processed > stopAfter) // MORE - bit of a strange place to check
  19815. {
  19816. eof = true;
  19817. return NULL;
  19818. }
  19819. return recBuffer.getClear();
  19820. }
  19821. };
  19822. class CRoxieServerDiskAggregateBaseActivity : public CRoxieServerDiskReadBaseActivity
  19823. {
  19824. protected:
  19825. bool done;
  19826. public:
  19827. CRoxieServerDiskAggregateBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager)
  19828. : CRoxieServerDiskReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, false, false, _manager),
  19829. done(false)
  19830. {
  19831. }
  19832. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19833. {
  19834. done = false;
  19835. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  19836. }
  19837. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  19838. {
  19839. if (idx==(unsigned)-1)
  19840. idx = 0;
  19841. return idx ? NULL: this;
  19842. }
  19843. };
  19844. class CRoxieServerDiskCountActivity : public CRoxieServerDiskAggregateBaseActivity
  19845. {
  19846. IHThorDiskCountArg & countHelper;
  19847. unsigned __int64 choosenLimit;
  19848. IHThorSourceCountLimit *limitHelper;
  19849. unsigned __int64 getSkippedCount()
  19850. {
  19851. unsigned flags = countHelper.getFlags();
  19852. if (flags & TDRlimitskips)
  19853. return 0;
  19854. else if (flags & TDRlimitcreates)
  19855. return 1;
  19856. else
  19857. {
  19858. assertex(limitHelper);
  19859. if (traceLevel > 4)
  19860. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  19861. limitHelper->onLimitExceeded();
  19862. throwUnexpected(); // onLimitExceeded should always throw exception
  19863. }
  19864. }
  19865. public:
  19866. CRoxieServerDiskCountActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager)
  19867. : CRoxieServerDiskAggregateBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _manager),
  19868. countHelper((IHThorDiskCountArg &)basehelper)
  19869. {
  19870. limitHelper = static_cast<IHThorSourceCountLimit *>(basehelper.selectInterface(TAIsourcecountlimit_1));
  19871. choosenLimit = 0;
  19872. }
  19873. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19874. {
  19875. choosenLimit = countHelper.getChooseNLimit();
  19876. if (limitHelper)
  19877. {
  19878. rowLimit = limitHelper->getRowLimit();
  19879. // keyedLimit = limitHelper->getKeyedLimit(); // more - should there be one?
  19880. }
  19881. CRoxieServerDiskAggregateBaseActivity::start(parentExtractSize, parentExtract, paused);
  19882. }
  19883. virtual const void *nextRow()
  19884. {
  19885. ActivityTimer t(totalCycles, timeActivities);
  19886. if (done) return NULL;
  19887. done = true;
  19888. unsigned __int64 totalCount = 0;
  19889. if (helper.canMatchAny() && !eof)
  19890. {
  19891. if (useRemote())
  19892. {
  19893. for (;;)
  19894. {
  19895. const void * next = remote->nextRow();
  19896. if (!next)
  19897. break;
  19898. if (meta.getFixedSize() == 1)
  19899. totalCount += *(byte *)next;
  19900. else
  19901. totalCount += *(unsigned __int64 *)next;
  19902. ReleaseRoxieRow(next);
  19903. if (totalCount > rowLimit)
  19904. {
  19905. totalCount = getSkippedCount();
  19906. break;
  19907. }
  19908. else if (totalCount >= choosenLimit)
  19909. {
  19910. totalCount = choosenLimit;
  19911. break;
  19912. }
  19913. }
  19914. }
  19915. else
  19916. {
  19917. if (isKeyed)
  19918. {
  19919. for (;;)
  19920. {
  19921. const void *nextCandidate = cursor->nextMatch();
  19922. if (!nextCandidate)
  19923. break;
  19924. totalCount += countHelper.numValid(nextCandidate);
  19925. if (totalCount > rowLimit)
  19926. {
  19927. totalCount = getSkippedCount();
  19928. break;
  19929. }
  19930. else if (totalCount >= choosenLimit)
  19931. {
  19932. totalCount = choosenLimit;
  19933. break;
  19934. }
  19935. }
  19936. }
  19937. else
  19938. {
  19939. assertex(reader != NULL);
  19940. while (!deserializeSource.eos())
  19941. {
  19942. prefetcher->readAhead(deserializeSource);
  19943. const byte *nextRec = deserializeSource.queryRow();
  19944. if (!cursor || !cursor->isFiltered(nextRec))
  19945. {
  19946. totalCount += countHelper.numValid(nextRec);
  19947. }
  19948. deserializeSource.finishedRow();
  19949. if (totalCount > rowLimit)
  19950. {
  19951. totalCount = getSkippedCount();
  19952. break;
  19953. }
  19954. else if (totalCount >= choosenLimit)
  19955. {
  19956. totalCount = choosenLimit;
  19957. break;
  19958. }
  19959. }
  19960. }
  19961. }
  19962. }
  19963. size32_t rowSize = meta.getFixedSize();
  19964. void * result = rowAllocator->createRow();
  19965. if (rowSize == 1)
  19966. *(byte *)result = (byte)totalCount;
  19967. else
  19968. {
  19969. assertex(rowSize == sizeof(unsigned __int64));
  19970. *(unsigned __int64 *)result = totalCount;
  19971. }
  19972. return rowAllocator->finalizeRow(rowSize, result, rowSize);
  19973. }
  19974. };
  19975. class CRoxieServerDiskAggregateActivity : public CRoxieServerDiskAggregateBaseActivity
  19976. {
  19977. IHThorCompoundAggregateExtra & aggregateHelper;
  19978. public:
  19979. CRoxieServerDiskAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  19980. unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager)
  19981. : CRoxieServerDiskAggregateBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _manager),
  19982. aggregateHelper((IHThorDiskAggregateArg &)basehelper)
  19983. {
  19984. }
  19985. const void * gatherMerged()
  19986. {
  19987. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  19988. size32_t finalSize = 0;
  19989. if (useRemote())
  19990. {
  19991. const void * firstRow = remote->nextRow();
  19992. if (!firstRow)
  19993. {
  19994. rowBuilder.ensureRow();
  19995. finalSize = aggregateHelper.clearAggregate(rowBuilder);
  19996. }
  19997. else
  19998. {
  19999. // NOTE need to clone this because going to modify below, could special case 1 row only
  20000. finalSize = cloneRow(rowBuilder, firstRow, meta);
  20001. ReleaseRoxieRow(firstRow);
  20002. }
  20003. for (;;)
  20004. {
  20005. const void * next = remote->nextRow();
  20006. if (!next)
  20007. break;
  20008. finalSize = aggregateHelper.mergeAggregate(rowBuilder, next);
  20009. ReleaseRoxieRow(next);
  20010. }
  20011. }
  20012. else
  20013. {
  20014. aggregateHelper.clearAggregate(rowBuilder);
  20015. if (helper.canMatchAny() && !eof)
  20016. {
  20017. if (isKeyed)
  20018. {
  20019. for (;;)
  20020. {
  20021. const void *next = cursor->nextMatch();
  20022. if (!next)
  20023. break;
  20024. aggregateHelper.processRow(rowBuilder, next);
  20025. }
  20026. }
  20027. else
  20028. {
  20029. assertex(reader != NULL);
  20030. while (!deserializeSource.eos())
  20031. {
  20032. prefetcher->readAhead(deserializeSource);
  20033. const byte *nextRec = deserializeSource.queryRow();
  20034. if (!cursor || !cursor->isFiltered(nextRec))
  20035. {
  20036. aggregateHelper.processRow(rowBuilder, nextRec);
  20037. }
  20038. deserializeSource.finishedRow();
  20039. }
  20040. }
  20041. }
  20042. finalSize = meta.getRecordSize(rowBuilder.getSelf());
  20043. }
  20044. return rowBuilder.finalizeRowClear(finalSize);
  20045. }
  20046. virtual const void *nextRow()
  20047. {
  20048. ActivityTimer t(totalCycles, timeActivities);
  20049. if (done) return NULL;
  20050. const void * ret = gatherMerged();
  20051. done = true;
  20052. return ret;
  20053. }
  20054. };
  20055. class CRoxieServerDiskGroupAggregateActivity : public CRoxieServerDiskAggregateBaseActivity
  20056. {
  20057. IHThorDiskGroupAggregateArg & aggregateHelper;
  20058. RowAggregator resultAggregator;
  20059. bool gathered;
  20060. public:
  20061. CRoxieServerDiskGroupAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager)
  20062. : CRoxieServerDiskAggregateBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _manager),
  20063. aggregateHelper((IHThorDiskGroupAggregateArg &)basehelper),
  20064. resultAggregator(aggregateHelper, aggregateHelper),
  20065. gathered(false)
  20066. {
  20067. }
  20068. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20069. {
  20070. gathered= false;
  20071. CRoxieServerDiskAggregateBaseActivity::start(parentExtractSize, parentExtract, paused);
  20072. resultAggregator.start(rowAllocator);
  20073. }
  20074. virtual void reset()
  20075. {
  20076. resultAggregator.reset();
  20077. CRoxieServerDiskAggregateBaseActivity::reset();
  20078. }
  20079. void gatherMerged()
  20080. {
  20081. if (useRemote())
  20082. {
  20083. for (;;)
  20084. {
  20085. const void * next = remote->nextRow();
  20086. if (!next)
  20087. break;
  20088. resultAggregator.mergeElement(next);
  20089. ReleaseRoxieRow(next);
  20090. }
  20091. }
  20092. else
  20093. {
  20094. if (helper.canMatchAny() && !eof)
  20095. {
  20096. Owned<IInMemoryFileProcessor> processor = isKeyed ?
  20097. createKeyedGroupAggregateRecordProcessor(cursor, resultAggregator, aggregateHelper) :
  20098. createUnkeyedGroupAggregateRecordProcessor(cursor, resultAggregator, aggregateHelper, manager->createReader(0, 0, 1),
  20099. ctx->queryCodeContext(), activityId);
  20100. processor->doQuery(NULL, 0, 0, 0);
  20101. }
  20102. }
  20103. gathered = true;
  20104. }
  20105. virtual const void *nextRow()
  20106. {
  20107. ActivityTimer t(totalCycles, timeActivities);
  20108. if (done)
  20109. return NULL;
  20110. if (!gathered)
  20111. gatherMerged();
  20112. Owned<AggregateRowBuilder> next = resultAggregator.nextResult();
  20113. if (next)
  20114. {
  20115. processed++;
  20116. return next->finalizeRowClear();
  20117. }
  20118. done = true;
  20119. return NULL;
  20120. }
  20121. };
  20122. class CRoxieServerDiskReadActivityFactory : public CRoxieServerActivityFactory
  20123. {
  20124. public:
  20125. RemoteActivityId remoteId;
  20126. bool isLocal;
  20127. bool sorted;
  20128. bool maySkip;
  20129. bool variableFileName;
  20130. Owned<IFileIOArray> files;
  20131. Owned<IInMemoryIndexManager> manager;
  20132. Owned<const IResolvedFile> datafile;
  20133. const char *quotes;
  20134. const char *separators;
  20135. const char *terminators;
  20136. const char *escapes;
  20137. size32_t maxCsvRowSize;
  20138. CRoxieServerDiskReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  20139. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), remoteId(_remoteId)
  20140. {
  20141. isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  20142. Owned<IHThorDiskReadBaseArg> helper = (IHThorDiskReadBaseArg *) helperFactory();
  20143. sorted = (helper->getFlags() & TDRunsorted) == 0;
  20144. variableFileName = allFilesDynamic || _queryFactory.isDynamic() || ((helper->getFlags() & (TDXvarfilename|TDXdynamicfilename)) != 0);
  20145. maySkip = (helper->getFlags() & (TDRkeyedlimitskips|TDRkeyedlimitcreates|TDRlimitskips|TDRlimitcreates)) != 0;
  20146. quotes = separators = terminators = escapes = NULL;
  20147. if (!variableFileName)
  20148. {
  20149. bool isOpt = (helper->getFlags() & TDRoptional) != 0;
  20150. OwnedRoxieString fileName(helper->getFileName());
  20151. datafile.setown(_queryFactory.queryPackage().lookupFileName(fileName, isOpt, true, true, _queryFactory.queryWorkUnit(), true));
  20152. Linked<IOutputMetaData> diskMeta(helper->queryDiskRecordSize()->querySerializedDiskMeta());
  20153. if (diskMeta->isGrouped())
  20154. diskMeta.setown(new CSuffixedOutputMeta(+1, diskMeta.getClear()));
  20155. if (datafile)
  20156. {
  20157. const IPropertyTree *options = datafile->queryProperties();
  20158. if (options)
  20159. {
  20160. bool isGrouped = options->getPropBool("@grouped");
  20161. if (isGrouped && !diskMeta->isGrouped())
  20162. {
  20163. // We are prepared to read contents of a grouped persist ungrouped... But not vice versa
  20164. WARNLOG("Published group information for file %s does not match coded information - assuming grouped", fileName.get());
  20165. diskMeta.setown(new CSuffixedOutputMeta(+1, diskMeta.getClear()));
  20166. }
  20167. size32_t dfsSize = options->getPropInt("@recordSize");
  20168. if (dfsSize && diskMeta->isFixedSize() && dfsSize != diskMeta->getFixedSize())
  20169. throw MakeStringException(ROXIE_LAYOUT_MISMATCH, "Published record size %d for file %s (%s) does not match coded record size %d", dfsSize, fileName.get(), isGrouped ? "grouped" : "ungrouped", diskMeta->getFixedSize());
  20170. }
  20171. }
  20172. bool isSimple = (datafile && datafile->getNumParts()==1 && !_queryFactory.queryOptions().disableLocalOptimizations);
  20173. if (isLocal || isSimple)
  20174. {
  20175. if (datafile)
  20176. {
  20177. unsigned channel = isLocal ? queryFactory.queryChannel() : 0;
  20178. files.setown(datafile->getIFileIOArray(isOpt, channel));
  20179. manager.setown(datafile->getIndexManager(isOpt, channel, files, diskMeta, _graphNode.getPropBool("att[@name=\"preload\"]/@value", false), _graphNode.getPropInt("att[@name=\"_preloadSize\"]/@value", 0)));
  20180. const IPropertyTree *options = datafile->queryProperties();
  20181. if (options)
  20182. {
  20183. quotes = options->queryProp("@csvQuote");
  20184. separators = options->queryProp("@csvSeparate");
  20185. terminators = options->queryProp("@csvTerminate");
  20186. escapes = options->queryProp("@csvEscape");
  20187. }
  20188. }
  20189. else
  20190. manager.setown(getEmptyIndexManager());
  20191. }
  20192. }
  20193. switch (kind)
  20194. {
  20195. case TAKcsvread:
  20196. {
  20197. maxCsvRowSize = defaultMaxCsvRowSize * 1024 * 1024;
  20198. IConstWorkUnit *workunit = _queryFactory.queryWorkUnit();
  20199. if (workunit)
  20200. maxCsvRowSize = workunit->getDebugValueInt(OPT_MAXCSVROWSIZE, defaultMaxCsvRowSize) * 1024 * 1024;
  20201. break;
  20202. }
  20203. default:
  20204. maxCsvRowSize = 0; // unused
  20205. }
  20206. }
  20207. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  20208. {
  20209. unsigned numParts = datafile ? datafile->getNumParts() : 0;
  20210. switch (kind)
  20211. {
  20212. case TAKcsvread:
  20213. return new CRoxieServerCsvReadActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, sorted, maySkip, manager,
  20214. quotes, separators, terminators, escapes, maxCsvRowSize);
  20215. case TAKxmlread:
  20216. case TAKjsonread:
  20217. return new CRoxieServerXmlReadActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, sorted, maySkip, manager);
  20218. case TAKdiskread:
  20219. return new CRoxieServerDiskReadActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, sorted, maySkip, manager);
  20220. case TAKdisknormalize:
  20221. return new CRoxieServerDiskNormalizeActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, sorted, manager);
  20222. case TAKdiskcount:
  20223. return new CRoxieServerDiskCountActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, manager);
  20224. case TAKdiskaggregate:
  20225. return new CRoxieServerDiskAggregateActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, manager);
  20226. case TAKdiskgroupaggregate:
  20227. return new CRoxieServerDiskGroupAggregateActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, manager);
  20228. }
  20229. throwUnexpected();
  20230. }
  20231. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  20232. {
  20233. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  20234. }
  20235. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  20236. {
  20237. if (datafile)
  20238. addXrefFileInfo(reply, datafile);
  20239. else
  20240. {
  20241. // Temporarily resolve the file
  20242. Owned<IHThorDiskReadBaseArg> helper = (IHThorDiskReadBaseArg *) helperFactory();
  20243. if ((helper->getFlags() & (TDXvarfilename|TDXdynamicfilename)) == 0)
  20244. {
  20245. OwnedRoxieString fileName(helper->getFileName());
  20246. Owned<const IResolvedFile> temp = queryFactory.queryPackage().lookupFileName(fileName, true, true, false, queryFactory.queryWorkUnit(), true);
  20247. if (temp)
  20248. addXrefFileInfo(reply, temp);
  20249. }
  20250. }
  20251. }
  20252. virtual const StatisticsMapping &queryStatsMapping() const
  20253. {
  20254. return diskStatistics;
  20255. }
  20256. };
  20257. IRoxieServerActivityFactory *createRoxieServerDiskReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  20258. {
  20259. return new CRoxieServerDiskReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  20260. }
  20261. //=================================================================================
  20262. class CRoxieServerIndexActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler
  20263. {
  20264. protected:
  20265. IHThorIndexReadBaseArg &indexHelper;
  20266. IHThorSteppedSourceExtra * steppedExtra;
  20267. Linked<IKeyArray> keySet;
  20268. Linked<TranslatorArray> translators;
  20269. CSkippableRemoteResultAdaptor remote;
  20270. CIndexTransformCallback callback;
  20271. bool sorted;
  20272. bool variableFileName;
  20273. bool variableInfoPending;
  20274. bool isOpt;
  20275. bool isLocal;
  20276. unsigned __int64 rowLimit;
  20277. unsigned __int64 keyedLimit;
  20278. unsigned __int64 choosenLimit;
  20279. unsigned accepted;
  20280. unsigned rejected;
  20281. unsigned seekGEOffset;
  20282. Owned<IKeyManager> tlk;
  20283. Owned<const IResolvedFile> varFileInfo;
  20284. const RemoteActivityId &remoteId;
  20285. void setVariableFileInfo()
  20286. {
  20287. OwnedRoxieString indexName(indexHelper.getFileName());
  20288. varFileInfo.setown(resolveLFN(indexName, isOpt));
  20289. if (varFileInfo)
  20290. {
  20291. translators.setown(new TranslatorArray) ;
  20292. keySet.setown(varFileInfo->getKeyArray(factory->queryActivityMeta(), translators, isOpt, isLocal ? factory->queryQueryFactory().queryChannel() : 0, factory->queryQueryFactory().queryOptions().enableFieldTranslation));
  20293. }
  20294. variableInfoPending = false;
  20295. }
  20296. public:
  20297. CRoxieServerIndexActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  20298. IKeyArray * _keySet, TranslatorArray *_translators, bool _sorted, bool _isLocal, bool _maySkip)
  20299. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  20300. keySet(_keySet),
  20301. translators(_translators),
  20302. indexHelper((IHThorIndexReadBaseArg &)basehelper),
  20303. remote(_ctx, this, _remoteId, meta.queryOriginal(), indexHelper, *this, _sorted, false, _maySkip),
  20304. remoteId(_remoteId),
  20305. sorted(_sorted),
  20306. isLocal(_isLocal)
  20307. {
  20308. indexHelper.setCallback(&callback);
  20309. steppedExtra = static_cast<IHThorSteppedSourceExtra *>(indexHelper.selectInterface(TAIsteppedsourceextra_1));
  20310. variableFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((indexHelper.getFlags() & (TIRvarfilename|TIRdynamicfilename)) != 0);
  20311. variableInfoPending = false;
  20312. isOpt = (indexHelper.getFlags() & TIRoptional) != 0;
  20313. seekGEOffset = 0;
  20314. // started = false;
  20315. rejected = accepted = 0;
  20316. rowLimit = choosenLimit = keyedLimit = 0;
  20317. }
  20318. virtual const IResolvedFile *queryVarFileInfo() const
  20319. {
  20320. return varFileInfo;
  20321. }
  20322. virtual void onCreate(IHThorArg *_colocalParent)
  20323. {
  20324. CRoxieServerActivity::onCreate(_colocalParent);
  20325. remote.onCreate(_colocalParent);
  20326. }
  20327. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20328. {
  20329. accepted = 0;
  20330. rejected = 0;
  20331. rowLimit = (unsigned __int64) -1;
  20332. keyedLimit = (unsigned __int64 ) -1;
  20333. choosenLimit = I64C(0x7fffffffffffffff);
  20334. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  20335. remote.onStart(parentExtractSize, parentExtract);
  20336. variableInfoPending = variableFileName;
  20337. }
  20338. void processAllKeys()
  20339. {
  20340. try
  20341. {
  20342. if (indexHelper.canMatchAny())
  20343. {
  20344. if (variableInfoPending)
  20345. setVariableFileInfo();
  20346. remote.setLimits(rowLimit, keyedLimit, choosenLimit);
  20347. if (keySet)
  20348. {
  20349. // MORE - this recreates the segmonitors per part but not per fileno (which is a little backwards).
  20350. // 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
  20351. // However order is probably better to iterate fileno's inside partnos
  20352. // MORE - also not properly supporting STEPPED I fear.
  20353. // A superkey that mixes single and multipart or tlk and roroot keys might be hard
  20354. for (unsigned partNo = 0; partNo < keySet->length(); partNo++)
  20355. {
  20356. IKeyIndexBase *thisBase = keySet->queryKeyPart(partNo);
  20357. if (thisBase)
  20358. {
  20359. unsigned fileNo = 0;
  20360. IKeyIndex *thisKey = thisBase->queryPart(fileNo);
  20361. if (!thisKey->isTopLevelKey())
  20362. {
  20363. if (keyedLimit != (unsigned __int64) -1)
  20364. {
  20365. if ((indexHelper.getFlags() & TIRcountkeyedlimit) != 0)
  20366. {
  20367. Owned<IKeyManager> countKey;
  20368. countKey.setown(createLocalKeyManager(thisKey, 0, this));
  20369. countKey->setLayoutTranslator(translators->item(fileNo));
  20370. createSegmentMonitors(countKey);
  20371. unsigned __int64 count = countKey->checkCount(keyedLimit);
  20372. if (count > keyedLimit)
  20373. {
  20374. if (traceLevel > 4)
  20375. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  20376. onLimitExceeded(true);
  20377. }
  20378. }
  20379. }
  20380. }
  20381. if (seekGEOffset && !thisKey->isTopLevelKey())
  20382. {
  20383. tlk.setown(createSingleKeyMerger(thisKey, 0, seekGEOffset, this));
  20384. }
  20385. else
  20386. {
  20387. tlk.setown(createLocalKeyManager(thisKey, 0, this));
  20388. tlk->setLayoutTranslator(translators->item(fileNo));
  20389. }
  20390. createSegmentMonitors(tlk);
  20391. if (queryTraceLevel() > 3 || ctx->queryProbeManager())
  20392. {
  20393. StringBuffer out;
  20394. printKeyedValues(out, tlk, indexHelper.queryDiskRecordSize());
  20395. CTXLOG("Using filter %s", out.str());
  20396. if (ctx->queryProbeManager())
  20397. ctx->queryProbeManager()->setNodeProperty(this, "filter", out.str());
  20398. }
  20399. tlk->reset();
  20400. for (;;) // for each file part
  20401. {
  20402. //block for TransformCallbackAssociation
  20403. {
  20404. TransformCallbackAssociation associate(callback, tlk);
  20405. if (thisKey->isTopLevelKey())
  20406. {
  20407. if (thisKey->isFullySorted())
  20408. {
  20409. while (tlk->lookup(false))
  20410. {
  20411. unsigned slavePart = (unsigned) tlk->queryFpos();
  20412. if (slavePart)
  20413. {
  20414. accepted++;
  20415. remote.getMem(slavePart, fileNo, 0); // the cached context is all we need to send
  20416. if (sorted && numChannels>1)
  20417. remote.flush(); // don't combine parts if we need result sorted, except on a 1-way
  20418. }
  20419. }
  20420. }
  20421. else
  20422. {
  20423. // MORE - we could check whether there are any matching parts if we wanted.
  20424. // If people are in the habit of sending null values that would be worthwhile
  20425. remote.getMem(0, fileNo, 0);
  20426. }
  20427. }
  20428. else
  20429. {
  20430. if (processSingleKey(thisKey, translators->item(fileNo)))
  20431. break;
  20432. }
  20433. }
  20434. if (++fileNo < thisBase->numParts())
  20435. {
  20436. thisKey = thisBase->queryPart(fileNo);
  20437. tlk->setKey(thisKey);
  20438. tlk->setLayoutTranslator(translators->item(fileNo));
  20439. tlk->reset();
  20440. }
  20441. else
  20442. break;
  20443. }
  20444. tlk->releaseSegmentMonitors();
  20445. tlk->setKey(NULL);
  20446. }
  20447. }
  20448. }
  20449. }
  20450. remote.flush();
  20451. remote.senddone();
  20452. }
  20453. catch (IException *E)
  20454. {
  20455. remote.setException(E);
  20456. }
  20457. }
  20458. virtual void createSegmentMonitors(IKeyManager *key)
  20459. {
  20460. indexHelper.createSegmentMonitors(key);
  20461. key->finishSegmentMonitors();
  20462. }
  20463. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans) = 0;
  20464. virtual void reset()
  20465. {
  20466. if (accepted)
  20467. noteStatistic(StNumIndexAccepted, accepted);
  20468. if (rejected)
  20469. noteStatistic(StNumIndexRejected, rejected);
  20470. remote.onReset();
  20471. CRoxieServerActivity::reset();
  20472. if (varFileInfo)
  20473. {
  20474. keySet.clear();
  20475. varFileInfo.clear();
  20476. }
  20477. variableInfoPending = false;
  20478. }
  20479. virtual void stop()
  20480. {
  20481. remote.onStop();
  20482. CRoxieServerActivity::stop();
  20483. }
  20484. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  20485. {
  20486. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  20487. }
  20488. };
  20489. class CRoxieServerIndexReadBaseActivity : public CRoxieServerIndexActivity
  20490. {
  20491. IHThorSourceLimitTransformExtra * limitTransformExtra;
  20492. public:
  20493. CRoxieServerIndexReadBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  20494. IKeyArray * _keySet, TranslatorArray *_translators, bool _sorted, bool _isLocal, bool _maySkip)
  20495. : CRoxieServerIndexActivity(_ctx, _factory, _probeManager, _remoteId, _keySet, _translators, _sorted, _isLocal, _maySkip)
  20496. {
  20497. limitTransformExtra = static_cast<IHThorSourceLimitTransformExtra *>(indexHelper.selectInterface(TAIsourcelimittransformextra_1));
  20498. }
  20499. virtual void reset()
  20500. {
  20501. remote.onReset();
  20502. CRoxieServerIndexActivity::reset();
  20503. }
  20504. virtual const void *nextRow()
  20505. {
  20506. ActivityTimer t(totalCycles, timeActivities);
  20507. try
  20508. {
  20509. const void *ret = remote.nextRow();
  20510. if (ret)
  20511. processed++;
  20512. return ret;
  20513. }
  20514. catch (IException *E)
  20515. {
  20516. throw makeWrappedException(E);
  20517. }
  20518. }
  20519. protected:
  20520. virtual const void * createLimitFailRow(bool isKeyed)
  20521. {
  20522. ensureRowAllocator();
  20523. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  20524. size32_t outSize = isKeyed ? limitTransformExtra->transformOnKeyedLimitExceeded(rowBuilder) : limitTransformExtra->transformOnLimitExceeded(rowBuilder);
  20525. if (outSize)
  20526. return rowBuilder.finalizeRowClear(outSize);
  20527. return NULL;
  20528. }
  20529. };
  20530. class CRoxieServerIndexReadActivity : public CRoxieServerIndexReadBaseActivity, implements IIndexReadActivityInfo
  20531. {
  20532. protected:
  20533. IHThorCompoundReadExtra & readHelper;
  20534. ISteppingMeta *rawMeta = nullptr;
  20535. CSteppingMeta steppingMeta;
  20536. unsigned * seekSizes = nullptr;
  20537. bool optimizeSteppedPostFilter;
  20538. ISteppingMeta * projectedMeta = nullptr;
  20539. unsigned maxSeekLookahead;
  20540. public:
  20541. CRoxieServerIndexReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  20542. IKeyArray * _keySet, TranslatorArray *_translators, bool _sorted, bool _isLocal, bool _maySkip, unsigned _maxSeekLookahead)
  20543. : CRoxieServerIndexReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _keySet, _translators, _sorted, _isLocal, _maySkip),
  20544. readHelper((IHThorIndexReadArg &)basehelper)
  20545. {
  20546. rawMeta = readHelper.queryRawSteppingMeta();
  20547. unsigned flags = indexHelper.getFlags();
  20548. optimizeSteppedPostFilter = (flags & TIRunfilteredtransform) != 0;
  20549. seekSizes = NULL;
  20550. maxSeekLookahead = _maxSeekLookahead;
  20551. if (rawMeta)
  20552. {
  20553. const CFieldOffsetSize * fields = rawMeta->queryFields();
  20554. unsigned maxFields = rawMeta->getNumFields();
  20555. seekGEOffset = fields[0].offset;
  20556. seekSizes = new unsigned[maxFields];
  20557. seekSizes[0] = fields[0].size;
  20558. for (unsigned i=1; i < maxFields; i++)
  20559. seekSizes[i] = seekSizes[i-1] + fields[i].size;
  20560. projectedMeta = readHelper.queryProjectedSteppingMeta();
  20561. ISteppingMeta *useMeta = projectedMeta ? projectedMeta : rawMeta;
  20562. remote.setMergeInfo(useMeta); // also need to consider superfile case where there is a mix of multiway and singleparts.. ?
  20563. bool hasPostFilter = readHelper.transformMayFilter() && optimizeSteppedPostFilter;
  20564. steppingMeta.init(useMeta, hasPostFilter);
  20565. }
  20566. }
  20567. ~CRoxieServerIndexReadActivity()
  20568. {
  20569. delete [] seekSizes;
  20570. }
  20571. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20572. {
  20573. CRoxieServerIndexReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  20574. steppingMeta.setDistributed();
  20575. if (steppedExtra)
  20576. steppingMeta.setExtra(steppedExtra);
  20577. rowLimit = readHelper.getRowLimit();
  20578. keyedLimit = readHelper.getKeyedLimit();
  20579. choosenLimit = readHelper.getChooseNLimit();
  20580. if (!paused)
  20581. processAllKeys();
  20582. }
  20583. class LazyLocalKeyReader : implements IMessageUnpackCursor, implements IMessageResult, public CInterface
  20584. {
  20585. public:
  20586. IMPLEMENT_IINTERFACE;
  20587. virtual IMessageUnpackCursor *getCursor(roxiemem::IRowManager *rowMgr) const
  20588. {
  20589. Link();
  20590. return const_cast<LazyLocalKeyReader*> (this);
  20591. }
  20592. virtual const void *getMessageHeader(unsigned &length) const
  20593. {
  20594. length = 0;
  20595. return NULL;
  20596. }
  20597. virtual const void *getMessageMetadata(unsigned &length) const
  20598. {
  20599. length = 0;
  20600. return NULL;
  20601. }
  20602. virtual void discard() const
  20603. {
  20604. // nothing to do.
  20605. }
  20606. unsigned keyedCount;
  20607. unsigned matched;
  20608. bool EOFseen;
  20609. Owned<IKeyIndexSet> keySet;
  20610. Owned<IKeyManager> tlk;
  20611. CRoxieServerIndexReadActivity &owner;
  20612. LazyLocalKeyReader(CRoxieServerIndexReadActivity &_owner, IKeyIndex *key, IRecordLayoutTranslator * trans)
  20613. : owner(_owner)
  20614. {
  20615. keyedCount = 0;
  20616. matched = 0;
  20617. EOFseen = false;
  20618. keySet.setown(createKeyIndexSet());
  20619. keySet->addIndex(LINK(key));
  20620. if (owner.seekGEOffset)
  20621. tlk.setown(createKeyMerger(keySet, 0, owner.seekGEOffset, &owner));
  20622. else
  20623. tlk.setown(createLocalKeyManager(keySet->queryPart(0), 0, &owner));
  20624. tlk->setLayoutTranslator(trans);
  20625. owner.indexHelper.createSegmentMonitors(tlk);
  20626. tlk->finishSegmentMonitors();
  20627. tlk->reset();
  20628. }
  20629. virtual const void *getNext(int length)
  20630. {
  20631. TransformCallbackAssociation associate(owner.callback, tlk);
  20632. while (tlk->lookup(true))
  20633. {
  20634. keyedCount++;
  20635. if (keyedCount > owner.keyedLimit)
  20636. {
  20637. owner.onLimitExceeded(true); // Should throw exception
  20638. throwUnexpected();
  20639. }
  20640. size32_t transformedSize;
  20641. RtlDynamicRowBuilder rowBuilder(owner.rowAllocator);
  20642. byte const * keyRow = tlk->queryKeyBuffer(owner.callback.getFPosRef());
  20643. try
  20644. {
  20645. transformedSize = owner.readHelper.transform(rowBuilder, keyRow);
  20646. owner.callback.finishedRow();
  20647. }
  20648. catch (IException *E)
  20649. {
  20650. throw owner.makeWrappedException(E);
  20651. }
  20652. if (transformedSize)
  20653. {
  20654. OwnedConstRoxieRow result = rowBuilder.finalizeRowClear(transformedSize);
  20655. matched++;
  20656. if (matched > owner.rowLimit)
  20657. {
  20658. owner.onLimitExceeded(false); // Should throw exception
  20659. throwUnexpected();
  20660. }
  20661. if (matched > owner.choosenLimit) // MORE - bit of a strange place to check
  20662. {
  20663. break;
  20664. }
  20665. owner.accepted++;
  20666. return result.getClear();
  20667. }
  20668. else
  20669. owner.rejected++;
  20670. }
  20671. EOFseen = true;
  20672. return NULL;
  20673. }
  20674. virtual bool atEOF() const
  20675. {
  20676. return EOFseen;
  20677. }
  20678. virtual bool isSerialized() const
  20679. {
  20680. return false;
  20681. }
  20682. };
  20683. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
  20684. {
  20685. ensureRowAllocator();
  20686. remote.injectResult(new LazyLocalKeyReader(*this, key, trans));
  20687. return false;
  20688. }
  20689. virtual void onLimitExceeded(bool isKeyed)
  20690. {
  20691. if (traceLevel > 4)
  20692. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  20693. if (isKeyed)
  20694. {
  20695. if (indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates))
  20696. {
  20697. if (ctx->queryDebugContext())
  20698. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  20699. throw makeLimitSkipException(true);
  20700. }
  20701. else
  20702. readHelper.onKeyedLimitExceeded();
  20703. }
  20704. else
  20705. {
  20706. if (indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates))
  20707. {
  20708. if (ctx->queryDebugContext())
  20709. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  20710. throw makeLimitSkipException(false);
  20711. }
  20712. else
  20713. readHelper.onLimitExceeded();
  20714. }
  20715. }
  20716. virtual void serializeSkipInfo(MemoryBuffer &out, unsigned seekLen, const void *rawSeek, unsigned numFields, const void * seek, const SmartStepExtra &stepExtra) const
  20717. {
  20718. out.append((unsigned short) numFields);
  20719. out.append((unsigned short) seekLen);
  20720. out.append((unsigned short) stepExtra.queryFlags());
  20721. IMultipleStepSeekInfo *seeks = stepExtra.queryExtraSeeks();
  20722. if (seeks)
  20723. {
  20724. unsigned lookahead = 40000/seekLen;
  20725. if (maxSeekLookahead && (lookahead > maxSeekLookahead))
  20726. lookahead = maxSeekLookahead;
  20727. seeks->ensureFilled(seek, numFields, lookahead);
  20728. out.append(lookahead != seeks->ordinality()); // seeksAreEof flag
  20729. unsigned serialized = 1; // rawseek is always serialized...
  20730. unsigned patchLength = out.length();
  20731. out.append(serialized); // NOTE - we come back and patch with the actual value...
  20732. out.append(seekLen, rawSeek);
  20733. if (seeks->ordinality())
  20734. {
  20735. const void *lastSeek = rawSeek;
  20736. byte *nextSeek = NULL;
  20737. if (projectedMeta)
  20738. nextSeek = (byte *) alloca(seekLen);
  20739. for (unsigned i = 0; i < seeks->ordinality(); i++)
  20740. {
  20741. if (projectedMeta)
  20742. {
  20743. RtlStaticRowBuilder rowBuilder(nextSeek-seekGEOffset, seekGEOffset+seekLen);
  20744. readHelper.mapOutputToInput(rowBuilder, seeks->querySeek(i), numFields); // NOTE - weird interface to mapOutputToInput means that it STARTS writing at seekGEOffset...
  20745. }
  20746. else
  20747. nextSeek = (byte *) seeks->querySeek(i)+seekGEOffset;
  20748. int diff = memcmp(nextSeek, lastSeek, seekLen);
  20749. if (diff > 0)
  20750. {
  20751. serialized++;
  20752. out.append(seekLen, nextSeek);
  20753. lastSeek = (const byte *) out.reserve(0) - seekLen;
  20754. }
  20755. }
  20756. unsigned length = out.length();
  20757. out.setWritePos(patchLength);
  20758. out.append(serialized);
  20759. out.setWritePos(length);
  20760. }
  20761. }
  20762. else
  20763. {
  20764. out.append(false);
  20765. out.append(1);
  20766. out.append(seekLen, rawSeek);
  20767. }
  20768. }
  20769. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  20770. {
  20771. ActivityTimer t(totalCycles, timeActivities);
  20772. try
  20773. {
  20774. unsigned seeklen = 0;
  20775. const void *rawSeek = NULL;
  20776. if (seek && numFields)
  20777. {
  20778. seeklen = seekSizes[numFields-1];
  20779. rawSeek = (const byte *)seek + seekGEOffset;
  20780. if (projectedMeta)
  20781. {
  20782. byte * temp = (byte *) alloca(seeklen);
  20783. RtlStaticRowBuilder rawBuilder(temp-seekGEOffset, seekGEOffset+seeklen);
  20784. readHelper.mapOutputToInput(rawBuilder, seek, numFields); // NOTE - weird interface to mapOutputToInput means that it STARTS writing at seekGEOffset...
  20785. rawSeek = (byte *)temp;
  20786. }
  20787. }
  20788. const void *ret = remote.nextRowGE(seek, rawSeek, numFields, seeklen, wasCompleteMatch, stepExtra);
  20789. if (ret && wasCompleteMatch) // GH pleas confirm the wasCompleteMatch I just added here is right
  20790. processed++;
  20791. return ret;
  20792. }
  20793. catch (IException *E)
  20794. {
  20795. throw makeWrappedException(E);
  20796. }
  20797. }
  20798. virtual IInputSteppingMeta * querySteppingMeta()
  20799. {
  20800. if (rawMeta && steppingEnabled && ((indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates|TIRkeyedlimitskips|TIRkeyedlimitcreates)) == 0))
  20801. return &steppingMeta;
  20802. return NULL;
  20803. }
  20804. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  20805. {
  20806. if (variableInfoPending)
  20807. setVariableFileInfo();
  20808. return this;
  20809. }
  20810. virtual IKeyArray *getKeySet() const
  20811. {
  20812. return keySet.getLink();
  20813. }
  20814. virtual const IResolvedFile *getVarFileInfo() const
  20815. {
  20816. return varFileInfo.getLink();
  20817. }
  20818. virtual TranslatorArray *getTranslators() const
  20819. {
  20820. return translators.getLink();
  20821. }
  20822. virtual void mergeSegmentMonitors(IIndexReadContext *irc) const
  20823. {
  20824. indexHelper.createSegmentMonitors(irc); // NOTE: they will merge
  20825. }
  20826. virtual IRoxieServerActivity *queryActivity() { return this; }
  20827. virtual const RemoteActivityId& queryRemoteId() const
  20828. {
  20829. return remoteId;
  20830. }
  20831. };
  20832. class CRoxieServerSimpleIndexReadActivity : public CRoxieServerActivity, implements IIndexReadActivityInfo
  20833. {
  20834. IHThorCompoundReadExtra & readHelper;
  20835. IHThorIndexReadBaseArg & indexHelper;
  20836. IHThorSourceLimitTransformExtra * limitTransformExtra;
  20837. IHThorSteppedSourceExtra * steppedExtra;
  20838. bool eof;
  20839. Linked<IKeyArray>keySet;
  20840. Owned<IKeyIndexSet>keyIndexSet;
  20841. Owned<IKeyManager> tlk;
  20842. Linked<TranslatorArray> translators;
  20843. CIndexTransformCallback callback;
  20844. unsigned __int64 keyedLimit;
  20845. unsigned rowLimit;
  20846. unsigned chooseNLimit;
  20847. unsigned accepted;
  20848. unsigned rejected;
  20849. unsigned keyedCount;
  20850. ISteppingMeta * rawMeta;
  20851. ISteppingMeta * projectedMeta;
  20852. size32_t seekGEOffset;
  20853. unsigned * seekSizes;
  20854. CSteppingMeta steppingMeta;
  20855. Owned<const IResolvedFile> varFileInfo;
  20856. const RemoteActivityId &remoteId;
  20857. bool firstRead;
  20858. bool variableFileName;
  20859. bool variableInfoPending;
  20860. bool isOpt;
  20861. bool isLocal;
  20862. bool optimizeSteppedPostFilter;
  20863. // MORE there may be enough in common between this and CRoxieServerIndexActivity to warrant some refactoring
  20864. void initKeySet()
  20865. {
  20866. if ((keySet->length() > 1 || rawMeta != NULL) && translators->needsTranslation())
  20867. {
  20868. throw MakeStringException(ROXIE_UNIMPLEMENTED_ERROR, "Layout translation is not available when merging key parts or smart-stepping, as it may change record order");
  20869. }
  20870. keyIndexSet.setown(createKeyIndexSet());
  20871. for (unsigned part = 0; part < keySet->length(); part++)
  20872. {
  20873. IKeyIndexBase *kib = keySet->queryKeyPart(part);
  20874. if (kib)
  20875. {
  20876. for (unsigned subpart = 0; subpart < kib->numParts(); subpart++)
  20877. {
  20878. IKeyIndex *k = kib->queryPart(subpart);
  20879. if (k)
  20880. {
  20881. assertex(!k->isTopLevelKey());
  20882. keyIndexSet->addIndex(LINK(k));
  20883. }
  20884. }
  20885. }
  20886. }
  20887. }
  20888. void setVariableFileInfo()
  20889. {
  20890. OwnedRoxieString indexName(indexHelper.getFileName());
  20891. varFileInfo.setown(resolveLFN(indexName, isOpt));
  20892. translators.setown(new TranslatorArray) ;
  20893. keySet.setown(varFileInfo->getKeyArray(factory->queryActivityMeta(), translators, isOpt, isLocal ? factory->queryQueryFactory().queryChannel() : 0, factory->queryQueryFactory().queryOptions().enableFieldTranslation));
  20894. initKeySet();
  20895. variableInfoPending = false;
  20896. }
  20897. void onEOF()
  20898. {
  20899. callback.setManager(NULL);
  20900. eof = true;
  20901. tlk.clear();
  20902. }
  20903. public:
  20904. CRoxieServerSimpleIndexReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  20905. IKeyArray *_keyArray, TranslatorArray *_translatorArray, bool _isLocal)
  20906. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  20907. readHelper((IHThorIndexReadArg &)basehelper),
  20908. indexHelper((IHThorIndexReadArg &)basehelper),
  20909. translators(_translatorArray),
  20910. keySet(_keyArray),
  20911. isLocal(_isLocal),
  20912. remoteId(_remoteId)
  20913. {
  20914. rowLimit = 0;
  20915. keyedLimit = 0;
  20916. chooseNLimit = 0;
  20917. indexHelper.setCallback(&callback);
  20918. steppedExtra = static_cast<IHThorSteppedSourceExtra *>(indexHelper.selectInterface(TAIsteppedsourceextra_1));
  20919. limitTransformExtra = static_cast<IHThorSourceLimitTransformExtra *>(indexHelper.selectInterface(TAIsourcelimittransformextra_1));
  20920. unsigned flags = indexHelper.getFlags();
  20921. variableFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((flags & (TIRvarfilename|TIRdynamicfilename)) != 0);
  20922. variableInfoPending = false;
  20923. isOpt = (flags & TIRoptional) != 0;
  20924. optimizeSteppedPostFilter = (flags & TIRunfilteredtransform) != 0;
  20925. firstRead = true;
  20926. accepted = 0;
  20927. rejected = 0;
  20928. keyedCount = 0;
  20929. eof = false;
  20930. rawMeta = readHelper.queryRawSteppingMeta();
  20931. projectedMeta = readHelper.queryProjectedSteppingMeta();
  20932. seekGEOffset = 0;
  20933. seekSizes = NULL;
  20934. if (rawMeta)
  20935. {
  20936. // MORE - should check all keys in maxFields list can actually be keyed.
  20937. const CFieldOffsetSize * fields = rawMeta->queryFields();
  20938. unsigned maxFields = rawMeta->getNumFields();
  20939. seekGEOffset = fields[0].offset;
  20940. seekSizes = new unsigned[maxFields];
  20941. seekSizes[0] = fields[0].size;
  20942. for (unsigned i=1; i < maxFields; i++)
  20943. seekSizes[i] = seekSizes[i-1] + fields[i].size;
  20944. bool hasPostFilter = readHelper.transformMayFilter() && optimizeSteppedPostFilter;
  20945. if (projectedMeta)
  20946. steppingMeta.init(projectedMeta, hasPostFilter);
  20947. else
  20948. steppingMeta.init(rawMeta, hasPostFilter);
  20949. }
  20950. }
  20951. virtual const IResolvedFile *queryVarFileInfo() const
  20952. {
  20953. return varFileInfo;
  20954. }
  20955. ~CRoxieServerSimpleIndexReadActivity()
  20956. {
  20957. delete [] seekSizes;
  20958. }
  20959. virtual bool needsAllocator() const { return true; }
  20960. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20961. {
  20962. firstRead = true;
  20963. accepted = 0;
  20964. rejected = 0;
  20965. keyedCount = 0;
  20966. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  20967. if (steppedExtra)
  20968. steppingMeta.setExtra(steppedExtra);
  20969. eof = !indexHelper.canMatchAny();
  20970. if (variableFileName)
  20971. variableInfoPending = true;
  20972. else
  20973. {
  20974. variableInfoPending = false;
  20975. if (!keyIndexSet)
  20976. initKeySet();
  20977. }
  20978. }
  20979. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  20980. {
  20981. if (variableInfoPending)
  20982. setVariableFileInfo();
  20983. return this;
  20984. }
  20985. virtual IKeyArray *getKeySet() const
  20986. {
  20987. return keySet.getLink();
  20988. }
  20989. virtual const IResolvedFile *getVarFileInfo() const
  20990. {
  20991. return varFileInfo.getLink();
  20992. }
  20993. virtual TranslatorArray *getTranslators() const
  20994. {
  20995. return translators.getLink();
  20996. }
  20997. virtual void mergeSegmentMonitors(IIndexReadContext *irc) const
  20998. {
  20999. indexHelper.createSegmentMonitors(irc); // NOTE: they will merge
  21000. }
  21001. virtual IRoxieServerActivity *queryActivity() { return this; }
  21002. virtual const RemoteActivityId& queryRemoteId() const
  21003. {
  21004. return remoteId;
  21005. }
  21006. const void *nextRow()
  21007. {
  21008. bool matched = true;
  21009. return nextRowGE(NULL, 0, matched, dummySmartStepExtra);
  21010. }
  21011. unsigned __int64 checkCount(unsigned __int64 limit)
  21012. {
  21013. unsigned numParts = keyIndexSet->numParts();
  21014. unsigned __int64 result = 0;
  21015. for (unsigned i = 0; i < numParts; i++)
  21016. {
  21017. Owned<IKeyManager> countTlk = createLocalKeyManager(keyIndexSet->queryPart(i), 0, this);
  21018. countTlk->setLayoutTranslator(translators->item(i));
  21019. indexHelper.createSegmentMonitors(countTlk);
  21020. countTlk->finishSegmentMonitors();
  21021. result += countTlk->checkCount(limit-result);
  21022. if (result > limit)
  21023. break;
  21024. }
  21025. return result;
  21026. }
  21027. virtual const void *nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  21028. {
  21029. ActivityTimer t(totalCycles, timeActivities);
  21030. if (eof)
  21031. return NULL;
  21032. if (firstRead)
  21033. {
  21034. if (variableInfoPending)
  21035. setVariableFileInfo();
  21036. rowLimit = (unsigned) readHelper.getRowLimit();
  21037. chooseNLimit = (unsigned) readHelper.getChooseNLimit();
  21038. unsigned numParts = keyIndexSet->numParts();
  21039. if (!numParts)
  21040. {
  21041. onEOF();
  21042. return NULL;
  21043. }
  21044. if (numParts > 1 || seekGEOffset)
  21045. {
  21046. tlk.setown(createKeyMerger(keyIndexSet, 0, seekGEOffset, this));
  21047. // note that we don't set up translator because we don't support it. If that ever changes...
  21048. }
  21049. else
  21050. {
  21051. tlk.setown(createLocalKeyManager(keyIndexSet->queryPart(0), 0, this));
  21052. tlk->setLayoutTranslator(translators->item(0));
  21053. }
  21054. indexHelper.createSegmentMonitors(tlk);
  21055. tlk->finishSegmentMonitors();
  21056. if (queryTraceLevel() > 3 || ctx->queryProbeManager())
  21057. {
  21058. StringBuffer out;
  21059. printKeyedValues(out, tlk, indexHelper.queryDiskRecordSize());
  21060. CTXLOG("Using filter %s", out.str());
  21061. if (ctx->queryProbeManager())
  21062. ctx->queryProbeManager()->setNodeProperty(this, "filter", out.str());
  21063. }
  21064. tlk->reset();
  21065. callback.setManager(tlk);
  21066. keyedLimit = readHelper.getKeyedLimit();
  21067. if (keyedLimit != (unsigned __int64) -1)
  21068. {
  21069. if ((indexHelper.getFlags() & TIRcountkeyedlimit) != 0)
  21070. {
  21071. unsigned __int64 count = checkCount(keyedLimit);
  21072. if (count > keyedLimit)
  21073. {
  21074. if ((indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates)) == 0)
  21075. readHelper.onKeyedLimitExceeded();
  21076. const void * ret = NULL;
  21077. if (indexHelper.getFlags() & TIRkeyedlimitcreates)
  21078. ret = createKeyedLimitOnFailRow();
  21079. onEOF();
  21080. return ret;
  21081. }
  21082. keyedLimit = (unsigned __int64) -1;
  21083. }
  21084. }
  21085. firstRead = false;
  21086. }
  21087. if (accepted == chooseNLimit)
  21088. {
  21089. onEOF();
  21090. return NULL;
  21091. }
  21092. const byte * rawSeek = NULL;
  21093. unsigned seekSize = 0;
  21094. if (seek)
  21095. {
  21096. seekSize = seekSizes[numFields-1];
  21097. rawSeek = (const byte *)seek + seekGEOffset;
  21098. if (projectedMeta)
  21099. {
  21100. byte *temp = (byte *) alloca(seekSize);
  21101. RtlStaticRowBuilder rawBuilder(temp-seekGEOffset, seekGEOffset+seekSize);
  21102. readHelper.mapOutputToInput(rawBuilder, seek, numFields);// NOTE - weird interface to mapOutputToInput means that it STARTS writing at seekGEOffset...
  21103. rawSeek = (byte *)temp;
  21104. }
  21105. #ifdef _DEBUG
  21106. // StringBuffer seekStr;
  21107. // for (unsigned i = 0; i < seekSize; i++)
  21108. // {
  21109. // seekStr.appendf("%02x ", ((unsigned char *) rawSeek)[i]);
  21110. // }
  21111. // DBGLOG("nextRowGE can skip offset %d size %d value %s", seekGEOffset, seekSize, seekStr.str());
  21112. #endif
  21113. }
  21114. const byte * originalRawSeek = rawSeek;
  21115. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  21116. while (rawSeek ? tlk->lookupSkip(rawSeek, seekGEOffset, seekSize) : tlk->lookup(true))
  21117. {
  21118. checkAbort();
  21119. keyedCount++;
  21120. if (keyedCount > keyedLimit)
  21121. {
  21122. readHelper.onKeyedLimitExceeded();
  21123. break;
  21124. }
  21125. byte const * keyRow = tlk->queryKeyBuffer(callback.getFPosRef());
  21126. #ifdef _DEBUG
  21127. // StringBuffer recstr;
  21128. // unsigned size = (tlk->queryRecordSize()<80) ? tlk->queryRecordSize() : 80;
  21129. // for (unsigned i = 0; i < size; i++)
  21130. // {
  21131. // recstr.appendf("%02x ", ((unsigned char *) keyRow)[i]);
  21132. // }
  21133. // DBGLOG("nextRowGE Got %s", recstr.str());
  21134. if (originalRawSeek && memcmp(keyRow + seekGEOffset, originalRawSeek, seekSize) < 0)
  21135. assertex(!"smart seek failure");
  21136. #endif
  21137. size32_t transformedSize;
  21138. rowBuilder.ensureRow();
  21139. try
  21140. {
  21141. transformedSize = readHelper.transform(rowBuilder, keyRow);
  21142. //if the post filter causes a mismatch, and the stepping condition no longer matches
  21143. //then return a mismatch record - so the join code can start seeking on the other input.
  21144. if (transformedSize == 0 && optimizeSteppedPostFilter && stepExtra.returnMismatches())
  21145. {
  21146. if (memcmp(keyRow + seekGEOffset, originalRawSeek, seekSize) != 0)
  21147. {
  21148. transformedSize = readHelper.unfilteredTransform(rowBuilder, keyRow);
  21149. if (transformedSize != 0)
  21150. wasCompleteMatch = false;
  21151. }
  21152. }
  21153. callback.finishedRow();
  21154. }
  21155. catch (IException *E)
  21156. {
  21157. throw makeWrappedException(E);
  21158. }
  21159. if (transformedSize)
  21160. {
  21161. accepted++;
  21162. if (accepted > rowLimit)
  21163. {
  21164. if ((indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates)) != 0)
  21165. {
  21166. throwUnexpected(); // should not have used simple variant if maySkip set...
  21167. }
  21168. if (traceLevel > 4)
  21169. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  21170. readHelper.onLimitExceeded();
  21171. break;
  21172. }
  21173. processed++;
  21174. #ifdef _DEBUG
  21175. // const byte *ret = (const byte *) out.get();
  21176. // CommonXmlWriter xmlwrite(XWFnoindent|XWFtrim|XWFopt);
  21177. // queryOutputMeta()->toXML(ret, xmlwrite);
  21178. // DBGLOG("ROW: {%p} %s", ret, xmlwrite.str());
  21179. #endif
  21180. return rowBuilder.finalizeRowClear(transformedSize);
  21181. }
  21182. else
  21183. rejected++;
  21184. rawSeek = NULL;
  21185. }
  21186. onEOF();
  21187. return NULL;
  21188. }
  21189. virtual void reset()
  21190. {
  21191. onEOF();
  21192. if (accepted)
  21193. noteStatistic(StNumIndexAccepted, accepted);
  21194. if (rejected)
  21195. noteStatistic(StNumIndexRejected, rejected);
  21196. if (variableFileName)
  21197. {
  21198. varFileInfo.clear();
  21199. translators.clear();
  21200. }
  21201. variableInfoPending = false;
  21202. CRoxieServerActivity::reset();
  21203. }
  21204. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  21205. {
  21206. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  21207. }
  21208. virtual IInputSteppingMeta * querySteppingMeta()
  21209. {
  21210. if (rawMeta && steppingEnabled && ((indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates|TIRkeyedlimitskips|TIRkeyedlimitcreates)) == 0))
  21211. return &steppingMeta;
  21212. return NULL;
  21213. }
  21214. protected:
  21215. const void * createKeyedLimitOnFailRow()
  21216. {
  21217. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  21218. size32_t outSize = limitTransformExtra->transformOnKeyedLimitExceeded(rowBuilder);
  21219. if (outSize)
  21220. return rowBuilder.finalizeRowClear(outSize);
  21221. return NULL;
  21222. }
  21223. };
  21224. class CRoxieServerBaseIndexActivityFactory : public CRoxieServerActivityFactory
  21225. {
  21226. public:
  21227. Owned<IKeyArray> keySet;
  21228. Owned<TranslatorArray> translatorArray;
  21229. Owned<IDefRecordMeta> activityMeta;
  21230. RemoteActivityId remoteId;
  21231. bool isSimple;
  21232. bool isLocal;
  21233. bool maySkip;
  21234. bool sorted;
  21235. bool variableFileName;
  21236. IRecordLayoutTranslator::Mode enableFieldTranslation;
  21237. unsigned maxSeekLookahead;
  21238. Owned<const IResolvedFile> indexfile;
  21239. CRoxieServerSideCache *cache;
  21240. CRoxieServerBaseIndexActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21241. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), remoteId(_remoteId)
  21242. {
  21243. Owned<IHThorIndexReadBaseArg> indexHelper = (IHThorIndexReadBaseArg *) helperFactory();
  21244. unsigned flags = indexHelper->getFlags();
  21245. sorted = (flags & TIRunordered) == 0;
  21246. isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  21247. rtlDataAttr indexLayoutMeta;
  21248. size32_t indexLayoutSize;
  21249. if(!indexHelper->getIndexLayout(indexLayoutSize, indexLayoutMeta.refdata()))
  21250. assertex(indexLayoutSize==0);
  21251. MemoryBuffer m;
  21252. m.setBuffer(indexLayoutSize, indexLayoutMeta.getdata());
  21253. activityMeta.setown(deserializeRecordMeta(m, true));
  21254. enableFieldTranslation = queryFactory.queryOptions().enableFieldTranslation;
  21255. translatorArray.setown(new TranslatorArray);
  21256. variableFileName = allFilesDynamic || _queryFactory.isDynamic() || ((flags & (TIRvarfilename|TIRdynamicfilename)) != 0);
  21257. if (!variableFileName)
  21258. {
  21259. bool isOpt = (flags & TIRoptional) != 0;
  21260. OwnedRoxieString indexName(indexHelper->getFileName());
  21261. indexfile.setown(queryFactory.queryPackage().lookupFileName(indexName, isOpt, true, true, queryFactory.queryWorkUnit(), true));
  21262. if (indexfile)
  21263. keySet.setown(indexfile->getKeyArray(activityMeta, translatorArray, isOpt, isLocal ? queryFactory.queryChannel() : 0, enableFieldTranslation));
  21264. }
  21265. isSimple = isLocal;
  21266. maySkip = (flags & (TIRkeyedlimitskips|TIRlimitskips|TIRlimitcreates|TIRkeyedlimitcreates)) != 0;
  21267. if (keySet && keySet->length()==1 && !isLocal && (flags & (TIRlimitskips|TIRlimitcreates|TIRkeyedlimitskips|TIRkeyedlimitcreates))==0)
  21268. {
  21269. IKeyIndexBase *thisBase = keySet->queryKeyPart(0);
  21270. if (thisBase->numParts()==1 && !thisBase->queryPart(0)->isTopLevelKey() && !_queryFactory.queryOptions().disableLocalOptimizations)
  21271. isSimple = true;
  21272. }
  21273. int cacheSize = _graphNode.getPropInt("hint[@name='cachehits']/@value", serverSideCacheSize);
  21274. cache = cacheSize ? new CRoxieServerSideCache(cacheSize) : NULL;
  21275. maxSeekLookahead = _graphNode.getPropInt("hint[@name='maxseeklookahead']/@value", 0);
  21276. }
  21277. ~CRoxieServerBaseIndexActivityFactory()
  21278. {
  21279. delete cache;
  21280. }
  21281. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  21282. {
  21283. if (indexfile)
  21284. addXrefFileInfo(reply, indexfile);
  21285. else
  21286. {
  21287. Owned<IHThorIndexReadBaseArg> indexHelper = (IHThorIndexReadBaseArg *) helperFactory();
  21288. if ((indexHelper->getFlags() & (TIRvarfilename|TIRdynamicfilename)) == 0)
  21289. {
  21290. OwnedRoxieString indexName(indexHelper->getFileName());
  21291. Owned<const IResolvedFile> temp = queryFactory.queryPackage().lookupFileName(indexName, true, true, false, queryFactory.queryWorkUnit(), true);
  21292. if (temp)
  21293. addXrefFileInfo(reply, temp);
  21294. }
  21295. }
  21296. }
  21297. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  21298. {
  21299. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for indexread activity");
  21300. }
  21301. virtual IRoxieServerSideCache *queryServerSideCache() const
  21302. {
  21303. return cache;
  21304. }
  21305. virtual bool getEnableFieldTranslation() const
  21306. {
  21307. return enableFieldTranslation;
  21308. }
  21309. virtual IDefRecordMeta *queryActivityMeta() const
  21310. {
  21311. return activityMeta;
  21312. }
  21313. virtual const StatisticsMapping &queryStatsMapping() const
  21314. {
  21315. return indexStatistics;
  21316. }
  21317. };
  21318. class CRoxieServerIndexReadActivityFactory : public CRoxieServerBaseIndexActivityFactory
  21319. {
  21320. public:
  21321. CRoxieServerIndexReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21322. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId)
  21323. {
  21324. }
  21325. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  21326. {
  21327. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  21328. return new CRoxieServerNullActivity(_ctx, this, _probeManager);
  21329. else if (isSimple && !maySkip)
  21330. return new CRoxieServerSimpleIndexReadActivity(_ctx, this, _probeManager, remoteId, keySet, translatorArray, isLocal);
  21331. else
  21332. return new CRoxieServerIndexReadActivity(_ctx, this, _probeManager, remoteId, keySet, translatorArray, sorted, isLocal, maySkip, maxSeekLookahead);
  21333. }
  21334. };
  21335. IRoxieServerActivityFactory *createRoxieServerIndexReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21336. {
  21337. return new CRoxieServerIndexReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  21338. }
  21339. //--------------------------------------------------------------------------------------------------------------------------
  21340. class CRoxieServerNullCountActivity : public CRoxieServerActivity
  21341. {
  21342. bool done;
  21343. public:
  21344. CRoxieServerNullCountActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  21345. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  21346. {
  21347. done = false;
  21348. }
  21349. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21350. {
  21351. done = false;
  21352. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  21353. }
  21354. virtual bool needsAllocator() const { return true; }
  21355. virtual const void *nextRow()
  21356. {
  21357. ActivityTimer t(totalCycles, timeActivities);
  21358. if (done) return NULL;
  21359. done = true;
  21360. size32_t rowSize = meta.getFixedSize();
  21361. void * nullRow = rowAllocator->createRow();
  21362. if (rowSize == 1)
  21363. *(byte *)nullRow = 0;
  21364. else
  21365. {
  21366. assertex(rowSize == sizeof(unsigned __int64));
  21367. *(unsigned __int64 *)nullRow = 0;
  21368. }
  21369. return rowAllocator->finalizeRow(rowSize, nullRow, rowSize);
  21370. }
  21371. };
  21372. class CRoxieServerIndexCountActivity : public CRoxieServerIndexActivity
  21373. {
  21374. IHThorCompoundCountExtra & countHelper;
  21375. IHThorSourceCountLimit * limitHelper;
  21376. bool done;
  21377. public:
  21378. CRoxieServerIndexCountActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IKeyArray * _keySet, TranslatorArray *_translators, bool _isLocal)
  21379. : CRoxieServerIndexActivity(_ctx, _factory, _probeManager, _remoteId, _keySet, _translators, false, _isLocal, false),
  21380. countHelper((IHThorIndexCountArg &)basehelper),
  21381. done(false)
  21382. {
  21383. limitHelper = static_cast<IHThorSourceCountLimit *>(basehelper.selectInterface(TAIsourcecountlimit_1));
  21384. }
  21385. virtual bool needsAllocator() const { return true; }
  21386. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21387. {
  21388. done = false;
  21389. CRoxieServerIndexActivity::start(parentExtractSize, parentExtract, paused);
  21390. choosenLimit = countHelper.getChooseNLimit();
  21391. if (limitHelper)
  21392. {
  21393. rowLimit = limitHelper->getRowLimit();
  21394. keyedLimit = limitHelper->getKeyedLimit();
  21395. }
  21396. if (!paused)
  21397. processAllKeys();
  21398. }
  21399. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
  21400. {
  21401. unsigned __int64 count = 0;
  21402. if (countHelper.hasFilter())
  21403. {
  21404. while (tlk->lookup(true))
  21405. {
  21406. try
  21407. {
  21408. count += countHelper.numValid(tlk->queryKeyBuffer(callback.getFPosRef()));
  21409. callback.finishedRow();
  21410. }
  21411. catch (IException *E)
  21412. {
  21413. throw makeWrappedException(E);
  21414. }
  21415. accepted++;
  21416. if (count >= choosenLimit) // MORE - what about limit?
  21417. break;
  21418. }
  21419. }
  21420. else
  21421. count = tlk->getCount(); //MORE: GH->RKC There should be value in providing a max limit to getCount()
  21422. if (count)
  21423. {
  21424. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), false);
  21425. if (count > choosenLimit)
  21426. count = choosenLimit;
  21427. void * recBuffer = rowAllocator->createRow();
  21428. if (meta.getFixedSize() == 1)
  21429. *(byte *)recBuffer = (byte)count;
  21430. else
  21431. {
  21432. assertex(meta.getFixedSize() == sizeof(unsigned __int64));
  21433. *(unsigned __int64 *)recBuffer = count;
  21434. }
  21435. recBuffer = rowAllocator->finalizeRow(meta.getFixedSize(), recBuffer, meta.getFixedSize());
  21436. result->append(recBuffer);
  21437. remote.injectResult(result.getClear());
  21438. //GH->RKC for count(,choosen)/exists passing in the previous count would short-circuit this much earlier
  21439. if (count >= choosenLimit)
  21440. return true;
  21441. }
  21442. return false;
  21443. }
  21444. virtual void onLimitExceeded(bool isKeyed)
  21445. {
  21446. if (traceLevel > 4)
  21447. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  21448. if (isKeyed)
  21449. {
  21450. if (indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates))
  21451. {
  21452. if (ctx->queryDebugContext())
  21453. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  21454. throw makeLimitSkipException(true);
  21455. }
  21456. else
  21457. {
  21458. assertex(limitHelper); // Should not be able to generate exception if there was not one...
  21459. limitHelper->onKeyedLimitExceeded();
  21460. }
  21461. }
  21462. else
  21463. {
  21464. if (indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates))
  21465. {
  21466. if (ctx->queryDebugContext())
  21467. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  21468. throw makeLimitSkipException(false);
  21469. }
  21470. else
  21471. {
  21472. assertex(limitHelper);
  21473. limitHelper->onLimitExceeded();
  21474. }
  21475. }
  21476. }
  21477. virtual const void *createLimitFailRow(bool isKeyed)
  21478. {
  21479. throwUnexpected();
  21480. }
  21481. virtual const void *nextRow()
  21482. {
  21483. ActivityTimer t(totalCycles, timeActivities);
  21484. if (done) return NULL;
  21485. done = true;
  21486. unsigned __int64 totalCount = 0;
  21487. bool hasLimit = rowLimit != (unsigned __int64) -1;
  21488. try
  21489. {
  21490. for (;;)
  21491. {
  21492. const void * next = remote.nextRow();
  21493. if (!next)
  21494. break;
  21495. if (meta.getFixedSize() == 1)
  21496. totalCount += *(byte *)next;
  21497. else
  21498. totalCount += *(unsigned __int64 *) next;
  21499. ReleaseRoxieRow(next);
  21500. if (totalCount > rowLimit || (totalCount > choosenLimit && !hasLimit)) // can't break out early if there is a possibility of later slave throwing limit exception
  21501. break;
  21502. }
  21503. if (totalCount > rowLimit)
  21504. {
  21505. unsigned flags = indexHelper.getFlags();
  21506. if (flags & TIRlimitskips)
  21507. totalCount = 0;
  21508. else if (flags & TIRlimitcreates)
  21509. totalCount = 1;
  21510. else
  21511. {
  21512. assertex(limitHelper);
  21513. limitHelper->onLimitExceeded();
  21514. }
  21515. }
  21516. else if (totalCount > choosenLimit)
  21517. totalCount = choosenLimit;
  21518. }
  21519. catch (IException *E)
  21520. {
  21521. if (QUERYINTERFACE(E, LimitSkipException))
  21522. {
  21523. totalCount = 0;
  21524. unsigned flags = indexHelper.getFlags();
  21525. if (E->errorCode() == KeyedLimitSkipErrorCode)
  21526. {
  21527. if (flags & TIRkeyedlimitcreates)
  21528. totalCount++;
  21529. }
  21530. else
  21531. {
  21532. if (flags & TIRlimitcreates)
  21533. totalCount++;
  21534. }
  21535. if (totalCount > choosenLimit)
  21536. totalCount = choosenLimit; // would have to be weird code (and escape the optimizer...)
  21537. E->Release();
  21538. }
  21539. else
  21540. throw ;
  21541. }
  21542. void * result = rowAllocator->createRow();
  21543. if (meta.getFixedSize() == 1)
  21544. *(byte *)result = (byte)totalCount;
  21545. else
  21546. {
  21547. assertex(meta.getFixedSize() == sizeof(unsigned __int64));
  21548. *(unsigned __int64 *)result = totalCount;
  21549. }
  21550. return rowAllocator->finalizeRow(meta.getFixedSize(), result, meta.getFixedSize());
  21551. }
  21552. };
  21553. class CRoxieServerIndexCountActivityFactory : public CRoxieServerBaseIndexActivityFactory
  21554. {
  21555. public:
  21556. CRoxieServerIndexCountActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21557. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId)
  21558. {
  21559. }
  21560. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  21561. {
  21562. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  21563. return new CRoxieServerNullCountActivity(_ctx, this, _probeManager);
  21564. // else if (isSimple)
  21565. // return new CRoxieServerSimpleIndexCountActivity(this, keySet->queryKeyPart(0)->queryPart(0));
  21566. else
  21567. return new CRoxieServerIndexCountActivity(_ctx, this, _probeManager, remoteId, keySet, translatorArray, isLocal);
  21568. }
  21569. };
  21570. IRoxieServerActivityFactory *createRoxieServerIndexCountActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21571. {
  21572. return new CRoxieServerIndexCountActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  21573. }
  21574. //--------------------------------------------------------------------------------------------------------------------------
  21575. class CRoxieServerNullIndexAggregateActivity : public CRoxieServerActivity
  21576. {
  21577. IHThorIndexAggregateArg &aggregateHelper;
  21578. bool done;
  21579. public:
  21580. CRoxieServerNullIndexAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  21581. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  21582. aggregateHelper((IHThorIndexAggregateArg &)basehelper)
  21583. {
  21584. done = false;
  21585. }
  21586. virtual bool needsAllocator() const { return true; }
  21587. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21588. {
  21589. done = false;
  21590. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  21591. }
  21592. virtual const void *nextRow()
  21593. {
  21594. ActivityTimer t(totalCycles, timeActivities);
  21595. if (done) return NULL;
  21596. done = true;
  21597. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  21598. size32_t thisSize = aggregateHelper.clearAggregate(rowBuilder);
  21599. return rowBuilder.finalizeRowClear(thisSize);
  21600. }
  21601. };
  21602. class CRoxieServerIndexAggregateActivity : public CRoxieServerIndexActivity
  21603. {
  21604. IHThorCompoundAggregateExtra & aggregateHelper;
  21605. bool done;
  21606. public:
  21607. CRoxieServerIndexAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  21608. IKeyArray * _keySet, TranslatorArray *_translators, bool _isLocal)
  21609. : CRoxieServerIndexActivity(_ctx, _factory, _probeManager, _remoteId, _keySet, _translators, false, _isLocal, false),
  21610. aggregateHelper((IHThorIndexAggregateArg &)basehelper),
  21611. done(false)
  21612. {
  21613. }
  21614. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21615. {
  21616. done = false;
  21617. CRoxieServerIndexActivity::start(parentExtractSize, parentExtract, paused);
  21618. if (!paused)
  21619. processAllKeys();
  21620. }
  21621. virtual bool needsAllocator() const { return true; }
  21622. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
  21623. {
  21624. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  21625. while (tlk->lookup(true))
  21626. {
  21627. if (!rowBuilder.exists())
  21628. {
  21629. rowBuilder.ensureRow();
  21630. aggregateHelper.clearAggregate(rowBuilder);
  21631. }
  21632. try
  21633. {
  21634. aggregateHelper.processRow(rowBuilder, tlk->queryKeyBuffer(callback.getFPosRef()));
  21635. callback.finishedRow();
  21636. }
  21637. catch (IException *E)
  21638. {
  21639. throw makeWrappedException(E);
  21640. }
  21641. accepted++;
  21642. }
  21643. if (aggregateHelper.processedAnyRows())
  21644. {
  21645. size32_t size = meta.getRecordSize(rowBuilder.getSelf());
  21646. const void * recBuffer = rowBuilder.finalizeRowClear(size);
  21647. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), meta.isVariableSize());
  21648. result->append(recBuffer);
  21649. remote.injectResult(result.getClear());
  21650. }
  21651. return false;
  21652. }
  21653. virtual void onLimitExceeded(bool isKeyed)
  21654. {
  21655. if (traceLevel > 4)
  21656. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  21657. throwUnexpected();
  21658. }
  21659. virtual const void *createLimitFailRow(bool isKeyed)
  21660. {
  21661. throwUnexpected();
  21662. }
  21663. const void * gatherMerged()
  21664. {
  21665. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  21666. const void * firstRow = remote.nextRow();
  21667. size32_t finalSize = 0;
  21668. if (!firstRow)
  21669. {
  21670. rowBuilder.ensureRow();
  21671. finalSize = aggregateHelper.clearAggregate(rowBuilder);
  21672. }
  21673. else
  21674. {
  21675. // NOTE need to clone this because going to modify below, could special case 1 row only
  21676. finalSize = cloneRow(rowBuilder, firstRow, meta);
  21677. ReleaseRoxieRow(firstRow);
  21678. }
  21679. for (;;)
  21680. {
  21681. const void * next = remote.nextRow();
  21682. if (!next)
  21683. break;
  21684. finalSize = aggregateHelper.mergeAggregate(rowBuilder, next);
  21685. ReleaseRoxieRow(next);
  21686. }
  21687. return rowBuilder.finalizeRowClear(finalSize);
  21688. }
  21689. virtual const void *nextRow()
  21690. {
  21691. ActivityTimer t(totalCycles, timeActivities);
  21692. if (done) return NULL;
  21693. const void * ret = gatherMerged();
  21694. done = true;
  21695. return ret;
  21696. }
  21697. };
  21698. class CRoxieServerIndexAggregateActivityFactory : public CRoxieServerBaseIndexActivityFactory
  21699. {
  21700. public:
  21701. CRoxieServerIndexAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21702. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId)
  21703. {
  21704. }
  21705. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  21706. {
  21707. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  21708. return new CRoxieServerNullIndexAggregateActivity(_ctx, this, _probeManager);
  21709. // else if (isSimple)
  21710. // return new CRoxieServerSimpleIndexAggregateActivity(this, keySet->queryKeyPart(0)->queryPart(0));
  21711. else
  21712. return new CRoxieServerIndexAggregateActivity(_ctx, this, _probeManager, remoteId, keySet, translatorArray, isLocal);
  21713. }
  21714. };
  21715. IRoxieServerActivityFactory *createRoxieServerIndexAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21716. {
  21717. return new CRoxieServerIndexAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  21718. }
  21719. //--------------------------------------------------------------------------------------------------------------------------
  21720. class CRoxieServerIndexGroupAggregateActivity : public CRoxieServerIndexActivity, implements IHThorGroupAggregateCallback
  21721. {
  21722. IHThorCompoundGroupAggregateExtra & aggregateHelper;
  21723. RowAggregator singleAggregator;
  21724. RowAggregator resultAggregator;
  21725. unsigned groupSegCount;
  21726. bool gathered;
  21727. bool eof;
  21728. public:
  21729. CRoxieServerIndexGroupAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  21730. IKeyArray * _keySet, TranslatorArray *_translators, bool _isLocal)
  21731. : CRoxieServerIndexActivity(_ctx, _factory, _probeManager, _remoteId, _keySet, _translators, false, _isLocal, false),
  21732. aggregateHelper((IHThorIndexGroupAggregateArg &)basehelper),
  21733. singleAggregator(aggregateHelper, aggregateHelper),
  21734. resultAggregator(aggregateHelper, aggregateHelper),
  21735. gathered(false), eof(true)
  21736. {
  21737. groupSegCount = 0;
  21738. }
  21739. IMPLEMENT_IINTERFACE_USING(CRoxieServerIndexActivity)
  21740. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21741. {
  21742. eof = false;
  21743. gathered= false;
  21744. CRoxieServerIndexActivity::start(parentExtractSize, parentExtract, paused);
  21745. groupSegCount = 0;
  21746. if (!paused)
  21747. processAllKeys();
  21748. resultAggregator.start(rowAllocator);
  21749. }
  21750. virtual bool needsAllocator() const { return true; }
  21751. virtual void reset()
  21752. {
  21753. resultAggregator.reset();
  21754. CRoxieServerIndexActivity::reset();
  21755. }
  21756. virtual void processRow(const void * next)
  21757. {
  21758. singleAggregator.addRow(next);
  21759. }
  21760. virtual void createSegmentMonitors(IKeyManager *key)
  21761. {
  21762. unsigned groupSegSize;
  21763. ThorActivityKind kind = factory->getKind();
  21764. if ((kind==TAKindexgroupcount || kind==TAKindexgroupexists))
  21765. groupSegSize = aggregateHelper.getGroupSegmentMonitorsSize();
  21766. else
  21767. groupSegSize = 0;
  21768. if (groupSegSize)
  21769. {
  21770. key->setMergeBarrier(groupSegSize);
  21771. CRoxieServerIndexActivity::createSegmentMonitors(key);
  21772. unsigned numSegs = tlk->ordinality();
  21773. for (unsigned segNo = 0; segNo < numSegs; segNo++)
  21774. {
  21775. IKeySegmentMonitor *seg = tlk->item(segNo);
  21776. if (seg->getOffset()+seg->getSize()==groupSegSize)
  21777. {
  21778. groupSegCount = segNo+1;
  21779. break;
  21780. }
  21781. }
  21782. assertex(groupSegCount);
  21783. }
  21784. else
  21785. CRoxieServerIndexActivity::createSegmentMonitors(key);
  21786. }
  21787. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
  21788. {
  21789. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), meta.isVariableSize());
  21790. singleAggregator.start(rowAllocator);
  21791. ThorActivityKind kind = factory->getKind();
  21792. while (tlk->lookup(true))
  21793. {
  21794. try
  21795. {
  21796. if (groupSegCount && !trans)
  21797. {
  21798. AggregateRowBuilder &rowBuilder = singleAggregator.addRow(tlk->queryKeyBuffer(callback.getFPosRef()));
  21799. callback.finishedRow();
  21800. if (kind==TAKindexgroupcount)
  21801. {
  21802. unsigned __int64 count = tlk->getCurrentRangeCount(groupSegCount);
  21803. aggregateHelper.processCountGrouping(rowBuilder, count-1);
  21804. }
  21805. if (!tlk->nextRange(groupSegCount))
  21806. break;
  21807. }
  21808. else
  21809. {
  21810. aggregateHelper.processRow(tlk->queryKeyBuffer(callback.getFPosRef()), this);
  21811. callback.finishedRow();
  21812. }
  21813. }
  21814. catch (IException *E)
  21815. {
  21816. throw makeWrappedException(E);
  21817. }
  21818. accepted++;
  21819. }
  21820. for (;;)
  21821. {
  21822. Owned<AggregateRowBuilder> next = singleAggregator.nextResult();
  21823. if (!next)
  21824. break;
  21825. size32_t size = next->querySize();
  21826. result->append(next->finalizeRowClear());
  21827. }
  21828. remote.injectResult(result.getClear());
  21829. singleAggregator.reset();
  21830. return false;
  21831. }
  21832. virtual void onLimitExceeded(bool isKeyed)
  21833. {
  21834. if (traceLevel > 4)
  21835. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  21836. throwUnexpected();
  21837. }
  21838. virtual const void *createLimitFailRow(bool isKeyed)
  21839. {
  21840. throwUnexpected();
  21841. }
  21842. void gatherMerged()
  21843. {
  21844. gathered = true;
  21845. for (;;)
  21846. {
  21847. const void * next = remote.nextRow();
  21848. if (!next)
  21849. break;
  21850. resultAggregator.mergeElement(next);
  21851. ReleaseRoxieRow(next);
  21852. }
  21853. }
  21854. virtual const void *nextRow()
  21855. {
  21856. ActivityTimer t(totalCycles, timeActivities);
  21857. if (eof)
  21858. return NULL;
  21859. if (!gathered)
  21860. gatherMerged();
  21861. Owned<AggregateRowBuilder> next = resultAggregator.nextResult();
  21862. if (next)
  21863. {
  21864. processed++;
  21865. return next->finalizeRowClear();
  21866. }
  21867. eof = true;
  21868. return NULL;
  21869. }
  21870. };
  21871. class CRoxieServerIndexGroupAggregateActivityFactory : public CRoxieServerBaseIndexActivityFactory
  21872. {
  21873. public:
  21874. CRoxieServerIndexGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21875. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId)
  21876. {
  21877. }
  21878. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  21879. {
  21880. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  21881. return new CRoxieServerNullActivity(_ctx, this, _probeManager);
  21882. // else if (isSimple)
  21883. // return new CRoxieServerSimpleIndexGroupAggregateActivity(this, keySet->queryKeyPart(0)->queryPart(0));
  21884. else
  21885. return new CRoxieServerIndexGroupAggregateActivity(_ctx, this, _probeManager, remoteId, keySet, translatorArray, isLocal);
  21886. }
  21887. };
  21888. IRoxieServerActivityFactory *createRoxieServerIndexGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21889. {
  21890. return new CRoxieServerIndexGroupAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  21891. }
  21892. //--------------------------------------------------------------------------------------------------------------------------
  21893. class CRoxieServerIndexNormalizeActivity : public CRoxieServerIndexReadBaseActivity
  21894. {
  21895. IHThorCompoundNormalizeExtra & readHelper;
  21896. public:
  21897. CRoxieServerIndexNormalizeActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  21898. IKeyArray * _keySet, TranslatorArray *_translators, bool _sorted, bool _isLocal)
  21899. : CRoxieServerIndexReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _keySet, _translators, _sorted, _isLocal, false),
  21900. readHelper((IHThorIndexNormalizeArg &)basehelper)
  21901. {
  21902. }
  21903. virtual bool needsAllocator() const { return true; }
  21904. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21905. {
  21906. CRoxieServerIndexReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  21907. rowLimit = readHelper.getRowLimit();
  21908. keyedLimit = readHelper.getKeyedLimit();
  21909. choosenLimit = readHelper.getChooseNLimit();
  21910. if (!paused)
  21911. processAllKeys();
  21912. }
  21913. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
  21914. {
  21915. unsigned keyedCount = 0;
  21916. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  21917. while (tlk->lookup(true))
  21918. {
  21919. keyedCount++;
  21920. if (keyedCount > keyedLimit)
  21921. {
  21922. if (traceLevel > 4)
  21923. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  21924. onLimitExceeded(true);
  21925. break;
  21926. }
  21927. size32_t transformedSize;
  21928. if (readHelper.first(tlk->queryKeyBuffer(callback.getFPosRef())))
  21929. {
  21930. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), meta.isVariableSize());
  21931. do
  21932. {
  21933. if (accepted>=choosenLimit)
  21934. break;
  21935. rowBuilder.ensureRow();
  21936. try
  21937. {
  21938. transformedSize = readHelper.transform(rowBuilder);
  21939. }
  21940. catch (IException *E)
  21941. {
  21942. throw makeWrappedException(E);
  21943. }
  21944. if (transformedSize)
  21945. {
  21946. // MORE - would be a good idea to stop these asap if rowlimit exceeded
  21947. result->append(rowBuilder.finalizeRowClear(transformedSize));
  21948. accepted++;
  21949. }
  21950. else
  21951. rejected++;
  21952. } while (readHelper.next());
  21953. remote.injectResult(result.getClear());
  21954. callback.finishedRow();
  21955. if (accepted>=choosenLimit)
  21956. return true;
  21957. }
  21958. }
  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. if (isKeyed)
  21966. {
  21967. if (indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates))
  21968. {
  21969. if (ctx->queryDebugContext())
  21970. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  21971. throw makeLimitSkipException(true);
  21972. }
  21973. else
  21974. readHelper.onKeyedLimitExceeded();
  21975. }
  21976. else
  21977. {
  21978. if (indexHelper.getFlags() & (TIRlimitskips||TIRlimitcreates))
  21979. {
  21980. if (ctx->queryDebugContext())
  21981. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  21982. throw makeLimitSkipException(false);
  21983. }
  21984. else
  21985. readHelper.onLimitExceeded();
  21986. }
  21987. }
  21988. virtual const void *createLimitFailRow(bool isKeyed)
  21989. {
  21990. UNIMPLEMENTED;
  21991. }
  21992. };
  21993. class CRoxieServerIndexNormalizeActivityFactory : public CRoxieServerBaseIndexActivityFactory
  21994. {
  21995. public:
  21996. CRoxieServerIndexNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21997. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId)
  21998. {
  21999. }
  22000. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  22001. {
  22002. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  22003. return new CRoxieServerNullActivity(_ctx, this, _probeManager);
  22004. else
  22005. return new CRoxieServerIndexNormalizeActivity(_ctx, this, _probeManager, remoteId, keySet, translatorArray, sorted, isLocal);
  22006. }
  22007. };
  22008. IRoxieServerActivityFactory *createRoxieServerIndexNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  22009. {
  22010. return new CRoxieServerIndexNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  22011. }
  22012. //=================================================================================
  22013. class CRoxieServerFetchActivity : public CRoxieServerActivity, implements IRecordPullerCallback, implements IRoxieServerErrorHandler
  22014. {
  22015. IHThorFetchBaseArg &helper;
  22016. IHThorFetchContext * fetchContext;
  22017. Linked<IFilePartMap> map;
  22018. CRemoteResultAdaptor remote;
  22019. RecordPullerThread puller;
  22020. bool needsRHS;
  22021. bool variableFileName;
  22022. bool isOpt;
  22023. Owned<const IResolvedFile> varFileInfo;
  22024. public:
  22025. CRoxieServerFetchActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IFilePartMap *_map)
  22026. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorFetchBaseArg &)basehelper), map(_map), remote(_ctx, this, _remoteId, meta.queryOriginal(), helper, *this, true, true), puller(false)
  22027. {
  22028. fetchContext = static_cast<IHThorFetchContext *>(helper.selectInterface(TAIfetchcontext_1));
  22029. needsRHS = helper.transformNeedsRhs();
  22030. variableFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((fetchContext->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  22031. isOpt = (fetchContext->getFetchFlags() & FFdatafileoptional) != 0;
  22032. }
  22033. virtual const IResolvedFile *queryVarFileInfo() const
  22034. {
  22035. return varFileInfo;
  22036. }
  22037. virtual void onCreate(IHThorArg *_colocalParent)
  22038. {
  22039. CRoxieServerActivity::onCreate(_colocalParent);
  22040. remote.onCreate(_colocalParent);
  22041. }
  22042. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  22043. {
  22044. if (idx)
  22045. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
  22046. puller.setInput(this, _sourceIdx, _in);
  22047. }
  22048. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  22049. {
  22050. puller.connectInputStreams(ctx, consumerOrdered);
  22051. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
  22052. }
  22053. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  22054. {
  22055. if (idx==0)
  22056. return puller.queryInput();
  22057. else
  22058. return NULL;
  22059. }
  22060. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  22061. {
  22062. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  22063. remote.onStart(parentExtractSize, parentExtract);
  22064. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  22065. if (variableFileName)
  22066. {
  22067. OwnedRoxieString fname(fetchContext->getFileName());
  22068. varFileInfo.setown(resolveLFN(fname, isOpt));
  22069. if (varFileInfo)
  22070. map.setown(varFileInfo->getFileMap());
  22071. }
  22072. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().fetchPreload, false, ctx);
  22073. }
  22074. virtual void stop()
  22075. {
  22076. // Called from remote, so no need to call back to it....
  22077. puller.stop();
  22078. CRoxieServerActivity::stop();
  22079. }
  22080. virtual void reset()
  22081. {
  22082. processed = remote.processed;
  22083. remote.processed = 0;
  22084. puller.reset();
  22085. if (variableFileName)
  22086. {
  22087. varFileInfo.clear();
  22088. map.clear();
  22089. }
  22090. CRoxieServerActivity::reset();
  22091. }
  22092. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  22093. {
  22094. if (idx==(unsigned)-1)
  22095. idx = 0;
  22096. return idx ? NULL : &remote;
  22097. }
  22098. virtual void processRow(const void *row)
  22099. {
  22100. // called from puller thread
  22101. offset_t rp = fetchContext->extractPosition(row);
  22102. unsigned partNo;
  22103. if (isLocalFpos(rp))
  22104. partNo = getLocalFposPart(rp) + 1;
  22105. else
  22106. partNo = map->mapOffset(rp);
  22107. if (needsRHS)
  22108. {
  22109. Owned<IEngineRowAllocator> extractAllocator = createRowAllocator(helper.queryExtractedSize());
  22110. RtlDynamicRowBuilder rb(extractAllocator, true);
  22111. unsigned rhsSize = helper.extractJoinFields(rb, row);
  22112. char * block = (char *) remote.getMem(partNo, 0, sizeof(rp) + sizeof(rhsSize) + rhsSize); // MORE - superfiles
  22113. *(offset_t *) block = rp;
  22114. block += sizeof(rp);
  22115. *(unsigned *) block = rhsSize;
  22116. block += sizeof(rhsSize);
  22117. memcpy(block, rb.row(), rhsSize);
  22118. }
  22119. else
  22120. *(offset_t *) remote.getMem(partNo, 0, sizeof(rp)) = rp; // MORE - superfiles
  22121. ReleaseRoxieRow(row);
  22122. }
  22123. void processEOG()
  22124. {
  22125. #ifdef FETCH_PRESERVES_GROUPING
  22126. UNIMPLEMENTED;
  22127. #endif
  22128. // else discard is correct
  22129. }
  22130. void processGroup(const ConstPointerArray &)
  22131. {
  22132. throwUnexpected();
  22133. }
  22134. void processDone()
  22135. {
  22136. // called from puller thread
  22137. remote.flush();
  22138. remote.senddone();
  22139. }
  22140. virtual bool fireException(IException *e)
  22141. {
  22142. return remote.fireException(e);
  22143. }
  22144. virtual void onLimitExceeded(bool isKeyed)
  22145. {
  22146. if (traceLevel > 4)
  22147. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  22148. if (isKeyed)
  22149. throwUnexpected();
  22150. helper.onLimitExceeded();
  22151. }
  22152. virtual const void *createLimitFailRow(bool isKeyed)
  22153. {
  22154. UNIMPLEMENTED;
  22155. }
  22156. virtual const void *nextRow()
  22157. {
  22158. throwUnexpected(); // I am nobody's input
  22159. }
  22160. };
  22161. class CRoxieServerFetchActivityFactory : public CRoxieServerActivityFactory
  22162. {
  22163. RemoteActivityId remoteId;
  22164. Owned<IFilePartMap> map;
  22165. bool variableFileName;
  22166. Owned<const IResolvedFile> datafile;
  22167. public:
  22168. CRoxieServerFetchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  22169. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), remoteId(_remoteId)
  22170. {
  22171. Owned<IHThorFetchBaseArg> helper = (IHThorFetchBaseArg *) helperFactory();
  22172. IHThorFetchContext *fetchContext = static_cast<IHThorFetchContext *>(helper->selectInterface(TAIfetchcontext_1));
  22173. variableFileName = allFilesDynamic || _queryFactory.isDynamic() || ((fetchContext->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  22174. if (!variableFileName)
  22175. {
  22176. OwnedRoxieString fname(fetchContext->getFileName());
  22177. datafile.setown(_queryFactory.queryPackage().lookupFileName(fname,
  22178. (fetchContext->getFetchFlags() & FFdatafileoptional) != 0,
  22179. true, true,
  22180. _queryFactory.queryWorkUnit(), true));
  22181. if (datafile)
  22182. map.setown(datafile->getFileMap());
  22183. }
  22184. }
  22185. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  22186. {
  22187. return new CRoxieServerFetchActivity(_ctx, this, _probeManager, remoteId, map);
  22188. }
  22189. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  22190. {
  22191. if (datafile)
  22192. addXrefFileInfo(reply, datafile);
  22193. else
  22194. {
  22195. // Temporarily resolve the file
  22196. Owned<IHThorFetchBaseArg> helper = (IHThorFetchBaseArg *) helperFactory();
  22197. IHThorFetchContext *fetchContext = static_cast<IHThorFetchContext *>(helper->selectInterface(TAIfetchcontext_1));
  22198. if ((fetchContext->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) == 0)
  22199. {
  22200. OwnedRoxieString fileName(fetchContext->getFileName());
  22201. Owned<const IResolvedFile> temp = queryFactory.queryPackage().lookupFileName(fileName, true, true, false, queryFactory.queryWorkUnit(), true);
  22202. if (temp)
  22203. addXrefFileInfo(reply, temp);
  22204. }
  22205. }
  22206. }
  22207. virtual const StatisticsMapping &queryStatsMapping() const
  22208. {
  22209. return diskStatistics;
  22210. }
  22211. };
  22212. IRoxieServerActivityFactory *createRoxieServerFetchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  22213. {
  22214. return new CRoxieServerFetchActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  22215. }
  22216. // MORE - is there any point keeping this now?
  22217. class CRoxieServerDummyActivityFactory : public CRoxieServerActivityFactory // not a real activity - just used to properly link files
  22218. {
  22219. public:
  22220. Owned<const IResolvedFile> indexfile;
  22221. Owned<const IResolvedFile> datafile;
  22222. StringAttr fileName;
  22223. StringAttr indexName;
  22224. Owned<IKeyArray> keySet;
  22225. Owned<IFileIOArray> files;
  22226. TranslatorArray layoutTranslators;
  22227. CRoxieServerDummyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool isLoadDataOnly)
  22228. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  22229. {
  22230. try // does not want any missing file errors to be fatal, or throw traps - just log it
  22231. {
  22232. if (_graphNode.getPropBool("att[@name='_isSpill']/@value", false) || _graphNode.getPropBool("att[@name='_isSpillGlobal']/@value", false))
  22233. return; // ignore 'spills'
  22234. bool isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  22235. ThorActivityKind kind = getActivityKind(_graphNode);
  22236. if (kind != TAKdiskwrite && kind != TAKindexwrite && kind != TAKpiperead && kind != TAKpipewrite)
  22237. {
  22238. fileName.set(queryNodeFileName(_graphNode, kind));
  22239. indexName.set(queryNodeIndexName(_graphNode, kind));
  22240. if (indexName && !allFilesDynamic && !queryFactory.isDynamic())
  22241. {
  22242. bool isOpt = pretendAllOpt || _graphNode.getPropBool("att[@name='_isIndexOpt']/@value");
  22243. indexfile.setown(queryFactory.queryPackage().lookupFileName(indexName, isOpt, true, true, queryFactory.queryWorkUnit(), true));
  22244. if (indexfile)
  22245. keySet.setown(indexfile->getKeyArray(NULL, &layoutTranslators, isOpt, isLocal ? queryFactory.queryChannel() : 0, IRecordLayoutTranslator::NoTranslation));
  22246. }
  22247. if (fileName && !allFilesDynamic && !queryFactory.isDynamic())
  22248. {
  22249. bool isOpt = pretendAllOpt || _graphNode.getPropBool("att[@name='_isOpt']/@value");
  22250. datafile.setown(_queryFactory.queryPackage().lookupFileName(fileName, isOpt, true, true, queryFactory.queryWorkUnit(), true));
  22251. if (datafile)
  22252. {
  22253. if (isLocal)
  22254. files.setown(datafile->getIFileIOArray(isOpt, queryFactory.queryChannel()));
  22255. }
  22256. }
  22257. }
  22258. }
  22259. catch(IException *E)
  22260. {
  22261. StringBuffer errors;
  22262. E->errorMessage(errors);
  22263. DBGLOG("%s File error = %s", (isLoadDataOnly) ? "LOADDATAONLY" : "SUSPENDED QUERY", errors.str());
  22264. E->Release();
  22265. }
  22266. }
  22267. 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__); }
  22268. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  22269. {
  22270. if (!allFilesDynamic)
  22271. {
  22272. if (datafile)
  22273. addXrefFileInfo(reply, datafile);
  22274. if (indexfile)
  22275. addXrefFileInfo(reply, indexfile);
  22276. }
  22277. else
  22278. {
  22279. Owned<const IResolvedFile> temp;
  22280. if (fileName.length())
  22281. {
  22282. temp.setown(queryFactory.queryPackage().lookupFileName(fileName, true, true, false, queryFactory.queryWorkUnit(), true));
  22283. if (temp)
  22284. addXrefFileInfo(reply, temp);
  22285. }
  22286. if (indexName.length())
  22287. {
  22288. temp.setown(queryFactory.queryPackage().lookupFileName(indexName, true, true, false, queryFactory.queryWorkUnit(), true));
  22289. if (temp)
  22290. addXrefFileInfo(reply, temp);
  22291. }
  22292. }
  22293. }
  22294. };
  22295. IRoxieServerActivityFactory *createRoxieServerDummyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool isLoadDataOnly)
  22296. {
  22297. return new CRoxieServerDummyActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, isLoadDataOnly);
  22298. }
  22299. //=====================================================================================================
  22300. // Keyed joins...
  22301. //
  22302. // Input records are pulled by a puller thread, which checks each LHS record to determine which (if any) channels it
  22303. // may have RHS matches on, and sends the relevant fields to the relevant slaves.
  22304. // 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
  22305. // the transform and returns rows that are created.
  22306. // 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)
  22307. //
  22308. //=====================================================================================================
  22309. class CJoinGroup;
  22310. interface IJoinProcessor
  22311. {
  22312. virtual void processEOG() = 0;
  22313. virtual CJoinGroup *createJoinGroup(const void *row) = 0;
  22314. virtual void noteEndReceived(CJoinGroup *jg, unsigned candidateCount) = 0;
  22315. virtual bool fireException(IException *E) = 0;
  22316. virtual void processCompletedGroups() = 0;
  22317. };
  22318. //------------------------------------------------------------------------------------------------------
  22319. // Class CJoinGroup has a record per LHS row, plus (if preserving grouping) a 'head of group' record
  22320. // It gathers all the corresponding RHS rows, keeping track of how may slave transactions are pending in endMarkersPending
  22321. // If preserving groups, the 'head of group' record keeps track of how many LHS records in the group are still incomplete.
  22322. // CJoinGroup records are allocated out of the Roxie row memory manager by overloading operator new, so that they are included in the
  22323. // per-query limits etc (Note that the pointer array block is not though).
  22324. // Because of that, the exact size is significant - especially whether fit just under or just over a chunking threshold...
  22325. //
  22326. // There are two phases to the life of a JoinGroup - it is created by the puller thread that is also firing off slave requests
  22327. // notePending will be called once for every slave request. Puller thread calls noteEndReceived(0) once when done - this corresponds to the
  22328. // initial count when created.
  22329. // Slave replies and are noted by the consumer thread calling addRightMatch() and noteEndReceived(n).
  22330. // Once endMarkersPending reaches 0, JoinGroup is complete. Last thread to call noteEndReceived will process the rows and destroy the group.
  22331. // There is no need for a critsec because although multiple threads will access at different times, only the consumer thread will
  22332. // access any modifiable member variables while endMarkersPending != 0 (i.e. complete() is false). Once complete returns true there is a single
  22333. // remaining reference and the JoinGroup will be processed and destroyed.
  22334. //
  22335. //------------------------------------------------------------------------------------------------------
  22336. class CJoinGroup : public CInterface
  22337. {
  22338. protected:
  22339. const void *left; // LHS row
  22340. PointerArrayOf<KeyedJoinHeader> rows; // matching RHS rows
  22341. atomic_t endMarkersPending; // How many slave responses still waiting for
  22342. CJoinGroup *groupStart; // Head of group, or NULL if not grouping
  22343. unsigned lastPartNo;
  22344. unsigned pos;
  22345. unsigned candidates; // Number of RHS keyed candidates - note this may not be the same as rows.ordinality()
  22346. public:
  22347. #undef new
  22348. void *operator new(size_t size, IRowManager *a, unsigned activityId)
  22349. {
  22350. return a->allocate(size, activityId);
  22351. }
  22352. #if defined(_DEBUG) && defined(_WIN32) && !defined(USING_MPATROL)
  22353. #define new new(_NORMAL_BLOCK, __FILE__, __LINE__)
  22354. #endif
  22355. void operator delete(void *ptr, IRowManager *a, unsigned activityId)
  22356. {
  22357. ReleaseRoxieRow(ptr);
  22358. }
  22359. void operator delete(void *ptr)
  22360. {
  22361. ReleaseRoxieRow(ptr);
  22362. }
  22363. public:
  22364. CJoinGroup(const void *_left, CJoinGroup *_groupStart)
  22365. {
  22366. #ifdef TRACE_JOINGROUPS
  22367. DBGLOG("Creating joinGroup %p, groupstart %p", this, _groupStart);
  22368. #endif
  22369. candidates = 0;
  22370. lastPartNo = 0;
  22371. pos = 0;
  22372. left = _left;
  22373. groupStart = _groupStart;
  22374. if (_groupStart)
  22375. {
  22376. atomic_inc(&_groupStart->endMarkersPending);
  22377. }
  22378. atomic_set(&endMarkersPending, 1);
  22379. }
  22380. ~CJoinGroup()
  22381. {
  22382. #ifdef TRACE_JOINGROUPS
  22383. DBGLOG("Destroying joinGroup %p", this);
  22384. #endif
  22385. if (left)
  22386. {
  22387. ReleaseRoxieRow(left);
  22388. roxiemem::ReleaseRoxieRowArray(rows.ordinality(), (const void * *)rows.getArray());
  22389. rows.kill();
  22390. }
  22391. }
  22392. inline bool isHeadRecord() const
  22393. {
  22394. return left==NULL;
  22395. }
  22396. inline bool complete() const
  22397. {
  22398. return atomic_read(&endMarkersPending) == 0;
  22399. }
  22400. #ifdef TRACE_JOINGROUPS
  22401. inline void notePending(unsigned lineNo)
  22402. #else
  22403. inline void notePending()
  22404. #endif
  22405. {
  22406. assert(!complete());
  22407. atomic_inc(&endMarkersPending);
  22408. #ifdef TRACE_JOINGROUPS
  22409. DBGLOG("CJoinGroup::notePending %p from %d, count became %d group count %d", this, lineNo, atomic_read(&endMarkersPending), groupStart ? atomic_read(&groupStart->endMarkersPending) : 0);
  22410. #endif
  22411. }
  22412. inline bool inGroup(CJoinGroup *leader) const
  22413. {
  22414. return groupStart==leader;
  22415. }
  22416. inline const KeyedJoinHeader *queryRow(unsigned idx) const
  22417. {
  22418. // Single threaded by now
  22419. assert(complete());
  22420. return rows.item(idx);
  22421. }
  22422. #ifdef TRACE_JOINGROUPS
  22423. bool noteEndReceived(unsigned candidateCount, unsigned lineNo)
  22424. #else
  22425. bool noteEndReceived(unsigned candidateCount)
  22426. #endif
  22427. {
  22428. assert(!complete());
  22429. if (candidateCount)
  22430. {
  22431. candidates += candidateCount;
  22432. }
  22433. #ifdef TRACE_JOINGROUPS
  22434. 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);
  22435. #endif
  22436. // NOTE - as soon as endMarkersPending and groupStart->endMarkersPending are decremented to zero this object may get released asynchronously by other threads
  22437. // There must therefore be nothing in this method after them that acceses member variables. Think of it as a delete this...
  22438. // In particular, we can't safely reference groupStart after the dec_and_test of endMarkersPending, hence copy local first
  22439. CJoinGroup *localGroupStart = groupStart;
  22440. if (atomic_dec_and_test(&endMarkersPending))
  22441. {
  22442. if (localGroupStart)
  22443. return atomic_dec_and_test(&localGroupStart->endMarkersPending);
  22444. else
  22445. return true;
  22446. }
  22447. else
  22448. return false;
  22449. }
  22450. inline const void *queryLeft() const
  22451. {
  22452. return left;
  22453. }
  22454. void addRightMatch(KeyedJoinHeader *right)
  22455. {
  22456. assert(!complete());
  22457. unsigned short partNo = right->partNo;
  22458. if (partNo != lastPartNo)
  22459. {
  22460. // MORE - should we binchop? If we did we would need to be careful to find LAST match
  22461. if (partNo > lastPartNo)
  22462. pos = rows.length();
  22463. while (pos>0)
  22464. {
  22465. if (rows.item(pos-1)->partNo <= partNo)
  22466. break;
  22467. pos--;
  22468. }
  22469. lastPartNo = partNo;
  22470. }
  22471. rows.add(right, pos);
  22472. pos++;
  22473. }
  22474. inline unsigned rowsSeen() const
  22475. {
  22476. assert(complete());
  22477. return rows.length();
  22478. }
  22479. inline unsigned candidateCount() const
  22480. {
  22481. assert(complete());
  22482. return candidates;
  22483. }
  22484. };
  22485. #ifdef TRACE_JOINGROUPS
  22486. #define notePending() notePending(__LINE__)
  22487. #define noteEndReceived(a) noteEndReceived(a, __LINE__)
  22488. #endif
  22489. class KeyedJoinRemoteAdaptor : public CRemoteResultAdaptor // MORE - not sure it should be derived from this - makes processed all wrong, for example
  22490. {
  22491. private:
  22492. SafeQueueOf<const void, true> ready;
  22493. public:
  22494. IHThorKeyedJoinArg &helper;
  22495. unsigned joinProcessed;
  22496. bool isFullKey;
  22497. bool eof;
  22498. bool isSimple;
  22499. bool allPulled;
  22500. ActivityTimeAccumulator totalCycles;
  22501. unsigned activityId;
  22502. RecordPullerThread &puller;
  22503. SafeQueueOf<const void, true> injected; // Used in isSimple mode
  22504. Owned<IEngineRowAllocator> ccdRecordAllocator;
  22505. IJoinProcessor &processor;
  22506. KeyedJoinRemoteAdaptor(IRoxieSlaveContext *_ctx, IRoxieServerErrorHandler *_errorHandler, const RemoteActivityId &_remoteId, IHThorKeyedJoinArg &_helper,
  22507. IRoxieServerActivity &_activity, bool _isFullKey, bool _isSimple,
  22508. RecordPullerThread &_puller, IJoinProcessor &_processor)
  22509. : helper(_helper),
  22510. CRemoteResultAdaptor(_ctx, _errorHandler, _remoteId, 0, _helper, _activity, true, true),
  22511. isFullKey(_isFullKey),
  22512. isSimple(_isSimple),
  22513. puller(_puller),
  22514. processor(_processor),
  22515. activityId(_activity.queryId())
  22516. {
  22517. joinProcessed = 0;
  22518. allPulled = false;
  22519. eof = false;
  22520. }
  22521. virtual void onCreate(IHThorArg *_colocalArg)
  22522. {
  22523. CRemoteResultAdaptor::onCreate(_colocalArg);
  22524. ccdRecordAllocator.setown(activity.createRowAllocator(helper.queryJoinFieldsRecordSize()));
  22525. }
  22526. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  22527. {
  22528. eof = false;
  22529. joinProcessed = 0;
  22530. totalCycles.totalCycles = 0;
  22531. allPulled = false;
  22532. assertex(ready.ordinality()==0);
  22533. CRemoteResultAdaptor::start(parentExtractSize, parentExtract, paused);
  22534. }
  22535. virtual void reset()
  22536. {
  22537. CRemoteResultAdaptor::reset();
  22538. while (ready.ordinality())
  22539. {
  22540. const void *goer = ready.dequeue();
  22541. if (goer)
  22542. ReleaseRoxieRow(goer);
  22543. }
  22544. while (injected.ordinality())
  22545. {
  22546. const void *goer = injected.dequeue();
  22547. if (goer)
  22548. ReleaseRoxieRow(goer);
  22549. }
  22550. }
  22551. inline void addResult(const void *row)
  22552. {
  22553. ready.enqueue(row);
  22554. }
  22555. virtual unsigned __int64 queryTotalCycles() const
  22556. {
  22557. return totalCycles.totalCycles;
  22558. }
  22559. virtual const void *nextRow()
  22560. {
  22561. ActivityTimer t(totalCycles, timeActivities);
  22562. for (;;)
  22563. {
  22564. if (eof)
  22565. return NULL;
  22566. processSlaveResults();
  22567. if (ready.ordinality())
  22568. {
  22569. const void *result = ready.dequeue();
  22570. if (result)
  22571. joinProcessed++;
  22572. return result;
  22573. }
  22574. else
  22575. eof = true;
  22576. }
  22577. }
  22578. private:
  22579. void processSlaveResults()
  22580. {
  22581. while (!ready.ordinality())
  22582. {
  22583. KeyedJoinHeader *fetchedData;
  22584. if (isSimple)
  22585. {
  22586. while (!allPulled && !injected.ordinality())
  22587. {
  22588. if (!puller.pullRecords(1))
  22589. {
  22590. puller.done();
  22591. allPulled = true;
  22592. }
  22593. }
  22594. fetchedData = (KeyedJoinHeader *) injected.dequeue();
  22595. }
  22596. else
  22597. fetchedData = (KeyedJoinHeader *) CRemoteResultAdaptor::nextRow();
  22598. if (fetchedData)
  22599. {
  22600. CJoinGroup *thisGroup = fetchedData->thisGroup;
  22601. if (fetchedData->partNo == (unsigned short) -1)
  22602. {
  22603. #ifdef TRACE_JOINGROUPS
  22604. CTXLOG("Got end for group %p", thisGroup);
  22605. #endif
  22606. unsigned candidateCount = (unsigned) fetchedData->fpos;
  22607. ReleaseRoxieRow(fetchedData);
  22608. processor.noteEndReceived(thisGroup, candidateCount); // note - this can throw exception. So release fetchdata before calling
  22609. }
  22610. else
  22611. {
  22612. #ifdef TRACE_JOINGROUPS
  22613. CTXLOG("Reading another %d bytes for group %p data", ccdRecordSize, thisGroup);
  22614. #endif
  22615. thisGroup->addRightMatch(fetchedData);
  22616. if (isFullKey)
  22617. {
  22618. #ifdef TRACE_JOINGROUPS
  22619. CTXLOG("Calling noteEndReceived for record returned from FETCH of full keyed join");
  22620. #endif
  22621. processor.noteEndReceived(thisGroup, 0); // note - this can throw exception. So release fetchdata before calling
  22622. }
  22623. }
  22624. }
  22625. else
  22626. break;
  22627. }
  22628. }
  22629. };
  22630. class CRoxieServerFullKeyedJoinHead: public CRoxieServerActivity, implements IRecordPullerCallback, implements IRoxieServerErrorHandler
  22631. {
  22632. IHThorKeyedJoinArg &helper;
  22633. Owned<IKeyManager> tlk;
  22634. Linked<IKeyArray> keySet;
  22635. Linked<TranslatorArray> translators;
  22636. CRemoteResultAdaptor remote;
  22637. RecordPullerThread puller;
  22638. IOutputMetaData *indexReadMeta;
  22639. IJoinProcessor *joinHandler;
  22640. bool variableIndexFileName;
  22641. bool indexReadInputRecordVariable;
  22642. bool isLocal;
  22643. Owned<IEngineRowAllocator> indexReadAllocator;
  22644. Owned<const IResolvedFile> varFileInfo;
  22645. IFinalRoxieInput *indexReadInput;
  22646. unsigned indexReadIdx = 0;
  22647. IIndexReadActivityInfo *rootIndex;
  22648. public:
  22649. CRoxieServerFullKeyedJoinHead(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IKeyArray * _keySet, TranslatorArray *_translators, IOutputMetaData *_indexReadMeta, IJoinProcessor *_joinHandler, bool _isLocal)
  22650. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  22651. helper((IHThorKeyedJoinArg &)basehelper),
  22652. tlk(createLocalKeyManager(NULL, 0, this)),
  22653. translators(_translators),
  22654. keySet(_keySet),
  22655. remote(_ctx, this, _remoteId, 0, helper, *this, true, true),
  22656. indexReadMeta(_indexReadMeta),
  22657. joinHandler(_joinHandler),
  22658. puller(false),
  22659. isLocal(_isLocal)
  22660. {
  22661. variableIndexFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getJoinFlags() & (JFvarindexfilename|JFdynamicindexfilename|JFindexfromactivity)) != 0);
  22662. indexReadInputRecordVariable = indexReadMeta->isVariableSize();
  22663. indexReadInput = NULL;
  22664. rootIndex = NULL;
  22665. }
  22666. virtual const IResolvedFile *queryVarFileInfo() const
  22667. {
  22668. return varFileInfo;
  22669. }
  22670. virtual void onCreate(IHThorArg *_colocalParent)
  22671. {
  22672. CRoxieServerActivity::onCreate(_colocalParent);
  22673. remote.onCreate(_colocalParent);
  22674. indexReadAllocator.setown(createRowAllocator(indexReadMeta));
  22675. }
  22676. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  22677. {
  22678. if (!idx)
  22679. puller.setInput(this, _sourceIdx, _in);
  22680. else if (idx==1)
  22681. {
  22682. indexReadInput = _in;
  22683. indexReadIdx = _sourceIdx;
  22684. }
  22685. else
  22686. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
  22687. }
  22688. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  22689. {
  22690. puller.connectInputStreams(ctx, consumerOrdered);
  22691. //No rows are read from indexReadInput, so no need to extract the streams
  22692. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
  22693. }
  22694. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  22695. {
  22696. switch (idx)
  22697. {
  22698. case 0:
  22699. return puller.queryInput();
  22700. case 1:
  22701. return indexReadInput;
  22702. default:
  22703. return NULL;
  22704. }
  22705. }
  22706. virtual void serializeExtra(MemoryBuffer &out)
  22707. {
  22708. if (helper.getJoinFlags() & JFindexfromactivity)
  22709. {
  22710. assertex(rootIndex);
  22711. const RemoteActivityId& indexId = rootIndex->queryRemoteId();
  22712. indexId.serialize(out);
  22713. // could mess about reserving space for length then patching it again, to avoid copy, but probably not worth it
  22714. MemoryBuffer tmp;
  22715. rootIndex->queryActivity()->serializeCreateStartContext(tmp);
  22716. if (rootIndex->queryActivity()->queryVarFileInfo())
  22717. {
  22718. rootIndex->queryActivity()->queryVarFileInfo()->queryTimeStamp().serialize(tmp);
  22719. tmp.append(rootIndex->queryActivity()->queryVarFileInfo()->queryCheckSum());
  22720. }
  22721. unsigned ctxlen = tmp.length();
  22722. out.append(ctxlen).append(tmp);
  22723. }
  22724. }
  22725. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  22726. {
  22727. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  22728. if (indexReadInput)
  22729. {
  22730. indexReadInput->start(parentExtractSize, parentExtract, true); // paused=true because we don't want to actually run the index read
  22731. rootIndex = indexReadInput->queryIndexReadActivity();
  22732. if (!rootIndex)
  22733. throw MakeStringException(ROXIE_INTERNAL_ERROR,"Index in keyed join %d could not be resolved", queryId());
  22734. }
  22735. remote.onStart(parentExtractSize, parentExtract);
  22736. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  22737. if (rootIndex)
  22738. {
  22739. varFileInfo.setown(rootIndex->getVarFileInfo());
  22740. translators.setown(rootIndex->getTranslators());
  22741. keySet.setown(rootIndex->getKeySet());
  22742. }
  22743. else if (variableIndexFileName)
  22744. {
  22745. OwnedRoxieString indexFileName(helper.getIndexFileName());
  22746. varFileInfo.setown(resolveLFN(indexFileName, (helper.getJoinFlags() & JFindexoptional) != 0));
  22747. if (varFileInfo)
  22748. {
  22749. translators.setown(new TranslatorArray);
  22750. keySet.setown(varFileInfo->getKeyArray(factory->queryActivityMeta(), translators, false, isLocal ? factory->queryQueryFactory().queryChannel() : 0, factory->queryQueryFactory().queryOptions().enableFieldTranslation)); // MORE - isLocal?
  22751. }
  22752. }
  22753. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().fullKeyedJoinPreload, false, ctx);
  22754. }
  22755. virtual void stop()
  22756. {
  22757. puller.stop();
  22758. CRoxieServerActivity::stop();
  22759. }
  22760. virtual void reset()
  22761. {
  22762. CRoxieServerActivity::reset();
  22763. puller.reset();
  22764. if (varFileInfo)
  22765. {
  22766. keySet.clear();
  22767. varFileInfo.clear();
  22768. }
  22769. }
  22770. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  22771. {
  22772. if (idx==(unsigned)-1)
  22773. idx = 0;
  22774. return idx ? NULL : &remote;
  22775. }
  22776. virtual void processRow(const void *row)
  22777. {
  22778. // MORE - this code seems to be pretty much duplicated below in half-keyed....
  22779. // called from front puller thread
  22780. // buffer up an IndexRead request
  22781. if (keySet && helper.leftCanMatch(row))
  22782. {
  22783. RtlDynamicRowBuilder extractedBuilder(indexReadAllocator);
  22784. unsigned indexReadSize = helper.extractIndexReadFields(extractedBuilder, row);
  22785. OwnedConstRoxieRow extracted;
  22786. if (indexReadSize)
  22787. extracted.setown(extractedBuilder.finalizeRowClear(indexReadSize));
  22788. CJoinGroup *jg = joinHandler->createJoinGroup(row);
  22789. for (unsigned partNo = 0; partNo < keySet->length(); partNo++)
  22790. {
  22791. IKeyIndexBase *thisBase = keySet->queryKeyPart(partNo);
  22792. if (thisBase)
  22793. {
  22794. unsigned fileNo = 0;
  22795. IKeyIndex *thisKey = thisBase->queryPart(fileNo);
  22796. try
  22797. {
  22798. tlk->setKey(thisKey);
  22799. tlk->setLayoutTranslator(translators->item(fileNo));
  22800. helper.createSegmentMonitors(tlk, extracted);
  22801. if (rootIndex)
  22802. rootIndex->mergeSegmentMonitors(tlk);
  22803. tlk->finishSegmentMonitors();
  22804. tlk->reset();
  22805. for (;;)
  22806. {
  22807. typedef const void * cvp;
  22808. if (thisKey->isTopLevelKey())
  22809. {
  22810. bool locallySorted = !thisKey->isFullySorted();
  22811. while (locallySorted || tlk->lookup(false))
  22812. {
  22813. unsigned slavePart = locallySorted ? 0 : (unsigned) tlk->queryFpos();
  22814. if (locallySorted || slavePart)
  22815. {
  22816. cvp *outputBuffer = (cvp *) remote.getMem(slavePart, fileNo, indexReadSize + sizeof(cvp) + (indexReadInputRecordVariable ? sizeof(unsigned) : 0));
  22817. *outputBuffer++ = jg;
  22818. if (indexReadInputRecordVariable)
  22819. {
  22820. *(unsigned *) outputBuffer = indexReadSize;
  22821. outputBuffer = (cvp*) (((unsigned *) outputBuffer) + 1);
  22822. }
  22823. jg->notePending();
  22824. memcpy(outputBuffer, extracted, indexReadSize);
  22825. if (locallySorted)
  22826. {
  22827. for (unsigned i = 1; i < numChannels; i++)
  22828. jg->notePending();
  22829. break;
  22830. }
  22831. }
  22832. }
  22833. }
  22834. else
  22835. {
  22836. // MORE - this code seems to be duplicated in half keyed
  22837. unsigned accepted = 0;
  22838. unsigned rejected = 0;
  22839. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), true);
  22840. jg->notePending();
  22841. unsigned candidateCount = 0;
  22842. while (tlk->lookup(true))
  22843. {
  22844. candidateCount++;
  22845. atomic_inc(&indexRecordsRead);
  22846. KLBlobProviderAdapter adapter(tlk);
  22847. offset_t recptr;
  22848. const byte *indexRow = tlk->queryKeyBuffer(recptr);
  22849. if (helper.indexReadMatch(extracted, indexRow, recptr, &adapter))
  22850. {
  22851. KeyedJoinHeader *rhs = (KeyedJoinHeader *) ctx->queryRowManager().allocate(KEYEDJOIN_RECORD_SIZE(0), activityId);
  22852. rhs->fpos = recptr;
  22853. rhs->thisGroup = jg;
  22854. rhs->partNo = partNo;
  22855. result->append(rhs);
  22856. }
  22857. else
  22858. {
  22859. rejected++;
  22860. atomic_inc(&postFiltered);
  22861. }
  22862. }
  22863. // output an end marker for the matches to this group
  22864. KeyedJoinHeader *endMarker = (KeyedJoinHeader *) ctx->queryRowManager().allocate(KEYEDJOIN_RECORD_SIZE(0), activityId);
  22865. endMarker->fpos = (offset_t) candidateCount;
  22866. endMarker->thisGroup = jg;
  22867. endMarker->partNo = (unsigned short) -1;
  22868. result->append(endMarker);
  22869. remote.injectResult(result.getClear());
  22870. if (accepted)
  22871. noteStatistic(StNumIndexAccepted, accepted);
  22872. if (rejected)
  22873. noteStatistic(StNumIndexRejected, rejected);
  22874. }
  22875. if (++fileNo < thisBase->numParts())
  22876. {
  22877. thisKey = thisBase->queryPart(fileNo);
  22878. tlk->setKey(thisKey);
  22879. tlk->setLayoutTranslator(translators->item(fileNo));
  22880. tlk->reset();
  22881. }
  22882. else
  22883. break;
  22884. }
  22885. tlk->releaseSegmentMonitors();
  22886. tlk->setKey(NULL);
  22887. }
  22888. catch (...)
  22889. {
  22890. tlk->releaseSegmentMonitors();
  22891. tlk->setKey(NULL);
  22892. throw;
  22893. }
  22894. }
  22895. }
  22896. joinHandler->noteEndReceived(jg, 0);
  22897. }
  22898. else
  22899. {
  22900. joinHandler->noteEndReceived(joinHandler->createJoinGroup(row), 0);
  22901. }
  22902. }
  22903. void processGroup(const ConstPointerArray &)
  22904. {
  22905. throwUnexpected();
  22906. }
  22907. virtual void processEOG()
  22908. {
  22909. joinHandler->processEOG();
  22910. }
  22911. virtual void processDone()
  22912. {
  22913. // called from puller thread
  22914. remote.flush();
  22915. remote.senddone();
  22916. }
  22917. virtual void onLimitExceeded(bool isKeyed)
  22918. {
  22919. if (traceLevel > 4)
  22920. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  22921. if (isKeyed)
  22922. throwUnexpected();
  22923. helper.onLimitExceeded();
  22924. }
  22925. virtual const void *createLimitFailRow(bool isKeyed)
  22926. {
  22927. throwUnexpected();
  22928. }
  22929. virtual bool fireException(IException *e)
  22930. {
  22931. // called from puller thread on failure
  22932. remote.fireException(LINK(e));
  22933. return joinHandler->fireException(e);
  22934. }
  22935. virtual const void *nextRow()
  22936. {
  22937. throwUnexpected(); // I am nobody's input
  22938. }
  22939. };
  22940. class CRoxieServerKeyedJoinBase : public CRoxieServerActivity, implements IRecordPullerCallback, implements IRoxieServerErrorHandler, implements IJoinProcessor
  22941. {
  22942. protected:
  22943. IHThorKeyedJoinArg &helper;
  22944. KeyedJoinRemoteAdaptor remote;
  22945. RecordPullerThread puller;
  22946. OwnedConstRoxieRow defaultRight;
  22947. Owned<IEngineRowAllocator> defaultRightAllocator;
  22948. unsigned joinFlags;
  22949. unsigned atMost;
  22950. unsigned atmostsTriggered;
  22951. unsigned abortLimit;
  22952. unsigned keepLimit;
  22953. bool limitFail;
  22954. bool limitOnFail;
  22955. bool preserveGroups;
  22956. bool cloneLeft;
  22957. bool isSimple;
  22958. bool isLocal;
  22959. ThorActivityKind activityKind;
  22960. CJoinGroup *groupStart;
  22961. CriticalSection groupsCrit;
  22962. QueueOf<CJoinGroup, false> groups;
  22963. IFinalRoxieInput *indexReadInput;
  22964. unsigned indexReadIdx = 0;
  22965. Owned<IStrandJunction> indexReadJunction;
  22966. IEngineRowStream *indexReadStream = NULL; // Never actually pulled
  22967. IIndexReadActivityInfo *rootIndex;
  22968. void createDefaultRight()
  22969. {
  22970. if (!defaultRight)
  22971. {
  22972. if (!defaultRightAllocator)
  22973. defaultRightAllocator.setown(createRowAllocator(helper.queryJoinFieldsRecordSize()));
  22974. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  22975. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  22976. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  22977. }
  22978. }
  22979. public:
  22980. CRoxieServerKeyedJoinBase(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _joinFlags
  22981. , bool isFull, bool _isSimple, bool _isLocal)
  22982. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  22983. helper((IHThorKeyedJoinArg &)basehelper),
  22984. remote(_ctx, this, _remoteId, helper, *this, isFull, _isSimple, puller, *this),
  22985. joinFlags(_joinFlags),
  22986. preserveGroups(meta.isGrouped()),
  22987. puller(false),
  22988. isSimple(_isSimple),
  22989. isLocal(_isLocal),
  22990. abortLimit(0),
  22991. keepLimit(0),
  22992. atMost(0),
  22993. limitFail(false),
  22994. limitOnFail(false),
  22995. cloneLeft(false)
  22996. {
  22997. groupStart = NULL;
  22998. activityKind = _factory->getKind();
  22999. indexReadInput = NULL;
  23000. rootIndex = NULL;
  23001. atmostsTriggered = 0;
  23002. // MORE - code would be easier to read if I got more values from helper rather than passing from factory
  23003. }
  23004. virtual void onCreate(IHThorArg *_colocalParent)
  23005. {
  23006. CRoxieServerActivity::onCreate(_colocalParent);
  23007. remote.onCreate(_colocalParent);
  23008. }
  23009. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  23010. {
  23011. if (!idx)
  23012. puller.setInput(this, _sourceIdx, _in);
  23013. else if (idx==1)
  23014. {
  23015. indexReadInput = _in;
  23016. indexReadIdx = _sourceIdx;
  23017. }
  23018. else
  23019. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
  23020. }
  23021. virtual void connectInputStreams(bool consumerOrdered)
  23022. {
  23023. CRoxieServerActivity::connectInputStreams(consumerOrdered);
  23024. puller.connectInputStreams(ctx, consumerOrdered);
  23025. if (indexReadInput)
  23026. indexReadStream = connectSingleStream(ctx, indexReadInput, indexReadIdx, indexReadJunction, consumerOrdered); // We never actually pull the stream
  23027. }
  23028. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  23029. {
  23030. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  23031. if (indexReadInput)
  23032. {
  23033. indexReadInput->start(parentExtractSize, parentExtract, true); // paused=true because we don't want to actually run the index read
  23034. rootIndex = indexReadInput->queryIndexReadActivity();
  23035. if (!rootIndex)
  23036. throw MakeStringException(ROXIE_INTERNAL_ERROR,"Index in keyed join %d could not be resolved", queryId());
  23037. }
  23038. remote.onStart(parentExtractSize, parentExtract);
  23039. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  23040. atmostsTriggered = 0;
  23041. atMost = helper.getJoinLimit();
  23042. if (atMost == 0) atMost = (unsigned)-1;
  23043. abortLimit = helper.getMatchAbortLimit();
  23044. if (abortLimit == 0 || atMost != (unsigned) -1) abortLimit = (unsigned)-1;
  23045. keepLimit = helper.getKeepLimit();
  23046. if (keepLimit == 0) keepLimit = (unsigned)-1;
  23047. getLimitType(joinFlags, limitFail, limitOnFail);
  23048. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  23049. if (joinFlags & JFleftouter || limitOnFail)
  23050. createDefaultRight();
  23051. }
  23052. virtual void stop()
  23053. {
  23054. puller.stop();
  23055. if (indexReadStream)
  23056. indexReadStream->stop(); // Could probably do this as soon as re have fetched rootIndex?
  23057. CRoxieServerActivity::stop();
  23058. }
  23059. virtual unsigned __int64 queryLocalCycles() const
  23060. {
  23061. __int64 localCycles = remote.totalCycles.totalCycles;
  23062. localCycles -= puller.queryTotalCycles(); // MORE - debatable... but probably fair.
  23063. if (localCycles < 0)
  23064. localCycles = 0;
  23065. return localCycles;
  23066. }
  23067. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  23068. {
  23069. if (idx==0)
  23070. return puller.queryInput();
  23071. else if (idx==1)
  23072. return indexReadInput;
  23073. else
  23074. return NULL;
  23075. }
  23076. virtual void reset()
  23077. {
  23078. totalCycles.totalCycles = remote.totalCycles.totalCycles;
  23079. remote.totalCycles.totalCycles = 0;
  23080. processed = remote.joinProcessed;
  23081. remote.joinProcessed = 0;
  23082. defaultRight.clear();
  23083. if (indexReadInput)
  23084. indexReadInput->reset();
  23085. if (atmostsTriggered)
  23086. noteStatistic(StNumAtmostTriggered, atmostsTriggered);
  23087. CRoxieServerActivity::reset();
  23088. puller.reset();
  23089. while (groups.ordinality())
  23090. {
  23091. ::Release(groups.dequeue());
  23092. }
  23093. }
  23094. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  23095. {
  23096. if (idx==(unsigned)-1)
  23097. idx = 0;
  23098. return idx ? NULL : &remote;
  23099. }
  23100. #undef new
  23101. virtual CJoinGroup *createJoinGroup(const void *row)
  23102. {
  23103. // NOTE - we need to protect access to queue, since it's also modified by consumer thread. Groupstart is only modified by puller thread.
  23104. CriticalBlock c(groupsCrit);
  23105. if (preserveGroups && !groupStart)
  23106. {
  23107. groupStart = new (&ctx->queryRowManager(), activityId) CJoinGroup(NULL, NULL);
  23108. groups.enqueue(groupStart);
  23109. }
  23110. CJoinGroup *jg = new (&ctx->queryRowManager(), activityId) CJoinGroup(row, groupStart);
  23111. groups.enqueue(jg);
  23112. return jg;
  23113. }
  23114. #if defined(_DEBUG) && defined(_WIN32) && !defined(USING_MPATROL)
  23115. #define new new(_NORMAL_BLOCK, __FILE__, __LINE__)
  23116. #endif
  23117. void endGroup()
  23118. {
  23119. CriticalBlock c(groupsCrit);
  23120. if (groupStart)
  23121. noteEndReceived(groupStart, 0);
  23122. groupStart = NULL;
  23123. }
  23124. virtual void noteEndReceived(CJoinGroup *jg, unsigned candidateCount)
  23125. {
  23126. if (jg->noteEndReceived(candidateCount))
  23127. processCompletedGroups();
  23128. }
  23129. void processCompletedGroups()
  23130. {
  23131. CriticalBlock c(groupsCrit);
  23132. while (groups.ordinality())
  23133. {
  23134. if (!groups.head()->complete())
  23135. break;
  23136. Owned<CJoinGroup> head = groups.dequeue();
  23137. if (preserveGroups)
  23138. {
  23139. assert(head->isHeadRecord());
  23140. assert(groups.head()->inGroup(head));
  23141. unsigned joinGroupSize = 0;
  23142. while (groups.ordinality() && groups.head()->inGroup(head))
  23143. {
  23144. Owned<CJoinGroup> finger = groups.dequeue();
  23145. joinGroupSize += doJoinGroup(finger);
  23146. }
  23147. if (joinGroupSize)
  23148. remote.addResult(NULL);
  23149. }
  23150. else
  23151. doJoinGroup(head);
  23152. }
  23153. }
  23154. void failLimit(const void * left)
  23155. {
  23156. helper.onMatchAbortLimitExceeded();
  23157. CommonXmlWriter xmlwrite(0);
  23158. if (input && input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  23159. {
  23160. input->queryOutputMeta()->toXML((byte *) left, xmlwrite);
  23161. }
  23162. throw MakeStringException(ROXIE_JOIN_ERROR, "More than %d match candidates in keyed join %d for row %s", abortLimit, queryId(), xmlwrite.str());
  23163. }
  23164. virtual bool needsAllocator() const { return true; }
  23165. unsigned doTransform(const void *left, const void *right, offset_t fpos_or_count, IException *except, const void **group, unsigned counter)
  23166. {
  23167. if (cloneLeft && !except)
  23168. {
  23169. LinkRoxieRow(left);
  23170. remote.addResult((void *) left);
  23171. return 1;
  23172. }
  23173. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  23174. unsigned outSize;
  23175. try
  23176. {
  23177. outSize = except ? helper.onFailTransform(rowBuilder, left, right, fpos_or_count, except) :
  23178. (activityKind == TAKkeyeddenormalizegroup) ? helper.transform(rowBuilder, left, right, (unsigned) fpos_or_count, group) :
  23179. helper.transform(rowBuilder, left, right, fpos_or_count, counter);
  23180. }
  23181. catch (IException *E)
  23182. {
  23183. throw makeWrappedException(E);
  23184. }
  23185. if (outSize)
  23186. {
  23187. const void *shrunk = rowBuilder.finalizeRowClear(outSize);
  23188. remote.addResult(shrunk);
  23189. return 1;
  23190. }
  23191. else
  23192. return 0;
  23193. }
  23194. unsigned doJoinGroup(CJoinGroup *jg)
  23195. {
  23196. unsigned matched = jg->rowsSeen();
  23197. unsigned added = 0;
  23198. const void *left = jg->queryLeft();
  23199. if (jg->candidateCount() > abortLimit)
  23200. {
  23201. if (limitFail)
  23202. failLimit(left);
  23203. if (ctx->queryDebugContext())
  23204. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  23205. if (limitOnFail)
  23206. {
  23207. Owned<IException> except;
  23208. try
  23209. {
  23210. failLimit(left);
  23211. }
  23212. catch(IException * e)
  23213. {
  23214. except.setown(e);
  23215. }
  23216. added = doTransform(left, defaultRight, 0, except, NULL, 0);
  23217. }
  23218. }
  23219. else if (!matched || jg->candidateCount() > atMost)
  23220. {
  23221. if (jg->candidateCount() > atMost)
  23222. atmostsTriggered++;
  23223. switch (joinFlags & JFtypemask)
  23224. {
  23225. case JFleftouter:
  23226. case JFleftonly:
  23227. switch (activityKind)
  23228. {
  23229. case TAKkeyedjoin:
  23230. case TAKkeyeddenormalizegroup:
  23231. added = doTransform(left, defaultRight, 0, NULL, NULL, 0);
  23232. break;
  23233. case TAKkeyeddenormalize:
  23234. LinkRoxieRow(left);
  23235. remote.addResult((void *) left);
  23236. added++;
  23237. break;
  23238. }
  23239. break;
  23240. }
  23241. }
  23242. else if (!(joinFlags & JFexclude))
  23243. {
  23244. unsigned idx = 0;
  23245. switch (activityKind)
  23246. {
  23247. case TAKkeyedjoin:
  23248. while (idx < matched)
  23249. {
  23250. const KeyedJoinHeader *rhs = jg->queryRow(idx);
  23251. added += doTransform(left, &rhs->rhsdata, rhs->fpos, NULL, NULL, idx+1);
  23252. if (added==keepLimit)
  23253. break;
  23254. idx++;
  23255. }
  23256. break;
  23257. case TAKkeyeddenormalize:
  23258. {
  23259. OwnedConstRoxieRow newLeft;
  23260. newLeft.set(left);
  23261. unsigned rowSize = 0;
  23262. unsigned rightAdded = 0;
  23263. while (idx < matched)
  23264. {
  23265. const KeyedJoinHeader *rhs = jg->queryRow(idx);
  23266. try
  23267. {
  23268. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  23269. size32_t transformedSize = helper.transform(rowBuilder, newLeft, &rhs->rhsdata, rhs->fpos, idx+1);
  23270. if (transformedSize)
  23271. {
  23272. rowSize = transformedSize;
  23273. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  23274. rightAdded++;
  23275. if (rightAdded==keepLimit)
  23276. break;
  23277. }
  23278. idx++;
  23279. }
  23280. catch (IException *E)
  23281. {
  23282. throw makeWrappedException(E);
  23283. }
  23284. }
  23285. if (rowSize)
  23286. {
  23287. remote.addResult(newLeft.getClear());
  23288. added++;
  23289. }
  23290. }
  23291. break;
  23292. case TAKkeyeddenormalizegroup:
  23293. {
  23294. ConstPointerArray extractedRows;
  23295. while (idx < matched && idx < keepLimit)
  23296. {
  23297. const KeyedJoinHeader *rhs = jg->queryRow(idx);
  23298. extractedRows.append((void *) &rhs->rhsdata);
  23299. idx++;
  23300. }
  23301. added += doTransform(left, extractedRows.item(0), extractedRows.ordinality(), NULL, (const void * *)extractedRows.getArray(), 0);
  23302. }
  23303. break;
  23304. }
  23305. }
  23306. return added;
  23307. }
  23308. virtual void processDone()
  23309. {
  23310. // called from puller thread
  23311. remote.flush();
  23312. remote.senddone();
  23313. }
  23314. virtual void onLimitExceeded(bool isKeyed)
  23315. {
  23316. if (traceLevel > 4)
  23317. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  23318. if (isKeyed)
  23319. throwUnexpected();
  23320. helper.onLimitExceeded();
  23321. }
  23322. virtual const void *createLimitFailRow(bool isKeyed)
  23323. {
  23324. throwUnexpected();
  23325. }
  23326. virtual bool fireException(IException *e)
  23327. {
  23328. // called from puller thread on failure
  23329. return remote.fireException(e);
  23330. }
  23331. virtual const void *nextRow()
  23332. {
  23333. throwUnexpected(); // I am nobody's input
  23334. }
  23335. };
  23336. #ifdef _MSC_VER
  23337. #pragma warning ( push )
  23338. #pragma warning ( disable: 4355 )
  23339. #endif
  23340. class CRoxieServerKeyedJoinActivity : public CRoxieServerKeyedJoinBase
  23341. {
  23342. CRoxieServerFullKeyedJoinHead head;
  23343. Owned<IEngineRowAllocator> fetchInputAllocator;
  23344. Linked<IFilePartMap> map;
  23345. bool variableFetchFileName;
  23346. Owned<const IResolvedFile> varFetchFileInfo;
  23347. CachedOutputMetaData fetchInputFields;
  23348. public:
  23349. CRoxieServerKeyedJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_headId, IKeyArray * _key, TranslatorArray *_translators, IOutputMetaData *_indexReadMeta,
  23350. const RemoteActivityId &_tailId, IFilePartMap *_map, unsigned _joinFlags, bool _isLocal)
  23351. : CRoxieServerKeyedJoinBase(_ctx, _factory, _probeManager, _tailId, _joinFlags, true, false, _isLocal),
  23352. head(_ctx, _factory, _probeManager, _headId, _key, _translators, _indexReadMeta, this, _isLocal),
  23353. map(_map)
  23354. {
  23355. CRoxieServerKeyedJoinBase::setInput(0, 0, head.queryOutput(0));
  23356. variableFetchFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  23357. }
  23358. virtual const IResolvedFile *queryVarFileInfo() const
  23359. {
  23360. return varFetchFileInfo;
  23361. }
  23362. virtual void onCreate(IHThorArg *_colocalParent)
  23363. {
  23364. CRoxieServerKeyedJoinBase::onCreate(_colocalParent);
  23365. head.onCreate(_colocalParent);
  23366. fetchInputFields.set(helper.queryFetchInputRecordSize());
  23367. fetchInputAllocator.setown(createRowAllocator(helper.queryFetchInputRecordSize()));
  23368. }
  23369. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  23370. {
  23371. CRoxieServerKeyedJoinBase::start(parentExtractSize, parentExtract, paused);
  23372. if (variableFetchFileName)
  23373. {
  23374. bool isFetchOpt = (helper.getFetchFlags() & FFdatafileoptional) != 0;
  23375. OwnedRoxieString fname(helper.getFileName());
  23376. varFetchFileInfo.setown(resolveLFN(fname, isFetchOpt));
  23377. if (varFetchFileInfo)
  23378. map.setown(varFetchFileInfo->getFileMap());
  23379. }
  23380. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().keyedJoinPreload, false, ctx);
  23381. }
  23382. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  23383. {
  23384. head.setInput(idx, _sourceIdx, _in);
  23385. }
  23386. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  23387. {
  23388. connectInputStreams(consumerOrdered);
  23389. return head.getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
  23390. }
  23391. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  23392. {
  23393. return head.queryInput(idx);
  23394. }
  23395. virtual void processRow(const void *_rhs)
  23396. {
  23397. // called from puller thread
  23398. KeyedJoinHeader *rhs = (KeyedJoinHeader *) _rhs;
  23399. CJoinGroup *jg = rhs->thisGroup;
  23400. if (rhs->partNo != (unsigned short) -1)
  23401. {
  23402. unsigned partNo = map->mapOffset(rhs->fpos);
  23403. RtlDynamicRowBuilder fetchBuilder(fetchInputAllocator, true);
  23404. size32_t fisize = helper.extractFetchFields(fetchBuilder, jg->queryLeft());
  23405. if (fetchInputFields.isVariableSize())
  23406. {
  23407. KeyedJoinHeader *outRow = (KeyedJoinHeader *) remote.getMem(partNo, 0, KEYEDJOIN_RECORD_SIZE(fisize + sizeof(fisize)));
  23408. memcpy(outRow, rhs, KEYEDJOIN_RECORD_SIZE(0)); // MORE - copy constructor might be more appropriate....
  23409. ReleaseRoxieRow(rhs);
  23410. jg->notePending();
  23411. memcpy(&outRow->rhsdata, &fisize, sizeof(fisize));
  23412. memcpy((&outRow->rhsdata)+sizeof(fisize), fetchBuilder.row(), fisize);
  23413. }
  23414. else
  23415. {
  23416. KeyedJoinHeader *outRow = (KeyedJoinHeader *) remote.getMem(partNo, 0, KEYEDJOIN_RECORD_SIZE(fisize));
  23417. memcpy(outRow, rhs, KEYEDJOIN_RECORD_SIZE(0)); // MORE - copy constructor might be more appropriate....
  23418. ReleaseRoxieRow(rhs);
  23419. jg->notePending();
  23420. memcpy(&outRow->rhsdata, fetchBuilder.row(), fisize);
  23421. }
  23422. }
  23423. else
  23424. {
  23425. unsigned candidateCount = (unsigned) rhs->fpos;
  23426. // CTXLOG("Full keyed join - all results back from index");
  23427. ReleaseRoxieRow(rhs);
  23428. noteEndReceived(jg, candidateCount); // may throw exception - so release row before calling
  23429. }
  23430. }
  23431. virtual void processEOG()
  23432. {
  23433. // called from front puller thread
  23434. if (preserveGroups)
  23435. endGroup();
  23436. }
  23437. void processGroup(const ConstPointerArray &)
  23438. {
  23439. throwUnexpected();
  23440. }
  23441. };
  23442. #ifdef _MSC_VER
  23443. #pragma warning ( pop )
  23444. #endif
  23445. class CRoxieServerHalfKeyedJoinActivity : public CRoxieServerKeyedJoinBase
  23446. {
  23447. IOutputMetaData *indexReadMeta;
  23448. Owned<IEngineRowAllocator> indexReadAllocator;
  23449. Owned<IKeyManager> tlk;
  23450. bool variableIndexFileName;
  23451. bool indexReadInputRecordVariable;
  23452. Owned<const IResolvedFile> varFileInfo;
  23453. Linked<TranslatorArray> translators;
  23454. Linked<IKeyArray> keySet;
  23455. Owned<IOutputMetaData> joinPrefixedMeta;
  23456. Owned<IEngineRowAllocator> joinFieldsAllocator;
  23457. public:
  23458. CRoxieServerHalfKeyedJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IKeyArray * _keySet, TranslatorArray *_translators,
  23459. IOutputMetaData *_indexReadMeta, unsigned _joinFlags, bool _isSimple, bool _isLocal)
  23460. : CRoxieServerKeyedJoinBase(_ctx, _factory, _probeManager, _remoteId, _joinFlags, false, _isSimple, _isLocal),
  23461. indexReadMeta(_indexReadMeta),
  23462. tlk(createLocalKeyManager(NULL, 0, this)),
  23463. keySet(_keySet),
  23464. translators(_translators)
  23465. {
  23466. variableIndexFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getJoinFlags() & (JFvarindexfilename|JFdynamicindexfilename|JFindexfromactivity)) != 0);
  23467. indexReadInputRecordVariable = indexReadMeta->isVariableSize();
  23468. }
  23469. virtual void serializeExtra(MemoryBuffer &out)
  23470. {
  23471. if (helper.getJoinFlags() & JFindexfromactivity)
  23472. {
  23473. assertex(rootIndex);
  23474. const RemoteActivityId& indexId = rootIndex->queryRemoteId();
  23475. indexId.serialize(out);
  23476. // could mess about reserving space for length then patching it again, to avoid copy, but probably not worth it
  23477. MemoryBuffer tmp;
  23478. rootIndex->queryActivity()->serializeCreateStartContext(tmp);
  23479. if (rootIndex->queryActivity()->queryVarFileInfo())
  23480. {
  23481. rootIndex->queryActivity()->queryVarFileInfo()->queryTimeStamp().serialize(tmp);
  23482. tmp.append(rootIndex->queryActivity()->queryVarFileInfo()->queryCheckSum());
  23483. }
  23484. unsigned ctxlen = tmp.length();
  23485. out.append(ctxlen).append(tmp);
  23486. }
  23487. }
  23488. virtual void onCreate(IHThorArg *_colocalParent)
  23489. {
  23490. CRoxieServerKeyedJoinBase::onCreate(_colocalParent);
  23491. indexReadAllocator.setown(createRowAllocator(indexReadMeta));
  23492. IOutputMetaData *joinFieldsMeta = helper.queryJoinFieldsRecordSize();
  23493. joinPrefixedMeta.setown(new CPrefixedOutputMeta(KEYEDJOIN_RECORD_SIZE(0), joinFieldsMeta)); // MORE - not sure if we really need this
  23494. joinFieldsAllocator.setown(createRowAllocator(joinPrefixedMeta));
  23495. }
  23496. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  23497. {
  23498. CRoxieServerKeyedJoinBase::start(parentExtractSize, parentExtract, paused);
  23499. if (rootIndex)
  23500. {
  23501. varFileInfo.setown(rootIndex->getVarFileInfo());
  23502. translators.setown(rootIndex->getTranslators());
  23503. keySet.setown(rootIndex->getKeySet());
  23504. }
  23505. else if (variableIndexFileName)
  23506. {
  23507. OwnedRoxieString indexFileName(helper.getIndexFileName());
  23508. varFileInfo.setown(resolveLFN(indexFileName, (helper.getJoinFlags() & JFindexoptional) != 0));
  23509. if (varFileInfo)
  23510. {
  23511. translators.setown(new TranslatorArray);
  23512. keySet.setown(varFileInfo->getKeyArray(factory->queryActivityMeta(), translators, false, isLocal ? factory->queryQueryFactory().queryChannel() : 0, factory->queryQueryFactory().queryOptions().enableFieldTranslation));
  23513. }
  23514. }
  23515. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().keyedJoinPreload, isSimple, ctx);
  23516. }
  23517. virtual const IResolvedFile *queryVarFileInfo() const
  23518. {
  23519. return varFileInfo;
  23520. }
  23521. virtual void reset()
  23522. {
  23523. CRoxieServerKeyedJoinBase::reset();
  23524. if (varFileInfo)
  23525. {
  23526. keySet.clear();
  23527. varFileInfo.clear();
  23528. }
  23529. }
  23530. virtual void processRow(const void *row)
  23531. {
  23532. // called from front puller thread
  23533. // buffer up an IndexRead request
  23534. if (keySet && helper.leftCanMatch(row))
  23535. {
  23536. RtlDynamicRowBuilder extractBuilder(indexReadAllocator);
  23537. unsigned indexReadRecordSize = helper.extractIndexReadFields(extractBuilder, row);
  23538. OwnedConstRoxieRow extracted;
  23539. if (indexReadRecordSize)
  23540. extracted.setown(extractBuilder.finalizeRowClear(indexReadRecordSize));
  23541. CJoinGroup *jg = createJoinGroup(row);
  23542. for (unsigned partNo = 0; partNo < keySet->length(); partNo++)
  23543. {
  23544. IKeyIndexBase *thisBase = keySet->queryKeyPart(partNo);
  23545. if (thisBase)
  23546. {
  23547. unsigned fileNo = 0;
  23548. IKeyIndex *thisKey = thisBase->queryPart(fileNo);
  23549. tlk->setKey(thisKey);
  23550. tlk->setLayoutTranslator(translators->item(fileNo));
  23551. helper.createSegmentMonitors(tlk, extracted);
  23552. if (rootIndex)
  23553. rootIndex->mergeSegmentMonitors(tlk);
  23554. tlk->finishSegmentMonitors();
  23555. try
  23556. {
  23557. tlk->reset();
  23558. for (;;)
  23559. {
  23560. typedef const void * cvp;
  23561. if (thisKey && thisKey->isTopLevelKey())
  23562. {
  23563. bool locallySorted = (!thisKey->isFullySorted());
  23564. while (locallySorted || tlk->lookup(false))
  23565. {
  23566. unsigned slavePart = locallySorted ? 0 : (unsigned) tlk->queryFpos();
  23567. if (locallySorted || slavePart)
  23568. {
  23569. cvp *outputBuffer = (cvp *) remote.getMem(slavePart, fileNo, indexReadRecordSize + sizeof(cvp) + (indexReadInputRecordVariable ? sizeof(unsigned) : 0));
  23570. *outputBuffer++ = jg;
  23571. if (indexReadInputRecordVariable)
  23572. {
  23573. *(unsigned *) outputBuffer = indexReadRecordSize;
  23574. outputBuffer = (cvp *) (((unsigned *) outputBuffer) + 1);
  23575. }
  23576. jg->notePending();
  23577. memcpy(outputBuffer, extracted, indexReadRecordSize);
  23578. if (locallySorted)
  23579. {
  23580. for (unsigned i = 1; i < numChannels; i++)
  23581. jg->notePending();
  23582. break;
  23583. }
  23584. }
  23585. }
  23586. }
  23587. else
  23588. {
  23589. unsigned accepted = 0;
  23590. unsigned rejected = 0;
  23591. Owned<CRowArrayMessageResult> result;
  23592. if (!isSimple)
  23593. result.setown(new CRowArrayMessageResult(ctx->queryRowManager(), true));
  23594. // MORE - This code seems to be duplicated in keyedJoinHead
  23595. jg->notePending();
  23596. unsigned candidateCount = 0;
  23597. while (tlk->lookup(true))
  23598. {
  23599. candidateCount++;
  23600. atomic_inc(&indexRecordsRead);
  23601. KLBlobProviderAdapter adapter(tlk);
  23602. offset_t recptr;
  23603. const byte *indexRow = tlk->queryKeyBuffer(recptr);
  23604. if (helper.indexReadMatch(extracted, indexRow, recptr, &adapter))
  23605. {
  23606. RtlDynamicRowBuilder rb(joinFieldsAllocator, true);
  23607. CPrefixedRowBuilder pb(KEYEDJOIN_RECORD_SIZE(0), rb);
  23608. accepted++;
  23609. KLBlobProviderAdapter adapter(tlk);
  23610. size32_t joinFieldsSize = helper.extractJoinFields(pb, indexRow, recptr, &adapter);
  23611. KeyedJoinHeader *rec = (KeyedJoinHeader *) rb.getUnfinalizedClear(); // lack of finalize ok as unserialized data here.
  23612. rec->fpos = recptr;
  23613. rec->thisGroup = jg;
  23614. rec->partNo = partNo;
  23615. if (isSimple)
  23616. remote.injected.enqueue(rec);
  23617. else
  23618. result->append(rec);
  23619. }
  23620. else
  23621. {
  23622. rejected++;
  23623. atomic_inc(&postFiltered);
  23624. }
  23625. }
  23626. // output an end marker for the matches to this group
  23627. KeyedJoinHeader *rec = (KeyedJoinHeader *) ctx->queryRowManager().allocate(KEYEDJOIN_RECORD_SIZE(0), activityId);
  23628. rec->fpos = (offset_t) candidateCount;
  23629. rec->thisGroup = jg;
  23630. rec->partNo = (unsigned short) -1;
  23631. if (isSimple)
  23632. remote.injected.enqueue(rec);
  23633. else
  23634. {
  23635. result->append(rec);
  23636. remote.injectResult(result.getClear());
  23637. }
  23638. if (accepted)
  23639. noteStatistic(StNumIndexAccepted, accepted);
  23640. if (rejected)
  23641. noteStatistic(StNumIndexRejected, rejected);
  23642. }
  23643. if (++fileNo < thisBase->numParts())
  23644. {
  23645. thisKey = thisBase->queryPart(fileNo);
  23646. tlk->setKey(thisKey);
  23647. tlk->setLayoutTranslator(translators->item(fileNo));
  23648. tlk->reset();
  23649. }
  23650. else
  23651. break;
  23652. }
  23653. tlk->releaseSegmentMonitors();
  23654. tlk->setKey(NULL);
  23655. }
  23656. catch (...)
  23657. {
  23658. tlk->releaseSegmentMonitors();
  23659. tlk->setKey(NULL);
  23660. throw;
  23661. }
  23662. }
  23663. }
  23664. noteEndReceived(jg, 0);
  23665. }
  23666. else
  23667. {
  23668. noteEndReceived(createJoinGroup(row), 0);
  23669. }
  23670. }
  23671. virtual void processEOG()
  23672. {
  23673. // called from front puller thread
  23674. if (preserveGroups)
  23675. endGroup();
  23676. }
  23677. void processGroup(const ConstPointerArray &)
  23678. {
  23679. throwUnexpected();
  23680. }
  23681. };
  23682. class CRoxieServerKeyedJoinActivityFactory : public CRoxieServerMultiInputFactory
  23683. {
  23684. Owned<const IResolvedFile> indexfile;
  23685. Owned<const IResolvedFile> datafile;
  23686. Owned<IKeyArray> keySet;
  23687. Owned<TranslatorArray> translatorArray;
  23688. Owned<IDefRecordMeta> activityMeta;
  23689. RemoteActivityId headId;
  23690. RemoteActivityId tailId;
  23691. IOutputMetaData *indexReadMeta;
  23692. Owned<IFilePartMap> map;
  23693. Owned<IFileIOArray> files;
  23694. unsigned joinFlags;
  23695. bool isHalfKeyed;
  23696. bool isLocal;
  23697. IRecordLayoutTranslator::Mode enableFieldTranslation;
  23698. bool variableFetchFileName;
  23699. bool variableIndexFileName;
  23700. bool isSimple;
  23701. public:
  23702. CRoxieServerKeyedJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_headId, const RemoteActivityId &_tailId)
  23703. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), headId(_headId), tailId(_tailId)
  23704. {
  23705. Owned<IHThorKeyedJoinArg> helper = (IHThorKeyedJoinArg *) helperFactory();
  23706. isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  23707. isSimple = isLocal;
  23708. rtlDataAttr indexLayoutMeta;
  23709. size32_t indexLayoutSize;
  23710. if(!helper->getIndexLayout(indexLayoutSize, indexLayoutMeta.refdata()))
  23711. assertex(indexLayoutSize== 0);
  23712. MemoryBuffer m;
  23713. m.setBuffer(indexLayoutSize, indexLayoutMeta.getdata());
  23714. activityMeta.setown(deserializeRecordMeta(m, true));
  23715. enableFieldTranslation = queryFactory.queryOptions().enableFieldTranslation;
  23716. translatorArray.setown(new TranslatorArray);
  23717. joinFlags = helper->getJoinFlags();
  23718. variableIndexFileName = allFilesDynamic || _queryFactory.isDynamic() || ((joinFlags & (JFvarindexfilename|JFdynamicindexfilename|JFindexfromactivity)) != 0);
  23719. variableFetchFileName = allFilesDynamic || _queryFactory.isDynamic() || ((helper->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  23720. if (!variableIndexFileName)
  23721. {
  23722. bool isOpt = (joinFlags & JFindexoptional) != 0;
  23723. OwnedRoxieString indexFileName(helper->getIndexFileName());
  23724. indexfile.setown(queryFactory.queryPackage().lookupFileName(indexFileName, isOpt, true, true, queryFactory.queryWorkUnit(), true));
  23725. if (indexfile)
  23726. keySet.setown(indexfile->getKeyArray(activityMeta, translatorArray, isOpt, isLocal ? queryFactory.queryChannel() : 0, enableFieldTranslation));
  23727. }
  23728. if (keySet && keySet->length()==1 && !isSimple)
  23729. {
  23730. IKeyIndexBase *thisBase = keySet->queryKeyPart(0);
  23731. if (thisBase->numParts()==1 && !thisBase->queryPart(0)->isTopLevelKey() && !_queryFactory.queryOptions().disableLocalOptimizations)
  23732. isSimple = true;
  23733. // MORE - if it's a variable filename then it MAY be simple, we don't know. Tough.
  23734. }
  23735. if (!simpleLocalKeyedJoins)
  23736. isSimple = false;
  23737. isHalfKeyed = !helper->diskAccessRequired();
  23738. indexReadMeta = QUERYINTERFACE(helper->queryIndexReadInputRecordSize(), IOutputMetaData);
  23739. if (!isHalfKeyed && !variableFetchFileName)
  23740. {
  23741. bool isFetchOpt = (helper->getFetchFlags() & FFdatafileoptional) != 0;
  23742. datafile.setown(_queryFactory.queryPackage().lookupFileName(queryNodeFileName(_graphNode, _kind), isFetchOpt, true, true, _queryFactory.queryWorkUnit(), true));
  23743. if (datafile)
  23744. {
  23745. if (isLocal)
  23746. files.setown(datafile->getIFileIOArray(isFetchOpt, queryFactory.queryChannel()));
  23747. else
  23748. map.setown(datafile->getFileMap());
  23749. }
  23750. }
  23751. }
  23752. virtual bool getEnableFieldTranslation() const
  23753. {
  23754. return enableFieldTranslation;
  23755. }
  23756. virtual IDefRecordMeta *queryActivityMeta() const
  23757. {
  23758. return activityMeta;
  23759. }
  23760. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  23761. {
  23762. if (isHalfKeyed)
  23763. return new CRoxieServerHalfKeyedJoinActivity(_ctx, this, _probeManager,
  23764. headId, keySet, translatorArray, indexReadMeta, joinFlags, isSimple, isLocal);
  23765. else
  23766. return new CRoxieServerKeyedJoinActivity(_ctx, this, _probeManager,
  23767. headId, keySet, translatorArray, indexReadMeta,
  23768. tailId, map, joinFlags, isLocal);
  23769. }
  23770. virtual const StatisticsMapping &queryStatsMapping() const
  23771. {
  23772. return keyedJoinStatistics;
  23773. }
  23774. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  23775. {
  23776. if (datafile)
  23777. addXrefFileInfo(reply, datafile);
  23778. if (indexfile)
  23779. addXrefFileInfo(reply, indexfile);
  23780. }
  23781. };
  23782. IRoxieServerActivityFactory *createRoxieServerKeyedJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId, const RemoteActivityId &_remoteId2)
  23783. {
  23784. return new CRoxieServerKeyedJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId, _remoteId2);
  23785. }
  23786. //=================================================================================
  23787. class CRoxieServerSoapActivityBase : public CRoxieServerActivity, implements ISoapCallRowProvider, implements IRoxieAbortMonitor
  23788. {
  23789. protected:
  23790. Owned<ISoapCallHelper> soaphelper;
  23791. IHThorSoapActionArg & helper;
  23792. StringBuffer authToken;
  23793. bool eof;
  23794. CriticalSection crit;
  23795. ClientCertificate *pClientCert;
  23796. public:
  23797. IMPLEMENT_IINTERFACE_USING(CRoxieServerActivity)
  23798. CRoxieServerSoapActivityBase(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  23799. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorSoapActionArg &)basehelper)
  23800. {
  23801. eof = false;
  23802. if (clientCert.certificate.length() > 0 && clientCert.privateKey.length() > 0 && clientCert.passphrase.length() > 0)
  23803. pClientCert = &clientCert;
  23804. else
  23805. pClientCert = NULL;
  23806. }
  23807. // ISoapCallRowProvider
  23808. virtual IHThorSoapActionArg * queryActionHelper() { return &helper; };
  23809. virtual IHThorSoapCallArg * queryCallHelper() { return NULL; };
  23810. virtual const void * getNextRow() { return NULL; };
  23811. virtual void releaseRow(const void * r) { ReleaseRoxieRow(r); };
  23812. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  23813. {
  23814. eof = false;
  23815. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  23816. authToken.append(ctx->queryAuthToken());
  23817. }
  23818. virtual void reset()
  23819. {
  23820. // MORE - Shouldn't we make sure thread is stopped etc???
  23821. soaphelper.clear();
  23822. CRoxieServerActivity::reset();
  23823. }
  23824. // IRoxieAbortMonitor
  23825. virtual void checkForAbort() { checkAbort(); }
  23826. };
  23827. //---------------------------------------------------------------------------
  23828. class CRoxieServerSoapRowCallActivity : public CRoxieServerSoapActivityBase
  23829. {
  23830. IHThorSoapCallArg & callHelper;
  23831. public:
  23832. CRoxieServerSoapRowCallActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  23833. : CRoxieServerSoapActivityBase(_ctx, _factory, _probeManager), callHelper((IHThorSoapCallArg &)basehelper)
  23834. {
  23835. }
  23836. virtual IHThorSoapCallArg * queryCallHelper()
  23837. {
  23838. return &callHelper;
  23839. }
  23840. virtual bool needsAllocator() const { return true; }
  23841. virtual const void *nextRow()
  23842. {
  23843. ActivityTimer t(totalCycles, timeActivities);
  23844. if(eof) return NULL;
  23845. if (soaphelper == NULL)
  23846. {
  23847. if (factory->getKind()==TAKhttp_rowdataset)
  23848. soaphelper.setown(createHttpCallHelper(this, rowAllocator, authToken.str(), SCrow, pClientCert, *this, this));
  23849. else
  23850. soaphelper.setown(createSoapCallHelper(this, rowAllocator, authToken.str(), SCrow, pClientCert, *this, this));
  23851. soaphelper->start();
  23852. }
  23853. OwnedConstRoxieRow ret = soaphelper->getRow();
  23854. if (!ret)
  23855. {
  23856. eof = true;
  23857. return NULL;
  23858. }
  23859. ++processed;
  23860. return ret.getClear();
  23861. }
  23862. };
  23863. class CRoxieServerSoapRowCallActivityFactory : public CRoxieServerActivityFactory
  23864. {
  23865. public:
  23866. CRoxieServerSoapRowCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  23867. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  23868. {
  23869. }
  23870. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  23871. {
  23872. return new CRoxieServerSoapRowCallActivity(_ctx, this, _probeManager);
  23873. }
  23874. virtual const StatisticsMapping &queryStatsMapping() const
  23875. {
  23876. return soapStatistics;
  23877. }
  23878. };
  23879. IRoxieServerActivityFactory *createRoxieServerSoapRowCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  23880. {
  23881. return new CRoxieServerSoapRowCallActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  23882. }
  23883. //---------------------------------------------------------------------------
  23884. class CRoxieServerSoapRowActionActivity : public CRoxieServerSoapActivityBase
  23885. {
  23886. public:
  23887. CRoxieServerSoapRowActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  23888. : CRoxieServerSoapActivityBase(_ctx, _factory, _probeManager)
  23889. {}
  23890. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  23891. {
  23892. //MORE: parentExtract not passed to start - although shouldn't be a problem.
  23893. soaphelper.setown(createSoapCallHelper(this, NULL, ctx->queryAuthToken(), SCrow, pClientCert, *this, this));
  23894. soaphelper->start();
  23895. soaphelper->waitUntilDone();
  23896. IException *e = soaphelper->getError();
  23897. soaphelper.clear();
  23898. if (e)
  23899. throw e;
  23900. }
  23901. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  23902. {
  23903. return NULL;
  23904. }
  23905. virtual const void *nextRow()
  23906. {
  23907. throwUnexpected(); // I am nobody's input
  23908. }
  23909. };
  23910. class CRoxieServerSoapRowActionActivityFactory : public CRoxieServerActivityFactory
  23911. {
  23912. bool isRoot;
  23913. public:
  23914. CRoxieServerSoapRowActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  23915. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  23916. {
  23917. }
  23918. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  23919. {
  23920. return new CRoxieServerSoapRowActionActivity(_ctx, this, _probeManager);
  23921. }
  23922. virtual bool isSink() const
  23923. {
  23924. return isRoot;
  23925. }
  23926. virtual const StatisticsMapping &queryStatsMapping() const
  23927. {
  23928. return soapStatistics;
  23929. }
  23930. };
  23931. IRoxieServerActivityFactory *createRoxieServerSoapRowActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  23932. {
  23933. return new CRoxieServerSoapRowActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  23934. }
  23935. //---------------------------------------------------------------------------
  23936. class CRoxieServerSoapDatasetCallActivity : public CRoxieServerSoapActivityBase
  23937. {
  23938. IHThorSoapCallArg & callHelper;
  23939. public:
  23940. CRoxieServerSoapDatasetCallActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  23941. : CRoxieServerSoapActivityBase(_ctx, _factory, _probeManager), callHelper((IHThorSoapCallArg &)basehelper)
  23942. {
  23943. }
  23944. virtual IHThorSoapCallArg * queryCallHelper()
  23945. {
  23946. return &callHelper;
  23947. }
  23948. virtual const void *getNextRow()
  23949. {
  23950. CriticalBlock b(crit); // MORE - why ?
  23951. return inputStream->ungroupedNextRow();
  23952. }
  23953. virtual bool needsAllocator() const { return true; }
  23954. virtual const void *nextRow()
  23955. {
  23956. ActivityTimer t(totalCycles, timeActivities);
  23957. if(eof) return NULL;
  23958. if (soaphelper == NULL)
  23959. {
  23960. soaphelper.setown(createSoapCallHelper(this, rowAllocator, authToken.str(), SCdataset, pClientCert, *this, this));
  23961. soaphelper->start();
  23962. }
  23963. OwnedConstRoxieRow ret = soaphelper->getRow();
  23964. if (!ret)
  23965. {
  23966. eof = true;
  23967. return NULL;
  23968. }
  23969. ++processed;
  23970. return ret.getClear();
  23971. }
  23972. };
  23973. class CRoxieServerSoapDatasetCallActivityFactory : public CRoxieServerActivityFactory
  23974. {
  23975. public:
  23976. CRoxieServerSoapDatasetCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  23977. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  23978. {
  23979. }
  23980. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  23981. {
  23982. return new CRoxieServerSoapDatasetCallActivity(_ctx, this, _probeManager);
  23983. }
  23984. virtual const StatisticsMapping &queryStatsMapping() const
  23985. {
  23986. return soapStatistics;
  23987. }
  23988. };
  23989. IRoxieServerActivityFactory *createRoxieServerSoapDatasetCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  23990. {
  23991. return new CRoxieServerSoapDatasetCallActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  23992. }
  23993. //---------------------------------------------------------------------------
  23994. class CRoxieServerSoapDatasetActionActivity : public CRoxieServerSoapActivityBase
  23995. {
  23996. public:
  23997. CRoxieServerSoapDatasetActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  23998. : CRoxieServerSoapActivityBase(_ctx, _factory, _probeManager)
  23999. {}
  24000. virtual const void *getNextRow()
  24001. {
  24002. CriticalBlock b(crit); // MORE - Why?
  24003. const void *nextrec = inputStream->ungroupedNextRow();
  24004. if (nextrec)
  24005. processed++;
  24006. return nextrec;
  24007. }
  24008. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  24009. {
  24010. try
  24011. {
  24012. start(parentExtractSize, parentExtract, false);
  24013. soaphelper.setown(createSoapCallHelper(this, NULL, ctx->queryAuthToken(), SCdataset, pClientCert, *this, this));
  24014. soaphelper->start();
  24015. soaphelper->waitUntilDone();
  24016. IException *e = soaphelper->getError();
  24017. soaphelper.clear();
  24018. if (e)
  24019. throw e;
  24020. stop();
  24021. }
  24022. catch (IException *E)
  24023. {
  24024. ctx->notifyAbort(E);
  24025. abort();
  24026. throw;
  24027. }
  24028. catch(...)
  24029. {
  24030. Owned<IException> E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught at %s:%d", sanitizeSourceFile(__FILE__), __LINE__);
  24031. ctx->notifyAbort(E);
  24032. abort();
  24033. throw;
  24034. }
  24035. }
  24036. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  24037. {
  24038. return NULL;
  24039. }
  24040. virtual const void *nextRow()
  24041. {
  24042. throwUnexpected(); // I am nobody's input
  24043. }
  24044. };
  24045. class CRoxieServerSoapDatasetActionActivityFactory : public CRoxieServerActivityFactory
  24046. {
  24047. bool isRoot;
  24048. public:
  24049. CRoxieServerSoapDatasetActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  24050. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  24051. {
  24052. }
  24053. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  24054. {
  24055. return new CRoxieServerSoapDatasetActionActivity(_ctx, this, _probeManager);
  24056. }
  24057. virtual bool isSink() const
  24058. {
  24059. return isRoot;
  24060. }
  24061. virtual const StatisticsMapping &queryStatsMapping() const
  24062. {
  24063. return soapStatistics;
  24064. }
  24065. };
  24066. IRoxieServerActivityFactory *createRoxieServerSoapDatasetActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  24067. {
  24068. return new CRoxieServerSoapDatasetActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  24069. }
  24070. //=====================================================================================================
  24071. class CGraphResults : implements IRoxieGraphResults, public CInterface
  24072. {
  24073. IArrayOf<IGraphResult> results;
  24074. CriticalSection cs;
  24075. IGraphResult & select(unsigned idx)
  24076. {
  24077. CriticalBlock procedure(cs);
  24078. if (idx >= results.ordinality())
  24079. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Error reading graph result %d before it is calculated", idx);
  24080. return results.item(idx);
  24081. }
  24082. public:
  24083. IMPLEMENT_IINTERFACE
  24084. void clear()
  24085. {
  24086. CriticalBlock procedure(cs);
  24087. results.kill();
  24088. }
  24089. virtual IEngineRowStream * createIterator(unsigned id)
  24090. {
  24091. return select(id).createIterator();
  24092. }
  24093. virtual void getLinkedResult(unsigned & count, byte * * & ret, unsigned id)
  24094. {
  24095. select(id).getLinkedResult(count, ret);
  24096. }
  24097. virtual void getDictionaryResult(unsigned & count, byte * * & ret, unsigned id)
  24098. {
  24099. select(id).getLinkedResult(count, ret);
  24100. }
  24101. virtual const void * getLinkedRowResult(unsigned id)
  24102. {
  24103. return select(id).getLinkedRowResult();
  24104. }
  24105. void setResult(unsigned id, IGraphResult * result)
  24106. {
  24107. CriticalBlock procedure(cs);
  24108. if (results.ordinality() <= id)
  24109. {
  24110. while (results.ordinality() < id)
  24111. results.append(*new CGraphResult);
  24112. results.append(*LINK(result));
  24113. }
  24114. else
  24115. results.replace(*LINK(result), id);
  24116. }
  24117. void appendResult(IGraphResult * result)
  24118. {
  24119. CriticalBlock procedure(cs);
  24120. results.append(*LINK(result));
  24121. }
  24122. };
  24123. //===================================================================================================================
  24124. class CPseudoArg : implements IHThorArg, public CInterface
  24125. {
  24126. public:
  24127. IMPLEMENT_IINTERFACE
  24128. virtual IOutputMetaData * queryOutputMeta() { return NULL; }
  24129. };
  24130. class CPseudoActivity : public CRoxieServerActivity
  24131. {
  24132. public:
  24133. CPseudoActivity(IRoxieSlaveContext *_ctx, IHThorArg & _helper) : CRoxieServerActivity(_ctx, _helper) {}
  24134. virtual const void *nextRow()
  24135. {
  24136. throwUnexpected(); // I am nobody's input
  24137. }
  24138. };
  24139. class CActivityGraph : implements IActivityGraph, implements IThorChildGraph, implements ILocalGraphEx, implements IRoxieServerChildGraph, public CInterface
  24140. {
  24141. protected:
  24142. class ActivityGraphSlaveContext : public IndirectSlaveContext
  24143. {
  24144. SpinLock abortLock;
  24145. bool aborted;
  24146. Owned<IException> exception;
  24147. public:
  24148. ActivityGraphSlaveContext(IRoxieSlaveContext *_ctx, const IRoxieContextLogger &_logctx) : IndirectSlaveContext(_ctx), logctx(_logctx), loopCounter(0), codeContext(NULL)
  24149. {
  24150. aborted = false;
  24151. }
  24152. // Note - we must track exceptions at the child level in case there is a CATCH in parent
  24153. virtual void notifyAbort(IException *E)
  24154. {
  24155. SpinBlock b(abortLock);
  24156. if (!aborted && QUERYINTERFACE(E, InterruptedSemaphoreException) == NULL)
  24157. {
  24158. aborted = true;
  24159. exception.set(E);
  24160. }
  24161. }
  24162. virtual void checkAbort()
  24163. {
  24164. if (aborted) // NOTE - don't bother getting lock before reading this (for speed) - a false read is very unlikely and not a problem
  24165. {
  24166. SpinBlock b(abortLock);
  24167. if (!exception)
  24168. exception.setown(MakeStringException(ROXIE_INTERNAL_ERROR, "Query was aborted"));
  24169. throw exception.getLink();
  24170. }
  24171. IndirectSlaveContext::checkAbort();
  24172. }
  24173. virtual ICodeContext *queryCodeContext()
  24174. {
  24175. return codeContext;
  24176. }
  24177. void setCodeContext(ICodeContext * _codeContext)
  24178. {
  24179. codeContext = _codeContext;
  24180. }
  24181. void setLoopCounter(unsigned _loopCounter)
  24182. {
  24183. loopCounter = _loopCounter;
  24184. }
  24185. virtual void noteChildGraph(unsigned id, IActivityGraph *childGraph)
  24186. {
  24187. childGraphs.setValue(id, childGraph);
  24188. }
  24189. virtual IActivityGraph * queryChildGraph(unsigned id)
  24190. {
  24191. if (queryTraceLevel() > 10)
  24192. CTXLOG("resolveChildGraph %d", id);
  24193. IActivityGraph *childGraph = childGraphs.getValue(id);
  24194. assertex(childGraph);
  24195. return childGraph;
  24196. }
  24197. // 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
  24198. virtual StringBuffer &getLogPrefix(StringBuffer &ret) const
  24199. {
  24200. logctx.getLogPrefix(ret);
  24201. if (loopCounter)
  24202. ret.appendf("{%u}", loopCounter);
  24203. return ret;
  24204. }
  24205. protected:
  24206. const IRoxieContextLogger &logctx;
  24207. unsigned loopCounter;
  24208. ICodeContext * codeContext;
  24209. MapXToMyClass<unsigned, unsigned, IActivityGraph> childGraphs;
  24210. } graphSlaveContext;
  24211. class ActivityGraphCodeContext : public IndirectCodeContext
  24212. {
  24213. public:
  24214. virtual IEclGraphResults * resolveLocalQuery(__int64 activityId)
  24215. {
  24216. if ((unsigned) activityId == container->queryId())
  24217. return container;
  24218. IActivityGraph * match = slaveContext->queryChildGraph((unsigned) activityId);
  24219. if (match)
  24220. return match->queryLocalGraph();
  24221. return IndirectCodeContext::resolveLocalQuery(activityId);
  24222. }
  24223. virtual IThorChildGraph * resolveChildQuery(__int64 activityId, IHThorArg * colocal)
  24224. {
  24225. IActivityGraph * match = slaveContext->queryChildGraph((unsigned) activityId);
  24226. return LINK(match->queryChildGraph());
  24227. }
  24228. virtual unsigned getGraphLoopCounter() const
  24229. {
  24230. return container->queryLoopCounter(); // only called if value is valid
  24231. }
  24232. void setContainer(IRoxieSlaveContext * _slaveContext, CActivityGraph * _container)
  24233. {
  24234. slaveContext = _slaveContext;
  24235. container = _container;
  24236. }
  24237. protected:
  24238. IRoxieSlaveContext * slaveContext;
  24239. CActivityGraph * container;
  24240. } graphCodeContext;
  24241. // NOTE - destructor order is significant - need to destroy graphCodeContext and graphSlaveContext last
  24242. IArrayOf<IRoxieServerActivity> activities;
  24243. IArrayOf<IRoxieProbe> probes;
  24244. IRoxieServerActivityCopyArray sinks;
  24245. StringAttr graphName;
  24246. Owned<CGraphResults> results;
  24247. CGraphResults graphLoopResults;
  24248. const ActivityArray & graphDefinition;
  24249. CriticalSection evaluateCrit;
  24250. IProbeManager *probeManager;
  24251. unsigned id;
  24252. unsigned loopCounter;
  24253. public:
  24254. IMPLEMENT_IINTERFACE;
  24255. CActivityGraph(IRoxieSlaveContext *_ctx, const char *_graphName, unsigned _id, const ActivityArray &x, IProbeManager *_probeManager, const IRoxieContextLogger &_logctx)
  24256. : probeManager(_probeManager), graphDefinition(x), graphName(_graphName), graphSlaveContext(_ctx, _logctx)
  24257. {
  24258. id = x.getLibraryGraphId();
  24259. if (!id)
  24260. id = _id;
  24261. loopCounter = 0;
  24262. graphSlaveContext.setCodeContext(&graphCodeContext);
  24263. graphCodeContext.setContainer(&graphSlaveContext, this);
  24264. }
  24265. ~CActivityGraph()
  24266. {
  24267. if (probeManager)
  24268. probeManager->deleteGraph((IArrayOf<IActivityBase>*)&activities, (IArrayOf<IInputBase>*)&probes);
  24269. }
  24270. virtual const char *queryName() const
  24271. {
  24272. return graphName.get();
  24273. }
  24274. void createGraph(IRoxieSlaveContext *_ctx)
  24275. {
  24276. if (graphDefinition.isMultiInstance())
  24277. {
  24278. graphCodeContext.set(_ctx->queryCodeContext());
  24279. _ctx = &graphSlaveContext;
  24280. }
  24281. ForEachItemIn(idx, graphDefinition)
  24282. {
  24283. IRoxieServerActivityFactory &donor = graphDefinition.serverItem(idx);
  24284. IRoxieServerActivity &activity = *donor.createActivity(_ctx, probeManager);
  24285. activities.append(activity);
  24286. if (donor.isSink())
  24287. {
  24288. sinks.append(activity);
  24289. if (probeManager)
  24290. probeManager->noteSink(&activity);
  24291. }
  24292. }
  24293. ForEachItemIn(idx1, graphDefinition)
  24294. {
  24295. IRoxieServerActivityFactory &donor = graphDefinition.serverItem(idx1);
  24296. IRoxieServerActivity &activity = activities.item(idx1);
  24297. unsigned inputidx = 0;
  24298. for (;;)
  24299. {
  24300. unsigned outputidx;
  24301. unsigned source = donor.getInput(inputidx, outputidx);
  24302. if (source==(unsigned) -1)
  24303. break;
  24304. connectInput(idx1, inputidx, source, outputidx, 0);
  24305. inputidx++;
  24306. }
  24307. IntArray &dependencies = donor.queryDependencies();
  24308. IntArray &dependencyIndexes = donor.queryDependencyIndexes();
  24309. IntArray &dependencyControlIds = donor.queryDependencyControlIds();
  24310. StringArray &dependencyEdgeIds = donor.queryDependencyEdgeIds();
  24311. ForEachItemIn(idx2, dependencies)
  24312. {
  24313. IRoxieServerActivity &dependencySourceActivity = activities.item(dependencies.item(idx2));
  24314. unsigned dependencySourceIndex = dependencyIndexes.item(idx2);
  24315. unsigned dependencyControlId = dependencyControlIds.item(idx2);
  24316. activity.addDependency(dependencySourceActivity, dependencySourceIndex, dependencyControlId);
  24317. if (probeManager)
  24318. probeManager->noteDependency( &dependencySourceActivity, dependencySourceIndex, dependencyControlId, dependencyEdgeIds.item(idx2), &activity);
  24319. }
  24320. }
  24321. ForEachItemIn(idx2, sinks)
  24322. {
  24323. IRoxieServerActivity &sink = sinks.item(idx2);
  24324. sink.connectInputStreams(true);
  24325. }
  24326. }
  24327. void connectInput(unsigned target, unsigned targetIdx, unsigned source, unsigned sourceIdx, unsigned iteration)
  24328. {
  24329. IRoxieServerActivity &targetActivity = activities.item(target);
  24330. IRoxieServerActivity &sourceActivity = activities.item(source);
  24331. IFinalRoxieInput * output = sourceActivity.queryOutput(sourceIdx);
  24332. if (probeManager)
  24333. {
  24334. IRoxieProbe * inputProbe = probeManager->createProbe(static_cast<IInputBase*>(output), &sourceActivity, &targetActivity, sourceIdx, targetIdx, iteration);
  24335. probes.append(*LINK(inputProbe));
  24336. output = &dynamic_cast<IFinalRoxieInput &>(inputProbe->queryInput());
  24337. }
  24338. targetActivity.setInput(targetIdx, sourceIdx, output);
  24339. }
  24340. virtual void onCreate(IHThorArg *_colocalParent)
  24341. {
  24342. ForEachItemIn(idx, activities)
  24343. {
  24344. IRoxieServerActivity *activity = &activities.item(idx);
  24345. if (activity)
  24346. activity->onCreate(_colocalParent);
  24347. }
  24348. }
  24349. virtual void abort()
  24350. {
  24351. ForEachItemIn(idx, sinks)
  24352. {
  24353. IRoxieServerActivity &sink = sinks.item(idx);
  24354. sink.abort();
  24355. }
  24356. }
  24357. virtual void reset()
  24358. {
  24359. ForEachItemIn(idx, sinks)
  24360. {
  24361. IRoxieServerActivity &sink = sinks.item(idx);
  24362. sink.reset();
  24363. }
  24364. }
  24365. Linked<IException> exception;
  24366. CriticalSection eCrit;
  24367. virtual void noteException(IException *E)
  24368. {
  24369. CriticalBlock b(eCrit);
  24370. if (!exception)
  24371. {
  24372. if (graphSlaveContext.queryDebugContext())
  24373. {
  24374. graphSlaveContext.queryDebugContext()->checkBreakpoint(DebugStateException, NULL, exception);
  24375. }
  24376. exception.set(E);
  24377. }
  24378. }
  24379. virtual void checkAbort()
  24380. {
  24381. CriticalBlock b(eCrit);
  24382. if (exception)
  24383. throw exception.getLink();
  24384. }
  24385. virtual void execute()
  24386. {
  24387. results.setown(new CGraphResults);
  24388. doExecute(0, NULL);
  24389. }
  24390. //New child query code...
  24391. virtual IThorChildGraph * queryChildGraph()
  24392. {
  24393. return this;
  24394. }
  24395. virtual IEclGraphResults * queryLocalGraph()
  24396. {
  24397. return this;
  24398. }
  24399. virtual IRoxieServerChildGraph * queryLoopGraph()
  24400. {
  24401. return this;
  24402. }
  24403. inline unsigned queryId() const
  24404. {
  24405. return id;
  24406. }
  24407. inline unsigned queryLoopCounter() const
  24408. {
  24409. return loopCounter;
  24410. }
  24411. void doExecute(unsigned parentExtractSize, const byte * parentExtract)
  24412. {
  24413. if (sinks.ordinality()==1)
  24414. sinks.item(0).execute(parentExtractSize, parentExtract);
  24415. #ifdef PARALLEL_EXECUTE
  24416. else if (!probeManager && !graphDefinition.isSequential())
  24417. {
  24418. class casyncfor: public CAsyncFor
  24419. {
  24420. public:
  24421. IActivityGraph &parent;
  24422. unsigned parentExtractSize;
  24423. const byte * parentExtract;
  24424. casyncfor(IRoxieServerActivityCopyArray &_sinks, IActivityGraph &_parent, unsigned _parentExtractSize, const byte * _parentExtract) :
  24425. sinks(_sinks), parent(_parent), parentExtractSize(_parentExtractSize), parentExtract(_parentExtract) { }
  24426. void Do(unsigned i)
  24427. {
  24428. try
  24429. {
  24430. sinks.item(i).execute(parentExtractSize, parentExtract);
  24431. }
  24432. catch (IException *E)
  24433. {
  24434. parent.noteException(E);
  24435. throw;
  24436. }
  24437. }
  24438. private:
  24439. IRoxieServerActivityCopyArray &sinks;
  24440. } afor(sinks, *this, parentExtractSize, parentExtract);
  24441. afor.For(sinks.ordinality(), sinks.ordinality());
  24442. }
  24443. #endif
  24444. else
  24445. {
  24446. ForEachItemIn(idx, sinks)
  24447. {
  24448. IRoxieServerActivity &sink = sinks.item(idx);
  24449. sink.execute(parentExtractSize, parentExtract);
  24450. }
  24451. }
  24452. }
  24453. virtual IEclGraphResults *evaluate(unsigned parentExtractSize, const byte * parentExtract)
  24454. {
  24455. CriticalBlock block(evaluateCrit);
  24456. results.setown(new CGraphResults);
  24457. try
  24458. {
  24459. doExecute(parentExtractSize, parentExtract);
  24460. }
  24461. catch (...)
  24462. {
  24463. DBGLOG("Exception thrown in child query - cleaning up");
  24464. reset();
  24465. throw;
  24466. }
  24467. reset();
  24468. return results.getClear();
  24469. }
  24470. //interface IRoxieServerChildGraph
  24471. virtual void beforeExecute()
  24472. {
  24473. results.setown(new CGraphResults);
  24474. }
  24475. virtual IFinalRoxieInput * startOutput(unsigned id, unsigned parentExtractSize, const byte *parentExtract, bool paused)
  24476. {
  24477. IFinalRoxieInput * ret = selectOutput(id);
  24478. ret->start(parentExtractSize, parentExtract, paused);
  24479. return ret;
  24480. }
  24481. virtual IFinalRoxieInput * selectOutput(unsigned id)
  24482. {
  24483. ForEachItemIn(i, sinks)
  24484. {
  24485. IFinalRoxieInput * ret = sinks.item(i).querySelectOutput(id);
  24486. if (ret)
  24487. return ret;
  24488. }
  24489. throwUnexpected();
  24490. return NULL;
  24491. }
  24492. virtual void setInputResult(unsigned id, IGraphResult * result)
  24493. {
  24494. results->setResult(id, result);
  24495. }
  24496. virtual bool querySetInputResult(unsigned id, unsigned _sourceIdx, IFinalRoxieInput * input)
  24497. {
  24498. ForEachItemIn(i, activities)
  24499. {
  24500. if (activities.item(i).querySetStreamInput(id, _sourceIdx, input))
  24501. return true;
  24502. }
  24503. return false;
  24504. }
  24505. virtual void stopUnusedOutputs()
  24506. {
  24507. //Hmm not sure how to do this...
  24508. }
  24509. virtual void afterExecute()
  24510. {
  24511. ForEachItemIn(i, sinks)
  24512. {
  24513. sinks.item(i).stop();
  24514. }
  24515. if (graphSlaveContext.queryDebugContext())
  24516. {
  24517. graphSlaveContext.queryDebugContext()->checkBreakpoint(DebugStateGraphFinished, NULL, NULL);
  24518. }
  24519. reset();
  24520. }
  24521. virtual IRoxieGraphResults * execute(size32_t parentExtractSize, const byte *parentExtract)
  24522. {
  24523. doExecute(parentExtractSize, parentExtract);
  24524. return LINK(results);
  24525. }
  24526. virtual void getLinkedResult(unsigned & count, byte * * & ret, unsigned id)
  24527. {
  24528. results->getLinkedResult(count, ret, id);
  24529. }
  24530. virtual void getDictionaryResult(unsigned & count, byte * * & ret, unsigned id)
  24531. {
  24532. results->getLinkedResult(count, ret, id);
  24533. }
  24534. virtual const void * getLinkedRowResult(unsigned id)
  24535. {
  24536. return results->getLinkedRowResult(id);
  24537. }
  24538. virtual void setResult(unsigned id, IGraphResult * result)
  24539. {
  24540. results->setResult(id, result);
  24541. }
  24542. virtual IEngineRowStream * createResultIterator(unsigned id)
  24543. {
  24544. return results->createIterator(id);
  24545. }
  24546. virtual void setGraphLoopResult(IGraphResult * result)
  24547. {
  24548. graphLoopResults.appendResult(result);
  24549. }
  24550. virtual IEngineRowStream * createGraphLoopResultIterator(unsigned id)
  24551. {
  24552. try
  24553. {
  24554. return graphLoopResults.createIterator(id);
  24555. }
  24556. catch (IException * e)
  24557. {
  24558. e->Release();
  24559. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Error reading graph result %d before it is calculated", id);
  24560. }
  24561. }
  24562. virtual void clearGraphLoopResults()
  24563. {
  24564. graphLoopResults.clear();
  24565. }
  24566. virtual void executeGraphLoop(size32_t parentExtractSize, const byte *parentExtract)
  24567. {
  24568. doExecute(parentExtractSize, parentExtract);
  24569. }
  24570. virtual void setGraphLoopResult(unsigned id, IGraphResult * result)
  24571. {
  24572. graphLoopResults.setResult(id, result);
  24573. }
  24574. virtual IEngineRowStream * getGraphLoopResult(unsigned id)
  24575. {
  24576. return graphLoopResults.createIterator(id);
  24577. }
  24578. virtual void getProbeResponse(IPropertyTree *query)
  24579. {
  24580. if (probeManager)
  24581. probeManager->getProbeResponse(query);
  24582. }
  24583. virtual IRoxieServerChildGraph * createGraphLoopInstance(IRoxieSlaveContext *ctx, unsigned loopCounter, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &logctx)
  24584. {
  24585. throwUnexpected();
  24586. }
  24587. virtual CGraphIterationInfo *selectGraphLoopOutput()
  24588. {
  24589. return NULL;
  24590. }
  24591. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor)
  24592. {
  24593. throwUnexpected();
  24594. }
  24595. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor)
  24596. {
  24597. throwUnexpected();
  24598. }
  24599. };
  24600. class CProxyActivityGraph : implements IActivityGraph, implements IThorChildGraph, public CInterface
  24601. {
  24602. public:
  24603. IMPLEMENT_IINTERFACE;
  24604. CProxyActivityGraph(IRoxieSlaveContext *_ctx, const char *_graphName, unsigned _id, ActivityArray &_graphDefinition, const IRoxieContextLogger &_logctx, unsigned _numParallel)
  24605. : ctx(_ctx), graphName(_graphName), id(_id), graphDefinition(_graphDefinition), logctx(_logctx), numParallel(_numParallel)
  24606. {
  24607. }
  24608. virtual void abort() { throwUnexpected(); }
  24609. virtual void reset() { throwUnexpected(); }
  24610. virtual void execute() { throwUnexpected(); }
  24611. virtual void getProbeResponse(IPropertyTree *query) { throwUnexpected(); }
  24612. virtual void onCreate(IHThorArg *_colocalArg)
  24613. {
  24614. colocalArg = _colocalArg;
  24615. }
  24616. virtual void noteException(IException *E) { throwUnexpected(); }
  24617. virtual void checkAbort() { throwUnexpected(); }
  24618. virtual IThorChildGraph * queryChildGraph() { return this; }
  24619. virtual IEclGraphResults * queryLocalGraph() { throwUnexpected(); }
  24620. virtual IRoxieServerChildGraph * queryLoopGraph() { throwUnexpected(); }
  24621. virtual IRoxieServerChildGraph * createGraphLoopInstance(IRoxieSlaveContext *ctx, unsigned loopCounter, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &logctx) { throwUnexpected(); }
  24622. virtual const char *queryName() const { throwUnexpected(); }
  24623. virtual IRoxieServerActivity *queryActivity(unsigned _activityId) { return nullptr; } // MORE - may need something here!?
  24624. virtual IEclGraphResults * evaluate(unsigned parentExtractSize, const byte * parentExtract)
  24625. {
  24626. Owned<CActivityGraph> realGraph;
  24627. {
  24628. CriticalBlock b(graphCrit);
  24629. if (stack.length())
  24630. realGraph.setown(&stack.popGet());
  24631. }
  24632. if (!realGraph)
  24633. {
  24634. realGraph.setown(new CActivityGraph(ctx, graphName, id, graphDefinition, NULL, logctx));
  24635. realGraph->createGraph(ctx);
  24636. realGraph->onCreate(colocalArg);
  24637. }
  24638. Owned<IEclGraphResults> results = realGraph->evaluate(parentExtractSize, parentExtract);
  24639. {
  24640. CriticalBlock b(graphCrit);
  24641. stack.append(*realGraph.getClear());
  24642. }
  24643. return results.getClear();
  24644. }
  24645. protected:
  24646. IRoxieSlaveContext *ctx;
  24647. StringAttr graphName;
  24648. unsigned id;
  24649. ActivityArray &graphDefinition;
  24650. const IRoxieContextLogger &logctx;
  24651. unsigned numParallel;
  24652. IHThorArg *colocalArg = nullptr;
  24653. CriticalSection graphCrit;
  24654. CIArrayOf<CActivityGraph> stack;
  24655. };
  24656. class CIterationActivityGraph : public CActivityGraph
  24657. {
  24658. IHThorArg * colocalParent;
  24659. unsigned fixedParentExtractSize;
  24660. const byte * fixedParentExtract;
  24661. unsigned graphOutputActivityIndex;
  24662. public:
  24663. CIterationActivityGraph(const char *_graphName, unsigned _id, ActivityArray &x, IProbeManager *_probeManager,
  24664. unsigned _loopCounter, IRoxieSlaveContext *_ctx, IHThorArg * _colocalParent, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &_logctx)
  24665. : CActivityGraph(_ctx, _graphName, _id, x, _probeManager, _logctx)
  24666. {
  24667. graphOutputActivityIndex = 0;
  24668. loopCounter = _loopCounter;
  24669. colocalParent = _colocalParent;
  24670. graphSlaveContext.setLoopCounter(loopCounter);
  24671. graphCodeContext.set(_ctx->queryCodeContext());
  24672. fixedParentExtractSize = parentExtractSize;
  24673. fixedParentExtract = parentExtract;
  24674. }
  24675. void createIterationGraph(IRoxieSlaveContext *_ctx)
  24676. {
  24677. Owned<IRoxieServerActivity> pseudoActivity = new CPseudoActivity(_ctx, *new CPseudoArg);
  24678. ForEachItemIn(idx1, graphDefinition)
  24679. activities.append(*LINK(pseudoActivity));
  24680. graphOutputActivityIndex = queryGraphOutputIndex();
  24681. recursiveCreateGraph(_ctx, graphOutputActivityIndex);
  24682. }
  24683. unsigned queryGraphOutputIndex() const
  24684. {
  24685. ForEachItemIn(i, graphDefinition)
  24686. if (graphDefinition.serverItem(i).getKind() == TAKgraphloopresultwrite)
  24687. return i;
  24688. throwUnexpected();
  24689. }
  24690. void recursiveCreateGraph(IRoxieSlaveContext *_ctx, unsigned whichActivity)
  24691. {
  24692. //Check to see if already created
  24693. IRoxieServerActivity & prevActivity = activities.item(whichActivity);
  24694. if (prevActivity.queryId() != 0)
  24695. {
  24696. prevActivity.noteOutputUsed(); //We need to patch up the number of outputs for splitters.
  24697. return;
  24698. }
  24699. IRoxieServerActivityFactory &donor = graphDefinition.serverItem(whichActivity);
  24700. IRoxieServerActivity * activity = NULL;
  24701. if (donor.isGraphInvariant())
  24702. {
  24703. ThorActivityKind kind = donor.getKind();
  24704. switch (kind)
  24705. {
  24706. case TAKif:
  24707. case TAKchildif:
  24708. case TAKcase:
  24709. case TAKchildcase: // MORE RKC->GH - what about FILTER with a graph-invariant condition and other latestart activities?
  24710. {
  24711. Owned<IHThorArg> helper = &donor.getHelper();
  24712. helper->onCreate(&graphCodeContext, colocalParent, NULL);
  24713. helper->onStart(fixedParentExtract, NULL);
  24714. unsigned branch;
  24715. switch (kind)
  24716. {
  24717. case TAKif: case TAKchildif:
  24718. branch = static_cast<IHThorIfArg *>(helper.get())->getCondition() ? 0 : 1;
  24719. break;
  24720. case TAKcase: case TAKchildcase:
  24721. branch = static_cast<IHThorCaseArg *>(helper.get())->getBranch();
  24722. if (branch >= donor.numInputs())
  24723. branch = donor.numInputs() - 1;
  24724. break;
  24725. default:
  24726. throwUnexpected();
  24727. }
  24728. helper.clear();
  24729. unsigned outputidx;
  24730. unsigned source = donor.getInput(branch, outputidx);
  24731. if (source ==(unsigned) -1)
  24732. activity = createRoxieServerNullActivity(&graphSlaveContext, &donor, probeManager);
  24733. else
  24734. activity = createRoxieServerPassThroughActivity(&graphSlaveContext, &donor, probeManager);
  24735. activities.replace(*activity, whichActivity);
  24736. activity->onCreate(colocalParent);
  24737. if (source ==(unsigned) -1)
  24738. return;
  24739. recursiveCreateGraph(_ctx, source);
  24740. connectInput(whichActivity, 0, source, outputidx, loopCounter);
  24741. break;
  24742. }
  24743. }
  24744. }
  24745. if (!activity)
  24746. {
  24747. activity = donor.createActivity(&graphSlaveContext, probeManager);
  24748. activities.replace(*activity, whichActivity);
  24749. activity->onCreate(colocalParent);
  24750. activity->resetOutputsUsed();
  24751. unsigned inputidx = 0;
  24752. for (;;)
  24753. {
  24754. unsigned outputidx;
  24755. unsigned source = donor.getInput(inputidx, outputidx);
  24756. if (source==(unsigned) -1)
  24757. break;
  24758. recursiveCreateGraph(_ctx, source);
  24759. connectInput(whichActivity, inputidx, source, outputidx, loopCounter);
  24760. inputidx++;
  24761. }
  24762. }
  24763. IntArray &dependencies = donor.queryDependencies();
  24764. IntArray &dependencyIndexes = donor.queryDependencyIndexes();
  24765. IntArray &dependencyControlIds = donor.queryDependencyControlIds();
  24766. ForEachItemIn(idx2, dependencies)
  24767. {
  24768. unsigned input = dependencies.item(idx2);
  24769. recursiveCreateGraph(_ctx, input);
  24770. activity->addDependency(activities.item(input),dependencyIndexes.item(idx2),dependencyControlIds.item(idx2));
  24771. }
  24772. }
  24773. virtual CGraphIterationInfo *selectGraphLoopOutput()
  24774. {
  24775. IRoxieServerActivity &sourceActivity = activities.item(graphOutputActivityIndex);
  24776. IFinalRoxieInput *sourceInput = sourceActivity.queryOutput(0);
  24777. return new CGraphIterationInfo(&sourceActivity, sourceInput, 0, loopCounter);
  24778. }
  24779. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor)
  24780. {
  24781. ForEachItemIn(i, activities)
  24782. activities.item(i).gatherIterationUsage(processor, fixedParentExtractSize, fixedParentExtract);
  24783. }
  24784. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor)
  24785. {
  24786. ForEachItemIn(i, activities)
  24787. activities.item(i).associateIterationOutputs(processor, fixedParentExtractSize, fixedParentExtract, probeManager, probes);
  24788. }
  24789. };
  24790. class CDelayedActivityGraph : implements IActivityGraph, public CInterface
  24791. {
  24792. StringAttr graphName;
  24793. ActivityArray & graphDefinition;
  24794. IProbeManager *probeManager;
  24795. unsigned id;
  24796. IRoxieSlaveContext * ctx;
  24797. IHThorArg * colocalParent;
  24798. public:
  24799. IMPLEMENT_IINTERFACE;
  24800. CDelayedActivityGraph(const char *_graphName, unsigned _id, ActivityArray &x, IProbeManager *_probeManager)
  24801. : probeManager(_probeManager), graphDefinition(x)
  24802. {
  24803. graphName.set(_graphName);
  24804. id = _id;
  24805. ctx = NULL;
  24806. colocalParent = NULL;
  24807. }
  24808. virtual const char *queryName() const { return graphName.get(); }
  24809. virtual void abort() { throwUnexpected(); }
  24810. virtual void reset() { }
  24811. virtual void execute() { throwUnexpected(); }
  24812. virtual void getProbeResponse(IPropertyTree *query) { throwUnexpected(); }
  24813. virtual void noteException(IException *E) { throwUnexpected(); }
  24814. virtual void checkAbort() { throwUnexpected(); }
  24815. virtual IThorChildGraph * queryChildGraph() { throwUnexpected(); }
  24816. virtual IEclGraphResults * queryLocalGraph() { throwUnexpected(); }
  24817. virtual IRoxieServerChildGraph * queryLoopGraph() { throwUnexpected(); }
  24818. virtual IRoxieServerActivity *queryActivity(unsigned _activityId) { return nullptr; } // MORE - may need something here!?
  24819. virtual void onCreate(IHThorArg *_colocalParent)
  24820. {
  24821. colocalParent = _colocalParent;
  24822. }
  24823. virtual IRoxieServerChildGraph * createGraphLoopInstance(IRoxieSlaveContext *ctx, unsigned loopCounter, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &logctx)
  24824. {
  24825. Owned<CIterationActivityGraph> ret = new CIterationActivityGraph(graphName, id, graphDefinition, probeManager, loopCounter, ctx, colocalParent, parentExtractSize, parentExtract, logctx);
  24826. ret->createIterationGraph(ctx);
  24827. return ret.getClear();
  24828. }
  24829. };
  24830. IActivityGraph *createActivityGraph(IRoxieSlaveContext *ctx, const char *_graphName, unsigned id, ActivityArray &childFactories, IRoxieServerActivity *parentActivity, IProbeManager *_probeManager, const IRoxieContextLogger &_logctx, unsigned numParallel)
  24831. {
  24832. if (childFactories.isDelayed())
  24833. {
  24834. assertex(numParallel==1);
  24835. return new CDelayedActivityGraph(_graphName, id, childFactories, _probeManager);
  24836. }
  24837. else
  24838. {
  24839. if (numParallel==1 || _probeManager != nullptr)
  24840. {
  24841. Owned<IProbeManager> childProbe;
  24842. if (_probeManager)
  24843. childProbe.setown(_probeManager->startChildGraph(id, parentActivity));
  24844. Owned<CActivityGraph> ret = new CActivityGraph(ctx, _graphName, id, childFactories, childProbe, _logctx);
  24845. ret->createGraph(ctx);
  24846. if (_probeManager)
  24847. _probeManager->endChildGraph(childProbe, parentActivity);
  24848. return ret.getClear();
  24849. }
  24850. else
  24851. return new CProxyActivityGraph(ctx, _graphName, id, childFactories, _logctx, numParallel);
  24852. }
  24853. }
  24854. //================================================================================================================
  24855. #ifdef _USE_CPPUNIT
  24856. #include "unittests.hpp"
  24857. // 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...
  24858. #if _MSC_VER==1200
  24859. #undef protected
  24860. #endif
  24861. static const char *sortAlgorithm;
  24862. class TestMetaData : public CInterface, implements IOutputMetaData
  24863. {
  24864. public:
  24865. IMPLEMENT_IINTERFACE;
  24866. virtual size32_t getRecordSize(const void *) { return 10; }
  24867. virtual size32_t getMinRecordSize() const { return 10; }
  24868. virtual size32_t getFixedSize() const { return 10; }
  24869. virtual void toXML(const byte * self, IXmlWriter & out) {}
  24870. virtual unsigned getVersion() const { return OUTPUTMETADATA_VERSION; }
  24871. virtual unsigned getMetaFlags() { return 0; }
  24872. virtual void destruct(byte * self) {}
  24873. virtual IOutputRowSerializer * createDiskSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  24874. virtual IOutputRowDeserializer * createDiskDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  24875. virtual ISourceRowPrefetcher * createDiskPrefetcher(ICodeContext * ctx, unsigned activityId) { return NULL; }
  24876. virtual IOutputMetaData * querySerializedDiskMeta() { return NULL; }
  24877. virtual IOutputRowSerializer * createInternalSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  24878. virtual IOutputRowDeserializer * createInternalDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  24879. virtual void walkIndirectMembers(const byte * self, IIndirectMemberVisitor & visitor) {}
  24880. virtual IOutputMetaData * queryChildMeta(unsigned i) { return NULL; }
  24881. } testMeta;
  24882. class TestInput : public CInterface, implements IFinalRoxieInput, implements IEngineRowStream
  24883. {
  24884. char const * const *input;
  24885. IRoxieSlaveContext *ctx;
  24886. unsigned endSeen;
  24887. bool eof;
  24888. unsigned count;
  24889. ActivityTimeAccumulator totalCycles;
  24890. size32_t recordSize;
  24891. unsigned activityId;
  24892. public:
  24893. enum { STATEreset, STATEstarted, STATEstopped } state;
  24894. bool allRead;
  24895. unsigned repeat;
  24896. IMPLEMENT_IINTERFACE;
  24897. TestInput(IRoxieSlaveContext *_ctx, char const * const *_input)
  24898. {
  24899. ctx = _ctx;
  24900. input = _input;
  24901. count = 0;
  24902. eof = false;
  24903. allRead = false;
  24904. endSeen = 0;
  24905. recordSize = testMeta.getFixedSize();
  24906. state = STATEreset;
  24907. activityId = 1;
  24908. repeat = 0;
  24909. }
  24910. virtual IOutputMetaData * queryOutputMeta() const { return &testMeta; }
  24911. virtual void prestart(unsigned parentExtractSize, const byte *parentExtract)
  24912. {
  24913. ASSERT(state == STATEreset);
  24914. }
  24915. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  24916. {
  24917. ASSERT(state == STATEreset);
  24918. state = STATEstarted;
  24919. }
  24920. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  24921. {
  24922. streams.append(this);
  24923. return NULL;
  24924. }
  24925. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { assertex(whichInput==0); return this; }
  24926. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { assertex(idx==0); return nullptr; }
  24927. virtual IRoxieServerActivity *queryActivity()
  24928. {
  24929. throwUnexpected();
  24930. }
  24931. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  24932. {
  24933. throwUnexpected();
  24934. }
  24935. virtual void stop()
  24936. {
  24937. state = STATEstopped;
  24938. }
  24939. virtual void reset()
  24940. {
  24941. ASSERT(state == STATEstopped);
  24942. eof = false; count = 0; endSeen = 0; allRead = false; state = STATEreset;
  24943. }
  24944. virtual void resetEOF()
  24945. {
  24946. throwUnexpected();
  24947. }
  24948. virtual void checkAbort() {}
  24949. virtual unsigned queryId() const { return activityId; };
  24950. virtual const void *nextRow()
  24951. {
  24952. ActivityTimer t(totalCycles, ctx->queryOptions().timeActivities);
  24953. ASSERT(state == STATEstarted);
  24954. ASSERT(allRead || !eof);
  24955. if (eof)
  24956. return NULL;
  24957. again:
  24958. const char *nextSource = input[count++];
  24959. if (nextSource)
  24960. {
  24961. endSeen = 0;
  24962. void *ret = ctx->queryRowManager().ALLOCATE(recordSize);
  24963. memset(ret, 0, recordSize);
  24964. strncpy((char *) ret, nextSource, recordSize);
  24965. return ret;
  24966. }
  24967. else if (repeat)
  24968. {
  24969. repeat--;
  24970. count = 0;
  24971. goto again;
  24972. }
  24973. else
  24974. {
  24975. endSeen++;
  24976. if (endSeen==2)
  24977. eof = true;
  24978. return NULL;
  24979. }
  24980. }
  24981. virtual bool nextGroup(ConstPointerArray & group)
  24982. {
  24983. const void * next;
  24984. while ((next = nextRow()) != NULL)
  24985. group.append(next);
  24986. if (group.ordinality())
  24987. return true;
  24988. return false;
  24989. }
  24990. virtual unsigned __int64 queryTotalCycles() const { return totalCycles.totalCycles; }
  24991. virtual unsigned __int64 queryLocalCycles() const { return totalCycles.totalCycles; }
  24992. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  24993. {
  24994. return NULL;
  24995. }
  24996. };
  24997. struct SortActivityTest : public ccdserver_hqlhelper::CThorSortArg {
  24998. public:
  24999. struct CompareClass : public ICompare {
  25000. virtual int docompare(const void * _left, const void * _right) const {
  25001. return memcmp(_left, _right, 5);
  25002. }
  25003. } compare;
  25004. virtual ICompare * queryCompare() { return &compare; }
  25005. virtual IOutputMetaData * queryOutputMeta()
  25006. {
  25007. return &testMeta;
  25008. }
  25009. virtual unsigned getAlgorithmFlags() { return TAFunstable; }
  25010. virtual const char * getAlgorithm() { return sortAlgorithm; }
  25011. };
  25012. extern "C" IHThorArg * sortActivityTestFactory() { return new SortActivityTest; }
  25013. struct MergeActivityTest : public ccdserver_hqlhelper::CThorMergeArg {
  25014. static bool isDedup;
  25015. public:
  25016. struct CompareClass : public ICompare {
  25017. virtual int docompare(const void * _left, const void * _right) const {
  25018. return memcmp(_left, _right, 5);
  25019. }
  25020. } compare;
  25021. virtual ICompare * queryCompare() { return &compare; }
  25022. virtual IOutputMetaData * queryOutputMeta()
  25023. {
  25024. return &testMeta;
  25025. }
  25026. virtual bool dedup() { return isDedup; }
  25027. };
  25028. bool MergeActivityTest::isDedup = false;
  25029. extern "C" IHThorArg * mergeActivityTestFactory() { return new MergeActivityTest; }
  25030. struct SplitActivityTest : public ccdserver_hqlhelper::CThorSplitArg {
  25031. public:
  25032. virtual unsigned numBranches() { return 2; }
  25033. virtual IOutputMetaData * queryOutputMeta()
  25034. {
  25035. return &testMeta;
  25036. }
  25037. };
  25038. extern "C" IHThorArg * splitActivityTestFactory() { return new SplitActivityTest; }
  25039. class CcdServerTest : public CppUnit::TestFixture
  25040. {
  25041. CPPUNIT_TEST_SUITE(CcdServerTest);
  25042. CPPUNIT_TEST(testSetup);
  25043. CPPUNIT_TEST(testHeapSort);
  25044. CPPUNIT_TEST(testQuickSort);
  25045. CPPUNIT_TEST(testMerge);
  25046. CPPUNIT_TEST(testMergeDedup);
  25047. CPPUNIT_TEST(testMiscellaneous);
  25048. CPPUNIT_TEST(testSplitter);
  25049. CPPUNIT_TEST(testCleanup);
  25050. CPPUNIT_TEST_SUITE_END();
  25051. protected:
  25052. SlaveContextLogger logctx;
  25053. Owned<const IQueryDll> queryDll;
  25054. Owned<IRoxiePackage> package;
  25055. Owned<IPropertyTree> stateInfo;
  25056. Owned<IQueryFactory> queryFactory;
  25057. Owned<IRoxieSlaveContext> ctx;
  25058. void testSetup()
  25059. {
  25060. selfTestMode = true;
  25061. roxiemem::setTotalMemoryLimit(false, true, false, 100 * 1024 * 1024, 0, NULL, NULL);
  25062. }
  25063. void testCleanup()
  25064. {
  25065. roxiemem::releaseRoxieHeap();
  25066. }
  25067. void init()
  25068. {
  25069. package.setown(createRoxiePackage(NULL, NULL));
  25070. queryDll.setown(createExeQueryDll("roxie"));
  25071. stateInfo.setown(createPTreeFromXMLString("<test memoryLimit='50000000'/>"));
  25072. queryFactory.setown(createServerQueryFactory("test", queryDll.getLink(), *package, stateInfo, false, false));
  25073. ctx.setown(createSlaveContext(queryFactory, logctx, NULL, false));
  25074. queryActiveTimer()->reset();
  25075. }
  25076. void testActivity(IRoxieServerActivity *activity, char const * const *input, char const * const *output)
  25077. {
  25078. testActivity(activity, input, NULL, output);
  25079. }
  25080. void testActivity(IRoxieServerActivity *activity, char const * const *input, char const * const *input2, char const * const *output, unsigned outputIdx = 0)
  25081. {
  25082. TestInput in(ctx, input);
  25083. TestInput in2(ctx, input2);
  25084. activity->setInput(0, 0, &in);
  25085. if (input2)
  25086. activity->setInput(1, 0, &in2);
  25087. IFinalRoxieInput *out = activity->queryOutput(outputIdx);
  25088. IEngineRowStream *outStream = connectSingleStream(ctx, out, outputIdx, true);
  25089. IOutputMetaData *meta = out->queryOutputMeta();
  25090. void *buf = alloca(meta->getFixedSize());
  25091. for (unsigned iteration = 0; iteration < 8; iteration++)
  25092. {
  25093. // 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)
  25094. // This should be true whether we read all, some, or none of the data.
  25095. // Should not matter if an activity is not started
  25096. if (iteration % 4 == 0)
  25097. activity->onCreate(NULL);
  25098. unsigned count = 0;
  25099. if (iteration % 4 != 3)
  25100. {
  25101. activity->start(0, NULL, false);
  25102. ASSERT(in.state == TestInput::STATEstarted);
  25103. ASSERT(!input2 || in2.state == TestInput::STATEstarted);
  25104. for (;;)
  25105. {
  25106. const void *next = outStream->nextRow();
  25107. if (!next)
  25108. {
  25109. ASSERT(output[count++] == NULL);
  25110. next = outStream->nextRow();
  25111. if (!next)
  25112. {
  25113. ASSERT(output[count++] == NULL);
  25114. break;
  25115. }
  25116. }
  25117. ASSERT(output[count] != NULL);
  25118. unsigned outsize = meta->getRecordSize(next);
  25119. memset(buf, 0, outsize);
  25120. strncpy((char *) buf, output[count++], outsize);
  25121. ASSERT(memcmp(next, buf, outsize) == 0);
  25122. ReleaseRoxieRow(next);
  25123. if (iteration % 4 == 2)
  25124. break;
  25125. }
  25126. if (iteration % 4 != 2)
  25127. {
  25128. // Check that reading after end is harmless
  25129. in.allRead = true;
  25130. const void *next = outStream->nextRow();
  25131. ASSERT(next == NULL);
  25132. }
  25133. }
  25134. activity->stop();
  25135. ASSERT(in.state == TestInput::STATEstopped);
  25136. ASSERT(!input2 || in2.state == TestInput::STATEstopped);
  25137. activity->reset();
  25138. ASSERT(in.state == TestInput::STATEreset);
  25139. ASSERT(!input2 || in2.state == TestInput::STATEreset);
  25140. ctx->queryRowManager().reportLeaks();
  25141. ASSERT(ctx->queryRowManager().numPagesAfterCleanup(true) == 0);
  25142. }
  25143. }
  25144. void testSplitActivity(IRoxieServerActivityFactory *factory, char const * const *input, char const * const *output, unsigned numOutputs, unsigned repeat)
  25145. {
  25146. Owned <IRoxieServerActivity> activity = factory->createActivity(ctx, NULL);
  25147. TestInput in(ctx, input);
  25148. in.repeat = repeat;
  25149. activity->setInput(0, 0, &in);
  25150. ArrayOf<IFinalRoxieInput *> out;
  25151. for (unsigned i = 0; i < numOutputs; i++)
  25152. {
  25153. out.append(activity->queryOutput(i));
  25154. }
  25155. activity->onCreate(NULL);
  25156. class casyncfor: public CAsyncFor
  25157. {
  25158. public:
  25159. casyncfor(CcdServerTest *_parent, IRoxieServerActivity *_activity, ArrayOf<IFinalRoxieInput *> &_outputs, char const * const *_input, char const * const *_output, unsigned _repeat)
  25160. : parent(_parent), activity(_activity), outputs(_outputs), input(_input), output(_output), repeat(_repeat)
  25161. {}
  25162. void Do(unsigned i)
  25163. {
  25164. IFinalRoxieInput *out = outputs.item(i);
  25165. IEngineRowStream *outStream = connectSingleStream(NULL, out, 0, true);
  25166. out->start(0, NULL, false);
  25167. IOutputMetaData *meta = out->queryOutputMeta();
  25168. void *buf = alloca(meta->getFixedSize());
  25169. unsigned count = 0;
  25170. unsigned repeats = repeat;
  25171. for (;;)
  25172. {
  25173. const void *next = outStream->nextRow();
  25174. if (!next)
  25175. {
  25176. ASSERT(repeats==0);
  25177. ASSERT(output[count] == NULL);
  25178. count++;
  25179. next = outStream->nextRow();
  25180. if (!next)
  25181. {
  25182. ASSERT(output[count] == NULL);
  25183. count++;
  25184. break;
  25185. }
  25186. }
  25187. if (output[count] == NULL && repeats)
  25188. {
  25189. repeats--;
  25190. count = 0;
  25191. }
  25192. ASSERT(output[count] != NULL);
  25193. unsigned outsize = meta->getRecordSize(next);
  25194. memset(buf, 0, outsize);
  25195. strncpy((char *) buf, output[count++], outsize);
  25196. ASSERT(memcmp(next, buf, outsize) == 0);
  25197. ReleaseRoxieRow(next);
  25198. }
  25199. outStream->stop();
  25200. }
  25201. private:
  25202. IRoxieServerActivity *activity;
  25203. ArrayOf<IFinalRoxieInput *> &outputs;
  25204. char const * const *input;
  25205. char const * const *output;
  25206. unsigned repeat;
  25207. CcdServerTest *parent;
  25208. } afor(this, activity, out, input, output, repeat);
  25209. afor.For(numOutputs, numOutputs);
  25210. ASSERT(in.state == TestInput::STATEstopped);
  25211. for (unsigned i2 = 0; i2 < numOutputs; i2++)
  25212. {
  25213. out.item(i2)->reset();
  25214. }
  25215. ASSERT(in.state == TestInput::STATEreset);
  25216. ctx->queryRowManager().reportLeaks();
  25217. ASSERT(ctx->queryRowManager().numPagesAfterCleanup(true) == 0);
  25218. }
  25219. static int compareFunc(const void *l, const void *r)
  25220. {
  25221. return strcmp(*(char **) l, *(char **) r);
  25222. }
  25223. void testSort(unsigned type)
  25224. {
  25225. init();
  25226. sortAlgorithm = NULL;
  25227. if (type==2)
  25228. sortAlgorithm = "heapSort";
  25229. else
  25230. sortAlgorithm = "quickSort";
  25231. DBGLOG("Testing %s activity", sortAlgorithm);
  25232. Owned<IPropertyTree> dummyNode = createPTree("node");
  25233. Owned <IRoxieServerActivityFactory> factory = createRoxieServerSortActivityFactory(1, 1, *queryFactory, sortActivityTestFactory, TAKsort, *dummyNode);
  25234. Owned <IRoxieServerActivity> activity = factory->createActivity(ctx, NULL);
  25235. const char * test[] = { NULL, NULL };
  25236. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  25237. const char * test54321[] = { "5", "4", "3", "2", "1", NULL, NULL };
  25238. const char * test11111[] = { "1", "1", "1", "1", "1", NULL, NULL };
  25239. const char * test11111_12345[] = { "1", "1", "1", "1", "1", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  25240. const char * test11111_54321[] = { "1", "1", "1", "1", "1", NULL, "5", "4", "3", "2", "1", NULL, NULL };
  25241. const char * test54321_54321[] = { "5", "4", "3", "2", "1", NULL, "5", "4", "3", "2", "1", NULL, NULL };
  25242. const char * test12345_12345[] = { "1", "2", "3", "4", "5", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  25243. testActivity(activity, test, test);
  25244. testActivity(activity, test12345, test12345);
  25245. testActivity(activity, test54321, test12345);
  25246. testActivity(activity, test11111, test11111);
  25247. testActivity(activity, test11111_12345, test11111_12345);
  25248. testActivity(activity, test11111_54321, test11111_12345);
  25249. testActivity(activity, test54321_54321, test12345_12345);
  25250. // A few larger tests
  25251. char *input[2002];
  25252. char *output[2002];
  25253. input[2000] = input[2001] = output[2000] = output[2001] = NULL;
  25254. unsigned i;
  25255. // identical
  25256. for (i=0; i<2000; i++)
  25257. {
  25258. input[i] = new char[11];
  25259. output[i] = new char[11];
  25260. sprintf(input[i], "1");
  25261. sprintf(output[i], "1");
  25262. }
  25263. testActivity(activity, input, output);
  25264. // Ascending
  25265. for (i=0; i<2000; i++)
  25266. {
  25267. sprintf(input[i], "%04d", i);
  25268. sprintf(output[i], "%04d", i);
  25269. }
  25270. testActivity(activity, input, output);
  25271. // Almost sorted
  25272. for (i=0; i<20; i++)
  25273. {
  25274. unsigned h = i*100;
  25275. sprintf(input[h], "%04d", 1900-h);
  25276. }
  25277. testActivity(activity, input, output);
  25278. // Descending
  25279. for (i=0; i<2000; i++)
  25280. {
  25281. sprintf(input[i], "%04d", 1999-i);
  25282. sprintf(output[i], "%04d", i);
  25283. }
  25284. testActivity(activity, input, output);
  25285. // Random
  25286. for (i=0; i<2000; i++)
  25287. {
  25288. unsigned r = rand() % 1500;
  25289. sprintf(input[i], "%04d", r);
  25290. sprintf(output[i], "%04d", r);
  25291. }
  25292. qsort(output, 2000, sizeof(output[0]), compareFunc);
  25293. testActivity(activity, input, output);
  25294. unsigned __int64 us = cycle_to_nanosec(factory->queryLocalCycles()/1000);
  25295. DBGLOG("Simple %s sorts: activity time %u.%u ms", type==2?"Heap" : (type==1 ? "Insertion" : "Quick"), (int)(us/1000), (int)(us%1000));
  25296. factory->resetNodeProgressInfo();
  25297. if (type)
  25298. {
  25299. // Other than quicksort, it's supposed to be stable. Let's check that it is
  25300. // All sort identical
  25301. for (i=0; i<2000; i++)
  25302. {
  25303. sprintf(input[i], "1 %d", i);
  25304. sprintf(output[i], "1 %d", i);
  25305. }
  25306. testActivity(activity, input, output);
  25307. // Already sorted
  25308. for (i=0; i<2000; i++)
  25309. {
  25310. sprintf(input[i], "%04d %d", i / 10, i);
  25311. sprintf(output[i], "%04d %d", i / 10, i);
  25312. }
  25313. testActivity(activity, input, output);
  25314. // Reverse order
  25315. for (i=0; i<2000; i++)
  25316. {
  25317. sprintf(input[i], "%04d %d", 199 - (i / 10), i%10);
  25318. sprintf(output[i], "%04d %d", i / 10, i%10);
  25319. }
  25320. testActivity(activity, input, output);
  25321. }
  25322. for (i=0; i<2000; i++)
  25323. {
  25324. delete [] input[i];
  25325. delete [] output[i];
  25326. }
  25327. DBGLOG("Finished testing %s sort", type==2?"Heap" : (type==1 ? "Insertion" : "Quick"));
  25328. }
  25329. void testQuickSort()
  25330. {
  25331. testSort(0);
  25332. }
  25333. void testHeapSort()
  25334. {
  25335. testSort(2);
  25336. }
  25337. void testMerge()
  25338. {
  25339. DBGLOG("testMerge");
  25340. init();
  25341. Owned<IPropertyTree> splitterNode = createPTree();
  25342. Owned <IRoxieServerActivityFactory> factory = createRoxieServerMergeActivityFactory(1, 1, *queryFactory, mergeActivityTestFactory, TAKmerge, *splitterNode);
  25343. factory->setInput(0,0,0);
  25344. factory->setInput(1,0,0);
  25345. Owned <IRoxieServerActivity> activity = factory->createActivity(ctx, NULL);
  25346. const char * test[] = { NULL, NULL };
  25347. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  25348. const char * test1122334455[] = { "1", "1", "2", "2", "3", "3", "4", "4", "5", "5", NULL, NULL };
  25349. const char * test11111[] = { "1", "1", "1", "1", "1", NULL, NULL };
  25350. const char * test1111111111[] = { "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", NULL, NULL };
  25351. const char * test11111_12345[] = { "1", "1", "1", "1", "1", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  25352. const char * test1111112345[] = { "1", "1", "1", "1", "1", "1", "2", "3", "4", "5", NULL, NULL };
  25353. 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 };
  25354. testActivity(activity, test, test, test);
  25355. testActivity(activity, test12345, test, test12345);
  25356. testActivity(activity, test, test12345, test12345);
  25357. testActivity(activity, test12345, test12345, test1122334455);
  25358. testActivity(activity, test11111, test, test11111);
  25359. testActivity(activity, test, test11111, test11111);
  25360. testActivity(activity, test11111, test11111, test1111111111);
  25361. testActivity(activity, test11111_12345, test, test1111112345);
  25362. testActivity(activity, test11111_12345, test11111_12345, test11111111111122334455);
  25363. // Should really test WHICH side gets kept...
  25364. // Should test with more than 2 inputs...
  25365. DBGLOG("testMerge done");
  25366. }
  25367. void testMergeDedup()
  25368. {
  25369. DBGLOG("testMergeDedup");
  25370. init();
  25371. MergeActivityTest::isDedup = true;
  25372. Owned<IPropertyTree> splitterNode = createPTree();
  25373. Owned <IRoxieServerActivityFactory> factory = createRoxieServerMergeActivityFactory(1, 1, *queryFactory, mergeActivityTestFactory, TAKmerge, *splitterNode);
  25374. factory->setInput(0,0,0);
  25375. factory->setInput(1,0,0);
  25376. Owned <IRoxieServerActivity> activity = factory->createActivity(ctx, NULL);
  25377. const char * test[] = { NULL, NULL };
  25378. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  25379. const char * test11111[] = { "1", "1", "1", "1", "1", NULL, NULL };
  25380. const char * test11111_12345[] = { "1", "1", "1", "1", "1", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  25381. const char * test1111112345[] = { "1", "1", "1", "1", "1", "1", "2", "3", "4", "5", NULL, NULL };
  25382. testActivity(activity, test11111, test, test11111); // No dedup within a stream
  25383. testActivity(activity, test11111, test11111, test11111); // No dedup within a stream
  25384. testActivity(activity, test, test11111, test11111);
  25385. testActivity(activity, test, test, test);
  25386. testActivity(activity, test12345, test, test12345);
  25387. testActivity(activity, test, test12345, test12345);
  25388. testActivity(activity, test12345, test12345, test12345);
  25389. testActivity(activity, test11111_12345, test, test1111112345);
  25390. testActivity(activity, test11111_12345, test11111_12345, test1111112345);
  25391. // Should really test WHICH side gets kept...
  25392. // Should test with more than 2 inputs...
  25393. DBGLOG("testMergeDedup done");
  25394. }
  25395. void doTestSplitter(unsigned numOutputs)
  25396. {
  25397. DBGLOG("testSplit %d", numOutputs);
  25398. init();
  25399. Owned<IPropertyTree> splitterNode = createPTree();
  25400. Owned <IRoxieServerActivityFactory> factory = createRoxieServerThroughSpillActivityFactory(*queryFactory, splitActivityTestFactory, numOutputs, *splitterNode);
  25401. factory->setInput(0,0,0);
  25402. Owned <IRoxieServerActivity> activity = factory->createActivity(ctx, NULL);
  25403. const char * test[] = { NULL, NULL };
  25404. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  25405. unsigned start = msTick();
  25406. testSplitActivity(factory, test, test, numOutputs, 0);
  25407. testSplitActivity(factory, test12345, test12345, numOutputs, 0);
  25408. testSplitActivity(factory, test12345, test12345, numOutputs, 100);
  25409. unsigned elapsed = msTick() - start;
  25410. DBGLOG("testSplit %d done in %dms", numOutputs, elapsed);
  25411. }
  25412. void testSplitter()
  25413. {
  25414. doTestSplitter(1);
  25415. doTestSplitter(2);
  25416. doTestSplitter(3);
  25417. doTestSplitter(10);
  25418. }
  25419. void testMiscellaneous()
  25420. {
  25421. DBGLOG("sizeof(CriticalSection)=%u", (unsigned) sizeof(CriticalSection));
  25422. DBGLOG("sizeof(SpinLock)=%u", (unsigned) sizeof(SpinLock));
  25423. DBGLOG("sizeof(CJoinGroup)=%u", (unsigned) sizeof(CJoinGroup));
  25424. ASSERT(sizeof(CJoinGroup) <= 120);
  25425. }
  25426. };
  25427. CPPUNIT_TEST_SUITE_REGISTRATION( CcdServerTest );
  25428. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( CcdServerTest, "CcdServerTest" );
  25429. #endif