ccdserver.cpp 982 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141
  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 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, __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, __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. const IRoxieServerActivityFactory *factory;
  822. IRoxieServerActivityCopyArray dependencies;
  823. IntArray dependencyIndexes;
  824. IntArray dependencyControlIds;
  825. IArrayOf<IActivityGraph> childGraphs;
  826. CachedOutputMetaData meta;
  827. IHThorArg *colocalParent;
  828. IEngineRowAllocator *rowAllocator;
  829. CriticalSection statecrit;
  830. CriticalSection statscrit;
  831. mutable CRuntimeStatisticCollection stats;
  832. MapStringToMyClass<ThorSectionTimer> functionTimers;
  833. unsigned processed;
  834. ActivityTimeAccumulator totalCycles;
  835. cycle_t localCycles;
  836. unsigned activityId;
  837. activityState state;
  838. bool createPending;
  839. bool debugging;
  840. bool timeActivities;
  841. bool aborted;
  842. bool connected = false;
  843. IProbeManager *probeManager = NULL;
  844. public:
  845. IMPLEMENT_IINTERFACE_USING(CInterfaceOf<IRoxieServerActivity>)
  846. CRoxieServerActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  847. : ctx(_ctx),
  848. factory(_factory),
  849. basehelper(_factory->getHelper()),
  850. activityId(_factory->queryId()),
  851. stats(_factory->queryStatsMapping()),
  852. probeManager(_probeManager)
  853. {
  854. input = NULL;
  855. sourceIdx = 0;
  856. inputStream = NULL;
  857. meta.set(basehelper.queryOutputMeta());
  858. processed = 0;
  859. localCycles = 0;
  860. state=STATEreset;
  861. rowAllocator = NULL;
  862. debugging = _probeManager != NULL; // Don't want to collect timing stats from debug sessions
  863. colocalParent = NULL;
  864. createPending = true;
  865. timeActivities = defaultTimeActivities;
  866. aborted = false;
  867. }
  868. CRoxieServerActivity(IRoxieSlaveContext *_ctx, IHThorArg & _helper) : ctx(_ctx), factory(NULL), basehelper(_helper), stats(allStatistics)
  869. {
  870. activityId = 0;
  871. input = NULL;
  872. sourceIdx = 0;
  873. inputStream = NULL;
  874. ctx = NULL;
  875. meta.set(basehelper.queryOutputMeta());
  876. processed = 0;
  877. localCycles = 0;
  878. state=STATEreset;
  879. rowAllocator = NULL;
  880. debugging = false;
  881. colocalParent = NULL;
  882. createPending = true;
  883. timeActivities = defaultTimeActivities;
  884. aborted = false;
  885. }
  886. ~CRoxieServerActivity()
  887. {
  888. if (traceStartStop)
  889. {
  890. // There was an old comment here stating // Note- CTXLOG may not be safe
  891. // There were problems in the destruction order of graphs that might mean an IndirectSlaveContext
  892. // was released while activities still referenced it.
  893. // However these should now all be fixed
  894. DBGLOG("%p destroy %d state=%s", this, activityId, queryStateText(state));
  895. if (watchActivityId && watchActivityId==activityId)
  896. {
  897. DBGLOG("WATCH: %p destroy %d state=%s", this, activityId, queryStateText(state));
  898. }
  899. }
  900. if (state!=STATEreset)
  901. {
  902. DBGLOG("STATE: Activity %d destroyed but not reset", activityId);
  903. state = STATEreset; // bit pointless but there you go...
  904. }
  905. if (factory && !debugging)
  906. {
  907. if (processed)
  908. factory->noteProcessed(0, processed);
  909. factory->mergeActivityStats(stats, totalCycles, localCycles);
  910. }
  911. if (ctx && factory)
  912. {
  913. if (processed)
  914. ctx->noteProcessed(factory->querySubgraphId(), activityId, 0, processed, 0);
  915. ctx->mergeActivityStats(stats, factory->querySubgraphId(), activityId, totalCycles, localCycles);
  916. }
  917. basehelper.Release();
  918. ::Release(rowAllocator);
  919. }
  920. virtual const IRoxieContextLogger &queryLogCtx()const
  921. {
  922. return *this;
  923. }
  924. inline const StatisticsMapping & queryStatsMapping() const
  925. {
  926. return factory ? factory->queryStatsMapping() : actStatistics;
  927. }
  928. virtual void mergeStats(MemoryBuffer &buf)
  929. {
  930. stats.deserializeMerge(buf);
  931. }
  932. virtual ISectionTimer *registerTimer(unsigned activityId, const char * name)
  933. {
  934. CriticalBlock b(statscrit); // reuse statscrit to protect functionTimers - it will not be held concurrently
  935. ISectionTimer *timer = functionTimers.getValue(name);
  936. if (!timer)
  937. {
  938. timer = ThorSectionTimer::createTimer(stats, name);
  939. functionTimers.setValue(name, timer);
  940. timer->Release(); // Value returned is not linked
  941. }
  942. return timer;
  943. }
  944. virtual IRoxieServerActivity * queryChildActivity(unsigned activityId)
  945. {
  946. ForEachItemIn(i, childGraphs)
  947. {
  948. IRoxieServerActivity * activity = childGraphs.item(i).queryActivity(activityId);
  949. if (activity)
  950. return activity;
  951. }
  952. #ifdef _DEBUG
  953. throwUnexpectedX("Unable to map child activity id to an activity");
  954. #endif
  955. return nullptr;
  956. }
  957. void mergeStrandStats(unsigned strandProcessed, const ActivityTimeAccumulator & strandCycles, const CRuntimeStatisticCollection & strandStats)
  958. {
  959. CriticalBlock cb(statscrit);
  960. processed += strandProcessed;
  961. totalCycles.merge(strandCycles);
  962. stats.merge(strandStats);
  963. }
  964. inline void ensureRowAllocator()
  965. {
  966. if (!rowAllocator)
  967. rowAllocator = createRowAllocator(meta.queryOriginal());
  968. }
  969. virtual IEngineRowAllocator * createRowAllocator(IOutputMetaData * metadata)
  970. {
  971. return ctx->getRowAllocatorEx(metadata, activityId, factory->getHeapFlags());
  972. }
  973. virtual IEngineRowAllocator * createRowAllocatorEx(IOutputMetaData * metadata, roxiemem::RoxieHeapFlags extraFlags)
  974. {
  975. return ctx->getRowAllocatorEx(metadata, activityId, (roxiemem::RoxieHeapFlags)(factory->getHeapFlags()|extraFlags));
  976. }
  977. inline ICodeContext *queryCodeContext()
  978. {
  979. return ctx->queryCodeContext();
  980. }
  981. // MORE - most of this is copied from ccd.hpp - can't we refactor?
  982. virtual void CTXLOGa(TracingCategory category, const char *prefix, const char *text) const
  983. {
  984. if (ctx)
  985. ctx->CTXLOGa(category, prefix, text);
  986. else
  987. DBGLOG("[%s] %s", prefix, text);
  988. }
  989. 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)))
  990. {
  991. if (ctx)
  992. ctx->CTXLOGaeva(E, file, line, prefix, format, args);
  993. else
  994. {
  995. StringBuffer ss;
  996. ss.appendf("[%s] ERROR", prefix);
  997. if (E)
  998. ss.append(": ").append(E->errorCode());
  999. if (file)
  1000. ss.appendf(": %s(%d) ", file, line);
  1001. if (E)
  1002. E->errorMessage(ss.append(": "));
  1003. if (format)
  1004. {
  1005. ss.append(": ").valist_appendf(format, args);
  1006. }
  1007. LOG(MCoperatorProgress, unknownJob, "%s", ss.str());
  1008. }
  1009. }
  1010. virtual void CTXLOGl(LogItem *log) const
  1011. {
  1012. if (ctx)
  1013. ctx->CTXLOGl(log);
  1014. else
  1015. {
  1016. assert(ctx);
  1017. log->Release(); // Should never happen
  1018. }
  1019. }
  1020. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value) const
  1021. {
  1022. stats.addStatistic(kind, value);
  1023. }
  1024. virtual void mergeStats(const CRuntimeStatisticCollection &from) const
  1025. {
  1026. stats.merge(from);
  1027. }
  1028. virtual const CRuntimeStatisticCollection &queryStats() const
  1029. {
  1030. return stats;
  1031. }
  1032. virtual StringBuffer &getLogPrefix(StringBuffer &ret) const
  1033. {
  1034. if (ctx)
  1035. ctx->getLogPrefix(ret);
  1036. return ret.append('@').append(activityId);
  1037. }
  1038. virtual bool isIntercepted() const
  1039. {
  1040. return ctx ? ctx->isIntercepted() : false;
  1041. }
  1042. virtual bool isBlind() const
  1043. {
  1044. return ctx ? ctx->isBlind() : blindLogging;
  1045. }
  1046. virtual unsigned queryTraceLevel() const
  1047. {
  1048. if (ctx)
  1049. return ctx->queryTraceLevel();
  1050. else
  1051. return traceLevel;
  1052. }
  1053. virtual bool isPassThrough()
  1054. {
  1055. return false;
  1056. }
  1057. virtual const IResolvedFile *resolveLFN(const char *filename, bool isOpt)
  1058. {
  1059. return ctx->resolveLFN(filename, isOpt);
  1060. }
  1061. virtual const IResolvedFile *queryVarFileInfo() const
  1062. {
  1063. throwUnexpected(); // should be implemented in more derived class by anyone that has a remote adaptor
  1064. return NULL;
  1065. }
  1066. virtual void serializeSkipInfo(MemoryBuffer &out, unsigned seekLen, const void *rawSeek, unsigned numFields, const void * seek, const SmartStepExtra &stepExtra) const
  1067. {
  1068. throwUnexpected(); // should be implemented in more derived class wherever needed
  1069. }
  1070. virtual IRoxieSlaveContext *queryContext()
  1071. {
  1072. return ctx;
  1073. }
  1074. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { assertex(whichInput==0); return this; }
  1075. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { assertex(idx==0); return junction; }
  1076. virtual IRoxieServerActivity *queryActivity() { return this; }
  1077. virtual IIndexReadActivityInfo *queryIndexReadActivity() { return NULL; }
  1078. virtual bool needsAllocator() const { return false; }
  1079. void _onCreate(IHThorArg *_colocalParent, unsigned _numParallel)
  1080. {
  1081. colocalParent = _colocalParent;
  1082. createPending = true;
  1083. if (needsAllocator())
  1084. ensureRowAllocator();
  1085. processed = 0;
  1086. if (factory)
  1087. factory->onCreateChildQueries(ctx, &basehelper, childGraphs, this, probeManager, *this, _numParallel);
  1088. if (ctx)
  1089. timeActivities = ctx->queryOptions().timeActivities;
  1090. }
  1091. virtual void onCreate(IHThorArg *_colocalParent)
  1092. {
  1093. _onCreate(_colocalParent, 1);
  1094. }
  1095. virtual void serializeCreateStartContext(MemoryBuffer &out)
  1096. {
  1097. //This should only be called after onStart has been called on the helper
  1098. assertex(!createPending);
  1099. assertex(state==STATEstarted);
  1100. unsigned startlen = out.length();
  1101. basehelper.serializeCreateContext(out);
  1102. basehelper.serializeStartContext(out);
  1103. if (queryTraceLevel() > 10)
  1104. CTXLOG("serializeCreateStartContext for %d added %d bytes", activityId, out.length()-startlen);
  1105. }
  1106. virtual void serializeExtra(MemoryBuffer &out) {}
  1107. inline void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  1108. {
  1109. CriticalBlock cb(statecrit);
  1110. if (state != STATEreset && state != STATEstarting)
  1111. {
  1112. CTXLOG("STATE: Expected state to be reset, but was %s, in activity %d", queryStateText(state), activityId);
  1113. }
  1114. state=STATEstarted;
  1115. #ifdef TRACE_STARTSTOP
  1116. if (traceStartStop)
  1117. {
  1118. CTXLOG("start %p %d", this, activityId);
  1119. if (watchActivityId && watchActivityId==activityId)
  1120. {
  1121. CTXLOG("WATCH: start %p %d", this, activityId);
  1122. }
  1123. }
  1124. #endif
  1125. executeDependencies(parentExtractSize, parentExtract, 0);
  1126. if (input)
  1127. input->start(parentExtractSize, parentExtract, paused);
  1128. ensureCreated();
  1129. basehelper.onStart(parentExtract, NULL);
  1130. if (factory)
  1131. factory->noteStarted();
  1132. startJunction(junction);
  1133. }
  1134. void executeDependencies(unsigned parentExtractSize, const byte *parentExtract, unsigned controlId)
  1135. {
  1136. //MORE: Create a filtered list and then use asyncfor
  1137. ForEachItemIn(idx, dependencies)
  1138. {
  1139. if (dependencyControlIds.item(idx) == controlId)
  1140. dependencies.item(idx).execute(parentExtractSize, parentExtract);
  1141. }
  1142. }
  1143. void stopDependencies(unsigned parentExtractSize, const byte *parentExtract, unsigned controlId)
  1144. {
  1145. ForEachItemIn(idx, dependencies)
  1146. {
  1147. if (dependencyControlIds.item(idx) == controlId)
  1148. dependencies.item(idx).stop();
  1149. }
  1150. }
  1151. virtual unsigned __int64 queryTotalCycles() const
  1152. {
  1153. return totalCycles.totalCycles;
  1154. }
  1155. virtual unsigned __int64 queryLocalCycles() const
  1156. {
  1157. __int64 ret = totalCycles.totalCycles;
  1158. if (input) ret -= input->queryTotalCycles();
  1159. if (ret < 0)
  1160. ret = 0;
  1161. return ret;
  1162. }
  1163. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  1164. {
  1165. if (idx==0)
  1166. return input;
  1167. else
  1168. return NULL;
  1169. }
  1170. inline void ensureCreated()
  1171. {
  1172. if (createPending)
  1173. {
  1174. createPending = false;
  1175. basehelper.onCreate(ctx->queryCodeContext(), colocalParent, NULL);
  1176. }
  1177. }
  1178. virtual void stop()
  1179. {
  1180. // NOTE - don't be tempted to skip the stop for activities that are reset - splitters need to see the stops
  1181. if (state != STATEstopped)
  1182. {
  1183. CriticalBlock cb(statecrit);
  1184. if (state != STATEstopped)
  1185. {
  1186. #ifdef TRACE_STARTSTOP
  1187. if (traceStartStop)
  1188. {
  1189. CTXLOG("stop %p %d (state currently %s)", this, activityId, queryStateText(state));
  1190. if (watchActivityId && watchActivityId==activityId)
  1191. {
  1192. CTXLOG("WATCH: stop %p %d", this, activityId);
  1193. }
  1194. }
  1195. #endif
  1196. state=STATEstopped;
  1197. // NOTE - this is needed to ensure that dependencies which were not used are properly stopped
  1198. ForEachItemIn(idx, dependencies)
  1199. {
  1200. if (dependencyControlIds.item(idx) == 0)
  1201. dependencies.item(idx).stopSink(dependencyIndexes.item(idx));
  1202. }
  1203. if (inputStream)
  1204. inputStream->stop();
  1205. if (rowAllocator)
  1206. {
  1207. stats.reset(heapStatistics);
  1208. rowAllocator->gatherStats(stats);
  1209. }
  1210. }
  1211. }
  1212. }
  1213. virtual void abort()
  1214. {
  1215. aborted = true;
  1216. // MORE - should abort dependencies here?
  1217. stop();
  1218. }
  1219. inline void reset()
  1220. {
  1221. if (state != STATEreset)
  1222. {
  1223. CriticalBlock cb(statecrit);
  1224. if (state != STATEreset)
  1225. {
  1226. if (state==STATEstarted || state==STATEstarting)
  1227. {
  1228. if (traceStartStop || traceLevel > 2)
  1229. CTXLOG("STATE: activity %d reset without stop", activityId);
  1230. stop();
  1231. }
  1232. state = STATEreset;
  1233. #ifdef TRACE_STARTSTOP
  1234. if (traceStartStop)
  1235. {
  1236. CTXLOG("reset %p %d", this, activityId);
  1237. if (watchActivityId && watchActivityId==activityId)
  1238. {
  1239. CTXLOG("WATCH: reset %p %d", this, activityId);
  1240. }
  1241. }
  1242. #endif
  1243. resetJunction(junction);
  1244. ForEachItemIn(idx, dependencies)
  1245. dependencies.item(idx).reset();
  1246. localCycles = queryLocalCycles(); // We can't call queryLocalCycles() in the destructor, so save the information here when we can.
  1247. if (input)
  1248. input->reset();
  1249. }
  1250. }
  1251. aborted = false;
  1252. }
  1253. virtual void addDependency(IRoxieServerActivity &source, unsigned sourceIdx, int controlId)
  1254. {
  1255. dependencies.append(source);
  1256. dependencyIndexes.append(sourceIdx);
  1257. dependencyControlIds.append(controlId);
  1258. }
  1259. virtual void resetEOF()
  1260. {
  1261. //would make more sense if the default implementation (and eof member) were in the base class
  1262. }
  1263. // Sink activities should override this....
  1264. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  1265. {
  1266. throw MakeStringException(ROXIE_SINK, "Internal error: execute() requires a sink");
  1267. }
  1268. virtual void executeChild(size32_t & retSize, void * & ret, unsigned parentExtractSize, const byte * parentExtract)
  1269. {
  1270. throw MakeStringException(ROXIE_SINK, "Internal error: executeChild() requires a suitable sink");
  1271. }
  1272. virtual void stopSink(unsigned idx)
  1273. {
  1274. throw MakeStringException(ROXIE_SINK, "Internal error: stopSink() requires a suitable sink");
  1275. }
  1276. virtual void connectInputStreams(bool consumerOrdered)
  1277. {
  1278. if (input && !inputStream)
  1279. inputStream = connectSingleStream(ctx, input, sourceIdx, junction, isInputOrdered(consumerOrdered, 0));
  1280. if (!connected)
  1281. {
  1282. connectDependencies();
  1283. connected = true;
  1284. }
  1285. }
  1286. void connectDependencies()
  1287. {
  1288. ForEachItemIn(i, dependencies)
  1289. dependencies.item(i).connectInputStreams(true);
  1290. }
  1291. virtual __int64 evaluate()
  1292. {
  1293. throw MakeStringException(ROXIE_SINK, "Internal error: evaluate() requires a function");
  1294. }
  1295. virtual IFinalRoxieInput * querySelectOutput(unsigned id)
  1296. {
  1297. return NULL;
  1298. }
  1299. virtual bool querySetStreamInput(unsigned id, unsigned _sourceIdx, IFinalRoxieInput * _input)
  1300. {
  1301. return false;
  1302. }
  1303. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  1304. {
  1305. assertex(!idx);
  1306. input = _in;
  1307. sourceIdx = _sourceIdx;
  1308. inputStream = NULL;
  1309. }
  1310. bool isInputOrdered(bool consumerOrdered, unsigned idx) const
  1311. {
  1312. if (!factory)
  1313. return true;
  1314. //Grouping implies the stream processing must be ordered - I think this always applies
  1315. IFinalRoxieInput * curInput = queryInput(idx);
  1316. if (curInput && curInput->queryOutputMeta()->isGrouped())
  1317. return true;
  1318. return factory->isInputOrdered(consumerOrdered, idx);
  1319. }
  1320. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  1321. {
  1322. assertex(!idx);
  1323. // By default, activities are assumed NOT to support streams
  1324. bool inputOrdered = isInputOrdered(consumerOrdered, 0);
  1325. connectInputStreams(inputOrdered);
  1326. // Return a single stream
  1327. streams.append(this);
  1328. return NULL;
  1329. }
  1330. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  1331. {
  1332. if (idx == (unsigned) -1)
  1333. idx = 0;
  1334. return idx ? NULL : this;
  1335. }
  1336. virtual IOutputMetaData *queryOutputMeta() const
  1337. {
  1338. return meta.queryOriginal();
  1339. }
  1340. virtual unsigned queryId() const
  1341. {
  1342. return activityId;
  1343. }
  1344. virtual unsigned querySubgraphId() const
  1345. {
  1346. return factory->querySubgraphId();
  1347. }
  1348. virtual void checkAbort()
  1349. {
  1350. ctx->checkAbort();
  1351. }
  1352. IException *makeWrappedException(IException *e)
  1353. {
  1354. StringBuffer msg;
  1355. ThorActivityKind activityKind = factory ? factory->getKind() : TAKnone;
  1356. CTXLOG("makeWrappedException - %s (in %s %d)", e->errorMessage(msg).str(), getActivityText(activityKind), activityId);
  1357. if (QUERYINTERFACE(e, CWrappedException) || QUERYINTERFACE(e, IUserException))
  1358. return e;
  1359. else
  1360. return new CWrappedException(e, activityKind, activityId);
  1361. }
  1362. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract)
  1363. {
  1364. }
  1365. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract, IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes)
  1366. {
  1367. }
  1368. virtual void resetOutputsUsed()
  1369. {
  1370. }
  1371. virtual void noteOutputUsed()
  1372. {
  1373. }
  1374. virtual IRoxieServerSideCache *queryServerSideCache() const
  1375. {
  1376. return factory->queryServerSideCache();
  1377. }
  1378. virtual const IRoxieServerActivityFactory *queryFactory() const
  1379. {
  1380. return factory;
  1381. }
  1382. inline ThorActivityKind getKind() const
  1383. {
  1384. return factory->getKind();
  1385. }
  1386. inline bool isSink() const
  1387. {
  1388. return (factory != NULL) && factory->isSink();
  1389. }
  1390. };
  1391. //=====================================================================================================
  1392. class CRoxieServerLateStartActivity : public CRoxieServerActivity
  1393. {
  1394. protected:
  1395. bool prefiltered;
  1396. bool eof;
  1397. void lateStart(unsigned parentExtractSize, const byte *parentExtract, bool any)
  1398. {
  1399. prefiltered = !any;
  1400. eof = prefiltered;
  1401. if (!prefiltered)
  1402. {
  1403. input->start(parentExtractSize, parentExtract, false);
  1404. startJunction(junction);
  1405. }
  1406. else
  1407. {
  1408. if (traceStartStop)
  1409. CTXLOG("lateStart activity stopping input early as prefiltered");
  1410. inputStream->stop();
  1411. }
  1412. }
  1413. public:
  1414. CRoxieServerLateStartActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  1415. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  1416. {
  1417. prefiltered = false;
  1418. eof = false;
  1419. }
  1420. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  1421. {
  1422. IFinalRoxieInput *saveInput = input;
  1423. Owned<IStrandJunction> saveJunction = junction.getClear();
  1424. input = NULL; // Make sure parent does not start the chain yet
  1425. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  1426. input = saveInput;
  1427. junction.setown(saveJunction.getClear());
  1428. }
  1429. virtual void stop()
  1430. {
  1431. if (!prefiltered)
  1432. {
  1433. inputStream->stop();
  1434. }
  1435. else if (traceStartStop)
  1436. CTXLOG("lateStart activity NOT stopping input late as prefiltered");
  1437. IEngineRowStream *save = inputStream;
  1438. inputStream = NULL; // We already stopped inputStream - prevent parent from doing so again
  1439. CRoxieServerActivity::stop();
  1440. inputStream = save;
  1441. }
  1442. virtual void reset()
  1443. {
  1444. CRoxieServerActivity::reset();
  1445. prefiltered = false;
  1446. }
  1447. };
  1448. //=================================================================================
  1449. class StrandOptions
  1450. {
  1451. // Typically set from hints, common to many stranded activities
  1452. public:
  1453. explicit StrandOptions(IPropertyTree &_graphNode)
  1454. {
  1455. //PARALLEL(1) can be used to explicitly disable parallel processing.
  1456. numStrands = _graphNode.getPropInt("att[@name='parallel']/@value", 0);
  1457. if ((numStrands == minus1U) || (numStrands > MAX_SENSIBLE_STRANDS))
  1458. numStrands = getAffinityCpus();
  1459. blockSize = _graphNode.getPropInt("hint[@name='strandblocksize']/@value", 0);
  1460. }
  1461. StrandOptions(const StrandOptions &from, IRoxieSlaveContext *ctx)
  1462. {
  1463. numStrands = from.numStrands;
  1464. blockSize = from.blockSize;
  1465. if (!blockSize)
  1466. blockSize = ctx->queryOptions().strandBlockSize;
  1467. if (numStrands == 0)
  1468. numStrands = ctx->queryOptions().forceNumStrands;
  1469. }
  1470. public:
  1471. unsigned numStrands = 0; // if 1 it forces single-stranded operations. (Useful for testing.)
  1472. unsigned blockSize = 0;
  1473. };
  1474. class StrandProcessor : public CInterfaceOf<IEngineRowStream>
  1475. {
  1476. protected:
  1477. CRoxieServerActivity &parent;
  1478. IEngineRowAllocator *rowAllocator;
  1479. IEngineRowStream *inputStream;
  1480. ActivityTimeAccumulator totalCycles;
  1481. mutable CRuntimeStatisticCollection stats;
  1482. unsigned processed = 0;
  1483. unsigned numProcessedLastGroup = 0;
  1484. const bool timeActivities;
  1485. bool stopped = false;
  1486. std::atomic<bool> abortRequested;
  1487. public:
  1488. explicit StrandProcessor(CRoxieServerActivity &_parent, IEngineRowStream *_inputStream, bool needsAllocator)
  1489. : parent(_parent), inputStream(_inputStream), stats(parent.queryStatsMapping()), timeActivities(_parent.timeActivities), abortRequested(false)
  1490. {
  1491. if (needsAllocator)
  1492. {
  1493. rowAllocator = parent.createRowAllocatorEx(parent.queryOutputMeta(), roxiemem::RHFunique);
  1494. }
  1495. else
  1496. rowAllocator = NULL;
  1497. }
  1498. ~StrandProcessor()
  1499. {
  1500. ::Release(rowAllocator);
  1501. }
  1502. virtual void start()
  1503. {
  1504. processed = 0;
  1505. numProcessedLastGroup = 0;
  1506. totalCycles.reset();
  1507. stats.reset();
  1508. }
  1509. virtual void stop()
  1510. {
  1511. if (!stopped)
  1512. {
  1513. if (inputStream)
  1514. inputStream->stop();
  1515. stats.reset(heapStatistics); // Heap stats are always gathered from scratch each time
  1516. if (rowAllocator)
  1517. rowAllocator->gatherStats(stats);
  1518. parent.stop();
  1519. parent.mergeStrandStats(processed, totalCycles, stats);
  1520. }
  1521. stopped = true;
  1522. }
  1523. virtual void reset()
  1524. {
  1525. stopped = false;
  1526. abortRequested.store(false, std::memory_order_relaxed);
  1527. }
  1528. virtual void resetEOF()
  1529. {
  1530. inputStream->resetEOF();
  1531. }
  1532. inline void requestAbort() { abortRequested.store(true, std::memory_order_relaxed); }
  1533. inline bool isAborting() { return abortRequested.load(std::memory_order_relaxed); }
  1534. };
  1535. class CRoxieServerStrandedActivity : public CRoxieServerActivity
  1536. {
  1537. protected:
  1538. StrandOptions strandOptions;
  1539. IArrayOf<StrandProcessor> strands;
  1540. Owned<IStrandBranch> branch;
  1541. Owned<IStrandJunction> splitter;
  1542. Owned<IStrandJunction> sourceJunction; // A junction applied to the output of a source activity
  1543. std::atomic<unsigned> active;
  1544. public:
  1545. CRoxieServerStrandedActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const StrandOptions &_strandOptions)
  1546. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  1547. strandOptions(_strandOptions, ctx)
  1548. {
  1549. active = 0;
  1550. }
  1551. ~CRoxieServerStrandedActivity()
  1552. {
  1553. if (strands.ordinality() > 1)
  1554. {
  1555. if (factory && !debugging)
  1556. factory->noteProcessed(0, processed);
  1557. if (ctx && factory)
  1558. ctx->noteProcessed(factory->querySubgraphId(), activityId, 0, processed, strands.ordinality());
  1559. processed = 0; // To avoid reprocessing in base destructor
  1560. }
  1561. }
  1562. virtual void onCreate(IHThorArg *_colocalArg)
  1563. {
  1564. CRoxieServerActivity::_onCreate(_colocalArg, strands.ordinality());
  1565. }
  1566. //This function is pure (But also implemented out of line) to force the derived classes to implement it.
  1567. //After calling the base class start method, and initialising any values from the helper they must call onStartStrands(),
  1568. //this must also happen before any rows are read from the strands (e.g., by a source junction)
  1569. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused) = 0;
  1570. virtual void reset()
  1571. {
  1572. assertex(active==0);
  1573. ForEachItemIn(idx, strands)
  1574. strands.item(idx).reset();
  1575. resetJunction(splitter);
  1576. CRoxieServerActivity::reset();
  1577. resetJunction(sourceJunction);
  1578. }
  1579. virtual void stop()
  1580. {
  1581. // Called from the strands... which should ensure that stop is not called more than once per strand
  1582. //The first strand to call
  1583. if (active)
  1584. --active;
  1585. if (!active)
  1586. CRoxieServerActivity::stop();
  1587. }
  1588. void requestAbort()
  1589. {
  1590. ForEachItemIn(idx, strands)
  1591. strands.item(idx).requestAbort();
  1592. }
  1593. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  1594. {
  1595. assertex(idx == 0);
  1596. assertex(strands.empty());
  1597. CRoxieServerActivity::connectDependencies();
  1598. bool inputOrdered = isInputOrdered(consumerOrdered, idx);
  1599. //Note, numStrands == 1 is an explicit request to disable threading
  1600. if (consumerOptions && (consumerOptions->numStrands != 1) && (strandOptions.numStrands != 1))
  1601. {
  1602. //Check to see if the consumer's settings should override
  1603. if (strandOptions.numStrands == 0)
  1604. {
  1605. strandOptions.numStrands = consumerOptions->numStrands;
  1606. strandOptions.blockSize = consumerOptions->blockSize;
  1607. }
  1608. else if (consumerOptions->numStrands > strandOptions.numStrands)
  1609. {
  1610. strandOptions.numStrands = consumerOptions->numStrands;
  1611. }
  1612. }
  1613. Owned <IStrandJunction> recombiner;
  1614. if (input)
  1615. {
  1616. if (strandOptions.numStrands == 1)
  1617. {
  1618. // 1 means explicitly requested single-strand.
  1619. IEngineRowStream *instream = connectSingleStream(ctx, input, sourceIdx, junction, inputOrdered);
  1620. strands.append(*createStrandProcessor(instream));
  1621. }
  1622. else
  1623. {
  1624. PointerArrayOf<IEngineRowStream> instreams;
  1625. recombiner.setown(input->getOutputStreams(ctx, sourceIdx, instreams, &strandOptions, inputOrdered, orderedCallbacks));
  1626. if ((instreams.length() == 1) && (strandOptions.numStrands != 0)) // 0 means did not specify - we should use the strands that our upstream provides
  1627. {
  1628. assertex(recombiner == NULL);
  1629. // Create a splitter to split the input into n... and a recombiner if need to preserve sorting
  1630. if (inputOrdered)
  1631. {
  1632. branch.setown(createStrandBranch(ctx->queryRowManager(), strandOptions.numStrands, strandOptions.blockSize, true, input->queryOutputMeta()->isGrouped(), false, orderedCallbacks));
  1633. splitter.set(branch->queryInputJunction());
  1634. recombiner.set(branch->queryOutputJunction());
  1635. }
  1636. else
  1637. {
  1638. splitter.setown(createStrandJunction(ctx->queryRowManager(), 1, strandOptions.numStrands, strandOptions.blockSize, false));
  1639. }
  1640. splitter->setInput(0, instreams.item(0));
  1641. for (unsigned strandNo = 0; strandNo < strandOptions.numStrands; strandNo++)
  1642. strands.append(*createStrandProcessor(splitter->queryOutput(strandNo)));
  1643. }
  1644. else
  1645. {
  1646. // Ignore my hint and just use the width already split into...
  1647. ForEachItemIn(strandNo, instreams)
  1648. strands.append(*createStrandProcessor(instreams.item(strandNo)));
  1649. }
  1650. }
  1651. }
  1652. else
  1653. {
  1654. unsigned numStrands = strandOptions.numStrands ? strandOptions.numStrands : 1;
  1655. for (unsigned i=0; i < numStrands; i++)
  1656. strands.append(*createStrandSourceProcessor(inputOrdered));
  1657. if (inputOrdered && (numStrands > 1))
  1658. {
  1659. if (consumerOptions)
  1660. {
  1661. //If the output activities are also stranded then need to create a version of the branch
  1662. bool isGrouped = queryOutputMeta()->isGrouped();
  1663. branch.setown(createStrandBranch(ctx->queryRowManager(), strandOptions.numStrands, strandOptions.blockSize, true, isGrouped, true, orderedCallbacks));
  1664. sourceJunction.set(branch->queryInputJunction());
  1665. recombiner.set(branch->queryOutputJunction());
  1666. assertex((orderedCallbacks && !recombiner) || (!orderedCallbacks && recombiner));
  1667. //This is different from the branch above. The first "junction" has the source activity as the input, and the outputs as the result of the activity
  1668. for (unsigned strandNo = 0; strandNo < strandOptions.numStrands; strandNo++)
  1669. {
  1670. sourceJunction->setInput(strandNo, &strands.item(strandNo));
  1671. streams.append(sourceJunction->queryOutput(strandNo));
  1672. }
  1673. #ifdef TRACE_STRANDS
  1674. if (traceLevel > 2)
  1675. DBGLOG("Executing activity %u with %u strands", activityId, strands.ordinality());
  1676. #endif
  1677. return recombiner.getClear();
  1678. }
  1679. else
  1680. {
  1681. //Feeding into a non threaded activity, so create a M:1 junction to combine the source strands
  1682. recombiner.setown(createStrandJunction(ctx->queryRowManager(), numStrands, 1, strandOptions.blockSize, inputOrdered));
  1683. }
  1684. }
  1685. }
  1686. ForEachItemIn(i, strands)
  1687. streams.append(&strands.item(i));
  1688. #ifdef TRACE_STRANDS
  1689. if (traceLevel > 2)
  1690. DBGLOG("Executing activity %u with %u strands", activityId, strands.ordinality());
  1691. #endif
  1692. return recombiner.getClear();
  1693. }
  1694. virtual StrandProcessor *createStrandProcessor(IEngineRowStream *instream) = 0;
  1695. //MORE: Possibly this class should be split into two for sinks and non sinks...
  1696. virtual StrandProcessor *createStrandSourceProcessor(bool inputOrdered) = 0;
  1697. virtual const void * nextRow()
  1698. {
  1699. throwUnexpected();
  1700. }
  1701. inline unsigned numStrands() const { return strands.ordinality(); }
  1702. protected:
  1703. void onStartStrands()
  1704. {
  1705. ForEachItemIn(idx, strands)
  1706. {
  1707. strands.item(idx).start();
  1708. active++;
  1709. }
  1710. }
  1711. };
  1712. //For some reason gcc doesn't let you specify a function as pure virtual and define it at the same time.
  1713. void CRoxieServerStrandedActivity::start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  1714. {
  1715. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  1716. startJunction(splitter);
  1717. }
  1718. class CRoxieServerStrandedLateStartActivity : public CRoxieServerStrandedActivity
  1719. {
  1720. protected:
  1721. bool prefiltered;
  1722. bool eof;
  1723. void lateStart(unsigned parentExtractSize, const byte *parentExtract, bool any)
  1724. {
  1725. prefiltered = !any;
  1726. eof = prefiltered;
  1727. if (!prefiltered)
  1728. {
  1729. //At this point
  1730. input->start(parentExtractSize, parentExtract, false);
  1731. startJunction(splitter);
  1732. onStartStrands(); // Initialise the strands - the helper will have been correctly initialized by this point.
  1733. startJunction(sourceJunction);
  1734. }
  1735. else
  1736. {
  1737. if (traceStartStop)
  1738. CTXLOG("strandedLateStart activity stopping input early as prefiltered");
  1739. ForEachItemIn(idx, strands)
  1740. strands.item(idx).stop();
  1741. }
  1742. }
  1743. public:
  1744. CRoxieServerStrandedLateStartActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const StrandOptions &_strandOptions)
  1745. : CRoxieServerStrandedActivity(_ctx, _factory, _probeManager, _strandOptions)
  1746. {
  1747. prefiltered = false;
  1748. eof = false;
  1749. }
  1750. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  1751. {
  1752. IFinalRoxieInput *save = input;
  1753. input = NULL; // Make sure parent does not start the chain yet - but we do want to do the dependencies (because the decision about whether to start may depend on them)
  1754. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  1755. input = save;
  1756. }
  1757. virtual void reset()
  1758. {
  1759. CRoxieServerStrandedActivity::reset();
  1760. prefiltered = false;
  1761. }
  1762. };
  1763. //=====================================================================================================
  1764. atomic_t nextInstanceId;
  1765. extern unsigned getNextInstanceId()
  1766. {
  1767. return atomic_add_exchange(&nextInstanceId, 1)+1;
  1768. }
  1769. atomic_t nextRuid;
  1770. ruid_t getNextRuid()
  1771. {
  1772. ruid_t ret = atomic_add_exchange(&nextRuid, 1)+1;
  1773. while (ret < RUID_FIRST)
  1774. ret = atomic_add_exchange(&nextRuid, 1)+1; // ruids 0 and 1 are reserved for pings/unwanted discarder.
  1775. return ret;
  1776. }
  1777. void setStartRuid(unsigned restarts)
  1778. {
  1779. atomic_set(&nextRuid, restarts * 0x10000);
  1780. atomic_set(&nextInstanceId, restarts * 10000);
  1781. }
  1782. enum { LimitSkipErrorCode = 0, KeyedLimitSkipErrorCode = 1 };
  1783. class LimitSkipException : public IException, public CInterface
  1784. {
  1785. int code;
  1786. public:
  1787. LimitSkipException(int _code) { code = _code; }
  1788. IMPLEMENT_IINTERFACE;
  1789. virtual int errorCode() const { return code; }
  1790. virtual StringBuffer & errorMessage(StringBuffer &msg) const { return msg.append("LimitSkipException"); }
  1791. virtual MessageAudience errorAudience() const { return MSGAUD_internal; }
  1792. };
  1793. IException *makeLimitSkipException(bool isKeyed)
  1794. {
  1795. // We need to make sure what we throw is IException not something derived from it....
  1796. return new LimitSkipException(isKeyed ? KeyedLimitSkipErrorCode : LimitSkipErrorCode);
  1797. }
  1798. //=================================================================================
  1799. interface IRecordPullerCallback : extends IExceptionHandler
  1800. {
  1801. virtual void processRow(const void *row) = 0;
  1802. virtual void processEOG() = 0;
  1803. virtual void processGroup(const ConstPointerArray &rows) = 0;
  1804. virtual void processDone() = 0;
  1805. };
  1806. class RecordPullerThread : public RestartableThread
  1807. {
  1808. protected:
  1809. IFinalRoxieInput *input;
  1810. Owned<IStrandJunction> junction;
  1811. unsigned sourceIdx = 0;
  1812. IEngineRowStream *inputStream;
  1813. IRecordPullerCallback *helper;
  1814. Semaphore started; // MORE: GH->RKC I'm pretty sure this can be deleted, since handled by RestartableThread
  1815. bool groupAtOnce, eof, eog;
  1816. CriticalSection crit;
  1817. public:
  1818. RecordPullerThread(bool _groupAtOnce)
  1819. : RestartableThread("RecordPullerThread"), groupAtOnce(_groupAtOnce)
  1820. {
  1821. input = NULL;
  1822. inputStream = NULL;
  1823. helper = NULL;
  1824. eof = eog = FALSE;
  1825. }
  1826. inline unsigned __int64 queryTotalCycles() const
  1827. {
  1828. return input->queryTotalCycles();
  1829. }
  1830. void setInput(IRecordPullerCallback *_helper, unsigned _sourceIdx, IFinalRoxieInput *_input)
  1831. {
  1832. helper = _helper;
  1833. input = _input;
  1834. sourceIdx = _sourceIdx;
  1835. }
  1836. IFinalRoxieInput *queryInput() const
  1837. {
  1838. return input;
  1839. }
  1840. virtual void connectInputStreams(IRoxieSlaveContext *ctx, bool consumerOrdered)
  1841. {
  1842. inputStream = connectSingleStream(ctx, input, sourceIdx, junction, consumerOrdered);
  1843. }
  1844. IEngineRowStream *queryStream() const
  1845. {
  1846. return inputStream;
  1847. }
  1848. void start(unsigned parentExtractSize, const byte *parentExtract, bool paused, unsigned preload, bool noThread, IRoxieSlaveContext *ctx)
  1849. {
  1850. eof = false;
  1851. eog = false;
  1852. input->start(parentExtractSize, parentExtract, paused);
  1853. startJunction(junction);
  1854. try
  1855. {
  1856. if (preload && !paused)
  1857. {
  1858. if (traceLevel > 4)
  1859. DBGLOG("Preload fetching first %d records", preload);
  1860. if (groupAtOnce)
  1861. pullGroups(preload);
  1862. else
  1863. pullRecords(preload);
  1864. }
  1865. if (eof)
  1866. {
  1867. if (traceLevel > 4)
  1868. DBGLOG("No need to start puller after preload");
  1869. helper->processDone();
  1870. }
  1871. else
  1872. {
  1873. if (!noThread)
  1874. {
  1875. StringBuffer logPrefix("[");
  1876. if (ctx) ctx->getLogPrefix(logPrefix);
  1877. logPrefix.append("] ");
  1878. RestartableThread::start(logPrefix);
  1879. started.wait();
  1880. }
  1881. }
  1882. }
  1883. catch (IException *e)
  1884. {
  1885. helper->fireException(e);
  1886. }
  1887. catch (...)
  1888. {
  1889. helper->fireException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unexpected exception caught in RecordPullerThread::start"));
  1890. }
  1891. }
  1892. void stop()
  1893. {
  1894. if (traceStartStop)
  1895. DBGLOG("RecordPullerThread::stop");
  1896. {
  1897. CriticalBlock c(crit); // stop is called on our consumer's thread. We need to take care calling stop for our input to make sure it is not in mid-nextRow etc etc.
  1898. if (inputStream)
  1899. inputStream->stop();
  1900. }
  1901. RestartableThread::join();
  1902. }
  1903. void reset()
  1904. {
  1905. input->reset();
  1906. resetJunction(junction);
  1907. }
  1908. virtual int run()
  1909. {
  1910. started.signal();
  1911. try
  1912. {
  1913. if (groupAtOnce)
  1914. pullGroups((unsigned) -1);
  1915. else
  1916. pullRecords((unsigned) -1);
  1917. helper->processDone();
  1918. }
  1919. catch (IException *e)
  1920. {
  1921. helper->fireException(e);
  1922. }
  1923. catch (...)
  1924. {
  1925. helper->fireException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unexpected exception caught in RecordPullerThread::run"));
  1926. }
  1927. return 0;
  1928. }
  1929. void done()
  1930. {
  1931. helper->processDone();
  1932. }
  1933. bool pullRecords(unsigned preload)
  1934. {
  1935. if (eof)
  1936. return false;
  1937. while (preload)
  1938. {
  1939. const void * row;
  1940. {
  1941. CriticalBlock c(crit); // See comments in stop for why this is needed
  1942. row = inputStream->nextRow();
  1943. }
  1944. if (row)
  1945. {
  1946. eog = false;
  1947. helper->processRow(row);
  1948. }
  1949. else if (!eog)
  1950. {
  1951. helper->processEOG();
  1952. eog = true;
  1953. }
  1954. else
  1955. {
  1956. eof = true;
  1957. return false;
  1958. }
  1959. if (preload != (unsigned) -1)
  1960. preload--;
  1961. }
  1962. return true;
  1963. }
  1964. void pullGroups(unsigned preload)
  1965. {
  1966. ConstPointerArray thisGroup;
  1967. unsigned rowsDone = 0;
  1968. while (preload && !eof)
  1969. {
  1970. const void *row;
  1971. {
  1972. CriticalBlock c(crit);
  1973. row = inputStream->nextRow();
  1974. }
  1975. if (row)
  1976. {
  1977. thisGroup.append(row);
  1978. rowsDone++;
  1979. }
  1980. else if (thisGroup.length())
  1981. {
  1982. helper->processGroup(thisGroup);
  1983. thisGroup.kill();
  1984. if (preload != (unsigned) -1)
  1985. {
  1986. if (preload > rowsDone)
  1987. preload -= rowsDone;
  1988. else
  1989. break;
  1990. }
  1991. rowsDone = 0;
  1992. }
  1993. else
  1994. {
  1995. eof = true;
  1996. break;
  1997. }
  1998. }
  1999. }
  2000. };
  2001. //=================================================================================
  2002. #define READAHEAD_SIZE 1000
  2003. // MORE - this code copied from ThreadedConcat code - may be able to common up some.
  2004. class CRoxieServerReadAheadInput : implements IEngineRowStream, implements IFinalRoxieInput, implements IRecordPullerCallback, public CInterface
  2005. {
  2006. QueueOf<const void, true> buffer;
  2007. InterruptableSemaphore ready;
  2008. InterruptableSemaphore space;
  2009. CriticalSection crit;
  2010. bool eof;
  2011. bool disabled;
  2012. IRoxieSlaveContext *ctx;
  2013. RecordPullerThread puller;
  2014. unsigned preload;
  2015. cycle_t totalCycles;
  2016. bool timeActivities;
  2017. public:
  2018. IMPLEMENT_IINTERFACE;
  2019. CRoxieServerReadAheadInput(IRoxieSlaveContext *_ctx, unsigned _preload) : ctx(_ctx), puller(true), preload(_preload)
  2020. {
  2021. eof = false;
  2022. disabled = (ctx->queryDebugContext() != NULL);
  2023. totalCycles = 0;
  2024. timeActivities = ctx->queryOptions().timeActivities;
  2025. }
  2026. virtual IRoxieServerActivity *queryActivity()
  2027. {
  2028. return puller.queryInput()->queryActivity();
  2029. }
  2030. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  2031. {
  2032. assertex(!idx);
  2033. puller.connectInputStreams(ctx, consumerOrdered);
  2034. streams.append(this);
  2035. return NULL;
  2036. }
  2037. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { return this; }
  2038. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { return nullptr; }
  2039. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  2040. {
  2041. return puller.queryInput()->queryIndexReadActivity();
  2042. }
  2043. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  2044. {
  2045. eof = false;
  2046. if (disabled)
  2047. puller.queryInput()->start(parentExtractSize, parentExtract, paused);
  2048. else
  2049. {
  2050. space.reinit(READAHEAD_SIZE);
  2051. ready.reinit();
  2052. puller.start(parentExtractSize, parentExtract, paused, preload, false, ctx);
  2053. }
  2054. }
  2055. virtual void stop()
  2056. {
  2057. if (disabled)
  2058. puller.queryStream()->stop();
  2059. else
  2060. {
  2061. space.interrupt();
  2062. ready.interrupt();
  2063. puller.stop();
  2064. }
  2065. }
  2066. virtual void reset()
  2067. {
  2068. if (disabled)
  2069. puller.queryInput()->reset();
  2070. else
  2071. {
  2072. puller.reset();
  2073. ForEachItemIn(idx1, buffer)
  2074. ReleaseRoxieRow(buffer.item(idx1));
  2075. buffer.clear();
  2076. }
  2077. }
  2078. virtual void resetEOF()
  2079. {
  2080. throwUnexpected();
  2081. }
  2082. virtual IOutputMetaData * queryOutputMeta() const
  2083. {
  2084. return puller.queryInput()->queryOutputMeta();
  2085. }
  2086. void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  2087. {
  2088. assertex(!idx);
  2089. puller.setInput(this, _sourceIdx, _in);
  2090. }
  2091. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  2092. {
  2093. if (idx==0)
  2094. return puller.queryInput();
  2095. else
  2096. return NULL;
  2097. }
  2098. virtual unsigned __int64 queryTotalCycles() const
  2099. {
  2100. return totalCycles;
  2101. }
  2102. virtual const void * nextRow()
  2103. {
  2104. SimpleActivityTimer t(totalCycles, timeActivities);
  2105. if (disabled)
  2106. return puller.queryStream()->nextRow();
  2107. else
  2108. {
  2109. loop
  2110. {
  2111. {
  2112. CriticalBlock b(crit);
  2113. if (eof && !buffer.ordinality())
  2114. return NULL; // eof
  2115. }
  2116. ready.wait();
  2117. const void *ret;
  2118. {
  2119. CriticalBlock b(crit);
  2120. ret = buffer.dequeue();
  2121. }
  2122. space.signal();
  2123. return ret;
  2124. }
  2125. }
  2126. }
  2127. virtual bool fireException(IException *e)
  2128. {
  2129. // called from puller thread on failure
  2130. ready.interrupt(LINK(e));
  2131. space.interrupt(e);
  2132. return true;
  2133. }
  2134. virtual void processRow(const void *row)
  2135. {
  2136. {
  2137. CriticalBlock b(crit);
  2138. buffer.enqueue(row);
  2139. }
  2140. ready.signal();
  2141. space.wait();
  2142. }
  2143. virtual void processGroup(const ConstPointerArray &rows)
  2144. {
  2145. // NOTE - a bit bizarre in that it waits for the space AFTER using it.
  2146. // But the space semaphore is only there to stop infinite readahead. And otherwise it would deadlock
  2147. // if group was larger than max(space)
  2148. {
  2149. CriticalBlock b(crit);
  2150. ForEachItemIn(idx, rows)
  2151. buffer.enqueue(rows.item(idx));
  2152. buffer.enqueue(NULL);
  2153. }
  2154. for (unsigned i2 = 0; i2 <= rows.length(); i2++) // note - does 1 extra for the null
  2155. {
  2156. ready.signal();
  2157. space.wait();
  2158. }
  2159. }
  2160. virtual void processEOG()
  2161. {
  2162. // Used when output is not grouped - just ignore
  2163. }
  2164. virtual void processDone()
  2165. {
  2166. CriticalBlock b(crit);
  2167. eof = true;
  2168. ready.signal();
  2169. }
  2170. };
  2171. //=================================================================================
  2172. class CRoxieServerTwoInputActivity : public CRoxieServerActivity
  2173. {
  2174. protected:
  2175. IFinalRoxieInput *input1;
  2176. IEngineRowStream *inputStream1;
  2177. Owned<IStrandJunction> junction1;
  2178. unsigned sourceIdx1 = 0;
  2179. Owned<CRoxieServerReadAheadInput> puller;
  2180. public:
  2181. CRoxieServerTwoInputActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  2182. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  2183. {
  2184. input1 = NULL;
  2185. inputStream1 = NULL;
  2186. }
  2187. ~CRoxieServerTwoInputActivity()
  2188. {
  2189. }
  2190. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  2191. {
  2192. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  2193. input1->start(parentExtractSize, parentExtract, paused);
  2194. startJunction(junction1);
  2195. }
  2196. virtual void stop()
  2197. {
  2198. inputStream1->stop();
  2199. CRoxieServerActivity::stop();
  2200. }
  2201. virtual unsigned __int64 queryLocalCycles() const
  2202. {
  2203. __int64 ret;
  2204. __int64 inputCycles = input->queryTotalCycles();
  2205. __int64 input1Cycles = input1->queryTotalCycles();
  2206. if (puller)
  2207. ret = totalCycles.totalCycles - (inputCycles > input1Cycles ? inputCycles : input1Cycles);
  2208. else
  2209. ret = totalCycles.totalCycles - (inputCycles + input1Cycles);
  2210. if (ret < 0)
  2211. ret = 0;
  2212. return ret;
  2213. }
  2214. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  2215. {
  2216. switch (idx)
  2217. {
  2218. case 0:
  2219. return input;
  2220. case 1:
  2221. return input1;
  2222. default:
  2223. return NULL;
  2224. }
  2225. }
  2226. virtual void reset()
  2227. {
  2228. CRoxieServerActivity::reset();
  2229. if (input1)
  2230. input1->reset();
  2231. resetJunction(junction1);
  2232. }
  2233. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  2234. {
  2235. switch(idx)
  2236. {
  2237. case 0:
  2238. CRoxieServerActivity::setInput(idx, _sourceIdx, _in);
  2239. break;
  2240. case 1:
  2241. input1 = _in;
  2242. sourceIdx1 = _sourceIdx;
  2243. break;
  2244. default:
  2245. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  2246. }
  2247. }
  2248. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  2249. {
  2250. inputStream1 = connectSingleStream(ctx, input1, sourceIdx1, junction1, isInputOrdered(consumerOrdered, 1));
  2251. //Assumes input1 will be stranded if any.
  2252. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
  2253. }
  2254. };
  2255. //=================================================================================
  2256. class CRoxieServerMultiInputBaseActivity : public CRoxieServerActivity
  2257. {
  2258. protected:
  2259. unsigned numInputs;
  2260. unsigned numStreams;
  2261. IFinalRoxieInput **inputArray;
  2262. unsigned *sourceIdxArray;
  2263. IEngineRowStream **streamArray;
  2264. Owned<IStrandJunction> *junctionArray;
  2265. public:
  2266. CRoxieServerMultiInputBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  2267. : CRoxieServerActivity(_ctx, _factory, _probeManager), numInputs(_numInputs)
  2268. {
  2269. numStreams = numInputs;
  2270. inputArray = new IFinalRoxieInput*[numInputs];
  2271. sourceIdxArray = new unsigned[numInputs];
  2272. streamArray = new IEngineRowStream*[numStreams];
  2273. junctionArray = new Owned<IStrandJunction>[numStreams];
  2274. for (unsigned i1 = 0; i1 < numInputs; i1++)
  2275. {
  2276. inputArray[i1] = NULL;
  2277. sourceIdxArray[i1] = 0;
  2278. }
  2279. for (unsigned i2 = 0; i2 < numStreams; i2++)
  2280. streamArray[i2] = NULL;
  2281. }
  2282. ~CRoxieServerMultiInputBaseActivity()
  2283. {
  2284. delete [] inputArray;
  2285. delete [] sourceIdxArray;
  2286. delete [] streamArray;
  2287. delete [] junctionArray;
  2288. }
  2289. virtual unsigned __int64 queryLocalCycles() const
  2290. {
  2291. __int64 localCycles = totalCycles.totalCycles;
  2292. for (unsigned i = 0; i < numInputs; i++)
  2293. localCycles -= inputArray[i]->queryTotalCycles();
  2294. if (localCycles < 0)
  2295. localCycles = 0;
  2296. return localCycles;
  2297. }
  2298. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  2299. {
  2300. if (idx < numInputs)
  2301. return inputArray[idx];
  2302. else
  2303. return NULL;
  2304. }
  2305. virtual IFinalRoxieInput * queryConcreteInput(unsigned idx)
  2306. {
  2307. return queryInput(idx);
  2308. }
  2309. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput)
  2310. {
  2311. if (whichInput < numInputs)
  2312. return streamArray[whichInput];
  2313. else
  2314. return NULL;
  2315. }
  2316. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const
  2317. {
  2318. if (idx < numInputs)
  2319. return junctionArray[idx];
  2320. else
  2321. return NULL;
  2322. }
  2323. virtual void reset()
  2324. {
  2325. for (unsigned i = 0; i < numInputs; i++)
  2326. inputArray[i]->reset();
  2327. for (unsigned iS = 0; iS < numStreams; iS++)
  2328. {
  2329. resetJunction(junctionArray[iS]);
  2330. }
  2331. CRoxieServerActivity::reset();
  2332. }
  2333. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  2334. {
  2335. assertex(idx < numInputs && idx < numStreams);
  2336. inputArray[idx] = _in;
  2337. sourceIdxArray[idx] = _sourceIdx;
  2338. }
  2339. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  2340. {
  2341. //There could be situations (e.g., NONEMPTY), where you might want to strand the activity.
  2342. for (unsigned i = 0; i < numInputs; i++)
  2343. streamArray[i] = connectSingleStream(ctx, inputArray[i], sourceIdxArray[i], junctionArray[i], consumerOrdered);
  2344. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, NULL, consumerOrdered, nullptr); // The input basesclass does not have an input
  2345. }
  2346. };
  2347. //=================================================================================
  2348. class CRoxieServerMultiInputActivity : public CRoxieServerMultiInputBaseActivity
  2349. {
  2350. public:
  2351. CRoxieServerMultiInputActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  2352. : CRoxieServerMultiInputBaseActivity(_ctx, _factory, _probeManager, _numInputs)
  2353. {
  2354. }
  2355. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  2356. {
  2357. CRoxieServerMultiInputBaseActivity::start(parentExtractSize, parentExtract, paused);
  2358. for (unsigned i = 0; i < numInputs; i++)
  2359. {
  2360. inputArray[i]->start(parentExtractSize, parentExtract, paused);
  2361. }
  2362. for (unsigned iS = 0; iS < numStreams; iS++)
  2363. {
  2364. startJunction(junctionArray[iS]);
  2365. }
  2366. }
  2367. virtual void stop()
  2368. {
  2369. for (unsigned i = 0; i < numStreams; i++)
  2370. {
  2371. streamArray[i]->stop();
  2372. }
  2373. CRoxieServerMultiInputBaseActivity::stop();
  2374. }
  2375. };
  2376. //=====================================================================================================
  2377. class CRoxieServerInternalSinkActivity : public CRoxieServerActivity
  2378. {
  2379. protected:
  2380. unsigned numOutputs;
  2381. bool executed;
  2382. bool *stopped;
  2383. CriticalSection ecrit;
  2384. Owned<IException> exception;
  2385. public:
  2386. CRoxieServerInternalSinkActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  2387. : CRoxieServerActivity(_ctx, _factory, _probeManager), numOutputs(_numOutputs)
  2388. {
  2389. executed = false;
  2390. stopped = new bool[numOutputs];
  2391. for (unsigned s = 0; s < numOutputs; s++)
  2392. stopped[s] = false;
  2393. }
  2394. ~CRoxieServerInternalSinkActivity()
  2395. {
  2396. delete [] stopped;
  2397. }
  2398. virtual void reset()
  2399. {
  2400. for (unsigned s = 0; s < numOutputs; s++)
  2401. stopped[s] = false;
  2402. executed = false;
  2403. exception.clear();
  2404. CRoxieServerActivity::reset();
  2405. }
  2406. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  2407. {
  2408. return NULL;
  2409. }
  2410. virtual void stopSink(unsigned outputIdx)
  2411. {
  2412. if (!stopped[outputIdx])
  2413. {
  2414. stopped[outputIdx] = true;
  2415. for (unsigned s = 0; s < numOutputs; s++)
  2416. if (!stopped[s])
  2417. return;
  2418. stop(); // all outputs stopped - stop parent.
  2419. }
  2420. }
  2421. virtual const void *nextRow()
  2422. {
  2423. throwUnexpected(); // I am nobody's input
  2424. }
  2425. virtual void onExecute() = 0;
  2426. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  2427. {
  2428. CriticalBlock b(ecrit);
  2429. if (exception)
  2430. throw exception.getLink();
  2431. if (!executed)
  2432. {
  2433. try
  2434. {
  2435. start(parentExtractSize, parentExtract, false);
  2436. {
  2437. ActivityTimer t(totalCycles, timeActivities); // unfortunately this is not really best place for seeing in debugger.
  2438. onExecute();
  2439. }
  2440. stop();
  2441. executed = true;
  2442. }
  2443. catch (IException *E)
  2444. {
  2445. exception.set(E); // (or maybe makeWrappedException?)
  2446. abort();
  2447. throw;
  2448. }
  2449. catch (...)
  2450. {
  2451. exception.set(MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught at %s:%d", __FILE__, __LINE__));
  2452. abort();
  2453. throw;
  2454. }
  2455. }
  2456. }
  2457. };
  2458. //=================================================================================
  2459. class CRoxieServerQueryPacket : implements IRoxieServerQueryPacket, public CInterface
  2460. {
  2461. protected:
  2462. Owned<IMessageResult> result;
  2463. Owned<IRoxieQueryPacket> packet;
  2464. Linked<IRoxieServerQueryPacket> continuation;
  2465. unsigned hash;
  2466. unsigned seq;
  2467. unsigned lastDebugSequence;
  2468. Owned<IRoxieQueryPacket> lastDebugResponse;
  2469. ILRUChain *prev;
  2470. ILRUChain *next;
  2471. bool delayed;
  2472. public:
  2473. IMPLEMENT_IINTERFACE;
  2474. CRoxieServerQueryPacket(IRoxieQueryPacket *p) : packet(p)
  2475. {
  2476. hash = 0;
  2477. seq = 0;
  2478. prev = NULL;
  2479. next = NULL;
  2480. delayed = false;
  2481. lastDebugSequence = 0;
  2482. }
  2483. virtual IRoxieQueryPacket *queryPacket() const
  2484. {
  2485. return packet;
  2486. }
  2487. virtual bool isContinuation() const
  2488. {
  2489. return packet && (packet->queryHeader().continueSequence & ~CONTINUE_SEQUENCE_SKIPTO) != 0;
  2490. }
  2491. virtual bool isDelayed() const
  2492. {
  2493. return delayed;
  2494. }
  2495. virtual bool isEnd() const
  2496. {
  2497. return false;
  2498. }
  2499. virtual bool isLimit(unsigned __int64 &_rowLimit, unsigned __int64 &_keyedLimit, unsigned __int64 &_stopAfter) const
  2500. {
  2501. return false;
  2502. }
  2503. virtual bool hasResult() const
  2504. {
  2505. return result != NULL;
  2506. }
  2507. virtual bool hasContinuation() const
  2508. {
  2509. return continuation != NULL;
  2510. }
  2511. virtual void setDelayed(bool _delayed)
  2512. {
  2513. delayed = _delayed;
  2514. }
  2515. virtual void setPacket(IRoxieQueryPacket *_packet)
  2516. {
  2517. packet.setown(_packet);
  2518. }
  2519. virtual void setSequence(unsigned _seq)
  2520. {
  2521. assertex(!IsShared());
  2522. seq = _seq;
  2523. }
  2524. virtual unsigned getSequence() const
  2525. {
  2526. return seq;
  2527. }
  2528. IMessageResult *getResult()
  2529. {
  2530. return result.getLink();
  2531. }
  2532. IMessageResult *queryResult()
  2533. {
  2534. return result;
  2535. }
  2536. void setResult(IMessageResult *r)
  2537. {
  2538. result.setown(r);
  2539. }
  2540. IRoxieServerQueryPacket *queryContinuation()
  2541. {
  2542. return continuation;
  2543. }
  2544. void setContinuation(IRoxieServerQueryPacket *c)
  2545. {
  2546. continuation.setown(c);
  2547. }
  2548. virtual unsigned queryHash() const
  2549. {
  2550. return hash;
  2551. }
  2552. virtual void setHash(unsigned _hash)
  2553. {
  2554. hash = _hash;
  2555. }
  2556. virtual ILRUChain *queryPrev() const { return prev; }
  2557. virtual ILRUChain *queryNext() const { return next; }
  2558. virtual void setPrev(ILRUChain *p) { prev = p; }
  2559. virtual void setNext(ILRUChain *n) { next = n; }
  2560. virtual void unchain()
  2561. {
  2562. if (prev && next)
  2563. {
  2564. prev->setNext(next);
  2565. next->setPrev(prev);
  2566. }
  2567. next = NULL;
  2568. prev = NULL;
  2569. }
  2570. virtual IRoxieQueryPacket *getDebugResponse(unsigned sequence)
  2571. {
  2572. if (sequence == lastDebugSequence)
  2573. return lastDebugResponse.getLink();
  2574. else if (sequence > lastDebugSequence)
  2575. {
  2576. lastDebugResponse.clear();
  2577. return NULL;
  2578. }
  2579. else
  2580. throwUnexpected();
  2581. }
  2582. virtual void setDebugResponse(unsigned sequence, IRoxieQueryPacket *response)
  2583. {
  2584. lastDebugSequence = sequence;
  2585. lastDebugResponse.set(response);
  2586. }
  2587. };
  2588. class CRoxieServerQueryPacketEndMarker : public CRoxieServerQueryPacket
  2589. {
  2590. public:
  2591. CRoxieServerQueryPacketEndMarker() : CRoxieServerQueryPacket(NULL)
  2592. {
  2593. }
  2594. virtual bool isEnd() const
  2595. {
  2596. return true;
  2597. }
  2598. };
  2599. class CRoxieServerQueryPacketLimitMarker : public CRoxieServerQueryPacket
  2600. {
  2601. unsigned __int64 rowLimit;
  2602. unsigned __int64 keyedLimit;
  2603. unsigned __int64 stopAfter;
  2604. public:
  2605. CRoxieServerQueryPacketLimitMarker(unsigned __int64 _rowLimit, unsigned __int64 _keyedLimit, unsigned __int64 _stopAfter) : CRoxieServerQueryPacket(NULL)
  2606. {
  2607. rowLimit = _rowLimit;
  2608. keyedLimit = _keyedLimit;
  2609. stopAfter = _stopAfter;
  2610. }
  2611. virtual bool isLimit(unsigned __int64 &_rowLimit, unsigned __int64 &_keyedLimit, unsigned __int64 &_stopAfter) const
  2612. {
  2613. _rowLimit = rowLimit;
  2614. _keyedLimit = keyedLimit;
  2615. _stopAfter = stopAfter;
  2616. return true;
  2617. }
  2618. };
  2619. class CRoxieServerSideCache : implements IRoxieServerSideCache, implements ILRUChain
  2620. {
  2621. protected:
  2622. unsigned cacheTableSize;
  2623. unsigned cacheTableSpace;
  2624. IRoxieServerQueryPacket **cacheTable;
  2625. mutable ILRUChain *prev;
  2626. mutable ILRUChain *next;
  2627. mutable CriticalSection crit;
  2628. virtual ILRUChain *queryPrev() const { return prev; }
  2629. virtual ILRUChain *queryNext() const { return next; }
  2630. virtual void setPrev(ILRUChain *p) { prev = p; }
  2631. virtual void setNext(ILRUChain *n) { next = n; }
  2632. virtual void unchain()
  2633. {
  2634. prev->setNext(next);
  2635. next->setPrev(prev);
  2636. next = NULL;
  2637. prev = NULL;
  2638. }
  2639. void moveToHead(IRoxieServerQueryPacket *mru)
  2640. {
  2641. mru->unchain();
  2642. mru->setNext(next);
  2643. next->setPrev(mru);
  2644. mru->setPrev(this);
  2645. next = mru;
  2646. }
  2647. IRoxieServerQueryPacket *removeLRU()
  2648. {
  2649. if (next==this)
  2650. assertex(next != this);
  2651. IRoxieServerQueryPacket *goer = (IRoxieServerQueryPacket *) next;
  2652. goer->unchain(); // NOTE - this will modify the value of next
  2653. return goer;
  2654. }
  2655. void removeEntry(IRoxieServerQueryPacket *goer)
  2656. {
  2657. unsigned v = goer->queryHash() % cacheTableSize;
  2658. loop
  2659. {
  2660. IRoxieServerQueryPacket *found = cacheTable[v];
  2661. assertex(found);
  2662. if (found == goer)
  2663. {
  2664. cacheTable[v] = NULL;
  2665. unsigned vn = v;
  2666. loop
  2667. {
  2668. vn++;
  2669. if (vn==cacheTableSize) vn = 0;
  2670. IRoxieServerQueryPacket *found2 = cacheTable[vn];
  2671. if (!found2)
  2672. break;
  2673. unsigned vm = found2->queryHash() % cacheTableSize;
  2674. if (((vn+cacheTableSize-vm) % cacheTableSize)>=((vn+cacheTableSize-v) % cacheTableSize)) // diff(vn,vm)>=diff(vn,v)
  2675. {
  2676. cacheTable[v] = found2;
  2677. v = vn;
  2678. cacheTable[v] = NULL;
  2679. }
  2680. }
  2681. cacheTableSpace++;
  2682. break;
  2683. }
  2684. v++;
  2685. if (v==cacheTableSize)
  2686. v = 0;
  2687. }
  2688. goer->Release();
  2689. }
  2690. public:
  2691. CRoxieServerSideCache(unsigned _cacheSize)
  2692. {
  2693. cacheTableSize = (_cacheSize*4)/3;
  2694. cacheTable = new IRoxieServerQueryPacket *[cacheTableSize];
  2695. memset(cacheTable, 0, cacheTableSize * sizeof(IRoxieServerQueryPacket *));
  2696. cacheTableSpace = _cacheSize;
  2697. prev = this;
  2698. next = this;
  2699. }
  2700. ~CRoxieServerSideCache()
  2701. {
  2702. for (unsigned i = 0; i < cacheTableSize; i++)
  2703. {
  2704. ::Release(cacheTable[i]);
  2705. }
  2706. delete [] cacheTable;
  2707. }
  2708. virtual IRoxieServerQueryPacket *findCachedResult(const IRoxieContextLogger &logctx, IRoxieQueryPacket *p) const
  2709. {
  2710. unsigned hash = p->hash();
  2711. unsigned et = hash % cacheTableSize;
  2712. if (traceServerSideCache)
  2713. {
  2714. StringBuffer s;
  2715. logctx.CTXLOG("CRoxieServerSideCache::findCachedResult hash %x slot %d %s", hash, et, p->queryHeader().toString(s).str());
  2716. }
  2717. CriticalBlock b(crit);
  2718. loop
  2719. {
  2720. IRoxieServerQueryPacket *found = cacheTable[et];
  2721. if (!found)
  2722. return NULL;
  2723. if (found->queryHash() == hash && found->queryPacket()->cacheMatch(p))
  2724. {
  2725. const_cast<CRoxieServerSideCache *>(this)->moveToHead(found);
  2726. if (traceServerSideCache)
  2727. logctx.CTXLOG("CRoxieServerSideCache::findCachedResult cache hit");
  2728. logctx.noteStatistic(StNumServerCacheHits, 1);
  2729. return NULL;
  2730. // Because IMessageResult cannot be replayed, this scheme is flawed. I'm leaving the code here just as a stats gatherer to see how useful it would have been....
  2731. //IRoxieServerQueryPacket *ret = new CRoxieServerQueryPacket(p);
  2732. //ret->setResult(found->getResult());
  2733. //return ret;
  2734. }
  2735. et++;
  2736. if (et == cacheTableSize)
  2737. et = 0;
  2738. }
  2739. }
  2740. virtual void noteCachedResult(IRoxieServerQueryPacket *out, IMessageResult *in)
  2741. {
  2742. if (true) //!in->getLength()) // MORE - separate caches for hits and nohits
  2743. {
  2744. unsigned hash = out->queryPacket()->hash();
  2745. out->setHash(hash);
  2746. unsigned et = hash % cacheTableSize;
  2747. if (traceServerSideCache)
  2748. {
  2749. StringBuffer s;
  2750. DBGLOG("CRoxieServerSideCache::noteCachedResult hash %x slot %d %s", hash, et, out->queryPacket()->queryHeader().toString(s).str());
  2751. }
  2752. CriticalBlock b(crit);
  2753. loop
  2754. {
  2755. IRoxieServerQueryPacket *found = cacheTable[et];
  2756. if (!found)
  2757. {
  2758. if (cacheTableSpace)
  2759. {
  2760. out->setResult(LINK(in));
  2761. cacheTable[et] = LINK(out);
  2762. cacheTableSpace--;
  2763. moveToHead(out);
  2764. break;
  2765. }
  2766. else
  2767. {
  2768. IRoxieServerQueryPacket *goer = removeLRU();
  2769. removeEntry(goer);
  2770. et = hash % cacheTableSize;
  2771. continue;
  2772. }
  2773. }
  2774. else if (found->queryHash()==hash && found->queryPacket()->cacheMatch(out->queryPacket()))
  2775. {
  2776. moveToHead(found);
  2777. return; // already in the cache. Because we don't cache until we have result, this can happen where
  2778. // multiple copies of a slave query are in-flight at once.
  2779. }
  2780. et++;
  2781. if (et == cacheTableSize)
  2782. et = 0;
  2783. }
  2784. }
  2785. // MORE - do we need to worry about the attachment between the MessageUnpacker and the current row manager. May all fall out ok...
  2786. // Can I easily spot a null result? Do I want to cache null results separately? only?
  2787. }
  2788. // Note that this caching mechanism (unlike the old keyed-join specific one) does not common up cases where multiple
  2789. // identical queries are in-flight at the same time. But if we can make it persistent between queries that will
  2790. // more than make up for it
  2791. };
  2792. class CRowArrayMessageUnpackCursor : implements IMessageUnpackCursor, public CInterface
  2793. {
  2794. ConstPointerArray &data;
  2795. Linked<IMessageResult> result;
  2796. public:
  2797. IMPLEMENT_IINTERFACE;
  2798. CRowArrayMessageUnpackCursor(ConstPointerArray &_data, IMessageResult *_result)
  2799. : data(_data), result(_result)
  2800. {
  2801. }
  2802. virtual bool atEOF() const
  2803. {
  2804. return data.length()==0;
  2805. }
  2806. virtual bool isSerialized() const
  2807. {
  2808. return false;
  2809. }
  2810. virtual const void * getNext(int length)
  2811. {
  2812. if (!data.length())
  2813. return NULL;
  2814. const void *ret = data.item(0);
  2815. data.remove(0);
  2816. return ret;
  2817. }
  2818. };
  2819. // MORE - should possibly move more over to the lazy version used in indexread?
  2820. class CRowArrayMessageResult : implements IMessageResult, public CInterface
  2821. {
  2822. ConstPointerArray data;
  2823. IRowManager &rowManager;
  2824. bool variableSize;
  2825. public:
  2826. IMPLEMENT_IINTERFACE;
  2827. CRowArrayMessageResult(IRowManager &_rowManager, bool _variableSize) : rowManager(_rowManager), variableSize(_variableSize)
  2828. {
  2829. }
  2830. ~CRowArrayMessageResult()
  2831. {
  2832. ReleaseRoxieRows(data);
  2833. }
  2834. virtual IMessageUnpackCursor *getCursor(IRowManager *rowMgr) const
  2835. {
  2836. CRowArrayMessageResult *_this = (CRowArrayMessageResult *) this;
  2837. return new CRowArrayMessageUnpackCursor(_this->data, _this);
  2838. }
  2839. virtual const void *getMessageHeader(unsigned &length) const
  2840. {
  2841. throwUnexpected(); // should never get called - I don't have a header available
  2842. }
  2843. virtual const void *getMessageMetadata(unsigned &length) const
  2844. {
  2845. length = 0;
  2846. return NULL;
  2847. }
  2848. virtual void discard() const
  2849. {
  2850. throwUnexpected();
  2851. }
  2852. void append(const void *row)
  2853. {
  2854. data.append(row);
  2855. }
  2856. };
  2857. void throwRemoteException(IMessageUnpackCursor *extra)
  2858. {
  2859. RecordLengthType *rowlen = (RecordLengthType *) extra->getNext(sizeof(RecordLengthType));
  2860. if (rowlen)
  2861. {
  2862. char *xml = (char *) extra->getNext(*rowlen);
  2863. ReleaseRoxieRow(rowlen);
  2864. Owned<IPropertyTree> p = createPTreeFromXMLString(xml);
  2865. ReleaseRoxieRow(xml);
  2866. unsigned code = p->getPropInt("Code", 0);
  2867. const char *msg = p->queryProp("Message");
  2868. if (!msg)
  2869. msg = xml;
  2870. throw MakeStringException(code, "%s", msg);
  2871. }
  2872. throwUnexpected();
  2873. }
  2874. class CRemoteResultAdaptor : implements IEngineRowStream, implements IFinalRoxieInput, implements IExceptionHandler, public CInterface
  2875. {
  2876. friend class CRemoteResultMerger;
  2877. class CRemoteResultMerger
  2878. {
  2879. class HeapEntry : public CInterface
  2880. {
  2881. private:
  2882. CRemoteResultAdaptor &adaptor;
  2883. IMessageUnpackCursor *cursor;
  2884. public:
  2885. const void *current;
  2886. bool isLast;
  2887. bool lastIsComplete;
  2888. IRoxieServerQueryPacket *packet;
  2889. unsigned seq;
  2890. public:
  2891. inline const void *noteResult(IMessageUnpackCursor *_cursor, bool _lastIsComplete)
  2892. {
  2893. cursor = _cursor;
  2894. lastIsComplete = _lastIsComplete;
  2895. return next();
  2896. }
  2897. public:
  2898. HeapEntry(CRemoteResultAdaptor &_adaptor, IRoxieServerQueryPacket *_packet, unsigned _seq) : adaptor(_adaptor), packet(_packet), seq(_seq)
  2899. {
  2900. cursor = NULL;
  2901. current = NULL;
  2902. isLast = false;
  2903. lastIsComplete = true;
  2904. }
  2905. ~HeapEntry()
  2906. {
  2907. ::Release(packet);
  2908. ::Release(cursor);
  2909. ReleaseRoxieRow(current);
  2910. }
  2911. bool isCompleteMatch() const
  2912. {
  2913. if (!isLast || lastIsComplete)
  2914. return true;
  2915. else
  2916. return false;
  2917. }
  2918. const void *next()
  2919. {
  2920. if (cursor)
  2921. {
  2922. ReleaseClearRoxieRow(current);
  2923. current = adaptor.getRow(cursor);
  2924. isLast = cursor->atEOF();
  2925. if (!current)
  2926. {
  2927. cursor->Release();
  2928. cursor = NULL;
  2929. }
  2930. }
  2931. return current;
  2932. }
  2933. unsigned skipTo(IRangeCompare *compare, const void *seek, unsigned numFields, bool requireExactMatch)
  2934. {
  2935. // MORE - This loop should possibly be a binchop... though it's not absolutely clear that is true (depends on term frequencies)
  2936. unsigned skipped = 0;
  2937. loop
  2938. {
  2939. int c = compare->docompare(current, seek, numFields);
  2940. //If larger than the seek values, then we may be allowed to return an inexact match,
  2941. //if equal then it is required to be an exact match,
  2942. if (c > 0)
  2943. {
  2944. if (!requireExactMatch || isCompleteMatch())
  2945. break;
  2946. }
  2947. else if ((c == 0) && isCompleteMatch())
  2948. break;
  2949. skipped++;
  2950. if (!next())
  2951. break;
  2952. }
  2953. return skipped;
  2954. }
  2955. };
  2956. CRemoteResultAdaptor &adaptor;
  2957. CIArrayOf<HeapEntry> heapEntries;
  2958. UnsignedArray heap;
  2959. IRowManager *rowManager;
  2960. unsigned numPending;
  2961. unsigned numFields;
  2962. bool endSeen;
  2963. bool remakePending;
  2964. IRangeCompare *compare;
  2965. bool deferredContinuation;
  2966. inline int doCompare(unsigned l, unsigned r)
  2967. {
  2968. int ret = compare->docompare(heapEntries.item(l).current, heapEntries.item(r).current, numFields);
  2969. if (!ret) ret = heapEntries.item(l).seq - heapEntries.item(r).seq;
  2970. return ret;
  2971. }
  2972. void makeHeap()
  2973. {
  2974. /* Permute blocks to establish the heap property
  2975. For each element p, the children are p*2+1 and p*2+2 (provided these are in range)
  2976. The children of p must both be greater than or equal to p
  2977. The parent of a child c is given by p = (c-1)/2
  2978. */
  2979. unsigned i;
  2980. unsigned n = heap.length();
  2981. unsigned *s = heap.getArray();
  2982. for (i=1; i<n; i++)
  2983. {
  2984. unsigned r = s[i];
  2985. int c = i; /* child */
  2986. while (c > 0)
  2987. {
  2988. int p = (c-1)/2; /* parent */
  2989. if ( doCompare( s[c], s[p] ) >= 0 )
  2990. break;
  2991. s[c] = s[p];
  2992. s[p] = r;
  2993. c = p;
  2994. }
  2995. }
  2996. remakePending = false;
  2997. }
  2998. void remakeHeap()
  2999. {
  3000. /* The row associated with block[0] will have changed
  3001. This code restores the heap property
  3002. */
  3003. unsigned p = 0; /* parent */
  3004. unsigned n = heap.length();
  3005. unsigned *s = heap.getArray();
  3006. while (1)
  3007. {
  3008. unsigned c = p*2 + 1; /* child */
  3009. if ( c >= n )
  3010. break;
  3011. /* Select smaller child */
  3012. if ( c+1 < n && doCompare( s[c+1], s[c] ) < 0 ) c += 1;
  3013. /* If child is greater or equal than parent then we are done */
  3014. if ( doCompare( s[c], s[p] ) >= 0 )
  3015. break;
  3016. /* Swap parent and child */
  3017. unsigned r = s[c];
  3018. s[c] = s[p];
  3019. s[p] = r;
  3020. /* child becomes parent */
  3021. p = c;
  3022. }
  3023. remakePending = false;
  3024. }
  3025. void append(IRoxieServerQueryPacket *p, unsigned seq)
  3026. {
  3027. HeapEntry &h = *new HeapEntry(adaptor, LINK(p), seq);
  3028. IMessageResult *result = p->queryResult();
  3029. assertex(result);
  3030. if (h.noteResult(result->getCursor(rowManager), isCompleteMatchFlag(result)))
  3031. {
  3032. heapEntries.append(h);
  3033. heap.append(heap.ordinality());
  3034. }
  3035. else
  3036. h.Release();
  3037. }
  3038. void removeHeap(unsigned idx)
  3039. {
  3040. heapEntries.remove(idx);
  3041. ForEachItemIn(i, heap)
  3042. {
  3043. unsigned v = heap.item(i);
  3044. assertex(v != idx);
  3045. if (v > idx)
  3046. heap.replace(v-1, i);
  3047. }
  3048. }
  3049. bool isCompleteMatchFlag(IMessageResult *result)
  3050. {
  3051. unsigned metaLen;
  3052. const byte *metaInfo = (const byte *) result->getMessageMetadata(metaLen);
  3053. if (metaLen)
  3054. {
  3055. unsigned short continuationLen = *(unsigned short *) metaInfo;
  3056. if (continuationLen >= sizeof(bool))
  3057. {
  3058. metaInfo += sizeof(unsigned short);
  3059. return *(bool *) metaInfo;
  3060. }
  3061. }
  3062. return true; // if no continuation info, last row was complete.
  3063. }
  3064. public:
  3065. CRemoteResultMerger(CRemoteResultAdaptor &_adaptor) : adaptor(_adaptor)
  3066. {
  3067. init(NULL, NULL);
  3068. }
  3069. void init(ISteppingMeta *meta, IRowManager *_rowManager)
  3070. {
  3071. if (meta)
  3072. {
  3073. numFields = meta->getNumFields();
  3074. compare = meta->queryCompare();
  3075. }
  3076. else
  3077. {
  3078. numFields = 0;
  3079. compare = NULL;
  3080. }
  3081. rowManager = _rowManager;
  3082. numPending = 0;
  3083. endSeen = false;
  3084. remakePending = false;
  3085. deferredContinuation = false;
  3086. }
  3087. void reset()
  3088. {
  3089. heapEntries.kill();
  3090. heap.kill();
  3091. numPending = 0;
  3092. endSeen = false;
  3093. remakePending = false;
  3094. deferredContinuation = false;
  3095. }
  3096. inline bool noteEndSeen()
  3097. {
  3098. bool hadSeen = endSeen;
  3099. if (!endSeen)
  3100. makeHeap();
  3101. endSeen = true;
  3102. return !hadSeen;
  3103. }
  3104. void noteResult(IRoxieServerQueryPacket *p, unsigned seq)
  3105. {
  3106. if (!p->isContinuation())
  3107. append(p, seq);
  3108. else
  3109. {
  3110. ForEachItemIn(idx, heapEntries)
  3111. {
  3112. HeapEntry &h = heapEntries.item(idx);
  3113. if (h.packet == p)
  3114. {
  3115. IMessageResult *result = p->queryResult();
  3116. if (!h.noteResult(result->getCursor(rowManager), isCompleteMatchFlag(result)))
  3117. {
  3118. heap.zap(idx);
  3119. removeHeap(idx);
  3120. }
  3121. numPending--;
  3122. if (!numPending)
  3123. makeHeap();
  3124. return;
  3125. }
  3126. }
  3127. }
  3128. // If we get here it must be a continuation for one that I have not yet consumed... we don't need to do anything.
  3129. return;
  3130. }
  3131. unsigned skipRows(unsigned &idx, const void *seek, const void *rawSeek, unsigned numFields, unsigned seekLen, const SmartStepExtra & stepExtra)
  3132. {
  3133. HeapEntry &entry = heapEntries.item(idx);
  3134. unsigned skipped = entry.current ? entry.skipTo(compare, seek, numFields, !stepExtra.returnMismatches()) : 0;
  3135. if (!entry.current)
  3136. {
  3137. IRoxieServerQueryPacket *continuation = entry.packet->queryContinuation();
  3138. if (continuation)
  3139. {
  3140. continuation->Link();
  3141. entry.packet->Release();
  3142. entry.packet = continuation;
  3143. if (continuation->hasResult())
  3144. {
  3145. IMessageResult *result = continuation->queryResult();
  3146. bool lastIsCompleteMatch = isCompleteMatchFlag(result);
  3147. entry.noteResult(result->getCursor(rowManager), lastIsCompleteMatch);
  3148. }
  3149. else
  3150. {
  3151. if (continuation->isDelayed())
  3152. {
  3153. continuation->setDelayed(false);
  3154. MemoryBuffer serializedSkip;
  3155. adaptor.activity.serializeSkipInfo(serializedSkip, seekLen, rawSeek, numFields, seek, stepExtra);
  3156. continuation->setPacket(continuation->queryPacket()->insertSkipData(serializedSkip.length(), serializedSkip.toByteArray()));
  3157. ROQ->sendPacket(continuation->queryPacket(), adaptor.activity.queryLogCtx());
  3158. adaptor.sentsome.signal();
  3159. }
  3160. numPending++;
  3161. }
  3162. }
  3163. else
  3164. {
  3165. heap.zap(idx);
  3166. removeHeap(idx);
  3167. idx--;
  3168. }
  3169. }
  3170. return skipped;
  3171. }
  3172. const void * nextRowGE(const void * seek, const void *rawSeek, unsigned numFields, unsigned seeklen, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  3173. {
  3174. // We discard all rows < seekval from all entries in heap
  3175. // If this results in additional slave requests, we return NULL so that we can wait for them
  3176. // If not, we rebuild the heap (if any were skipped) and return the first row
  3177. deferredContinuation = false;
  3178. if (heap.length())
  3179. {
  3180. unsigned skipped = 0;
  3181. unsigned idx = 0;
  3182. while(heapEntries.isItem(idx))
  3183. {
  3184. skipped += skipRows(idx, seek, rawSeek, numFields, seeklen, stepExtra);
  3185. idx++;
  3186. }
  3187. if (numPending)
  3188. return NULL; // can't answer yet, need more results from slaves
  3189. else
  3190. {
  3191. if (skipped)
  3192. makeHeap();
  3193. return next(wasCompleteMatch, stepExtra);
  3194. }
  3195. }
  3196. else
  3197. return NULL;
  3198. }
  3199. bool doContinuation(HeapEntry &topEntry, bool canDefer)
  3200. {
  3201. IRoxieServerQueryPacket *continuation = topEntry.packet->queryContinuation();
  3202. if (continuation)
  3203. {
  3204. if (continuation->isDelayed() && canDefer)
  3205. {
  3206. if (adaptor.activity.queryLogCtx().queryTraceLevel() > 10)
  3207. adaptor.activity.queryLogCtx().CTXLOG("Deferring continuation");
  3208. deferredContinuation = true;
  3209. }
  3210. else
  3211. {
  3212. deferredContinuation = false;
  3213. continuation->Link();
  3214. topEntry.packet->Release();
  3215. topEntry.packet = continuation;
  3216. if (continuation->hasResult())
  3217. {
  3218. IMessageResult *result = continuation->queryResult();
  3219. bool lastIsCompleteMatch = isCompleteMatchFlag(result);
  3220. topEntry.noteResult(result->getCursor(rowManager), lastIsCompleteMatch);
  3221. }
  3222. else
  3223. {
  3224. if (continuation->isDelayed()) // has the continuation been requested yet?
  3225. {
  3226. continuation->Link();
  3227. topEntry.packet->Release();
  3228. topEntry.packet = continuation;
  3229. continuation->setDelayed(false);
  3230. if (adaptor.activity.queryLogCtx().queryTraceLevel() > 10)
  3231. adaptor.activity.queryLogCtx().CTXLOG("About to send continuation, from doContinuation");
  3232. ROQ->sendPacket(continuation->queryPacket(), adaptor.activity.queryLogCtx());
  3233. adaptor.sentsome.signal();
  3234. }
  3235. numPending++; // we are waiting for one that is already in flight
  3236. }
  3237. }
  3238. return true; // next not known yet
  3239. }
  3240. else
  3241. return false;
  3242. }
  3243. const void *next(bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  3244. {
  3245. OwnedConstRoxieRow ret;
  3246. if (heap.length())
  3247. {
  3248. if (deferredContinuation)
  3249. {
  3250. unsigned top = heap.item(0);
  3251. HeapEntry &topEntry = heapEntries.item(top);
  3252. doContinuation(topEntry, false);
  3253. return NULL;
  3254. }
  3255. if (remakePending)
  3256. remakeHeap();
  3257. unsigned top = heap.item(0);
  3258. HeapEntry &topEntry = heapEntries.item(top);
  3259. ret.set(topEntry.current);
  3260. wasCompleteMatch = topEntry.isCompleteMatch();
  3261. const void *next = topEntry.next();
  3262. if (!next)
  3263. {
  3264. if (!doContinuation(topEntry, stepExtra.returnMismatches()))
  3265. {
  3266. unsigned last = heap.popGet();
  3267. if (heap.length())
  3268. heap.replace(last, 0);
  3269. removeHeap(top);
  3270. }
  3271. }
  3272. remakePending = true;
  3273. }
  3274. return ret.getClear();
  3275. }
  3276. bool ready()
  3277. {
  3278. return endSeen && numPending == 0;
  3279. }
  3280. };
  3281. IRoxieServerQueryPacket *createRoxieServerQueryPacket(IRoxieQueryPacket *p, bool &cached)
  3282. {
  3283. if (serverSideCache && !debugContext)
  3284. {
  3285. IRoxieServerQueryPacket *ret = serverSideCache->findCachedResult(activity.queryLogCtx(), p);
  3286. if (ret)
  3287. {
  3288. p->Release();
  3289. cached = true;
  3290. return ret;
  3291. }
  3292. }
  3293. cached = false;
  3294. return new CRoxieServerQueryPacket(p);
  3295. }
  3296. #ifdef _DEBUG
  3297. void dumpPending()
  3298. {
  3299. CriticalBlock b(pendingCrit);
  3300. ForEachItemIn(idx, pending)
  3301. {
  3302. IRoxieServerQueryPacket &p = pending.item(idx);
  3303. StringBuffer s;
  3304. unsigned __int64 dummy;
  3305. if (p.isEnd())
  3306. s.append("END");
  3307. else if (p.isLimit(dummy, dummy, dummy))
  3308. s.append("LIMIT");
  3309. else
  3310. {
  3311. IRoxieQueryPacket *i = p.queryPacket();
  3312. s.appendf("%s", p.hasResult() ? "COMPLETE " : "PENDING ");
  3313. if (i)
  3314. {
  3315. RoxiePacketHeader &header = i->queryHeader();
  3316. header.toString(s);
  3317. }
  3318. }
  3319. DBGLOG("Pending %d %s", idx, s.str());
  3320. }
  3321. }
  3322. #endif
  3323. void abortPending()
  3324. {
  3325. CriticalBlock b(pendingCrit);
  3326. ForEachItemIn(idx, pending)
  3327. {
  3328. IRoxieServerQueryPacket &p = pending.item(idx);
  3329. if (!p.hasResult())
  3330. {
  3331. IRoxieQueryPacket *i = p.queryPacket();
  3332. if (i)
  3333. {
  3334. RoxiePacketHeader &header = i->queryHeader();
  3335. ROQ->sendAbort(header, activity.queryLogCtx());
  3336. }
  3337. }
  3338. }
  3339. pending.kill();
  3340. }
  3341. void checkDelayed()
  3342. {
  3343. if (ctx->queryDebugContext() && ctx->queryDebugContext()->getExecuteSequentially())
  3344. {
  3345. bool allDelayed = true;
  3346. CriticalBlock b(pendingCrit);
  3347. unsigned sendIdx = (unsigned) -1;
  3348. ForEachItemIn(idx, pending)
  3349. {
  3350. IRoxieServerQueryPacket &p = pending.item(idx);
  3351. if (p.queryPacket())
  3352. {
  3353. if (p.isDelayed())
  3354. {
  3355. if (sendIdx == (unsigned) -1)
  3356. sendIdx = idx;
  3357. }
  3358. else if (!p.hasResult())
  3359. {
  3360. allDelayed = false;
  3361. break;
  3362. }
  3363. }
  3364. }
  3365. if (allDelayed && sendIdx != (unsigned) -1)
  3366. {
  3367. if (activity.queryLogCtx().queryTraceLevel() > 10)
  3368. activity.queryLogCtx().CTXLOG("About to send debug-deferred from next");
  3369. pending.item(sendIdx).setDelayed(false);
  3370. ROQ->sendPacket(pending.item(sendIdx).queryPacket(), activity.queryLogCtx());
  3371. sentsome.signal();
  3372. }
  3373. }
  3374. else if (deferredStart)
  3375. {
  3376. CriticalBlock b(pendingCrit);
  3377. ForEachItemIn(idx, pending)
  3378. {
  3379. IRoxieServerQueryPacket &p = pending.item(idx);
  3380. if (p.isDelayed())
  3381. {
  3382. if (activity.queryLogCtx().queryTraceLevel() > 10)
  3383. activity.queryLogCtx().CTXLOG("About to send deferred start from next");
  3384. p.setDelayed(false);
  3385. ROQ->sendPacket(p.queryPacket(), activity.queryLogCtx());
  3386. sentsome.signal();
  3387. }
  3388. }
  3389. deferredStart = false;
  3390. }
  3391. }
  3392. void retryPending()
  3393. {
  3394. CriticalBlock b(pendingCrit);
  3395. checkDelayed();
  3396. ForEachItemIn(idx, pending)
  3397. {
  3398. IRoxieServerQueryPacket &p = pending.item(idx);
  3399. if (!p.hasResult() && !p.isDelayed())
  3400. {
  3401. IRoxieQueryPacket *i = p.queryPacket();
  3402. if (i)
  3403. {
  3404. if (!i->queryHeader().retry())
  3405. {
  3406. StringBuffer s;
  3407. IException *E = MakeStringException(ROXIE_MULTICAST_ERROR, "Failed to get response from slave(s) for %s in activity %d", i->queryHeader().toString(s).str(), activity.queryId());
  3408. activity.queryLogCtx().logOperatorException(E, __FILE__, __LINE__, "CRemoteResultAdaptor::retry");
  3409. throw E;
  3410. }
  3411. if (!localSlave)
  3412. {
  3413. ROQ->sendPacket(i, activity.queryLogCtx());
  3414. atomic_inc(&retriesSent);
  3415. }
  3416. }
  3417. }
  3418. }
  3419. }
  3420. class ChannelBuffer
  3421. {
  3422. protected:
  3423. unsigned bufferLeft;
  3424. MemoryBuffer buffer;
  3425. char *nextBuf;
  3426. unsigned overflowSequence;
  3427. unsigned channel; // == bonded channel
  3428. bool needsFlush;
  3429. InterruptableSemaphore flowController;
  3430. const CRemoteResultAdaptor &owner;
  3431. CriticalSection crit;
  3432. public:
  3433. ChannelBuffer(const CRemoteResultAdaptor &_owner, unsigned _channel) : owner(_owner), channel(_channel), flowController(perChannelFlowLimit)
  3434. {
  3435. overflowSequence = 0;
  3436. needsFlush = false;
  3437. bufferLeft = 0;
  3438. nextBuf = NULL;
  3439. }
  3440. void init(unsigned minSize)
  3441. {
  3442. assertex(!buffer.length());
  3443. if (minSize < MIN_PAYLOAD_SIZE)
  3444. minSize = MIN_PAYLOAD_SIZE;
  3445. unsigned headerSize = sizeof(RoxiePacketHeader)+owner.headerLength();
  3446. unsigned bufferSize = headerSize+minSize;
  3447. if (bufferSize < mtu_size)
  3448. bufferSize = mtu_size;
  3449. buffer.reserveTruncate(bufferSize);
  3450. bufferLeft = bufferSize - headerSize;
  3451. assertex(buffer.toByteArray());
  3452. nextBuf = (char *) buffer.toByteArray() + headerSize;
  3453. needsFlush = false;
  3454. }
  3455. inline IRoxieQueryPacket *flush()
  3456. {
  3457. CriticalBlock cb(crit);
  3458. Owned<IRoxieQueryPacket> ret;
  3459. if (needsFlush)
  3460. {
  3461. buffer.setLength(nextBuf - buffer.toByteArray());
  3462. RoxiePacketHeader *h = (RoxiePacketHeader *) buffer.toByteArray();
  3463. h->init(owner.remoteId, owner.ruid, channel, overflowSequence);
  3464. //patch logPrefix, cachedContext and parent extract into the place reserved in the message buffer
  3465. byte * tgt = (byte*)(h+1);
  3466. owner.copyHeader(tgt, channel);
  3467. ret.setown(createRoxiePacket(buffer));
  3468. if (overflowSequence == OVERFLOWSEQUENCE_MAX)
  3469. overflowSequence = 1; // don't wrap to 0 - that is a bit special
  3470. else
  3471. overflowSequence++;
  3472. needsFlush = false;
  3473. bufferLeft = 0;
  3474. if (owner.flowControlled)
  3475. {
  3476. CriticalUnblock cub(crit);
  3477. while (!flowController.wait(1000))
  3478. {
  3479. StringBuffer s;
  3480. owner.activity.queryLogCtx().CTXLOG("Channel %d blocked by flow control: %s", channel, h->toString(s).str());
  3481. }
  3482. }
  3483. }
  3484. return ret.getClear();
  3485. }
  3486. inline void signal()
  3487. {
  3488. if (owner.flowControlled)
  3489. flowController.signal();
  3490. }
  3491. inline void interrupt(IException *e)
  3492. {
  3493. flowController.interrupt(e);
  3494. }
  3495. inline void *getBuffer(unsigned size)
  3496. {
  3497. CriticalBlock cb(crit);
  3498. if (bufferLeft >= size)
  3499. {
  3500. needsFlush = true;
  3501. void * ret = nextBuf;
  3502. nextBuf += size;
  3503. bufferLeft -= size;
  3504. return ret;
  3505. }
  3506. else if (!needsFlush)
  3507. {
  3508. init(size);
  3509. return getBuffer(size);
  3510. }
  3511. else if (owner.mergeOrder)
  3512. {
  3513. return buffer.reserve(size); // whole query needs to go as single packet if we are to merge
  3514. }
  3515. else
  3516. return NULL; // will force it to flush and start a new packet
  3517. }
  3518. };
  3519. private:
  3520. friend class CRemoteResultMerger;
  3521. bool allread;
  3522. bool contextCached;
  3523. bool preserveOrder;
  3524. InterruptableSemaphore sentsome;
  3525. Owned <IMessageCollator> mc;
  3526. Owned<IMessageUnpackCursor> mu;
  3527. Owned<IMessageResult> mr;
  3528. ChannelBuffer **buffers;
  3529. IHThorArg &helper;
  3530. unsigned __int64 stopAfter;
  3531. unsigned resendSequence;
  3532. IHThorArg *colocalArg;
  3533. IArrayOf<IRoxieServerQueryPacket> pending;
  3534. CriticalSection pendingCrit;
  3535. IRoxieServerSideCache *serverSideCache;
  3536. unsigned sentSequence;
  3537. Owned<IOutputRowDeserializer> deserializer;
  3538. Owned<IEngineRowAllocator> rowAllocator;
  3539. CRemoteResultMerger merger;
  3540. // this is only used to avoid recreating a bufferStream for each row. A better solution may be needed
  3541. MemoryBuffer tempRowBuffer;
  3542. Owned<ISerialStream> bufferStream;
  3543. CThorStreamDeserializerSource rowSource;
  3544. protected:
  3545. IRowManager *rowManager;
  3546. unsigned __int64 rowLimit;
  3547. unsigned __int64 keyedLimit;
  3548. IRoxieServerErrorHandler *errorHandler;
  3549. CachedOutputMetaData meta;
  3550. public:
  3551. ISteppingMeta *mergeOrder;
  3552. IRoxieSlaveContext *ctx;
  3553. IDebuggableContext *debugContext;
  3554. IRoxieServerActivity &activity;
  3555. unsigned parentExtractSize;
  3556. const byte * parentExtract;
  3557. bool flowControlled;
  3558. bool deferredStart;
  3559. MemoryBuffer logInfo;
  3560. MemoryBuffer cachedContext;
  3561. const RemoteActivityId &remoteId;
  3562. ruid_t ruid;
  3563. mutable CriticalSection buffersCrit;
  3564. unsigned processed;
  3565. cycle_t totalCycles;
  3566. bool timeActivities;
  3567. //private: //vc6 doesn't like this being private yet accessed by nested class...
  3568. const void *getRow(IMessageUnpackCursor *mu)
  3569. {
  3570. if (!mu->isSerialized() || (meta.isFixedSize() && !deserializer))
  3571. return mu->getNext(meta.getFixedSize());
  3572. else
  3573. {
  3574. RecordLengthType *rowlen = (RecordLengthType *) mu->getNext(sizeof(RecordLengthType));
  3575. if (rowlen)
  3576. {
  3577. RecordLengthType len = *rowlen;
  3578. ReleaseRoxieRow(rowlen);
  3579. const void *slaveRec = mu->getNext(len);
  3580. if (deserializer && mu->isSerialized())
  3581. {
  3582. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  3583. tempRowBuffer.setBuffer(len, const_cast<void *>(slaveRec), false);
  3584. size_t outsize = deserializer->deserialize(rowBuilder, rowSource);
  3585. ReleaseRoxieRow(slaveRec);
  3586. return rowBuilder.finalizeRowClear(outsize);
  3587. }
  3588. else
  3589. return slaveRec;
  3590. }
  3591. else
  3592. return NULL;
  3593. }
  3594. }
  3595. private:
  3596. ChannelBuffer *queryChannelBuffer(unsigned channel, bool force=false)
  3597. {
  3598. CriticalBlock cb(buffersCrit);
  3599. ChannelBuffer *b = buffers[channel];
  3600. if (!b && force)
  3601. {
  3602. if (!contextCached)
  3603. {
  3604. logInfo.clear();
  3605. unsigned char loggingFlags = LOGGING_FLAGSPRESENT | LOGGING_TRACELEVELSET;
  3606. unsigned char ctxTraceLevel = activity.queryLogCtx().queryTraceLevel() + 1; // Avoid passing a 0
  3607. const QueryOptions &options = ctx->queryOptions();
  3608. if (activity.queryLogCtx().isIntercepted())
  3609. loggingFlags |= LOGGING_INTERCEPTED;
  3610. if (options.timeActivities)
  3611. loggingFlags |= LOGGING_TIMEACTIVITIES;
  3612. if (activity.queryLogCtx().isBlind())
  3613. loggingFlags |= LOGGING_BLIND;
  3614. if (options.checkingHeap)
  3615. loggingFlags |= LOGGING_CHECKINGHEAP;
  3616. if (ctx->queryWorkUnit())
  3617. loggingFlags |= LOGGING_WUID;
  3618. if (debugContext)
  3619. {
  3620. loggingFlags |= LOGGING_DEBUGGERACTIVE;
  3621. logInfo.append(loggingFlags).append(ctxTraceLevel);
  3622. MemoryBuffer bpInfo;
  3623. debugContext->serialize(bpInfo);
  3624. bpInfo.append((__uint64)(memsize_t) &activity);
  3625. logInfo.append((unsigned short) bpInfo.length());
  3626. logInfo.append(bpInfo.length(), bpInfo.toByteArray());
  3627. }
  3628. else
  3629. logInfo.append(loggingFlags).append(ctxTraceLevel);
  3630. StringBuffer logPrefix;
  3631. activity.queryLogCtx().getLogPrefix(logPrefix);
  3632. logInfo.append(logPrefix);
  3633. activity.serializeCreateStartContext(cachedContext.clear());
  3634. activity.serializeExtra(cachedContext);
  3635. if (activity.queryVarFileInfo())
  3636. {
  3637. activity.queryVarFileInfo()->queryTimeStamp().serialize(cachedContext);
  3638. cachedContext.append(activity.queryVarFileInfo()->queryCheckSum());
  3639. }
  3640. contextCached = true;
  3641. }
  3642. b = buffers[channel] = new ChannelBuffer(*this, channel);
  3643. }
  3644. return b;
  3645. }
  3646. void processRow(const void *got)
  3647. {
  3648. processed++;
  3649. if (processed > rowLimit)
  3650. {
  3651. ReleaseRoxieRow(got);
  3652. errorHandler->onLimitExceeded(false); // NOTE - should throw exception
  3653. throwUnexpected();
  3654. }
  3655. else if (processed > keyedLimit)
  3656. {
  3657. ReleaseRoxieRow(got);
  3658. errorHandler->onLimitExceeded(true); // NOTE - should throw exception
  3659. throwUnexpected();
  3660. }
  3661. }
  3662. public:
  3663. IMPLEMENT_IINTERFACE;
  3664. CRemoteResultAdaptor(IRoxieSlaveContext *_ctx, IRoxieServerErrorHandler *_errorHandler, const RemoteActivityId &_remoteId, IOutputMetaData *_meta, IHThorArg &_helper, IRoxieServerActivity &_activity, bool _preserveOrder, bool _flowControlled)
  3665. : remoteId(_remoteId), meta(_meta), activity(_activity), helper(_helper), preserveOrder(_preserveOrder), flowControlled(_flowControlled), merger(*this)
  3666. {
  3667. ctx = _ctx;
  3668. errorHandler = _errorHandler;
  3669. colocalArg = NULL;
  3670. allread = false;
  3671. ruid = 0;
  3672. rowLimit = (unsigned __int64) -1;
  3673. keyedLimit = (unsigned __int64) -1;
  3674. contextCached = false;
  3675. stopAfter = I64C(0x7FFFFFFFFFFFFFFF);
  3676. buffers = new ChannelBuffer*[numChannels+1];
  3677. memset(buffers, 0, (numChannels+1)*sizeof(ChannelBuffer *));
  3678. parentExtractSize = 0;
  3679. rowManager = NULL;
  3680. parentExtract = NULL;
  3681. debugContext = NULL;
  3682. mergeOrder = NULL;
  3683. deferredStart = false;
  3684. processed = 0;
  3685. sentSequence = 0;
  3686. resendSequence = 0;
  3687. totalCycles = 0;
  3688. serverSideCache = activity.queryServerSideCache();
  3689. bufferStream.setown(createMemoryBufferSerialStream(tempRowBuffer));
  3690. rowSource.setStream(bufferStream);
  3691. timeActivities = defaultTimeActivities;
  3692. }
  3693. ~CRemoteResultAdaptor()
  3694. {
  3695. if (mc)
  3696. {
  3697. ROQ->queryReceiveManager()->detachCollator(mc);
  3698. mc.clear();
  3699. }
  3700. for (unsigned channel = 0; channel <= numChannels; channel++)
  3701. {
  3702. delete(buffers[channel]);
  3703. }
  3704. delete [] buffers;
  3705. }
  3706. void setMeta(IOutputMetaData *newmeta)
  3707. {
  3708. meta.set(newmeta);
  3709. }
  3710. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { assertex(whichInput==0); return this; }
  3711. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { assertex(idx==0); return nullptr; }
  3712. virtual IRoxieServerActivity *queryActivity()
  3713. {
  3714. return &activity;
  3715. }
  3716. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  3717. {
  3718. return NULL;
  3719. }
  3720. void setMergeInfo(ISteppingMeta *_mergeOrder)
  3721. {
  3722. mergeOrder = _mergeOrder;
  3723. deferredStart = true;
  3724. }
  3725. void send(IRoxieQueryPacket *p)
  3726. {
  3727. if (p)
  3728. {
  3729. Linked<IRoxieQueryPacket> saver(p); // avoids a race with abortPending, without keeping pendingCrit locked over the send which we might prefer not to
  3730. assertex(p->queryHeader().uid==ruid);
  3731. // MORE: Maybe we should base the fastlane flag on some other
  3732. // criteria !! (i.e A Roxie server prediction based on the
  3733. // activity type/activity behaviour/expected reply size .. etc).
  3734. //
  3735. // Currently (code below) based on high priority, seq=0, and none-child activity.
  3736. // But this could still cause too many reply packets on the fatlane
  3737. // (higher priority output Q), which may cause the activities on the
  3738. // low priority output Q to not get service on time.
  3739. if ((colocalArg == 0) && // not a child query activity??
  3740. (p->queryHeader().activityId & (ROXIE_SLA_PRIORITY | ROXIE_HIGH_PRIORITY)) &&
  3741. (p->queryHeader().overflowSequence == 0) &&
  3742. (p->queryHeader().continueSequence & ~CONTINUE_SEQUENCE_SKIPTO)==0)
  3743. p->queryHeader().retries |= ROXIE_FASTLANE;
  3744. if (p->queryHeader().channel)
  3745. {
  3746. bool cached = false;
  3747. IRoxieServerQueryPacket *rsqp = createRoxieServerQueryPacket(p, cached);
  3748. if (deferredStart)
  3749. rsqp->setDelayed(true);
  3750. rsqp->setSequence(sentSequence++);
  3751. {
  3752. CriticalBlock b(pendingCrit);
  3753. pending.append(*rsqp);
  3754. }
  3755. if (!deferredStart)
  3756. {
  3757. if (!cached)
  3758. ROQ->sendPacket(p, activity.queryLogCtx());
  3759. sentsome.signal();
  3760. }
  3761. }
  3762. else
  3763. {
  3764. // 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
  3765. // Need to add first, then send
  3766. unsigned i;
  3767. bool allCached = true;
  3768. for (i = 1; i <= numChannels; i++)
  3769. {
  3770. IRoxieQueryPacket *q = p->clonePacket(i);
  3771. bool thisChannelCached;
  3772. IRoxieServerQueryPacket *rsqp = createRoxieServerQueryPacket(q, thisChannelCached);
  3773. if (!thisChannelCached)
  3774. allCached = false;
  3775. rsqp->setSequence(sentSequence++);
  3776. if (deferredStart)
  3777. {
  3778. rsqp->setDelayed(true);
  3779. }
  3780. {
  3781. CriticalBlock b(pendingCrit);
  3782. pending.append(*rsqp);
  3783. }
  3784. if (!deferredStart)
  3785. sentsome.signal();
  3786. }
  3787. if (!allCached && !deferredStart)
  3788. ROQ->sendPacket(p, activity.queryLogCtx());
  3789. buffers[0]->signal(); // since replies won't come back on that channel...
  3790. p->Release();
  3791. }
  3792. }
  3793. }
  3794. void *getMem(unsigned partNo, unsigned fileNo, unsigned size)
  3795. {
  3796. unsigned channel = partNo ? getBondedChannel(partNo) : 0;
  3797. size += sizeof(PartNoType);
  3798. ChannelBuffer *b = queryChannelBuffer(channel, true);
  3799. char *buffer = (char *) b->getBuffer(size);
  3800. if (!buffer)
  3801. {
  3802. send(b->flush());
  3803. buffer = (char *) b->getBuffer(size);
  3804. }
  3805. PartNoType sp;
  3806. sp.partNo = partNo;
  3807. sp.fileNo = fileNo;
  3808. memcpy(buffer, &sp, sizeof(sp));
  3809. buffer += sizeof(sp);
  3810. return buffer;
  3811. }
  3812. void injectResult(IMessageResult *result)
  3813. {
  3814. IRoxieServerQueryPacket *f = new CRoxieServerQueryPacket(NULL);
  3815. f->setSequence(sentSequence++);
  3816. f->setResult(result);
  3817. CriticalBlock b(pendingCrit);
  3818. pending.append(*f);
  3819. sentsome.signal(); // MORE - arguably should only send if there is any point waking up the listener thread, to save context swicth
  3820. }
  3821. void flush()
  3822. {
  3823. for (unsigned channel = 0; channel <= numChannels; channel++)
  3824. {
  3825. ChannelBuffer *b = queryChannelBuffer(channel, false);
  3826. if (b)
  3827. send(b->flush());
  3828. }
  3829. }
  3830. void interruptBuffers(IException *e)
  3831. {
  3832. for (unsigned channel = 0; channel <= numChannels; channel++)
  3833. {
  3834. ChannelBuffer *b = queryChannelBuffer(channel, false);
  3835. if (b)
  3836. b->interrupt(LINK(e));
  3837. }
  3838. }
  3839. void senddone()
  3840. {
  3841. CriticalBlock b(pendingCrit);
  3842. pending.append(*new CRoxieServerQueryPacketEndMarker);
  3843. sentsome.signal();
  3844. }
  3845. bool fireException(IException *e)
  3846. {
  3847. {
  3848. CriticalBlock b(pendingCrit);
  3849. pending.append(*new CRoxieServerQueryPacketEndMarker);
  3850. }
  3851. interruptBuffers(e);
  3852. if (mc)
  3853. mc->interrupt(LINK(e));
  3854. sentsome.interrupt(e);
  3855. return true;
  3856. }
  3857. virtual void onCreate(IHThorArg *_colocalArg)
  3858. {
  3859. debugContext = ctx->queryDebugContext();
  3860. colocalArg = _colocalArg;
  3861. if (meta.needsSerializeDisk())
  3862. {
  3863. deserializer.setown(meta.createDiskDeserializer(ctx->queryCodeContext(), activity.queryId()));
  3864. rowAllocator.setown(activity.createRowAllocator(meta.queryOriginal()));
  3865. }
  3866. if (ctx->queryDebugContext() && ctx->queryDebugContext()->getExecuteSequentially())
  3867. deferredStart = true;
  3868. timeActivities = ctx->queryOptions().timeActivities;
  3869. }
  3870. virtual void onStart(unsigned _parentExtractSize, const byte * _parentExtract)
  3871. {
  3872. #ifdef TRACE_STARTSTOP
  3873. if (traceStartStop)
  3874. activity.queryLogCtx().CTXLOG("RRAonstart");
  3875. #endif
  3876. sentsome.reinit();
  3877. ruid = getNextRuid();
  3878. rowManager = &ctx->queryRowManager();
  3879. if (mergeOrder)
  3880. merger.init(mergeOrder, rowManager);
  3881. if (mc)
  3882. {
  3883. ROQ->queryReceiveManager()->detachCollator(mc); // Should never happen - implies someone forgot to call onReset!
  3884. }
  3885. mc.setown(ROQ->queryReceiveManager()->createMessageCollator(rowManager, ruid));
  3886. allread = false;
  3887. mu.clear();
  3888. contextCached = false;
  3889. processed = 0;
  3890. resendSequence = 0;
  3891. sentSequence = 0;
  3892. for (unsigned channel = 0; channel <= numChannels; channel++)
  3893. {
  3894. delete(buffers[channel]);
  3895. buffers[channel] = NULL;
  3896. }
  3897. flush();
  3898. parentExtractSize = _parentExtractSize;
  3899. parentExtract = _parentExtract;
  3900. }
  3901. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  3902. {
  3903. #ifdef TRACE_STARTSTOP
  3904. if (traceStartStop)
  3905. activity.queryLogCtx().CTXLOG("RRAstart");
  3906. #endif
  3907. activity.start(parentExtractSize, parentExtract, paused);
  3908. }
  3909. void setLimits(unsigned __int64 _rowLimit, unsigned __int64 _keyedLimit, unsigned __int64 _stopAfter)
  3910. {
  3911. if (ctx->queryProbeManager())
  3912. {
  3913. if (_rowLimit != (unsigned __int64) -1) ctx->queryProbeManager()->setNodePropertyInt(&activity, "rowLimit", _rowLimit);
  3914. if (_keyedLimit != (unsigned __int64) -1) ctx->queryProbeManager()->setNodePropertyInt(&activity, "keyedLimit", _keyedLimit);
  3915. if (_stopAfter != I64C(0x7FFFFFFFFFFFFFFF)) ctx->queryProbeManager()->setNodePropertyInt(&activity, "choosenLimit", _stopAfter);
  3916. }
  3917. {
  3918. CriticalBlock b(pendingCrit);
  3919. if (pending.length())
  3920. {
  3921. #ifdef _DEBUG
  3922. dumpPending(); // MORE - only defined in debug build - could have put the ifdef inside the dumpPending method
  3923. #endif
  3924. assertex(pending.length()==0);
  3925. }
  3926. pending.append(*new CRoxieServerQueryPacketLimitMarker(_rowLimit, _keyedLimit, _stopAfter));
  3927. }
  3928. sentsome.signal();
  3929. rowLimit = _rowLimit;
  3930. keyedLimit = _keyedLimit;
  3931. stopAfter = _stopAfter;
  3932. }
  3933. virtual void stop()
  3934. {
  3935. #ifdef TRACE_STARTSTOP
  3936. if (traceStartStop)
  3937. activity.queryLogCtx().CTXLOG("RRAstop");
  3938. #endif
  3939. onStop();
  3940. activity.stop();
  3941. }
  3942. void onStop()
  3943. {
  3944. #ifdef TRACE_STARTSTOP
  3945. if (traceStartStop)
  3946. activity.queryLogCtx().CTXLOG("RRAonstop");
  3947. #endif
  3948. abortPending();
  3949. interruptBuffers(NULL);
  3950. sentsome.interrupt();
  3951. if (mc) // May not be set if start() chain threw exception
  3952. mc->interrupt();
  3953. }
  3954. virtual void reset()
  3955. {
  3956. #ifdef TRACE_STARTSTOP
  3957. if (traceStartStop)
  3958. activity.queryLogCtx().CTXLOG("RRAreset");
  3959. #endif
  3960. activity.reset();
  3961. onReset();
  3962. }
  3963. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  3964. {
  3965. // Make sure parent activity calls up the tree
  3966. PointerArrayOf<IEngineRowStream> instreams;
  3967. IStrandJunction *junction = activity.getOutputStreams(ctx, idx, instreams, consumerOptions, consumerOrdered, orderedCallbacks);
  3968. assertex (junction == NULL);
  3969. // I return a single strand (we could change that sometime I guess...)
  3970. streams.append(this);
  3971. return NULL;
  3972. }
  3973. virtual void resetEOF()
  3974. {
  3975. throwUnexpected();
  3976. }
  3977. virtual void onReset()
  3978. {
  3979. #ifdef TRACE_STARTSTOP
  3980. if (traceStartStop)
  3981. activity.queryLogCtx().CTXLOG("RRAonreset");
  3982. #endif
  3983. if (mc)
  3984. ROQ->queryReceiveManager()->detachCollator(mc);
  3985. merger.reset();
  3986. pending.kill();
  3987. if (mc && ctx)
  3988. ctx->addSlavesReplyLen(mc->queryBytesReceived());
  3989. mc.clear(); // Or we won't free memory for graphs that get recreated
  3990. mu.clear(); //ditto
  3991. deferredStart = false;
  3992. // NOTE: do NOT clear mergeOrder - this is set at create time not per child query
  3993. }
  3994. virtual IOutputMetaData * queryOutputMeta() const
  3995. {
  3996. return helper.queryOutputMeta();
  3997. }
  3998. virtual unsigned __int64 queryTotalCycles() const
  3999. {
  4000. return totalCycles;
  4001. }
  4002. const void * nextRowGE(const void *seek, const void *rawSeek, unsigned numFields, unsigned seekLen, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  4003. {
  4004. if (activity.queryLogCtx().queryTraceLevel() > 20)
  4005. {
  4006. StringBuffer recstr;
  4007. unsigned i;
  4008. for (i = 0; i < seekLen; i++)
  4009. {
  4010. recstr.appendf("%02x ", ((unsigned char *) rawSeek)[i]);
  4011. }
  4012. activity.queryLogCtx().CTXLOG("CRemoteResultAdaptor::nextRowGE(rawSeek=%s numFields=%d, seeklen=%d, returnMismatches=%d)", recstr.str(), numFields, seekLen, stepExtra.returnMismatches());
  4013. }
  4014. assertex(mergeOrder);
  4015. if (deferredStart)
  4016. {
  4017. CriticalBlock b(pendingCrit);
  4018. ForEachItemIn(idx, pending)
  4019. {
  4020. IRoxieServerQueryPacket &p = pending.item(idx);
  4021. if (p.isDelayed())
  4022. {
  4023. p.setDelayed(false);
  4024. if (activity.queryLogCtx().queryTraceLevel() > 10)
  4025. activity.queryLogCtx().CTXLOG("About to send deferred start from nextRowGE, setting requireExact to %d", !stepExtra.returnMismatches());
  4026. MemoryBuffer serializedSkip;
  4027. activity.serializeSkipInfo(serializedSkip, seekLen, rawSeek, numFields, seek, stepExtra);
  4028. p.setPacket(p.queryPacket()->insertSkipData(serializedSkip.length(), serializedSkip.toByteArray()));
  4029. ROQ->sendPacket(p.queryPacket(), activity.queryLogCtx());
  4030. sentsome.signal();
  4031. }
  4032. }
  4033. deferredStart = false;
  4034. }
  4035. SimpleActivityTimer t(totalCycles, timeActivities);
  4036. if (processed==stopAfter)
  4037. return NULL;
  4038. if (allread)
  4039. return NULL;
  4040. loop
  4041. {
  4042. if (merger.ready())
  4043. {
  4044. const void *got = merger.nextRowGE(seek, rawSeek, numFields, seekLen, wasCompleteMatch, stepExtra);
  4045. if (got)
  4046. {
  4047. processRow(got);
  4048. return got;
  4049. }
  4050. }
  4051. if (!reload()) // MORE - should pass the seek info here...
  4052. return NULL;
  4053. }
  4054. }
  4055. virtual const void *nextRow()
  4056. {
  4057. // If we are merging then we need to do a heapsort on all
  4058. SimpleActivityTimer t(totalCycles, timeActivities);
  4059. if (activity.queryLogCtx().queryTraceLevel() > 10)
  4060. {
  4061. activity.queryLogCtx().CTXLOG("CRemoteResultAdaptor::nextRow()");
  4062. }
  4063. loop
  4064. {
  4065. checkDelayed();
  4066. if (processed==stopAfter)
  4067. return NULL;
  4068. if (allread)
  4069. return NULL;
  4070. // If we can still consume from the merger or the most recently retrieved mu, do so.
  4071. const void *got = NULL;
  4072. if (mergeOrder && merger.ready())
  4073. {
  4074. bool matched = true;
  4075. got = merger.next(matched, dummySmartStepExtra);
  4076. }
  4077. else if (mu)
  4078. got = getRow(mu);
  4079. if (got)
  4080. {
  4081. processRow(got);
  4082. return got;
  4083. }
  4084. if (!reload())
  4085. return NULL;
  4086. }
  4087. }
  4088. bool reload()
  4089. {
  4090. // Wait for something to be returned from a slave....
  4091. mu.clear();
  4092. sentsome.wait();
  4093. // must be at least an endMarker on the queue since sentsome was signalled
  4094. {
  4095. CriticalBlock b(pendingCrit);
  4096. IRoxieServerQueryPacket &top = pending.item(0);
  4097. if (top.isLimit(rowLimit, keyedLimit, stopAfter)) // This is really a start marker...
  4098. {
  4099. pending.remove(0);
  4100. return true;
  4101. }
  4102. else if (top.isEnd())
  4103. {
  4104. pending.remove(0);
  4105. allread = true;
  4106. if (activity.queryLogCtx().queryTraceLevel() > 5)
  4107. activity.queryLogCtx().CTXLOG("All read on ruid %x", ruid);
  4108. return false;
  4109. }
  4110. else if (mergeOrder)
  4111. {
  4112. unsigned idx = 0;
  4113. bool added = false;
  4114. while (pending.isItem(idx))
  4115. {
  4116. IRoxieServerQueryPacket &item = pending.item(idx);
  4117. if (item.isEnd())
  4118. {
  4119. if (merger.noteEndSeen())
  4120. {
  4121. sentsome.signal(); // Because we waited, yet didn't actually consume anything
  4122. added = true;
  4123. }
  4124. break;
  4125. }
  4126. else if (item.hasResult())
  4127. {
  4128. merger.noteResult(&item, item.getSequence());
  4129. pending.remove(idx);
  4130. added = true;
  4131. }
  4132. else if (item.isContinuation())
  4133. idx++;
  4134. else
  4135. break;
  4136. }
  4137. if (added)
  4138. return true;
  4139. }
  4140. else if (top.hasResult())
  4141. {
  4142. mr.setown(pending.item(0).getResult());
  4143. mu.setown(mr->getCursor(rowManager));
  4144. pending.remove(0);
  4145. return true;
  4146. }
  4147. }
  4148. getNextUnpacker();
  4149. return true;
  4150. }
  4151. void getNextUnpacker()
  4152. {
  4153. mu.clear();
  4154. unsigned ctxTraceLevel = activity.queryLogCtx().queryTraceLevel();
  4155. loop
  4156. {
  4157. checkDelayed();
  4158. unsigned timeout = remoteId.isSLAPriority() ? slaTimeout : (remoteId.isHighPriority() ? highTimeout : lowTimeout);
  4159. activity.queryContext()->checkAbort();
  4160. bool anyActivity;
  4161. if (ctxTraceLevel > 5)
  4162. activity.queryLogCtx().CTXLOG("Calling getNextUnpacker(%d)", timeout);
  4163. mr.setown(mc->getNextResult(timeout, anyActivity));
  4164. if (ctxTraceLevel > 6)
  4165. activity.queryLogCtx().CTXLOG("Called getNextUnpacker(%d), activity=%d", timeout, anyActivity);
  4166. activity.queryContext()->checkAbort();
  4167. if (mr)
  4168. {
  4169. unsigned roxieHeaderLen;
  4170. const RoxiePacketHeader &header = *(const RoxiePacketHeader *) mr->getMessageHeader(roxieHeaderLen);
  4171. #ifdef _DEBUG
  4172. assertex(roxieHeaderLen == sizeof(RoxiePacketHeader));
  4173. #endif
  4174. if (ctxTraceLevel > 5)
  4175. {
  4176. StringBuffer s;
  4177. activity.queryLogCtx().CTXLOG("getNextUnpacker got packet %s", header.toString(s).str());
  4178. }
  4179. CriticalBlock b(pendingCrit);
  4180. unsigned idx = 0;
  4181. IRoxieServerQueryPacket *original = NULL;
  4182. IRoxieQueryPacket *op;
  4183. while (pending.isItem(idx))
  4184. {
  4185. original = &pending.item(idx);
  4186. op = original->queryPacket();
  4187. if (op && header.matchPacket(op->queryHeader()))
  4188. break;
  4189. original = NULL;
  4190. idx++;
  4191. }
  4192. if (!original || original->hasResult())
  4193. {
  4194. switch (header.activityId)
  4195. {
  4196. case ROXIE_FILECALLBACK:
  4197. {
  4198. // tell slave to abort
  4199. //if (ctxTraceLevel > 5)
  4200. {
  4201. StringBuffer s;
  4202. activity.queryLogCtx().CTXLOG("Redundant callback on query %s", header.toString(s).str());
  4203. }
  4204. Owned<IMessageUnpackCursor> callbackData = mr->getCursor(rowManager);
  4205. OwnedConstRoxieRow len = callbackData->getNext(sizeof(RecordLengthType));
  4206. if (len)
  4207. {
  4208. RecordLengthType *rowlen = (RecordLengthType *) len.get();
  4209. OwnedConstRoxieRow row = callbackData->getNext(*rowlen);
  4210. const char *rowdata = (const char *) row.get();
  4211. // bool isOpt = * (bool *) rowdata;
  4212. // bool isLocal = * (bool *) (rowdata+1);
  4213. ROQ->sendAbortCallback(header, rowdata+2, activity.queryLogCtx());
  4214. }
  4215. else
  4216. throwUnexpected();
  4217. break;
  4218. }
  4219. // MORE - ROXIE_ALIVE perhaps should go here too
  4220. default:
  4221. if (ctxTraceLevel > 3)
  4222. activity.queryLogCtx().CTXLOG("Discarding packet %p - original %p is NULL or has result already", mr.get(), original);
  4223. mr->discard();
  4224. break;
  4225. }
  4226. mr.clear();
  4227. }
  4228. else
  4229. {
  4230. atomic_inc(&resultsReceived);
  4231. switch (header.activityId)
  4232. {
  4233. case ROXIE_DEBUGCALLBACK:
  4234. {
  4235. Owned<IMessageUnpackCursor> callbackData = mr->getCursor(rowManager);
  4236. OwnedConstRoxieRow len = callbackData->getNext(sizeof(RecordLengthType));
  4237. if (len)
  4238. {
  4239. RecordLengthType *rowlen = (RecordLengthType *) len.get();
  4240. OwnedConstRoxieRow row = callbackData->getNext(*rowlen);
  4241. char *rowdata = (char *) row.get();
  4242. if (ctxTraceLevel > 5)
  4243. {
  4244. StringBuffer s;
  4245. activity.queryLogCtx().CTXLOG("Callback on query %s for debug", header.toString(s).str());
  4246. }
  4247. MemoryBuffer slaveInfo;
  4248. slaveInfo.setBuffer(*rowlen, rowdata, false);
  4249. unsigned debugSequence;
  4250. slaveInfo.read(debugSequence);
  4251. Owned<IRoxieQueryPacket> reply = original->getDebugResponse(debugSequence);
  4252. if (!reply)
  4253. reply.setown(activity.queryContext()->queryDebugContext()->onDebugCallback(header, *rowlen, rowdata));
  4254. if (reply)
  4255. {
  4256. original->setDebugResponse(debugSequence, reply);
  4257. ROQ->sendPacket(reply, activity.queryLogCtx());
  4258. }
  4259. }
  4260. else
  4261. throwUnexpected();
  4262. // MORE - somehow we need to make sure slave gets a reply even if I'm not waiting (in udp layer)
  4263. // Leave original message on pending queue in original location - this is not a reply to it.
  4264. break;
  4265. }
  4266. case ROXIE_FILECALLBACK:
  4267. {
  4268. // we need to send back to the slave a message containing the file info requested.
  4269. Owned<IMessageUnpackCursor> callbackData = mr->getCursor(rowManager);
  4270. OwnedConstRoxieRow len = callbackData->getNext(sizeof(RecordLengthType));
  4271. if (len)
  4272. {
  4273. RecordLengthType *rowlen = (RecordLengthType *) len.get();
  4274. OwnedConstRoxieRow row = callbackData->getNext(*rowlen);
  4275. const char *rowdata = (const char *) row.get();
  4276. bool isOpt = * (bool *) rowdata;
  4277. bool isLocal = * (bool *) (rowdata+1);
  4278. const char *lfn = rowdata+2;
  4279. if (ctxTraceLevel > 5)
  4280. {
  4281. StringBuffer s;
  4282. activity.queryLogCtx().CTXLOG("Callback on query %s file %s", header.toString(s).str(),(const char *) lfn);
  4283. }
  4284. activity.queryContext()->onFileCallback(header, lfn, isOpt, isLocal);
  4285. }
  4286. else
  4287. throwUnexpected();
  4288. // MORE - somehow we need to make sure slave gets a reply even if I'm not waiting (in udp layer)
  4289. // Leave original message on pending queue in original location - this is not a reply to it.
  4290. break;
  4291. }
  4292. case ROXIE_KEYEDLIMIT_EXCEEDED:
  4293. activity.queryLogCtx().CTXLOG("ROXIE_KEYEDLIMIT_EXCEEDED");
  4294. errorHandler->onLimitExceeded(true); // NOTE - should throw exception!
  4295. throwUnexpected();
  4296. case ROXIE_LIMIT_EXCEEDED:
  4297. activity.queryLogCtx().CTXLOG("ROXIE_LIMIT_EXCEEDED");
  4298. errorHandler->onLimitExceeded(false); // NOTE - should throw exception!
  4299. throwUnexpected();
  4300. case ROXIE_TRACEINFO:
  4301. {
  4302. Owned<IMessageUnpackCursor> extra = mr->getCursor(rowManager);
  4303. loop
  4304. {
  4305. RecordLengthType *rowlen = (RecordLengthType *) extra->getNext(sizeof(RecordLengthType));
  4306. if (rowlen)
  4307. {
  4308. char *logInfo = (char *) extra->getNext(*rowlen);
  4309. MemoryBuffer buf;
  4310. buf.setBuffer(*rowlen, logInfo, false);
  4311. switch ((TracingCategory) *logInfo)
  4312. {
  4313. case LOG_TRACING:
  4314. case LOG_ERROR:
  4315. activity.queryLogCtx().CTXLOGl(new LogItem(buf));
  4316. break;
  4317. case LOG_STATVALUES:
  4318. buf.skip(1);
  4319. activity.mergeStats(buf);
  4320. break;
  4321. case LOG_CHILDCOUNT:
  4322. case LOG_CHILDSTATS:
  4323. unsigned graphId, childId;
  4324. buf.skip(1);
  4325. buf.read(graphId);
  4326. buf.read(childId);
  4327. if (*logInfo == LOG_CHILDCOUNT)
  4328. {
  4329. unsigned idx;
  4330. unsigned childProcessed;
  4331. unsigned childStrands;
  4332. buf.read(idx);
  4333. buf.read(childProcessed);
  4334. buf.read(childStrands);
  4335. if (traceLevel > 5)
  4336. activity.queryLogCtx().CTXLOG("Processing ChildCount %d idx %d strands %d for child %d subgraph %d", childProcessed, idx, childStrands, childId, graphId);
  4337. activity.queryContext()->noteProcessed(graphId, childId, idx, childProcessed, childStrands);
  4338. }
  4339. else
  4340. {
  4341. ActivityTimeAccumulator dummy; // We could serialize from slave? Would get confusing though
  4342. CRuntimeStatisticCollection childStats(allStatistics);
  4343. childStats.deserialize(buf);
  4344. if (traceLevel > 5)
  4345. {
  4346. StringBuffer s;
  4347. activity.queryLogCtx().CTXLOG("Processing ChildStats for child %d subgraph %d: %s", childId, graphId, childStats.toStr(s).str());
  4348. }
  4349. activity.queryContext()->mergeActivityStats(childStats, graphId, childId, dummy, 0);
  4350. }
  4351. }
  4352. ReleaseRoxieRow(rowlen);
  4353. ReleaseRoxieRow(logInfo);
  4354. }
  4355. else
  4356. break;
  4357. }
  4358. break;
  4359. }
  4360. case ROXIE_EXCEPTION:
  4361. if (ctxTraceLevel > 1)
  4362. {
  4363. StringBuffer s;
  4364. activity.queryLogCtx().CTXLOG("Exception on query %s", header.toString(s).str());
  4365. }
  4366. op->queryHeader().noteException(header.retries);
  4367. if (op->queryHeader().allChannelsFailed())
  4368. {
  4369. activity.queryLogCtx().CTXLOG("Multiple exceptions on query - aborting");
  4370. Owned<IMessageUnpackCursor> exceptionData = mr->getCursor(rowManager);
  4371. throwRemoteException(exceptionData);
  4372. }
  4373. // Leave it on pending queue in original location
  4374. break;
  4375. case ROXIE_ALIVE:
  4376. if (ctxTraceLevel > 4)
  4377. {
  4378. StringBuffer s;
  4379. activity.queryLogCtx().CTXLOG("ROXIE_ALIVE: %s", header.toString(s).str());
  4380. }
  4381. op->queryHeader().noteAlive(header.retries & ROXIE_RETRIES_MASK);
  4382. // Leave it on pending queue in original location
  4383. break;
  4384. default:
  4385. if (header.retries & ROXIE_RETRIES_MASK)
  4386. atomic_inc(&retriesNeeded);
  4387. unsigned metaLen;
  4388. const void *metaData = mr->getMessageMetadata(metaLen);
  4389. if (metaLen)
  4390. {
  4391. // We got back first chunk but there is more.
  4392. // resend the packet, with the cursor info provided.
  4393. // MORE - if smart-stepping, we don't want to send the continuation immediately. Other cases it's not clear that we do.
  4394. if (ctxTraceLevel > 1)
  4395. {
  4396. StringBuffer s;
  4397. activity.queryLogCtx().CTXLOG("Additional data size %d on query %s mergeOrder %p", metaLen, header.toString(s).str(), mergeOrder);
  4398. }
  4399. if (*((unsigned short *) metaData) + sizeof(unsigned short) != metaLen)
  4400. {
  4401. StringBuffer s;
  4402. activity.queryLogCtx().CTXLOG("Additional data size %d on query %s mergeOrder %p", metaLen, header.toString(s).str(), mergeOrder);
  4403. activity.queryLogCtx().CTXLOG("Additional data is corrupt");
  4404. throwUnexpected();
  4405. }
  4406. MemoryBuffer nextQuery;
  4407. nextQuery.append(sizeof(RoxiePacketHeader), &header);
  4408. nextQuery.append(metaLen, metaData);
  4409. nextQuery.append(op->getTraceLength(), op->queryTraceInfo());
  4410. nextQuery.append(op->getContextLength(), op->queryContextData());
  4411. if (resendSequence == CONTINUESEQUENCE_MAX)
  4412. {
  4413. activity.queryLogCtx().CTXLOG("ERROR: Continuation sequence wrapped"); // shouldn't actually matter.... but suggests a very iffy query!
  4414. resendSequence = 1;
  4415. }
  4416. else
  4417. resendSequence++;
  4418. RoxiePacketHeader *newHeader = (RoxiePacketHeader *) nextQuery.toByteArray();
  4419. newHeader->continueSequence = resendSequence; // NOTE - we clear the skipTo flag since continuation of a skip is NOT a skip...
  4420. newHeader->retries &= ~ROXIE_RETRIES_MASK;
  4421. IRoxieQueryPacket *resend = createRoxiePacket(nextQuery);
  4422. CRoxieServerQueryPacket *fqp = new CRoxieServerQueryPacket(resend);
  4423. fqp->setSequence(original->getSequence());
  4424. pending.add(*fqp, idx+1); // note that pending takes ownership. sendPacket does not release.
  4425. original->setContinuation(LINK(fqp));
  4426. if (mergeOrder)
  4427. fqp->setDelayed(true);
  4428. else
  4429. {
  4430. ROQ->sendPacket(resend, activity.queryLogCtx());
  4431. sentsome.signal();
  4432. }
  4433. // Note that we don't attempt to cache results that have continuation records - too tricky !
  4434. }
  4435. else
  4436. {
  4437. if (serverSideCache)
  4438. serverSideCache->noteCachedResult(original, mr);
  4439. }
  4440. unsigned channel = header.channel;
  4441. {
  4442. ChannelBuffer *b = queryChannelBuffer(channel); // If not something is wrong, or we sent out on channel 0?
  4443. if (b)
  4444. b->signal();
  4445. }
  4446. original->setResult(mr.getClear());
  4447. sentsome.signal();
  4448. return;
  4449. }
  4450. }
  4451. }
  4452. else
  4453. {
  4454. if (!anyActivity && !localSlave)
  4455. {
  4456. activity.queryLogCtx().CTXLOG("Input has stalled - retry required?");
  4457. retryPending();
  4458. }
  4459. }
  4460. }
  4461. }
  4462. inline unsigned headerLength() const
  4463. {
  4464. return logInfo.length() + cachedContext.length() + sizeof(unsigned) + parentExtractSize;
  4465. }
  4466. void copyHeader(byte *tgt, unsigned channel) const
  4467. {
  4468. unsigned len = logInfo.length();
  4469. memcpy(tgt, logInfo.toByteArray(), len);
  4470. tgt += len;
  4471. *(unsigned *) tgt = parentExtractSize;
  4472. tgt += sizeof(unsigned);
  4473. memcpy(tgt, parentExtract, parentExtractSize);
  4474. tgt += parentExtractSize;
  4475. memcpy(tgt, cachedContext.toByteArray(), cachedContext.length());
  4476. tgt += cachedContext.length();
  4477. }
  4478. };
  4479. class CSkippableRemoteResultAdaptor : public CRemoteResultAdaptor
  4480. {
  4481. Owned <IException> exception;
  4482. bool skipping;
  4483. ConstPointerArray buff;
  4484. unsigned index;
  4485. bool pulled;
  4486. void pullInput()
  4487. {
  4488. try
  4489. {
  4490. if (exception)
  4491. throw exception.getClear();
  4492. unsigned __int64 count = 0;
  4493. loop
  4494. {
  4495. const void * next = CRemoteResultAdaptor::nextRow();
  4496. if (next == NULL)
  4497. {
  4498. next = CRemoteResultAdaptor::nextRow();
  4499. if(next == NULL)
  4500. break;
  4501. buff.append(NULL);
  4502. }
  4503. count++;
  4504. if (count > rowLimit)
  4505. {
  4506. ReleaseRoxieRow(next);
  4507. ReleaseRoxieRows(buff);
  4508. errorHandler->onLimitExceeded(false); // throws an exception - user or LimitSkipException
  4509. throwUnexpected();
  4510. }
  4511. else if (count > keyedLimit)
  4512. {
  4513. ReleaseRoxieRow(next);
  4514. ReleaseRoxieRows(buff);
  4515. errorHandler->onLimitExceeded(true); // throws an exception - user or LimitSkipException
  4516. throwUnexpected();
  4517. }
  4518. buff.append(next);
  4519. }
  4520. }
  4521. catch (IException *E)
  4522. {
  4523. if (QUERYINTERFACE(E, LimitSkipException))
  4524. {
  4525. Owned<IException> cleanup = E;
  4526. ReleaseRoxieRows(buff);
  4527. const void *onfail = errorHandler->createLimitFailRow(E->errorCode() == KeyedLimitSkipErrorCode);
  4528. if (onfail)
  4529. buff.append(onfail);
  4530. }
  4531. else
  4532. throw;
  4533. }
  4534. pulled = true;
  4535. }
  4536. public:
  4537. CSkippableRemoteResultAdaptor(IRoxieSlaveContext *_ctx, IRoxieServerErrorHandler *_errorHandler, const RemoteActivityId &_remoteId, IOutputMetaData *_meta, IHThorArg &_helper, IRoxieServerActivity &_activity, bool _preserveOrder, bool _flowControlled, bool _skipping) :
  4538. CRemoteResultAdaptor(_ctx, _errorHandler, _remoteId, _meta, _helper, _activity, _preserveOrder, _flowControlled)
  4539. {
  4540. skipping = _skipping;
  4541. index = 0;
  4542. pulled = false;
  4543. }
  4544. void setException(IException *E)
  4545. {
  4546. exception.setown(E);
  4547. }
  4548. virtual void onReset()
  4549. {
  4550. roxiemem::ReleaseRoxieRowRange(buff.getArray(), index, buff.ordinality());
  4551. buff.kill();
  4552. index = 0;
  4553. pulled = false;
  4554. exception.clear();
  4555. CRemoteResultAdaptor::onReset();
  4556. }
  4557. void onStart(unsigned _parentExtractSize, const byte * _parentExtract)
  4558. {
  4559. index = 0;
  4560. pulled = false;
  4561. CRemoteResultAdaptor::onStart(_parentExtractSize, _parentExtract);
  4562. }
  4563. virtual const void * nextRowGE(const void *seek, const void *rawSeek, unsigned numFields, unsigned seeklen, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  4564. {
  4565. // 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
  4566. if (exception)
  4567. throw exception.getClear();
  4568. return CRemoteResultAdaptor::nextRowGE(seek, rawSeek, numFields, seeklen, wasCompleteMatch, stepExtra);
  4569. }
  4570. virtual const void *nextRow()
  4571. {
  4572. if (skipping)
  4573. {
  4574. if(!pulled)
  4575. pullInput();
  4576. if(buff.isItem(index))
  4577. {
  4578. const void * next = buff.item(index++);
  4579. if(next)
  4580. processed++;
  4581. return next;
  4582. }
  4583. return NULL;
  4584. }
  4585. else
  4586. {
  4587. if (exception)
  4588. throw exception.getClear();
  4589. return CRemoteResultAdaptor::nextRow();
  4590. }
  4591. }
  4592. };
  4593. //=================================================================================
  4594. class CRoxieServerApplyActivity : public CRoxieServerInternalSinkActivity
  4595. {
  4596. IHThorApplyArg &helper;
  4597. public:
  4598. CRoxieServerApplyActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4599. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, 0), helper((IHThorApplyArg &) basehelper)
  4600. {
  4601. }
  4602. virtual void onExecute()
  4603. {
  4604. helper.start();
  4605. loop
  4606. {
  4607. const void * next = inputStream->ungroupedNextRow();
  4608. if (!next)
  4609. break;
  4610. helper.apply(next);
  4611. ReleaseRoxieRow(next);
  4612. }
  4613. helper.end();
  4614. }
  4615. };
  4616. class CRoxieServerApplyActivityFactory : public CRoxieServerActivityFactory
  4617. {
  4618. bool isRoot;
  4619. public:
  4620. CRoxieServerApplyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  4621. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  4622. {
  4623. }
  4624. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  4625. {
  4626. return new CRoxieServerApplyActivity(_ctx, this, _probeManager);
  4627. }
  4628. virtual bool isSink() const
  4629. {
  4630. return isRoot;
  4631. }
  4632. };
  4633. IRoxieServerActivityFactory *createRoxieServerApplyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  4634. {
  4635. return new CRoxieServerApplyActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  4636. }
  4637. //=================================================================================
  4638. class CRoxieServerNullActivity : public CRoxieServerActivity
  4639. {
  4640. public:
  4641. CRoxieServerNullActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4642. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  4643. {
  4644. }
  4645. virtual const void *nextRow()
  4646. {
  4647. return NULL;
  4648. }
  4649. };
  4650. IRoxieServerActivity * createRoxieServerNullActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4651. {
  4652. return new CRoxieServerNullActivity(_ctx, _factory, _probeManager);
  4653. }
  4654. class CRoxieServerNullActivityFactory : public CRoxieServerActivityFactory
  4655. {
  4656. public:
  4657. CRoxieServerNullActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4658. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  4659. {
  4660. }
  4661. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  4662. {
  4663. return new CRoxieServerNullActivity(_ctx, this, _probeManager);
  4664. }
  4665. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  4666. {
  4667. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for null activity");
  4668. }
  4669. };
  4670. IRoxieServerActivityFactory *createRoxieServerNullActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4671. {
  4672. return new CRoxieServerNullActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  4673. }
  4674. //=================================================================================
  4675. class CRoxieServerPassThroughActivity : public CRoxieServerActivity
  4676. {
  4677. public:
  4678. CRoxieServerPassThroughActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4679. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  4680. {
  4681. }
  4682. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  4683. {
  4684. return input->gatherConjunctions(collector);
  4685. }
  4686. virtual void resetEOF()
  4687. {
  4688. inputStream->resetEOF();
  4689. }
  4690. virtual const void *nextRow()
  4691. {
  4692. const void * next = inputStream->nextRow();
  4693. if (next)
  4694. processed++;
  4695. return next;
  4696. }
  4697. virtual bool isPassThrough()
  4698. {
  4699. return true;
  4700. }
  4701. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  4702. {
  4703. ActivityTimer t(totalCycles, timeActivities);
  4704. const void * next = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  4705. if (next)
  4706. processed++;
  4707. return next;
  4708. }
  4709. IInputSteppingMeta * querySteppingMeta()
  4710. {
  4711. return input->querySteppingMeta();
  4712. }
  4713. };
  4714. IRoxieServerActivity * createRoxieServerPassThroughActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4715. {
  4716. return new CRoxieServerPassThroughActivity(_ctx, _factory, _probeManager);
  4717. }
  4718. //=================================================================================
  4719. class CRoxieServerChildBaseActivity : public CRoxieServerActivity
  4720. {
  4721. protected:
  4722. bool eof;
  4723. bool first;
  4724. public:
  4725. CRoxieServerChildBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4726. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  4727. {
  4728. eof = false;
  4729. first = true;
  4730. }
  4731. ~CRoxieServerChildBaseActivity()
  4732. {
  4733. }
  4734. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4735. {
  4736. eof = false;
  4737. first = true;
  4738. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  4739. }
  4740. };
  4741. class CRoxieServerChildBaseActivityFactory : public CRoxieServerActivityFactory
  4742. {
  4743. public:
  4744. CRoxieServerChildBaseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4745. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  4746. {
  4747. }
  4748. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  4749. {
  4750. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  4751. }
  4752. };
  4753. //=================================================================================
  4754. class CRoxieServerChildIteratorActivity : public CRoxieServerChildBaseActivity
  4755. {
  4756. IHThorChildIteratorArg &helper;
  4757. public:
  4758. CRoxieServerChildIteratorActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4759. : CRoxieServerChildBaseActivity(_ctx, _factory, _probeManager), helper((IHThorChildIteratorArg &) basehelper)
  4760. {
  4761. }
  4762. virtual bool needsAllocator() const { return true; }
  4763. virtual const void *nextRow()
  4764. {
  4765. ActivityTimer t(totalCycles, timeActivities);
  4766. if (eof)
  4767. return NULL;
  4768. bool ok;
  4769. if (first)
  4770. {
  4771. ok = helper.first();
  4772. first = false;
  4773. }
  4774. else
  4775. ok = helper.next();
  4776. try
  4777. {
  4778. while (ok)
  4779. {
  4780. processed++;
  4781. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  4782. unsigned outSize = helper.transform(rowBuilder);
  4783. if (outSize)
  4784. return rowBuilder.finalizeRowClear(outSize);
  4785. ok = helper.next();
  4786. }
  4787. }
  4788. catch (IException *E)
  4789. {
  4790. throw makeWrappedException(E);
  4791. }
  4792. eof = true;
  4793. return NULL;
  4794. }
  4795. };
  4796. class CRoxieServerChildIteratorActivityFactory : public CRoxieServerChildBaseActivityFactory
  4797. {
  4798. public:
  4799. CRoxieServerChildIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4800. : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  4801. {
  4802. }
  4803. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  4804. {
  4805. return new CRoxieServerChildIteratorActivity(_ctx, this, _probeManager);
  4806. }
  4807. };
  4808. IRoxieServerActivityFactory *createRoxieServerChildIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4809. {
  4810. return new CRoxieServerChildIteratorActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  4811. }
  4812. //=================================================================================
  4813. class CRoxieServerChildNormalizeActivity : public CRoxieServerChildBaseActivity
  4814. {
  4815. IHThorChildNormalizeArg &helper;
  4816. public:
  4817. CRoxieServerChildNormalizeActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4818. : CRoxieServerChildBaseActivity(_ctx, _factory, _probeManager), helper((IHThorChildNormalizeArg &) basehelper)
  4819. {
  4820. }
  4821. virtual bool needsAllocator() const { return true; }
  4822. virtual const void *nextRow()
  4823. {
  4824. ActivityTimer t(totalCycles, timeActivities);
  4825. if (eof)
  4826. return NULL;
  4827. bool ok;
  4828. if (first)
  4829. {
  4830. ok = helper.first();
  4831. first = false;
  4832. }
  4833. else
  4834. ok = helper.next();
  4835. if (ok)
  4836. {
  4837. try
  4838. {
  4839. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  4840. do {
  4841. unsigned outSize = helper.transform(rowBuilder);
  4842. if (outSize)
  4843. {
  4844. processed++;
  4845. return rowBuilder.finalizeRowClear(outSize);
  4846. }
  4847. ok = helper.next();
  4848. }
  4849. while (ok);
  4850. }
  4851. catch (IException *E)
  4852. {
  4853. throw makeWrappedException(E);
  4854. }
  4855. }
  4856. eof = true;
  4857. return NULL;
  4858. }
  4859. };
  4860. class CRoxieServerChildNormalizeActivityFactory : public CRoxieServerChildBaseActivityFactory
  4861. {
  4862. public:
  4863. CRoxieServerChildNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4864. : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  4865. {
  4866. }
  4867. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  4868. {
  4869. return new CRoxieServerChildNormalizeActivity(_ctx, this, _probeManager);
  4870. }
  4871. };
  4872. IRoxieServerActivityFactory *createRoxieServerNewChildNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4873. {
  4874. return new CRoxieServerChildNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  4875. }
  4876. //=================================================================================
  4877. class CRoxieServerChildAggregateActivity : public CRoxieServerChildBaseActivity
  4878. {
  4879. IHThorChildAggregateArg &helper;
  4880. public:
  4881. CRoxieServerChildAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4882. : CRoxieServerChildBaseActivity(_ctx, _factory, _probeManager), helper((IHThorChildAggregateArg &) basehelper)
  4883. {
  4884. }
  4885. virtual bool needsAllocator() const { return true; }
  4886. virtual const void *nextRow()
  4887. {
  4888. ActivityTimer t(totalCycles, timeActivities);
  4889. if (eof)
  4890. return NULL;
  4891. eof = true;
  4892. processed++;
  4893. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  4894. helper.clearAggregate(rowBuilder);
  4895. helper.processRows(rowBuilder);
  4896. size32_t finalSize = meta.getRecordSize(rowBuilder.getSelf());
  4897. return rowBuilder.finalizeRowClear(finalSize);
  4898. }
  4899. };
  4900. class CRoxieServerChildAggregateActivityFactory : public CRoxieServerChildBaseActivityFactory
  4901. {
  4902. public:
  4903. CRoxieServerChildAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4904. : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  4905. {
  4906. }
  4907. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  4908. {
  4909. return new CRoxieServerChildAggregateActivity(_ctx, this, _probeManager);
  4910. }
  4911. };
  4912. IRoxieServerActivityFactory *createRoxieServerNewChildAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4913. {
  4914. return new CRoxieServerChildAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  4915. }
  4916. //=================================================================================
  4917. class CRoxieServerChildGroupAggregateActivity : public CRoxieServerChildBaseActivity, public IHThorGroupAggregateCallback
  4918. {
  4919. IHThorChildGroupAggregateArg &helper;
  4920. RowAggregator aggregated;
  4921. public:
  4922. IMPLEMENT_IINTERFACE_USING(CRoxieServerChildBaseActivity)
  4923. CRoxieServerChildGroupAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4924. : CRoxieServerChildBaseActivity(_ctx, _factory, _probeManager), helper((IHThorChildGroupAggregateArg &) basehelper),
  4925. aggregated(helper, helper)
  4926. {
  4927. }
  4928. void processRow(const void * next)
  4929. {
  4930. aggregated.addRow(next);
  4931. }
  4932. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4933. {
  4934. CRoxieServerChildBaseActivity::start(parentExtractSize, parentExtract, paused);
  4935. aggregated.start(rowAllocator);
  4936. }
  4937. virtual void reset()
  4938. {
  4939. aggregated.reset();
  4940. CRoxieServerChildBaseActivity::reset();
  4941. }
  4942. virtual bool needsAllocator() const { return true; }
  4943. virtual const void *nextRow()
  4944. {
  4945. ActivityTimer t(totalCycles, timeActivities);
  4946. if (eof)
  4947. return NULL;
  4948. if (first)
  4949. {
  4950. helper.processRows(this);
  4951. first = false;
  4952. }
  4953. Owned<AggregateRowBuilder> next = aggregated.nextResult();
  4954. if (next)
  4955. {
  4956. processed++;
  4957. return next->finalizeRowClear();
  4958. }
  4959. eof = true;
  4960. return NULL;
  4961. }
  4962. };
  4963. class CRoxieServerChildGroupAggregateActivityFactory : public CRoxieServerChildBaseActivityFactory
  4964. {
  4965. public:
  4966. CRoxieServerChildGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4967. : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  4968. {
  4969. }
  4970. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  4971. {
  4972. return new CRoxieServerChildGroupAggregateActivity(_ctx, this, _probeManager);
  4973. }
  4974. };
  4975. IRoxieServerActivityFactory *createRoxieServerNewChildGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4976. {
  4977. return new CRoxieServerChildGroupAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  4978. }
  4979. //=================================================================================
  4980. class CRoxieServerChildThroughNormalizeActivity : public CRoxieServerChildBaseActivity
  4981. {
  4982. IHThorChildThroughNormalizeArg &helper;
  4983. const void * lastInput;
  4984. unsigned numProcessedLastGroup;
  4985. bool ok;
  4986. public:
  4987. CRoxieServerChildThroughNormalizeActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4988. : CRoxieServerChildBaseActivity(_ctx, _factory, _probeManager), helper((IHThorChildThroughNormalizeArg &) basehelper)
  4989. {
  4990. lastInput = NULL;
  4991. numProcessedLastGroup = 0;
  4992. ok = false;
  4993. }
  4994. virtual void stop()
  4995. {
  4996. CRoxieServerChildBaseActivity::stop();
  4997. ReleaseRoxieRow(lastInput);
  4998. lastInput = NULL;
  4999. }
  5000. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5001. {
  5002. CRoxieServerChildBaseActivity::start(parentExtractSize, parentExtract, paused);
  5003. numProcessedLastGroup = processed;
  5004. ok = false;
  5005. }
  5006. virtual bool needsAllocator() const { return true; }
  5007. virtual const void *nextRow()
  5008. {
  5009. ActivityTimer t(totalCycles, timeActivities);
  5010. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  5011. loop
  5012. {
  5013. if (ok)
  5014. ok = helper.next();
  5015. while (!ok)
  5016. {
  5017. ReleaseRoxieRow(lastInput);
  5018. lastInput = inputStream->nextRow();
  5019. if (!lastInput)
  5020. {
  5021. if (numProcessedLastGroup != processed)
  5022. {
  5023. numProcessedLastGroup = processed;
  5024. return NULL;
  5025. }
  5026. lastInput = inputStream->nextRow();
  5027. if (!lastInput)
  5028. return NULL;
  5029. }
  5030. ok = helper.first(lastInput);
  5031. }
  5032. try
  5033. {
  5034. do
  5035. {
  5036. unsigned outSize = helper.transform(rowBuilder);
  5037. if (outSize)
  5038. {
  5039. processed++;
  5040. return rowBuilder.finalizeRowClear(outSize);
  5041. }
  5042. ok = helper.next();
  5043. } while (ok);
  5044. }
  5045. catch (IException *E)
  5046. {
  5047. throw makeWrappedException(E);
  5048. }
  5049. }
  5050. }
  5051. };
  5052. class CRoxieServerChildThroughNormalizeActivityFactory : public CRoxieServerActivityFactory
  5053. {
  5054. public:
  5055. CRoxieServerChildThroughNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5056. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  5057. {
  5058. }
  5059. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  5060. {
  5061. return new CRoxieServerChildThroughNormalizeActivity(_ctx, this, _probeManager);
  5062. }
  5063. };
  5064. IRoxieServerActivityFactory *createRoxieServerNewChildThroughNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5065. {
  5066. return new CRoxieServerChildThroughNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  5067. }
  5068. //=================================================================================
  5069. class CRoxieServerDistributionActivity : public CRoxieServerInternalSinkActivity
  5070. {
  5071. IHThorDistributionArg &helper;
  5072. public:
  5073. CRoxieServerDistributionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5074. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, 0), helper((IHThorDistributionArg &)basehelper)
  5075. {
  5076. }
  5077. virtual void onExecute()
  5078. {
  5079. MemoryAttr ma;
  5080. IDistributionTable * * accumulator = (IDistributionTable * *)ma.allocate(helper.queryInternalRecordSize()->getMinRecordSize());
  5081. helper.clearAggregate(accumulator);
  5082. OwnedConstRoxieRow nextrec(inputStream->nextRow());
  5083. loop
  5084. {
  5085. if (!nextrec)
  5086. {
  5087. nextrec.setown(inputStream->nextRow());
  5088. if (!nextrec)
  5089. break;
  5090. }
  5091. helper.process(accumulator, nextrec);
  5092. nextrec.setown(inputStream->nextRow());
  5093. }
  5094. StringBuffer result;
  5095. result.append("<XML>");
  5096. helper.gatherResult(accumulator, result);
  5097. result.append("</XML>");
  5098. helper.sendResult(result.length(), result.str());
  5099. helper.destruct(accumulator);
  5100. }
  5101. };
  5102. class CRoxieServerDistributionActivityFactory : public CRoxieServerActivityFactory
  5103. {
  5104. bool isRoot;
  5105. public:
  5106. CRoxieServerDistributionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  5107. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  5108. {
  5109. }
  5110. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  5111. {
  5112. return new CRoxieServerDistributionActivity(_ctx, this, _probeManager);
  5113. }
  5114. virtual bool isSink() const
  5115. {
  5116. return isRoot;
  5117. }
  5118. };
  5119. IRoxieServerActivityFactory *createRoxieServerDistributionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  5120. {
  5121. return new CRoxieServerDistributionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  5122. }
  5123. //=================================================================================
  5124. class CRoxieServerLinkedRawIteratorActivity : public CRoxieServerActivity
  5125. {
  5126. IHThorLinkedRawIteratorArg &helper;
  5127. public:
  5128. CRoxieServerLinkedRawIteratorActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5129. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorLinkedRawIteratorArg &) basehelper)
  5130. {
  5131. }
  5132. virtual const void *nextRow()
  5133. {
  5134. ActivityTimer t(totalCycles, timeActivities);
  5135. const void *ret =helper.next();
  5136. if (ret)
  5137. {
  5138. LinkRoxieRow(ret);
  5139. processed++;
  5140. }
  5141. return ret;
  5142. }
  5143. };
  5144. class CRoxieServerLinkedRawIteratorActivityFactory : public CRoxieServerActivityFactory
  5145. {
  5146. public:
  5147. CRoxieServerLinkedRawIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5148. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  5149. {
  5150. }
  5151. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  5152. {
  5153. return new CRoxieServerLinkedRawIteratorActivity(_ctx, this, _probeManager);
  5154. }
  5155. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  5156. {
  5157. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  5158. }
  5159. };
  5160. IRoxieServerActivityFactory *createRoxieServerLinkedRawIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5161. {
  5162. return new CRoxieServerLinkedRawIteratorActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  5163. }
  5164. //=================================================================================
  5165. class CRoxieServerDatasetResultActivity : public CRoxieServerActivity
  5166. {
  5167. public:
  5168. CRoxieServerDatasetResultActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5169. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  5170. {
  5171. }
  5172. virtual const void *nextRow()
  5173. {
  5174. throwUnexpected();
  5175. }
  5176. virtual void executeChild(size32_t & retSize, void * & ret, unsigned parentExtractSize, const byte * parentExtract)
  5177. {
  5178. try
  5179. {
  5180. start(parentExtractSize, parentExtract, false);
  5181. {
  5182. ActivityTimer t(totalCycles, timeActivities);
  5183. MemoryBuffer result;
  5184. IRecordSize * inputMeta = input->queryOutputMeta();
  5185. loop
  5186. {
  5187. const void *nextrec = inputStream->ungroupedNextRow();
  5188. if (!nextrec)
  5189. break;
  5190. result.append(inputMeta->getRecordSize(nextrec), nextrec);
  5191. ReleaseRoxieRow(nextrec);
  5192. }
  5193. retSize = result.length();
  5194. ret = result.detach();
  5195. }
  5196. stop();
  5197. reset();
  5198. }
  5199. catch(IException *E)
  5200. {
  5201. ctx->notifyAbort(E);
  5202. abort();
  5203. reset();
  5204. throw;
  5205. }
  5206. catch(...)
  5207. {
  5208. Owned<IException> E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught at %s:%d", __FILE__, __LINE__);
  5209. ctx->notifyAbort(E);
  5210. abort();
  5211. reset();
  5212. throw;
  5213. }
  5214. }
  5215. };
  5216. class CRoxieServerDatasetResultActivityFactory : public CRoxieServerActivityFactory
  5217. {
  5218. bool isRoot;
  5219. public:
  5220. CRoxieServerDatasetResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  5221. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  5222. {
  5223. }
  5224. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  5225. {
  5226. return new CRoxieServerDatasetResultActivity(_ctx, this, _probeManager);
  5227. }
  5228. virtual bool isSink() const
  5229. {
  5230. return isRoot;
  5231. }
  5232. };
  5233. IRoxieServerActivityFactory *createRoxieServerDatasetResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  5234. {
  5235. return new CRoxieServerDatasetResultActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  5236. }
  5237. //=================================================================================
  5238. class CRoxieServerInlineTableActivity : public CRoxieServerActivity
  5239. {
  5240. IHThorInlineTableArg &helper;
  5241. __uint64 curRow;
  5242. __uint64 numRows;
  5243. public:
  5244. CRoxieServerInlineTableActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5245. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorInlineTableArg &) basehelper)
  5246. {
  5247. curRow = 0;
  5248. numRows = 0;
  5249. }
  5250. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5251. {
  5252. curRow = 0;
  5253. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5254. numRows = helper.numRows();
  5255. }
  5256. virtual bool needsAllocator() const { return true; }
  5257. virtual const void *nextRow()
  5258. {
  5259. ActivityTimer t(totalCycles, timeActivities);
  5260. // Filtering empty rows, returns the next valid row
  5261. while (curRow < numRows)
  5262. {
  5263. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  5264. unsigned outSize = helper.getRow(rowBuilder, curRow++);
  5265. if (outSize)
  5266. {
  5267. processed++;
  5268. return rowBuilder.finalizeRowClear(outSize);
  5269. }
  5270. }
  5271. return NULL;
  5272. }
  5273. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  5274. {
  5275. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  5276. }
  5277. };
  5278. class CRoxieServerStrandedInlineTableActivity : public CRoxieServerStrandedActivity
  5279. {
  5280. IHThorInlineTableArg &helper;
  5281. __uint64 numRows;
  5282. //An inline table that isn't stranded
  5283. class InlineTableSimpleProcessor : public StrandProcessor
  5284. {
  5285. protected:
  5286. IHThorInlineTableArg &helper;
  5287. __uint64 curRow;
  5288. __uint64 maxRows;
  5289. public:
  5290. InlineTableSimpleProcessor(CRoxieServerActivity &_parent, IHThorInlineTableArg &_helper)
  5291. : StrandProcessor(_parent, NULL, true), helper(_helper), curRow(0), maxRows(0)
  5292. {
  5293. }
  5294. virtual void start() override
  5295. {
  5296. StrandProcessor::start();
  5297. curRow = 0;
  5298. maxRows = queryParent().numRows;
  5299. }
  5300. virtual const void * nextRow()
  5301. {
  5302. ActivityTimer t(totalCycles, timeActivities);
  5303. //Return rows while the current section is active
  5304. while (curRow < maxRows)
  5305. {
  5306. RtlDynamicRowBuilder rowBuilder(*rowAllocator);
  5307. unsigned outSize = helper.getRow(rowBuilder, curRow++);
  5308. if (outSize)
  5309. {
  5310. processed++;
  5311. return rowBuilder.finalizeRowClear(outSize);
  5312. }
  5313. }
  5314. return NULL;
  5315. }
  5316. CRoxieServerStrandedInlineTableActivity & queryParent() { return static_cast<CRoxieServerStrandedInlineTableActivity&>(parent); }
  5317. };
  5318. class InlineTableStrandProcessor : public StrandProcessor
  5319. {
  5320. protected:
  5321. IHThorInlineTableArg &helper;
  5322. unsigned whichStrand;
  5323. unsigned numStrands = 0;
  5324. __uint64 sectionSize;
  5325. __uint64 curRow = 0;
  5326. __uint64 sectionMaxRows = 0;
  5327. __uint64 maxRows = 0;
  5328. bool isOrdered;
  5329. bool eosPending;
  5330. public:
  5331. InlineTableStrandProcessor(CRoxieServerActivity &_parent, IHThorInlineTableArg &_helper, unsigned _whichStrand, bool _isOrdered)
  5332. : StrandProcessor(_parent, NULL, true), helper(_helper), whichStrand(_whichStrand), isOrdered(_isOrdered)
  5333. {
  5334. sectionSize = queryParent().strandOptions.blockSize;
  5335. eosPending = false;
  5336. }
  5337. virtual void start() override
  5338. {
  5339. StrandProcessor::start();
  5340. numStrands = queryParent().numStrands();
  5341. maxRows = queryParent().numRows;
  5342. curRow = std::min(whichStrand * sectionSize, maxRows);
  5343. sectionMaxRows = std::min(curRow + sectionSize, maxRows);
  5344. eosPending = isOrdered && (curRow != maxRows);
  5345. }
  5346. virtual const void * nextRow()
  5347. {
  5348. ActivityTimer t(totalCycles, timeActivities);
  5349. loop
  5350. {
  5351. //Return rows while the current section is active
  5352. while (curRow < sectionMaxRows)
  5353. {
  5354. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  5355. unsigned outSize = helper.getRow(rowBuilder, curRow++);
  5356. if (outSize)
  5357. {
  5358. processed++;
  5359. return rowBuilder.finalizeRowClear(outSize);
  5360. }
  5361. }
  5362. if (curRow == maxRows)
  5363. return NULL;
  5364. //Update current position to the next section
  5365. curRow += (numStrands - 1) * sectionSize;
  5366. if (curRow > maxRows)
  5367. curRow = maxRows;
  5368. sectionMaxRows = std::min(curRow + sectionSize, maxRows);
  5369. //If we have output a block of rows, then send the block as a unit - results now come from the next strand
  5370. if (eosPending)
  5371. {
  5372. //If there is another block, then second an end of section marker after it, otherwise make sure NULL is returned next.
  5373. eosPending = isOrdered && (curRow != maxRows);
  5374. return queryEndOfSectionMarker();
  5375. }
  5376. }
  5377. }
  5378. CRoxieServerStrandedInlineTableActivity & queryParent() { return static_cast<CRoxieServerStrandedInlineTableActivity&>(parent); }
  5379. };
  5380. public:
  5381. CRoxieServerStrandedInlineTableActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const StrandOptions &_strandOptions)
  5382. : CRoxieServerStrandedActivity(_ctx, _factory, _probeManager, _strandOptions), helper((IHThorInlineTableArg &) basehelper)
  5383. {
  5384. numRows = 0;
  5385. }
  5386. virtual StrandProcessor *createStrandProcessor(IEngineRowStream *instream) { throwUnexpected(); }
  5387. virtual StrandProcessor *createStrandSourceProcessor(bool inputOrdered)
  5388. {
  5389. if (strandOptions.numStrands <= 1)
  5390. return new InlineTableSimpleProcessor(*this, helper);
  5391. return new InlineTableStrandProcessor(*this, helper, strands.ordinality(), inputOrdered);
  5392. }
  5393. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5394. {
  5395. CRoxieServerStrandedActivity::start(parentExtractSize, parentExtract, paused);
  5396. numRows = helper.numRows();
  5397. onStartStrands();
  5398. startJunction(sourceJunction); // This must be started *after* all the strands have been initialised
  5399. }
  5400. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  5401. {
  5402. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  5403. }
  5404. };
  5405. class CRoxieServerInlineTableActivityFactory : public CRoxieServerActivityFactory
  5406. {
  5407. StrandOptions strandOptions;
  5408. public:
  5409. CRoxieServerInlineTableActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5410. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), strandOptions(_graphNode)
  5411. {
  5412. optStableInput = false; // do not force the output to be ordered
  5413. }
  5414. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  5415. {
  5416. return new CRoxieServerStrandedInlineTableActivity(_ctx, this, _probeManager, strandOptions);
  5417. }
  5418. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  5419. {
  5420. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for InlineTable activity");
  5421. }
  5422. };
  5423. IRoxieServerActivityFactory *createRoxieServerInlineTableActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5424. {
  5425. return new CRoxieServerInlineTableActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  5426. }
  5427. //=================================================================================
  5428. class CRoxieServerWorkUnitReadActivity : public CRoxieServerActivity
  5429. {
  5430. IHThorWorkunitReadArg &helper;
  5431. CriticalSection readerCrit;
  5432. Owned<IWorkUnitRowReader> wuReader;
  5433. public:
  5434. CRoxieServerWorkUnitReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5435. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorWorkunitReadArg &)basehelper)
  5436. {
  5437. }
  5438. virtual void onCreate(IHThorArg *_colocalParent)
  5439. {
  5440. CRoxieServerActivity::onCreate(_colocalParent);
  5441. if (!ctx->queryServerContext())
  5442. {
  5443. throw MakeStringException(ROXIE_INTERNAL_ERROR, "Workunit read activity cannot be executed in slave context");
  5444. }
  5445. }
  5446. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5447. {
  5448. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5449. IXmlToRowTransformer * xmlTransformer = helper.queryXmlTransformer();
  5450. OwnedRoxieString fromWuid(helper.getWUID());
  5451. wuReader.setown(ctx->getWorkunitRowReader(fromWuid, helper.queryName(), helper.querySequence(), xmlTransformer, rowAllocator, meta.isGrouped()));
  5452. // MORE _ should that be in onCreate?
  5453. }
  5454. virtual void reset()
  5455. {
  5456. {
  5457. CriticalBlock b(readerCrit);
  5458. wuReader.clear();
  5459. }
  5460. CRoxieServerActivity::reset();
  5461. };
  5462. virtual bool needsAllocator() const { return true; }
  5463. virtual const void *nextRow()
  5464. {
  5465. ActivityTimer t(totalCycles, timeActivities);
  5466. Linked<IWorkUnitRowReader> useReader;
  5467. {
  5468. CriticalBlock b(readerCrit);
  5469. if (!wuReader)
  5470. return NULL;
  5471. useReader.set(wuReader);
  5472. }
  5473. const void *ret = useReader->nextRow();
  5474. if (ret)
  5475. processed++;
  5476. return ret;
  5477. }
  5478. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  5479. {
  5480. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  5481. }
  5482. };
  5483. class CRoxieServerWorkUnitReadActivityFactory : public CRoxieServerActivityFactory
  5484. {
  5485. public:
  5486. CRoxieServerWorkUnitReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5487. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  5488. {
  5489. }
  5490. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  5491. {
  5492. return new CRoxieServerWorkUnitReadActivity(_ctx, this, _probeManager);
  5493. }
  5494. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  5495. {
  5496. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for WorkUnitRead activity");
  5497. }
  5498. };
  5499. IRoxieServerActivityFactory *createRoxieServerWorkUnitReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5500. {
  5501. return new CRoxieServerWorkUnitReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  5502. }
  5503. //=================================================================================
  5504. interface ILocalGraphEx : public IEclGraphResults
  5505. {
  5506. public:
  5507. virtual void setResult(unsigned id, IGraphResult * result) = 0;
  5508. virtual IEngineRowStream * createResultIterator(unsigned id) = 0;
  5509. virtual void setGraphLoopResult(IGraphResult * result) = 0;
  5510. virtual IEngineRowStream * createGraphLoopResultIterator(unsigned id) = 0;
  5511. };
  5512. class CSafeRoxieInput : implements IEngineRowStream, implements IFinalRoxieInput, public CInterface
  5513. {
  5514. public:
  5515. CSafeRoxieInput(unsigned _sourceIdx, IFinalRoxieInput * _input) : input(_input), inputStream(NULL), sourceIdx(_sourceIdx) {}
  5516. IMPLEMENT_IINTERFACE
  5517. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  5518. {
  5519. connectInputStreams(ctx, consumerOrdered);
  5520. streams.append(this);
  5521. return NULL;
  5522. }
  5523. void connectInputStreams(IRoxieSlaveContext *ctx, bool consumerOrdered)
  5524. {
  5525. inputStream.set(connectSingleStream(ctx, input, sourceIdx, junction, consumerOrdered));
  5526. }
  5527. virtual IOutputMetaData * queryOutputMeta() const
  5528. {
  5529. return input->queryOutputMeta();
  5530. }
  5531. virtual unsigned __int64 queryTotalCycles() const
  5532. {
  5533. return input->queryTotalCycles();
  5534. }
  5535. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { assertex(whichInput==0); return this; }
  5536. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { assertex(idx==0); return nullptr; }
  5537. virtual IRoxieServerActivity *queryActivity()
  5538. {
  5539. return input->queryActivity();
  5540. }
  5541. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  5542. {
  5543. return input->queryIndexReadActivity();
  5544. }
  5545. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5546. {
  5547. CriticalBlock procedure(cs);
  5548. input->start(parentExtractSize, parentExtract, paused);
  5549. startJunction(junction);
  5550. }
  5551. virtual void stop()
  5552. {
  5553. CriticalBlock procedure(cs);
  5554. inputStream->stop();
  5555. }
  5556. virtual void reset()
  5557. {
  5558. CriticalBlock procedure(cs);
  5559. input->reset();
  5560. resetJunction(junction);
  5561. }
  5562. virtual void resetEOF()
  5563. {
  5564. CriticalBlock procedure(cs);
  5565. inputStream->resetEOF();
  5566. }
  5567. virtual const void *nextRow()
  5568. {
  5569. CriticalBlock procedure(cs);
  5570. return inputStream->nextRow();
  5571. }
  5572. virtual bool nextGroup(ConstPointerArray & group)
  5573. {
  5574. CriticalBlock procedure(cs);
  5575. return inputStream->nextGroup(group);
  5576. }
  5577. private:
  5578. CriticalSection cs;
  5579. Linked<IFinalRoxieInput> input;
  5580. Linked<IEngineRowStream> inputStream;
  5581. Owned<IStrandJunction> junction;
  5582. unsigned sourceIdx;
  5583. };
  5584. //=================================================================================
  5585. class CPseudoRoxieInput : implements IEngineRowStream, implements IFinalRoxieInput, public CInterface
  5586. {
  5587. public:
  5588. IMPLEMENT_IINTERFACE;
  5589. CPseudoRoxieInput()
  5590. {
  5591. }
  5592. virtual unsigned __int64 queryTotalCycles() const
  5593. {
  5594. return 0;
  5595. }
  5596. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { assertex(whichInput==0); return this; }
  5597. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { assertex(idx==0); return nullptr; }
  5598. virtual IRoxieServerActivity *queryActivity()
  5599. {
  5600. throwUnexpected();
  5601. }
  5602. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  5603. {
  5604. throwUnexpected();
  5605. }
  5606. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  5607. {
  5608. assertex(!idx);
  5609. streams.append(this);
  5610. return NULL;
  5611. }
  5612. virtual IOutputMetaData * queryOutputMeta() const { throwUnexpected(); }
  5613. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused) { }
  5614. virtual void stop() { }
  5615. virtual void reset() { }
  5616. virtual void checkAbort() { }
  5617. virtual void resetEOF() { }
  5618. };
  5619. class CIndirectRoxieInput : public CPseudoRoxieInput
  5620. {
  5621. public:
  5622. CIndirectRoxieInput() : input(NULL)
  5623. {
  5624. stream = NULL;
  5625. sourceIdx = 0;
  5626. }
  5627. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5628. {
  5629. input->start(parentExtractSize, parentExtract, paused);
  5630. startJunction(junction);
  5631. }
  5632. virtual void stop()
  5633. {
  5634. stream->stop();
  5635. }
  5636. virtual void reset()
  5637. {
  5638. input->reset();
  5639. resetJunction(junction);
  5640. }
  5641. virtual const void * nextRow()
  5642. {
  5643. return stream->nextRow();
  5644. }
  5645. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  5646. {
  5647. return stream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  5648. }
  5649. virtual unsigned __int64 queryTotalCycles() const
  5650. {
  5651. return input->queryTotalCycles();
  5652. }
  5653. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  5654. {
  5655. return input->gatherConjunctions(collector);
  5656. }
  5657. virtual void resetEOF()
  5658. {
  5659. stream->resetEOF();
  5660. }
  5661. virtual unsigned numConcreteOutputs() const
  5662. {
  5663. return input->numConcreteOutputs();
  5664. }
  5665. virtual IFinalRoxieInput * queryConcreteInput(unsigned idx)
  5666. {
  5667. return input->queryConcreteInput(idx);
  5668. }
  5669. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput)
  5670. {
  5671. return input->queryConcreteOutputStream(whichInput);
  5672. }
  5673. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const
  5674. {
  5675. return input->queryConcreteOutputJunction(idx);
  5676. }
  5677. virtual IOutputMetaData * queryOutputMeta() const
  5678. {
  5679. return input->queryOutputMeta();
  5680. }
  5681. virtual IRoxieServerActivity *queryActivity()
  5682. {
  5683. return input->queryActivity();
  5684. }
  5685. inline void setInput(unsigned _sourceIdx, IFinalRoxieInput * _input)
  5686. {
  5687. input = _input;
  5688. sourceIdx = _sourceIdx;
  5689. }
  5690. inline void connectInputStreams(IRoxieSlaveContext *ctx, bool consumerOrdered)
  5691. {
  5692. stream = connectSingleStream(ctx, input, sourceIdx, junction, consumerOrdered);
  5693. }
  5694. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  5695. {
  5696. assertex(idx == 0);
  5697. connectInputStreams(ctx, consumerOrdered);
  5698. streams.append(this);
  5699. return NULL;
  5700. }
  5701. inline IFinalRoxieInput *queryInput() const
  5702. {
  5703. return input;
  5704. }
  5705. protected:
  5706. unsigned sourceIdx;
  5707. IFinalRoxieInput *input;
  5708. IEngineRowStream *stream;
  5709. Owned<IStrandJunction> junction;
  5710. };
  5711. class CExtractMapperInput : public CIndirectRoxieInput
  5712. {
  5713. unsigned savedParentExtractSize;
  5714. const byte * savedParentExtract;
  5715. public:
  5716. CExtractMapperInput()
  5717. {
  5718. savedParentExtractSize = 0;
  5719. savedParentExtract = NULL;
  5720. }
  5721. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5722. {
  5723. CIndirectRoxieInput::start(savedParentExtractSize, savedParentExtract, paused);
  5724. }
  5725. void setParentExtract(unsigned _savedParentExtractSize, const byte * _savedParentExtract)
  5726. {
  5727. savedParentExtractSize = _savedParentExtractSize;
  5728. savedParentExtract = _savedParentExtract;
  5729. }
  5730. };
  5731. class CGraphResult : implements IGraphResult, public CInterface
  5732. {
  5733. CriticalSection cs;
  5734. byte **rowset;
  5735. size32_t count;
  5736. bool complete;
  5737. void clear()
  5738. {
  5739. CriticalBlock func(cs);
  5740. rtlReleaseRowset(count, rowset);
  5741. rowset = NULL;
  5742. count = 0;
  5743. complete = false;
  5744. }
  5745. public:
  5746. IMPLEMENT_IINTERFACE
  5747. CGraphResult()
  5748. {
  5749. complete = false; // dummy result is not supposed to be used...
  5750. rowset = NULL;
  5751. count = 0;
  5752. }
  5753. CGraphResult(size32_t _count, byte **_rowset)
  5754. : count(_count), rowset(_rowset)
  5755. {
  5756. complete = true;
  5757. }
  5758. ~CGraphResult()
  5759. {
  5760. clear();
  5761. }
  5762. // interface IGraphResult
  5763. virtual IEngineRowStream * createIterator()
  5764. {
  5765. if (!complete)
  5766. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Internal Error: Reading uninitialised graph result");
  5767. return new CGraphResultIterator(this);
  5768. }
  5769. virtual void getLinkedResult(unsigned & countResult, byte * * & result)
  5770. {
  5771. if (!complete)
  5772. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Internal Error: Reading uninitialised graph result");
  5773. result = rtlLinkRowset(rowset);
  5774. countResult = count;
  5775. }
  5776. virtual const void * getLinkedRowResult()
  5777. {
  5778. if (!complete)
  5779. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Internal Error: Reading uninitialised graph result");
  5780. if (count != 1)
  5781. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Internal Error: Expected a single row result");
  5782. const void * ret = rowset[0];
  5783. LinkRoxieRow(ret);
  5784. return ret;
  5785. }
  5786. //other
  5787. const void * getRow(unsigned i)
  5788. {
  5789. CriticalBlock func(cs);
  5790. if (i >= count)
  5791. return NULL;
  5792. const void * ret = rowset[i];
  5793. if (ret) LinkRoxieRow(ret);
  5794. return ret;
  5795. }
  5796. protected:
  5797. class CGraphResultIterator : public CInterfaceOf<IEngineRowStream>
  5798. {
  5799. unsigned i;
  5800. Linked<CGraphResult> result;
  5801. public:
  5802. CGraphResultIterator(CGraphResult * _result) : result(_result) { i = 0; }
  5803. public:
  5804. virtual const void * nextRow()
  5805. {
  5806. return result->getRow(i++);
  5807. }
  5808. virtual void stop()
  5809. {
  5810. }
  5811. virtual void resetEOF()
  5812. {
  5813. throwUnexpected();
  5814. }
  5815. };
  5816. };
  5817. //=================================================================================
  5818. class CRoxieServerLocalResultReadActivity : public CRoxieServerActivity
  5819. {
  5820. IHThorLocalResultReadArg &helper;
  5821. CriticalSection iterCrit;
  5822. Owned<IEngineRowStream> iter;
  5823. ILocalGraphEx * graph;
  5824. unsigned graphId;
  5825. unsigned sequence;
  5826. public:
  5827. CRoxieServerLocalResultReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId)
  5828. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorLocalResultReadArg &)basehelper), graphId(_graphId)
  5829. {
  5830. graph = NULL;
  5831. sequence = 0;
  5832. }
  5833. virtual void onCreate(IHThorArg *_colocalParent)
  5834. {
  5835. CRoxieServerActivity::onCreate(_colocalParent);
  5836. graph = static_cast<ILocalGraphEx *>(ctx->queryCodeContext()->resolveLocalQuery(graphId));
  5837. sequence = helper.querySequence();
  5838. }
  5839. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5840. {
  5841. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5842. iter.setown(graph->createResultIterator(sequence));
  5843. }
  5844. virtual void reset()
  5845. {
  5846. {
  5847. CriticalBlock b(iterCrit);
  5848. iter.clear();
  5849. }
  5850. CRoxieServerActivity::reset();
  5851. };
  5852. virtual const void *nextRow()
  5853. {
  5854. ActivityTimer t(totalCycles, timeActivities);
  5855. Linked<IEngineRowStream> useIter;
  5856. {
  5857. CriticalBlock b(iterCrit);
  5858. if (!iter)
  5859. return NULL;
  5860. useIter.set(iter);
  5861. }
  5862. const void * next = useIter->nextRow();
  5863. if (next)
  5864. {
  5865. processed++;
  5866. atomic_inc(&rowsIn);
  5867. }
  5868. return next;
  5869. }
  5870. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  5871. {
  5872. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  5873. }
  5874. };
  5875. class CRoxieServerLocalResultReadActivityFactory : public CRoxieServerActivityFactory
  5876. {
  5877. unsigned graphId;
  5878. public:
  5879. CRoxieServerLocalResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _graphId)
  5880. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), graphId(_graphId)
  5881. {
  5882. }
  5883. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  5884. {
  5885. return new CRoxieServerLocalResultReadActivity(_ctx, this, _probeManager, graphId);
  5886. }
  5887. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  5888. {
  5889. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for LocalResultRead activity");
  5890. }
  5891. };
  5892. IRoxieServerActivityFactory *createRoxieServerLocalResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned graphId)
  5893. {
  5894. return new CRoxieServerLocalResultReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, graphId);
  5895. }
  5896. //=================================================================================
  5897. class CRoxieServerLocalResultStreamReadActivity : public CRoxieServerActivity
  5898. {
  5899. IHThorLocalResultReadArg &helper;
  5900. unsigned sequence;
  5901. public:
  5902. CRoxieServerLocalResultStreamReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5903. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorLocalResultReadArg &)basehelper)
  5904. {
  5905. sequence = 0;
  5906. }
  5907. virtual void onCreate(IHThorArg *_colocalParent)
  5908. {
  5909. CRoxieServerActivity::onCreate(_colocalParent);
  5910. sequence = helper.querySequence();
  5911. }
  5912. virtual const void *nextRow()
  5913. {
  5914. ActivityTimer t(totalCycles, timeActivities);
  5915. const void * next = inputStream->nextRow();
  5916. if (next)
  5917. {
  5918. processed++;
  5919. atomic_inc(&rowsIn);
  5920. }
  5921. return next;
  5922. }
  5923. virtual bool querySetStreamInput(unsigned id, unsigned _sourceIdx, IFinalRoxieInput * _input)
  5924. {
  5925. if (id == sequence)
  5926. {
  5927. CRoxieServerActivity::setInput(0, _sourceIdx, _input);
  5928. connectInputStreams(true);
  5929. return true;
  5930. }
  5931. return false;
  5932. }
  5933. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  5934. {
  5935. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  5936. }
  5937. };
  5938. class CRoxieServerLocalResultStreamReadActivityFactory : public CRoxieServerActivityFactory
  5939. {
  5940. public:
  5941. CRoxieServerLocalResultStreamReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5942. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  5943. {
  5944. }
  5945. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  5946. {
  5947. return new CRoxieServerLocalResultStreamReadActivity(_ctx, this, _probeManager);
  5948. }
  5949. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  5950. {
  5951. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for LocalResultRead activity");
  5952. }
  5953. };
  5954. IRoxieServerActivityFactory *createRoxieServerLocalResultStreamReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5955. {
  5956. return new CRoxieServerLocalResultStreamReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  5957. }
  5958. //=====================================================================================================
  5959. class CRoxieServerLocalResultWriteActivity : public CRoxieServerInternalSinkActivity
  5960. {
  5961. IHThorLocalResultWriteArg &helper;
  5962. ILocalGraphEx * graph;
  5963. unsigned graphId;
  5964. public:
  5965. CRoxieServerLocalResultWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId, unsigned _numOutputs)
  5966. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _numOutputs), helper((IHThorLocalResultWriteArg &)basehelper), graphId(_graphId)
  5967. {
  5968. graph = NULL;
  5969. }
  5970. virtual bool needsAllocator() const { return true; }
  5971. virtual void onCreate(IHThorArg *_colocalParent)
  5972. {
  5973. CRoxieServerInternalSinkActivity::onCreate(_colocalParent);
  5974. graph = static_cast<ILocalGraphEx *>(ctx->queryCodeContext()->resolveLocalQuery(graphId));
  5975. }
  5976. virtual void onExecute()
  5977. {
  5978. RtlLinkedDatasetBuilder builder(rowAllocator);
  5979. inputStream->readAll(builder);
  5980. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  5981. graph->setResult(helper.querySequence(), result);
  5982. }
  5983. virtual const void *nextRow()
  5984. {
  5985. return inputStream->nextRow(); // I can act as a passthrough input
  5986. }
  5987. IFinalRoxieInput * querySelectOutput(unsigned id)
  5988. {
  5989. if (id == helper.querySequence())
  5990. {
  5991. executed = true; // Ensure that we don't try to pull as a sink as well as via the passthrough
  5992. return LINK(this);
  5993. }
  5994. return NULL;
  5995. }
  5996. };
  5997. class CRoxieServerLocalResultWriteActivityFactory : public CRoxieServerInternalSinkFactory
  5998. {
  5999. unsigned graphId;
  6000. public:
  6001. CRoxieServerLocalResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, unsigned _graphId, bool _isRoot)
  6002. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot), graphId(_graphId)
  6003. {
  6004. isInternal = true;
  6005. Owned<IHThorLocalResultWriteArg> helper = (IHThorLocalResultWriteArg *) helperFactory();
  6006. }
  6007. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  6008. {
  6009. return new CRoxieServerLocalResultWriteActivity(_ctx, this, _probeManager, graphId, usageCount);
  6010. }
  6011. };
  6012. IRoxieServerActivityFactory *createRoxieServerLocalResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, unsigned _graphId, bool _isRoot)
  6013. {
  6014. return new CRoxieServerLocalResultWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _graphId, _isRoot);
  6015. }
  6016. //=====================================================================================================
  6017. class CRoxieServerDictionaryResultWriteActivity : public CRoxieServerInternalSinkActivity
  6018. {
  6019. IHThorDictionaryResultWriteArg &helper;
  6020. ILocalGraphEx * graph;
  6021. unsigned graphId;
  6022. public:
  6023. CRoxieServerDictionaryResultWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _usageCount, unsigned _graphId)
  6024. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _usageCount), helper((IHThorDictionaryResultWriteArg &)basehelper), graphId(_graphId)
  6025. {
  6026. graph = NULL;
  6027. }
  6028. virtual bool needsAllocator() const { return true; }
  6029. virtual void onCreate(IHThorArg *_colocalParent)
  6030. {
  6031. CRoxieServerInternalSinkActivity::onCreate(_colocalParent);
  6032. graph = static_cast<ILocalGraphEx *>(ctx->queryCodeContext()->resolveLocalQuery(graphId));
  6033. }
  6034. virtual void onExecute()
  6035. {
  6036. unsigned sequence = helper.querySequence();
  6037. RtlLinkedDictionaryBuilder builder(rowAllocator, helper.queryHashLookupInfo());
  6038. loop
  6039. {
  6040. const void *row = inputStream->ungroupedNextRow();
  6041. if (!row)
  6042. break;
  6043. builder.appendOwn(row);
  6044. processed++;
  6045. }
  6046. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  6047. graph->setResult(helper.querySequence(), result);
  6048. }
  6049. virtual const void *nextRow()
  6050. {
  6051. return inputStream->nextRow(); // I can act as a passthrough input
  6052. }
  6053. IFinalRoxieInput * querySelectOutput(unsigned id)
  6054. {
  6055. if (id == helper.querySequence())
  6056. {
  6057. executed = true; // Ensure that we don't try to pull as a sink as well as via the passthrough
  6058. return LINK(this);
  6059. }
  6060. return NULL;
  6061. }
  6062. };
  6063. class CRoxieServerDictionaryResultWriteActivityFactory : public CRoxieServerInternalSinkFactory
  6064. {
  6065. unsigned graphId;
  6066. public:
  6067. CRoxieServerDictionaryResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, unsigned _graphId, bool _isRoot)
  6068. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot), graphId(_graphId)
  6069. {
  6070. isInternal = true;
  6071. }
  6072. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  6073. {
  6074. return new CRoxieServerDictionaryResultWriteActivity(_ctx, this, _probeManager, usageCount, graphId);
  6075. }
  6076. };
  6077. IRoxieServerActivityFactory *createRoxieServerDictionaryResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, unsigned _graphId, bool _isRoot)
  6078. {
  6079. return new CRoxieServerDictionaryResultWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _graphId, _isRoot);
  6080. }
  6081. //=================================================================================
  6082. class CRoxieServerGraphLoopResultReadActivity : public CRoxieServerActivity
  6083. {
  6084. protected:
  6085. IHThorGraphLoopResultReadArg &helper;
  6086. CriticalSection iterCrit;
  6087. Owned<IFinalRoxieInput> iterInput;
  6088. Owned<IEngineRowStream> iterStream;
  6089. Owned<IStrandJunction> iterJunction;
  6090. ILocalGraphEx * graph;
  6091. unsigned graphId;
  6092. unsigned sequence;
  6093. public:
  6094. CRoxieServerGraphLoopResultReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId)
  6095. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorGraphLoopResultReadArg &)basehelper), graphId(_graphId)
  6096. {
  6097. graph = NULL;
  6098. sequence = 0;
  6099. }
  6100. virtual void onCreate(IHThorArg *_colocalParent)
  6101. {
  6102. CRoxieServerActivity::onCreate(_colocalParent);
  6103. graph = static_cast<ILocalGraphEx *>(ctx->queryCodeContext()->resolveLocalQuery(graphId));
  6104. }
  6105. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6106. {
  6107. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6108. if (iterInput)
  6109. iterInput->start(parentExtractSize, parentExtract, paused);
  6110. else
  6111. {
  6112. sequence = helper.querySequence();
  6113. if ((int)sequence >= 0)
  6114. {
  6115. try
  6116. {
  6117. iterStream.setown(graph->createGraphLoopResultIterator(sequence));
  6118. iterInput.clear();
  6119. }
  6120. catch (IException * E)
  6121. {
  6122. throw makeWrappedException(E);
  6123. }
  6124. }
  6125. }
  6126. startJunction(iterJunction);
  6127. }
  6128. virtual void stop()
  6129. {
  6130. if (iterStream)
  6131. iterStream->stop();
  6132. CRoxieServerActivity::stop();
  6133. }
  6134. virtual void reset()
  6135. {
  6136. {
  6137. CriticalBlock b(iterCrit);
  6138. if (iterInput)
  6139. iterInput->reset();
  6140. resetJunction(iterJunction);
  6141. iterInput.clear();
  6142. iterStream.clear();
  6143. iterJunction.clear();
  6144. }
  6145. CRoxieServerActivity::reset();
  6146. };
  6147. virtual const void *nextRow()
  6148. {
  6149. ActivityTimer t(totalCycles, timeActivities);
  6150. Linked<IEngineRowStream> useStream;
  6151. {
  6152. CriticalBlock b(iterCrit);
  6153. if (!iterStream)
  6154. return NULL;
  6155. useStream.set(iterStream);
  6156. }
  6157. const void * next = useStream->nextRow();
  6158. if (next)
  6159. {
  6160. processed++;
  6161. atomic_inc(&rowsIn);
  6162. }
  6163. return next;
  6164. }
  6165. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  6166. {
  6167. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  6168. }
  6169. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract)
  6170. {
  6171. ensureCreated();
  6172. basehelper.onStart(parentExtract, NULL);
  6173. processor.noteUseIteration(helper.querySequence());
  6174. }
  6175. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract, IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes)
  6176. {
  6177. //helper already initialised from the gatherIterationUsage() call.
  6178. CRoxieServerActivity::connectInputStreams(true);
  6179. iterInput.set(processor.connectIterationOutput(helper.querySequence(), probeManager, probes, this, 0));
  6180. iterStream.set(connectSingleStream(ctx, iterInput, 0, iterJunction, true));
  6181. }
  6182. virtual IInputSteppingMeta * querySteppingMeta()
  6183. {
  6184. assertex(iterInput);
  6185. return iterInput->querySteppingMeta();
  6186. }
  6187. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  6188. {
  6189. assertex(iterStream);
  6190. return iterStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  6191. }
  6192. };
  6193. //variety of CRoxieServerGraphLoopResultReadActivity created internally with a predefined sequence number
  6194. class CRoxieServerInternalGraphLoopResultReadActivity : public CRoxieServerGraphLoopResultReadActivity
  6195. {
  6196. public:
  6197. CRoxieServerInternalGraphLoopResultReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId, unsigned _sequence)
  6198. : CRoxieServerGraphLoopResultReadActivity(_ctx, _factory, _probeManager, _graphId)
  6199. {
  6200. sequence = _sequence;
  6201. }
  6202. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6203. {
  6204. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6205. if ((int)sequence >= 0)
  6206. {
  6207. try
  6208. {
  6209. iterStream.setown(graph->createGraphLoopResultIterator(sequence));
  6210. iterInput.clear();
  6211. }
  6212. catch (IException * E)
  6213. {
  6214. throw makeWrappedException(E);
  6215. }
  6216. }
  6217. }
  6218. };
  6219. class CRoxieServerGraphLoopResultReadActivityFactory : public CRoxieServerActivityFactory
  6220. {
  6221. unsigned graphId;
  6222. public:
  6223. CRoxieServerGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _graphId)
  6224. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), graphId(_graphId)
  6225. {
  6226. }
  6227. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  6228. {
  6229. return new CRoxieServerGraphLoopResultReadActivity(_ctx, this, _probeManager, graphId);
  6230. }
  6231. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  6232. {
  6233. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for GraphLoopResultRead activity");
  6234. }
  6235. };
  6236. IRoxieServerActivityFactory *createRoxieServerGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned graphId)
  6237. {
  6238. return new CRoxieServerGraphLoopResultReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, graphId);
  6239. }
  6240. //=====================================================================================================
  6241. class CRoxieServerGraphLoopResultWriteActivity : public CRoxieServerInternalSinkActivity
  6242. {
  6243. IHThorGraphLoopResultWriteArg &helper;
  6244. ILocalGraphEx * graph;
  6245. unsigned graphId;
  6246. public:
  6247. CRoxieServerGraphLoopResultWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId, unsigned _numOutputs)
  6248. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _numOutputs), helper((IHThorGraphLoopResultWriteArg &)basehelper), graphId(_graphId)
  6249. {
  6250. graph = NULL;
  6251. }
  6252. virtual bool needsAllocator() const { return true; }
  6253. virtual void onCreate(IHThorArg *_colocalParent)
  6254. {
  6255. CRoxieServerInternalSinkActivity::onCreate(_colocalParent);
  6256. graph = static_cast<ILocalGraphEx *>(ctx->queryCodeContext()->resolveLocalQuery(graphId));
  6257. }
  6258. virtual void onExecute()
  6259. {
  6260. RtlLinkedDatasetBuilder builder(rowAllocator);
  6261. inputStream->readAll(builder);
  6262. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  6263. graph->setGraphLoopResult(result);
  6264. }
  6265. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  6266. {
  6267. if (idx==0)
  6268. return this;
  6269. else
  6270. return NULL;
  6271. }
  6272. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  6273. {
  6274. return input->gatherConjunctions(collector);
  6275. }
  6276. virtual void resetEOF()
  6277. {
  6278. inputStream->resetEOF();
  6279. }
  6280. virtual const void *nextRow()
  6281. {
  6282. const void * next = inputStream->nextRow();
  6283. if (next)
  6284. processed++;
  6285. return next;
  6286. }
  6287. virtual bool isPassThrough()
  6288. {
  6289. return true;
  6290. }
  6291. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  6292. {
  6293. ActivityTimer t(totalCycles, timeActivities);
  6294. const void * next = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  6295. if (next)
  6296. processed++;
  6297. return next;
  6298. }
  6299. IInputSteppingMeta * querySteppingMeta()
  6300. {
  6301. return input->querySteppingMeta();
  6302. }
  6303. virtual IOutputMetaData * queryOutputMeta() const
  6304. {
  6305. return input->queryOutputMeta();
  6306. }
  6307. };
  6308. class CRoxieServerGraphLoopResultWriteActivityFactory : public CRoxieServerInternalSinkFactory
  6309. {
  6310. unsigned graphId;
  6311. public:
  6312. CRoxieServerGraphLoopResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, unsigned _graphId)
  6313. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, true), graphId(_graphId)
  6314. {
  6315. isInternal = true;
  6316. Owned<IHThorGraphLoopResultWriteArg> helper = (IHThorGraphLoopResultWriteArg *) helperFactory();
  6317. }
  6318. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  6319. {
  6320. return new CRoxieServerGraphLoopResultWriteActivity(_ctx, this, _probeManager, graphId, usageCount);
  6321. }
  6322. };
  6323. IRoxieServerActivityFactory *createRoxieServerGraphLoopResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, unsigned _graphId)
  6324. {
  6325. return new CRoxieServerGraphLoopResultWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _graphId);
  6326. }
  6327. //=================================================================================
  6328. class CRoxieServerDedupActivity : public CRoxieServerActivity
  6329. {
  6330. protected:
  6331. IHThorDedupArg &helper;
  6332. unsigned numKept;
  6333. unsigned numToKeep;
  6334. public:
  6335. CRoxieServerDedupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6336. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorDedupArg &)basehelper)
  6337. {
  6338. numKept = 0;
  6339. numToKeep = 0;
  6340. }
  6341. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6342. {
  6343. numKept = 0;
  6344. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6345. numToKeep = helper.numToKeep();
  6346. }
  6347. };
  6348. class CRoxieServerDedupKeepLeftActivity : public CRoxieServerDedupActivity
  6349. {
  6350. IRangeCompare * stepCompare;
  6351. const void *prev;
  6352. public:
  6353. CRoxieServerDedupKeepLeftActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6354. : CRoxieServerDedupActivity(_ctx, _factory, _probeManager)
  6355. {
  6356. prev = NULL;
  6357. stepCompare = NULL;
  6358. }
  6359. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6360. {
  6361. prev = NULL;
  6362. CRoxieServerDedupActivity::start(parentExtractSize, parentExtract, paused);
  6363. IInputSteppingMeta * stepMeta = input->querySteppingMeta();
  6364. stepCompare = NULL;
  6365. if (stepMeta)
  6366. stepCompare = stepMeta->queryCompare();
  6367. }
  6368. virtual void reset()
  6369. {
  6370. ReleaseClearRoxieRow(prev);
  6371. CRoxieServerDedupActivity::reset();
  6372. }
  6373. virtual const void * nextRow()
  6374. {
  6375. ActivityTimer t(totalCycles, timeActivities);
  6376. const void * next;
  6377. loop
  6378. {
  6379. next = inputStream->nextRow();
  6380. if (!prev || !next || !helper.matches(prev,next))
  6381. {
  6382. numKept = 0;
  6383. break;
  6384. }
  6385. if (numKept < numToKeep-1)
  6386. {
  6387. numKept++;
  6388. break;
  6389. }
  6390. ReleaseRoxieRow(next);
  6391. }
  6392. ReleaseRoxieRow(prev);
  6393. prev = next;
  6394. if (next)
  6395. {
  6396. LinkRoxieRow(next);
  6397. processed++;
  6398. }
  6399. return next;
  6400. }
  6401. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  6402. {
  6403. ActivityTimer t(totalCycles, timeActivities);
  6404. const void * next;
  6405. loop
  6406. {
  6407. next = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  6408. //If the record was an in-exact match from the index then return it immediately
  6409. //and don't cause it to dedup following legal records.
  6410. if (!wasCompleteMatch)
  6411. {
  6412. assertex(stepExtra.returnMismatches());
  6413. return next;
  6414. }
  6415. if (!prev || !next || !helper.matches(prev,next))
  6416. {
  6417. numKept = 0;
  6418. break;
  6419. }
  6420. if (numKept < numToKeep-1)
  6421. {
  6422. numKept++;
  6423. break;
  6424. }
  6425. //Unusual - deduping by x,y stepped on x,y,z - still want any record back as soon as possible.
  6426. if (stepExtra.returnMismatches())
  6427. {
  6428. //If asked to return mismatches we are only interested in mismatches that will force the stepped
  6429. //condition to advance
  6430. if (stepCompare->docompare(next, seek, numFields) != 0)
  6431. {
  6432. wasCompleteMatch = false;
  6433. break;
  6434. }
  6435. }
  6436. ReleaseRoxieRow(next);
  6437. }
  6438. ReleaseRoxieRow(prev);
  6439. prev = next;
  6440. if (next)
  6441. {
  6442. LinkRoxieRow(next);
  6443. processed++;
  6444. }
  6445. return next;
  6446. }
  6447. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  6448. {
  6449. return input->gatherConjunctions(collector);
  6450. }
  6451. virtual void resetEOF()
  6452. {
  6453. inputStream->resetEOF();
  6454. }
  6455. IInputSteppingMeta * querySteppingMeta()
  6456. {
  6457. return input->querySteppingMeta();
  6458. }
  6459. };
  6460. //=================================================================================
  6461. class CRoxieServerDedupKeepRightActivity : public CRoxieServerDedupActivity
  6462. {
  6463. const void *kept;
  6464. bool first;
  6465. public:
  6466. CRoxieServerDedupKeepRightActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6467. : CRoxieServerDedupActivity(_ctx, _factory, _probeManager)
  6468. {
  6469. kept = NULL;
  6470. first = true;
  6471. }
  6472. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6473. {
  6474. first = true;
  6475. kept = NULL;
  6476. CRoxieServerDedupActivity::start(parentExtractSize, parentExtract, paused);
  6477. }
  6478. virtual void reset()
  6479. {
  6480. ReleaseClearRoxieRow(kept);
  6481. CRoxieServerActivity::reset();
  6482. }
  6483. virtual const void * nextRow()
  6484. {
  6485. ActivityTimer t(totalCycles, timeActivities);
  6486. if (first)
  6487. {
  6488. kept = inputStream->nextRow();
  6489. first = false;
  6490. }
  6491. const void * next;
  6492. loop
  6493. {
  6494. next = inputStream->nextRow();
  6495. if (!kept || !next || !helper.matches(kept,next))
  6496. {
  6497. numKept = 0;
  6498. break;
  6499. }
  6500. if (numKept < numToKeep-1)
  6501. {
  6502. numKept++;
  6503. break;
  6504. }
  6505. ReleaseRoxieRow(kept);
  6506. kept = next;
  6507. }
  6508. const void * ret = kept;
  6509. kept = next;
  6510. // CTXLOG("dedup returns %p", ret);
  6511. if (ret) processed++;
  6512. return ret;
  6513. }
  6514. };
  6515. class CRoxieServerDedupAllActivity : public CRoxieServerActivity
  6516. {
  6517. IHThorDedupArg &helper;
  6518. unsigned survivorIndex;
  6519. ConstPointerArray survivors;
  6520. bool keepLeft;
  6521. bool eof;
  6522. bool first;
  6523. ICompare *primaryCompare;
  6524. public:
  6525. CRoxieServerDedupAllActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _keepLeft)
  6526. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorDedupArg &)basehelper)
  6527. {
  6528. keepLeft = _keepLeft;
  6529. primaryCompare = helper.queryComparePrimary();
  6530. eof = false;
  6531. first = true;
  6532. survivorIndex = 0;
  6533. }
  6534. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6535. {
  6536. eof = false;
  6537. first = true;
  6538. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6539. }
  6540. virtual void reset()
  6541. {
  6542. #ifdef _DEBUG
  6543. while (survivors.isItem(survivorIndex))
  6544. {
  6545. ReleaseRoxieRow(survivors.item(survivorIndex++));
  6546. }
  6547. #endif
  6548. survivors.kill();
  6549. eof = false;
  6550. first = true;
  6551. CRoxieServerActivity::reset();
  6552. }
  6553. void dedupRange(unsigned first, unsigned last, ConstPointerArray & group)
  6554. {
  6555. for (unsigned idxL = first; idxL < last; idxL++)
  6556. {
  6557. const void * left = group.item(idxL);
  6558. if (left)
  6559. {
  6560. for (unsigned idxR = first; idxR < last; idxR++)
  6561. {
  6562. const void * right = group.item(idxR);
  6563. if ((idxL != idxR) && right)
  6564. {
  6565. if (helper.matches(left, right))
  6566. {
  6567. if (keepLeft)
  6568. {
  6569. group.replace(NULL, idxR);
  6570. ReleaseRoxieRow(right);
  6571. }
  6572. else
  6573. {
  6574. group.replace(NULL, idxL);
  6575. ReleaseRoxieRow(left);
  6576. break;
  6577. }
  6578. }
  6579. }
  6580. }
  6581. }
  6582. }
  6583. }
  6584. void dedupRange(unsigned first, unsigned last, void ** rows)
  6585. {
  6586. for (unsigned idxL = first; idxL < last; idxL++)
  6587. {
  6588. void * left = rows[idxL];
  6589. if (left)
  6590. {
  6591. for (unsigned idxR = first; idxR < last; idxR++)
  6592. {
  6593. void * right = rows[idxR];
  6594. if ((idxL != idxR) && right)
  6595. {
  6596. if (helper.matches(left, right))
  6597. {
  6598. if (keepLeft)
  6599. {
  6600. rows[idxR] = NULL;
  6601. ReleaseRoxieRow(right);
  6602. }
  6603. else
  6604. {
  6605. rows[idxL] = NULL;
  6606. ReleaseRoxieRow(left);
  6607. break;
  6608. }
  6609. }
  6610. }
  6611. }
  6612. }
  6613. }
  6614. }
  6615. bool calcNextDedupAll()
  6616. {
  6617. survivors.kill();
  6618. survivorIndex = 0;
  6619. ConstPointerArray group;
  6620. if (eof || !inputStream->nextGroup(group))
  6621. {
  6622. eof = true;
  6623. return false;
  6624. }
  6625. unsigned max = group.ordinality();
  6626. if (primaryCompare)
  6627. {
  6628. //hard, if not impossible, to hit this code once optimisations in place
  6629. MemoryAttr indexbuff(max*sizeof(void *));
  6630. void ** temp = (void **)indexbuff.bufferBase();
  6631. void * *rows = const_cast<void * *>(group.getArray());
  6632. msortvecstableinplace(rows, max, *primaryCompare, temp);
  6633. unsigned first = 0;
  6634. for (unsigned idx = 1; idx < max; idx++)
  6635. {
  6636. if (primaryCompare->docompare(rows[first], rows[idx]) != 0)
  6637. {
  6638. dedupRange(first, idx, rows);
  6639. first = idx;
  6640. }
  6641. }
  6642. dedupRange(first, max, rows);
  6643. for(unsigned idx2=0; idx2<max; ++idx2)
  6644. {
  6645. void * cur = rows[idx2];
  6646. if(cur)
  6647. survivors.append(cur);
  6648. }
  6649. }
  6650. else
  6651. {
  6652. dedupRange(0, max, group);
  6653. for(unsigned idx=0; idx<max; ++idx)
  6654. {
  6655. const void * cur = group.item(idx);
  6656. if(cur)
  6657. survivors.append(cur);
  6658. }
  6659. }
  6660. return true;
  6661. }
  6662. virtual const void *nextRow()
  6663. {
  6664. ActivityTimer t(totalCycles, timeActivities);
  6665. if (first)
  6666. {
  6667. calcNextDedupAll();
  6668. first = false;
  6669. }
  6670. while (survivors.isItem(survivorIndex))
  6671. {
  6672. const void *ret = survivors.item(survivorIndex++);
  6673. if (ret)
  6674. {
  6675. processed++;
  6676. return ret;
  6677. }
  6678. }
  6679. calcNextDedupAll();
  6680. return NULL;
  6681. }
  6682. };
  6683. class CRoxieServerDedupActivityFactory : public CRoxieServerActivityFactory
  6684. {
  6685. bool compareAll;
  6686. bool keepLeft;
  6687. public:
  6688. CRoxieServerDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  6689. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  6690. {
  6691. Owned<IHThorDedupArg> helper = (IHThorDedupArg *) helperFactory();
  6692. compareAll = helper->compareAll();
  6693. keepLeft = helper->keepLeft();
  6694. }
  6695. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  6696. {
  6697. if (compareAll)
  6698. return new CRoxieServerDedupAllActivity(_ctx, this, _probeManager, keepLeft);
  6699. else if (keepLeft)
  6700. return new CRoxieServerDedupKeepLeftActivity(_ctx, this, _probeManager);
  6701. else
  6702. return new CRoxieServerDedupKeepRightActivity(_ctx, this, _probeManager);
  6703. }
  6704. };
  6705. IRoxieServerActivityFactory *createRoxieServerDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  6706. {
  6707. return new CRoxieServerDedupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  6708. }
  6709. //=================================================================================
  6710. class CRoxieServerHashDedupActivity : public CRoxieServerActivity
  6711. {
  6712. bool eof;
  6713. IHThorHashDedupArg &helper;
  6714. class HashDedupElement
  6715. {
  6716. public:
  6717. HashDedupElement(unsigned _hash, const void *_keyRow)
  6718. : hash(_hash), keyRow(_keyRow)
  6719. {
  6720. }
  6721. ~HashDedupElement()
  6722. {
  6723. ReleaseRoxieRow(keyRow);
  6724. }
  6725. inline unsigned queryHash() const
  6726. {
  6727. return hash;
  6728. }
  6729. inline const void *queryRow() const
  6730. {
  6731. return keyRow;
  6732. }
  6733. private:
  6734. unsigned hash;
  6735. const void *keyRow;
  6736. };
  6737. class HashDedupTable : public SuperHashTable
  6738. {
  6739. public:
  6740. HashDedupTable(IHThorHashDedupArg & _helper, CRoxieServerHashDedupActivity & _activity)
  6741. : helper(_helper),
  6742. activity(_activity),
  6743. keySize(helper.queryKeySize())
  6744. {
  6745. }
  6746. virtual ~HashDedupTable() { _releaseAll(); }
  6747. virtual unsigned getHashFromElement(const void *et) const
  6748. {
  6749. const HashDedupElement *element = reinterpret_cast<const HashDedupElement *>(et);
  6750. return element->queryHash();
  6751. }
  6752. virtual unsigned getHashFromFindParam(const void *fp) const { throwUnexpected(); }
  6753. virtual const void * getFindParam(const void *et) const { throwUnexpected(); }
  6754. virtual bool matchesElement(const void *et, const void *searchET) const { throwUnexpected(); }
  6755. virtual bool matchesFindParam(const void *et, const void *key, unsigned fphash) const
  6756. {
  6757. const HashDedupElement *element = reinterpret_cast<const HashDedupElement *>(et);
  6758. if (fphash != element->queryHash())
  6759. return false;
  6760. return (helper.queryKeyCompare()->docompare(element->queryRow(), key) == 0);
  6761. }
  6762. virtual void onAdd(void *et) {}
  6763. virtual void onRemove(void *et)
  6764. {
  6765. const HashDedupElement *element = reinterpret_cast<const HashDedupElement *>(et);
  6766. delete element;
  6767. }
  6768. void onCreate(IRoxieSlaveContext *ctx)
  6769. {
  6770. keyRowAllocator.setown(activity.createRowAllocator(keySize.queryOriginal()));
  6771. }
  6772. void reset()
  6773. {
  6774. kill();
  6775. }
  6776. bool insert(const void * row)
  6777. {
  6778. unsigned hash = helper.queryHash()->hash(row);
  6779. RtlDynamicRowBuilder keyRowBuilder(keyRowAllocator, true);
  6780. size32_t thisKeySize = helper.recordToKey(keyRowBuilder, row);
  6781. OwnedConstRoxieRow keyRow = keyRowBuilder.finalizeRowClear(thisKeySize);
  6782. if (find(hash, keyRow.get()))
  6783. return false;
  6784. addNew(new HashDedupElement(hash, keyRow.getClear()), hash);
  6785. return true;
  6786. }
  6787. private:
  6788. IHThorHashDedupArg & helper;
  6789. CachedOutputMetaData keySize;
  6790. Owned<IEngineRowAllocator> keyRowAllocator;
  6791. CRoxieServerHashDedupActivity & activity;
  6792. } table;
  6793. public:
  6794. CRoxieServerHashDedupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6795. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorHashDedupArg &)basehelper), table(helper, *this)
  6796. {
  6797. eof = false;
  6798. }
  6799. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6800. {
  6801. eof = false;
  6802. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6803. }
  6804. virtual void onCreate(IHThorArg *_colocalParent)
  6805. {
  6806. CRoxieServerActivity::onCreate(colocalParent);
  6807. table.onCreate(ctx);
  6808. }
  6809. virtual void reset()
  6810. {
  6811. table.reset();
  6812. eof = false;
  6813. CRoxieServerActivity::reset();
  6814. }
  6815. virtual const void *nextRow()
  6816. {
  6817. ActivityTimer t(totalCycles, timeActivities);
  6818. while(!eof)
  6819. {
  6820. const void * next = inputStream->nextRow();
  6821. if(!next)
  6822. {
  6823. if (table.count() == 0)
  6824. eof = true;
  6825. table.reset();
  6826. return NULL;
  6827. }
  6828. if(table.insert(next))
  6829. return next;
  6830. else
  6831. ReleaseRoxieRow(next);
  6832. }
  6833. return NULL;
  6834. }
  6835. };
  6836. class CRoxieServerHashDedupActivityFactory : public CRoxieServerActivityFactory
  6837. {
  6838. public:
  6839. CRoxieServerHashDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  6840. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  6841. {
  6842. }
  6843. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  6844. {
  6845. return new CRoxieServerHashDedupActivity(_ctx, this, _probeManager);
  6846. }
  6847. };
  6848. IRoxieServerActivityFactory *createRoxieServerHashDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  6849. {
  6850. return new CRoxieServerHashDedupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  6851. }
  6852. //=================================================================================
  6853. class CRoxieServerRollupActivity : public CRoxieServerActivity
  6854. {
  6855. IHThorRollupArg &helper;
  6856. OwnedConstRoxieRow left;
  6857. OwnedConstRoxieRow prev;
  6858. OwnedConstRoxieRow right;
  6859. bool readFirstRow;
  6860. public:
  6861. CRoxieServerRollupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6862. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorRollupArg &)basehelper)
  6863. {
  6864. readFirstRow = false;
  6865. }
  6866. ~CRoxieServerRollupActivity()
  6867. {
  6868. }
  6869. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6870. {
  6871. readFirstRow = false;
  6872. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6873. }
  6874. virtual void reset()
  6875. {
  6876. left.clear();
  6877. prev.clear();
  6878. right.clear();
  6879. CRoxieServerActivity::reset();
  6880. }
  6881. virtual bool needsAllocator() const { return true; }
  6882. virtual const void * nextRow()
  6883. {
  6884. ActivityTimer t(totalCycles, timeActivities);
  6885. if (!readFirstRow)
  6886. {
  6887. left.setown(inputStream->nextRow());
  6888. prev.set(left);
  6889. readFirstRow = true;
  6890. }
  6891. loop
  6892. {
  6893. right.setown(inputStream->nextRow());
  6894. if(!prev || !right || !helper.matches(prev,right))
  6895. {
  6896. const void * ret = left.getClear();
  6897. if(ret)
  6898. processed++;
  6899. left.setown(right.getClear());
  6900. prev.set(left);
  6901. return ret;
  6902. }
  6903. try
  6904. {
  6905. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  6906. unsigned outSize = helper.transform(rowBuilder, left, right);
  6907. if (outSize)
  6908. left.setown(rowBuilder.finalizeRowClear(outSize));
  6909. if (helper.getFlags() & RFrolledismatchleft)
  6910. prev.set(left);
  6911. else
  6912. prev.set(right);
  6913. }
  6914. catch(IException * E)
  6915. {
  6916. throw makeWrappedException(E);
  6917. }
  6918. }
  6919. }
  6920. };
  6921. class CRoxieServerRollupActivityFactory : public CRoxieServerActivityFactory
  6922. {
  6923. public:
  6924. CRoxieServerRollupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  6925. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  6926. {
  6927. }
  6928. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  6929. {
  6930. return new CRoxieServerRollupActivity(_ctx, this, _probeManager);
  6931. }
  6932. };
  6933. IRoxieServerActivityFactory *createRoxieServerRollupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  6934. {
  6935. return new CRoxieServerRollupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  6936. }
  6937. //=================================================================================
  6938. class CRoxieServerNormalizeActivity : public CRoxieServerActivity
  6939. {
  6940. IHThorNormalizeArg &helper;
  6941. unsigned numThisRow;
  6942. unsigned curRow;
  6943. const void *buffer;
  6944. unsigned numProcessedLastGroup;
  6945. public:
  6946. CRoxieServerNormalizeActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6947. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorNormalizeArg &)basehelper)
  6948. {
  6949. buffer = NULL;
  6950. numThisRow = 0;
  6951. curRow = 0;
  6952. numProcessedLastGroup = 0;
  6953. }
  6954. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6955. {
  6956. numThisRow = 0;
  6957. curRow = 0;
  6958. numProcessedLastGroup = 0;
  6959. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6960. }
  6961. virtual void reset()
  6962. {
  6963. ReleaseClearRoxieRow(buffer);
  6964. CRoxieServerActivity::reset();
  6965. }
  6966. virtual bool needsAllocator() const { return true; }
  6967. virtual const void * nextRow()
  6968. {
  6969. ActivityTimer t(totalCycles, timeActivities);
  6970. loop
  6971. {
  6972. while (curRow == numThisRow)
  6973. {
  6974. if (buffer)
  6975. ReleaseClearRoxieRow(buffer);
  6976. buffer = inputStream->nextRow();
  6977. if (!buffer && (processed == numProcessedLastGroup))
  6978. buffer = inputStream->nextRow();
  6979. if (!buffer)
  6980. {
  6981. numProcessedLastGroup = processed;
  6982. return NULL;
  6983. }
  6984. curRow = 0;
  6985. numThisRow = helper.numExpandedRows(buffer);
  6986. }
  6987. try
  6988. {
  6989. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  6990. unsigned actualSize = helper.transform(rowBuilder, buffer, ++curRow);
  6991. if (actualSize != 0)
  6992. {
  6993. processed++;
  6994. return rowBuilder.finalizeRowClear(actualSize);
  6995. }
  6996. }
  6997. catch (IException *E)
  6998. {
  6999. throw makeWrappedException(E);
  7000. }
  7001. }
  7002. }
  7003. };
  7004. class CRoxieServerNormalizeActivityFactory : public CRoxieServerActivityFactory
  7005. {
  7006. public:
  7007. CRoxieServerNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7008. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  7009. {
  7010. }
  7011. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  7012. {
  7013. return new CRoxieServerNormalizeActivity(_ctx, this, _probeManager);
  7014. }
  7015. };
  7016. IRoxieServerActivityFactory *createRoxieServerNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7017. {
  7018. return new CRoxieServerNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  7019. }
  7020. //=================================================================================
  7021. class CRoxieServerNormalizeChildActivity : public CRoxieServerActivity
  7022. {
  7023. IHThorNormalizeChildArg &helper;
  7024. unsigned numThisRow;
  7025. unsigned curRow;
  7026. const void *buffer;
  7027. unsigned numProcessedLastGroup;
  7028. INormalizeChildIterator * cursor;
  7029. const void * curChildRow;
  7030. bool advanceInput()
  7031. {
  7032. loop
  7033. {
  7034. ReleaseClearRoxieRow(buffer);
  7035. buffer = inputStream->nextRow();
  7036. if (!buffer && (processed == numProcessedLastGroup))
  7037. buffer = inputStream->nextRow();
  7038. if (!buffer)
  7039. {
  7040. numProcessedLastGroup = processed;
  7041. return false;
  7042. }
  7043. curChildRow = cursor->first(buffer);
  7044. if (curChildRow)
  7045. {
  7046. curRow = 0;
  7047. return true;
  7048. }
  7049. }
  7050. }
  7051. public:
  7052. CRoxieServerNormalizeChildActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  7053. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorNormalizeChildArg &)basehelper)
  7054. {
  7055. buffer = NULL;
  7056. cursor = NULL;
  7057. numThisRow = 0;
  7058. curRow = 0;
  7059. numProcessedLastGroup = 0;
  7060. curChildRow = NULL;
  7061. }
  7062. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7063. {
  7064. numThisRow = 0;
  7065. curRow = 0;
  7066. numProcessedLastGroup = 0;
  7067. curChildRow = NULL;
  7068. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7069. cursor = helper.queryIterator();
  7070. }
  7071. virtual void stop()
  7072. {
  7073. CRoxieServerActivity::stop();
  7074. }
  7075. virtual void reset()
  7076. {
  7077. cursor = NULL;
  7078. ReleaseClearRoxieRow(buffer);
  7079. CRoxieServerActivity::reset();
  7080. }
  7081. virtual bool needsAllocator() const { return true; }
  7082. const void *nextRow()
  7083. {
  7084. ActivityTimer t(totalCycles, timeActivities);
  7085. loop
  7086. {
  7087. if (!buffer)
  7088. {
  7089. if (!advanceInput())
  7090. return NULL;
  7091. }
  7092. try
  7093. {
  7094. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  7095. size32_t outSize = helper.transform(rowBuilder, buffer, curChildRow, ++curRow);
  7096. curChildRow = cursor->next();
  7097. if (!curChildRow)
  7098. ReleaseClearRoxieRow(buffer);
  7099. if (outSize != 0)
  7100. {
  7101. processed++;
  7102. return rowBuilder.finalizeRowClear(outSize);
  7103. }
  7104. }
  7105. catch (IException *E)
  7106. {
  7107. throw makeWrappedException(E);
  7108. }
  7109. }
  7110. }
  7111. };
  7112. class CRoxieServerNormalizeChildActivityFactory : public CRoxieServerActivityFactory
  7113. {
  7114. public:
  7115. CRoxieServerNormalizeChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7116. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  7117. {
  7118. }
  7119. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  7120. {
  7121. return new CRoxieServerNormalizeChildActivity(_ctx, this, _probeManager);
  7122. }
  7123. };
  7124. IRoxieServerActivityFactory *createRoxieServerNormalizeChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7125. {
  7126. return new CRoxieServerNormalizeChildActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  7127. }
  7128. //=================================================================================
  7129. class CRoxieServerNormalizeLinkedChildActivity : public CRoxieServerActivity
  7130. {
  7131. IHThorNormalizeLinkedChildArg &helper;
  7132. OwnedConstRoxieRow curParent;
  7133. OwnedConstRoxieRow curChild;
  7134. unsigned numProcessedLastGroup;
  7135. bool advanceInput()
  7136. {
  7137. loop
  7138. {
  7139. curParent.setown(inputStream->nextRow());
  7140. if (!curParent && (processed == numProcessedLastGroup))
  7141. curParent.setown(inputStream->nextRow());
  7142. if (!curParent)
  7143. {
  7144. numProcessedLastGroup = processed;
  7145. return false;
  7146. }
  7147. curChild.set(helper.first(curParent));
  7148. if (curChild)
  7149. return true;
  7150. }
  7151. }
  7152. public:
  7153. CRoxieServerNormalizeLinkedChildActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  7154. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorNormalizeLinkedChildArg &)basehelper)
  7155. {
  7156. numProcessedLastGroup = 0;
  7157. }
  7158. ~CRoxieServerNormalizeLinkedChildActivity()
  7159. {
  7160. }
  7161. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7162. {
  7163. numProcessedLastGroup = 0;
  7164. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7165. }
  7166. virtual void reset()
  7167. {
  7168. curParent.clear();
  7169. curChild.clear();
  7170. CRoxieServerActivity::reset();
  7171. }
  7172. const void *nextRow()
  7173. {
  7174. ActivityTimer t(totalCycles, timeActivities);
  7175. loop
  7176. {
  7177. if (!curParent)
  7178. {
  7179. if (!advanceInput())
  7180. return NULL;
  7181. }
  7182. try
  7183. {
  7184. const void *ret = curChild.getClear();
  7185. curChild.set(helper.next());
  7186. if (!curChild)
  7187. curParent.clear();
  7188. if (ret)
  7189. {
  7190. processed++;
  7191. return ret;
  7192. }
  7193. }
  7194. catch (IException *E)
  7195. {
  7196. throw makeWrappedException(E);
  7197. }
  7198. }
  7199. }
  7200. };
  7201. class CRoxieServerNormalizeLinkedChildActivityFactory : public CRoxieServerActivityFactory
  7202. {
  7203. public:
  7204. CRoxieServerNormalizeLinkedChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7205. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  7206. {
  7207. }
  7208. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  7209. {
  7210. return new CRoxieServerNormalizeLinkedChildActivity(_ctx, this, _probeManager);
  7211. }
  7212. };
  7213. IRoxieServerActivityFactory *createRoxieServerNormalizeLinkedChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7214. {
  7215. return new CRoxieServerNormalizeLinkedChildActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  7216. }
  7217. //=================================================================================
  7218. class CRoxieServerSortActivity : public CRoxieServerActivity
  7219. {
  7220. protected:
  7221. IHThorSortArg &helper;
  7222. ICompare *compare;
  7223. Owned<ISortAlgorithm> sorter;
  7224. bool readInput;
  7225. RoxieSortAlgorithm sortAlgorithm;
  7226. unsigned sortFlags;
  7227. public:
  7228. CRoxieServerSortActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, RoxieSortAlgorithm _sortAlgorithm, unsigned _sortFlags)
  7229. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorSortArg &)basehelper), sortAlgorithm(_sortAlgorithm), sortFlags(_sortFlags)
  7230. {
  7231. compare = helper.queryCompare();
  7232. readInput = false;
  7233. }
  7234. virtual void onCreate(IHThorArg *_colocalParent)
  7235. {
  7236. CRoxieServerActivity::onCreate(_colocalParent);
  7237. if (sortAlgorithm==unknownSortAlgorithm)
  7238. sorter.clear();
  7239. else
  7240. sorter.setown(createSortAlgorithm(sortAlgorithm, compare, ctx->queryRowManager(), meta, ctx->queryCodeContext(), tempDirectory, activityId));
  7241. }
  7242. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7243. {
  7244. assertex(!readInput);
  7245. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7246. }
  7247. virtual void reset()
  7248. {
  7249. if (sorter)
  7250. sorter->reset();
  7251. readInput = false;
  7252. CRoxieServerActivity::reset();
  7253. }
  7254. static RoxieSortAlgorithm useAlgorithm(const char *algorithmName, unsigned sortFlags)
  7255. {
  7256. RoxieSortAlgorithm sortAlgorithm = unknownSortAlgorithm;
  7257. if (!algorithmName)
  7258. algorithmName = "";
  7259. if (stricmp(algorithmName, "quicksort")==0)
  7260. {
  7261. switch (sortFlags & (TAFstable|TAFspill))
  7262. {
  7263. case 0: sortAlgorithm = quickSortAlgorithm; break;
  7264. case TAFstable: sortAlgorithm = stableQuickSortAlgorithm; break;
  7265. case TAFspill: sortAlgorithm = spillingQuickSortAlgorithm; break;
  7266. case TAFstable|TAFspill: sortAlgorithm = stableSpillingQuickSortAlgorithm; break;
  7267. }
  7268. }
  7269. else if (stricmp(algorithmName, "parquicksort")==0)
  7270. {
  7271. switch (sortFlags & TAFstable)
  7272. {
  7273. case 0: sortAlgorithm = parallelQuickSortAlgorithm; break;
  7274. case TAFstable: sortAlgorithm = parallelStableQuickSortAlgorithm; break;
  7275. default: throwUnexpected();
  7276. }
  7277. }
  7278. else if (stricmp(algorithmName, "heapsort")==0)
  7279. sortAlgorithm = heapSortAlgorithm; // NOTE - we do allow UNSTABLE('heapsort') in order to facilitate runtime selection. Also explicit selection of heapsort overrides request to spill
  7280. else if (stricmp(algorithmName, "mergesort")==0)
  7281. sortAlgorithm = (sortFlags & TAFspill) ? spillingMergeSortAlgorithm : mergeSortAlgorithm;
  7282. else if (stricmp(algorithmName, "parmergesort")==0)
  7283. sortAlgorithm = (sortFlags & TAFspill) ? spillingParallelMergeSortAlgorithm : parallelMergeSortAlgorithm;
  7284. else if (stricmp(algorithmName, "tbbqsort")==0)
  7285. sortAlgorithm = tbbQuickSortAlgorithm;
  7286. else if (stricmp(algorithmName, "tbbstableqsort")==0)
  7287. sortAlgorithm = tbbStableQuickSortAlgorithm;
  7288. else
  7289. {
  7290. if (*algorithmName)
  7291. WARNLOG(ROXIE_UNKNOWN_ALGORITHM, "Ignoring unsupported sort order algorithm '%s', using default", algorithmName);
  7292. if (sortFlags & TAFspill)
  7293. sortAlgorithm = ((sortFlags & TAFunstable) != 0) ? spillingQuickSortAlgorithm : stableSpillingQuickSortAlgorithm;
  7294. else if (sortFlags & TAFunstable)
  7295. sortAlgorithm = quickSortAlgorithm;
  7296. else
  7297. sortAlgorithm = heapSortAlgorithm;
  7298. }
  7299. return sortAlgorithm;
  7300. }
  7301. virtual const void * nextRow()
  7302. {
  7303. ActivityTimer t(totalCycles, timeActivities);
  7304. if (!readInput)
  7305. {
  7306. if (sortAlgorithm == unknownSortAlgorithm)
  7307. {
  7308. sorter.clear();
  7309. IHThorAlgorithm *sortMethod = static_cast<IHThorAlgorithm *>(helper.selectInterface(TAIalgorithm_1));
  7310. OwnedRoxieString algorithmName(sortMethod->getAlgorithm());
  7311. sortAlgorithm = useAlgorithm(algorithmName, sortFlags);
  7312. sorter.setown(createSortAlgorithm(sortAlgorithm, compare, ctx->queryRowManager(), meta, ctx->queryCodeContext(), tempDirectory, activityId));
  7313. }
  7314. sorter->prepare(inputStream);
  7315. noteStatistic(StTimeSortElapsed, cycle_to_nanosec(sorter->getElapsedCycles(true)));
  7316. readInput = true;
  7317. }
  7318. const void *ret = sorter->next();
  7319. if (ret)
  7320. processed++;
  7321. else
  7322. {
  7323. sorter->reset();
  7324. readInput = false; // ready for next group
  7325. }
  7326. return ret;
  7327. }
  7328. };
  7329. class CRoxieServerSortActivityFactory : public CRoxieServerActivityFactory
  7330. {
  7331. RoxieSortAlgorithm sortAlgorithm;
  7332. unsigned sortFlags;
  7333. public:
  7334. CRoxieServerSortActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7335. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  7336. {
  7337. Owned<IHThorSortArg> sortHelper = (IHThorSortArg *) helperFactory();
  7338. const char *algorithmName = NULL;
  7339. IHThorAlgorithm *sortMethod = static_cast<IHThorAlgorithm *>(sortHelper->selectInterface(TAIalgorithm_1));
  7340. if (sortMethod)
  7341. {
  7342. sortFlags = sortMethod->getAlgorithmFlags();
  7343. if (sortFlags & TAFconstant)
  7344. algorithmName = sortMethod->getAlgorithm();
  7345. }
  7346. else
  7347. sortFlags = TAFstable|TAFconstant;
  7348. bool forceSpill = _queryFactory.queryOptions().allSortsMaySpill || _graphNode.getPropBool("hint[@name='spill']/@value", false);
  7349. if (forceSpill)
  7350. sortFlags |= TAFspill;
  7351. if (!(sortFlags & TAFunstable))
  7352. sortFlags |= TAFstable; // Assume stable unless specifically requested otherwise
  7353. if (sortFlags & TAFconstant)
  7354. sortAlgorithm = CRoxieServerSortActivity::useAlgorithm(algorithmName, sortFlags);
  7355. else
  7356. sortAlgorithm = unknownSortAlgorithm;
  7357. }
  7358. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  7359. {
  7360. return new CRoxieServerSortActivity(_ctx, this, _probeManager, sortAlgorithm, sortFlags);
  7361. }
  7362. virtual const StatisticsMapping &queryStatsMapping() const
  7363. {
  7364. return sortStatistics;
  7365. }
  7366. };
  7367. IRoxieServerActivityFactory *createRoxieServerSortActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7368. {
  7369. return new CRoxieServerSortActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  7370. }
  7371. //=====================================================================================================
  7372. static int compareUint64(const void * _left, const void * _right)
  7373. {
  7374. const unsigned __int64 left = *static_cast<const unsigned __int64 *>(_left);
  7375. const unsigned __int64 right = *static_cast<const unsigned __int64 *>(_right);
  7376. if (left < right)
  7377. return -1;
  7378. if (left > right)
  7379. return -1;
  7380. return 0;
  7381. }
  7382. class CRoxieServerQuantileActivity : public CRoxieServerActivity
  7383. {
  7384. protected:
  7385. Owned<ISortAlgorithm> sorter;
  7386. IHThorQuantileArg &helper;
  7387. ConstPointerArray sorted;
  7388. ICompare *compare;
  7389. unsigned flags;
  7390. double skew;
  7391. unsigned __int64 numDivisions;
  7392. bool rangeIsAll;
  7393. size32_t rangeSize;
  7394. rtlDataAttr rangeValues;
  7395. bool calculated;
  7396. bool processedAny;
  7397. bool anyThisGroup;
  7398. bool eof;
  7399. unsigned curQuantile;
  7400. unsigned curIndex;
  7401. unsigned curIndexExtra;
  7402. unsigned skipSize;
  7403. unsigned skipExtra;
  7404. unsigned prevIndex;
  7405. public:
  7406. CRoxieServerQuantileActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _flags)
  7407. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorQuantileArg &)basehelper), flags(_flags)
  7408. {
  7409. compare = helper.queryCompare();
  7410. skew = 0.0;
  7411. numDivisions = 0;
  7412. calculated = false;
  7413. processedAny = false;
  7414. anyThisGroup = false;
  7415. eof = false;
  7416. rangeIsAll = true;
  7417. rangeSize = 0;
  7418. curQuantile = 0;
  7419. prevIndex = 0;
  7420. curIndex = 0;
  7421. curIndexExtra = 0;
  7422. skipSize = 0;
  7423. skipExtra = 0;
  7424. if (flags & TQFunstable)
  7425. sorter.setown(createQuickSortAlgorithm(compare));
  7426. else
  7427. sorter.setown(createMergeSortAlgorithm(compare));
  7428. }
  7429. virtual void reset()
  7430. {
  7431. sorter->reset();
  7432. calculated = false;
  7433. processedAny = false;
  7434. anyThisGroup = false;
  7435. CRoxieServerActivity::reset();
  7436. }
  7437. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7438. {
  7439. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7440. skew = helper.getSkew();
  7441. numDivisions = helper.getNumDivisions();
  7442. //Check for -ve integer values and treat as out of range
  7443. if ((__int64)numDivisions < 1)
  7444. numDivisions = 1;
  7445. if (flags & TQFhasrange)
  7446. helper.getRange(rangeIsAll, rangeSize, rangeValues.refdata());
  7447. else
  7448. {
  7449. rangeIsAll = true;
  7450. rangeSize = 0;
  7451. }
  7452. if (rangeSize)
  7453. {
  7454. //Sort the range items into order to allow quick comparison
  7455. qsort(rangeValues.getdata(), rangeSize / sizeof(unsigned __int64), sizeof(unsigned __int64), compareUint64);
  7456. }
  7457. calculated = false;
  7458. processedAny = false;
  7459. anyThisGroup = false;
  7460. eof = false;
  7461. curQuantile = 0;
  7462. prevIndex = 0;
  7463. curIndex = 0;
  7464. curIndexExtra = 0;
  7465. }
  7466. virtual bool needsAllocator() const { return true; }
  7467. virtual const void * nextRow()
  7468. {
  7469. ActivityTimer t(totalCycles, timeActivities);
  7470. if (eof)
  7471. return NULL;
  7472. const void * ret = NULL;
  7473. for(;;)
  7474. {
  7475. if (!calculated)
  7476. {
  7477. if (flags & TQFlocalsorted)
  7478. {
  7479. for (;;)
  7480. {
  7481. const void * next = inputStream->nextRow();
  7482. if (!next)
  7483. break;
  7484. sorted.append(next);
  7485. }
  7486. }
  7487. else
  7488. {
  7489. sorter->prepare(inputStream);
  7490. sorter->getSortedGroup(sorted);
  7491. }
  7492. if (sorted.ordinality() == 0)
  7493. {
  7494. if (processedAny)
  7495. {
  7496. eof = true;
  7497. return NULL;
  7498. }
  7499. //Unusual case 0 rows - add a default row instead
  7500. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  7501. size32_t thisSize = helper.createDefault(rowBuilder);
  7502. sorted.append(rowBuilder.finalizeRowClear(thisSize));
  7503. }
  7504. calculated = true;
  7505. processedAny = true;
  7506. anyThisGroup = false;
  7507. curQuantile = 0;
  7508. curIndex = 0;
  7509. curIndexExtra = (numDivisions-1) / 2; // to ensure correctly rounded up
  7510. prevIndex = curIndex-1; // Ensure it doesn't match
  7511. skipSize = (sorted.ordinality() / numDivisions);
  7512. skipExtra = (sorted.ordinality() % numDivisions);
  7513. }
  7514. if (isQuantileIncluded(curQuantile))
  7515. {
  7516. if (!(flags & TQFdedup) || (prevIndex != curIndex))
  7517. {
  7518. const void * lhs = sorted.item(curIndex);
  7519. if (flags & TQFneedtransform)
  7520. {
  7521. unsigned outSize;
  7522. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  7523. try
  7524. {
  7525. outSize = helper.transform(rowBuilder, lhs, curQuantile);
  7526. }
  7527. catch (IException *E)
  7528. {
  7529. throw makeWrappedException(E);
  7530. }
  7531. if (outSize)
  7532. ret = rowBuilder.finalizeRowClear(outSize);
  7533. }
  7534. else
  7535. {
  7536. LinkRoxieRow(lhs);
  7537. ret = lhs;
  7538. }
  7539. prevIndex = curIndex; // even if output was skipped?
  7540. }
  7541. }
  7542. curIndex += skipSize;
  7543. curIndexExtra += skipExtra;
  7544. if (curIndexExtra >= numDivisions)
  7545. {
  7546. curIndex++;
  7547. curIndexExtra -= numDivisions;
  7548. }
  7549. //Ensure the current index always stays valid.
  7550. if (curIndex >= sorted.ordinality())
  7551. curIndex = sorted.ordinality()-1;
  7552. curQuantile++;
  7553. if (curQuantile > numDivisions)
  7554. {
  7555. sorted.kill();
  7556. sorter->reset();
  7557. calculated = false; // ready for next group
  7558. }
  7559. if (ret)
  7560. {
  7561. anyThisGroup = true;
  7562. processed++;
  7563. return ret;
  7564. }
  7565. if (curQuantile > numDivisions)
  7566. {
  7567. if (anyThisGroup)
  7568. return NULL;
  7569. }
  7570. }
  7571. }
  7572. bool isQuantileIncluded(unsigned quantile) const
  7573. {
  7574. if (quantile == 0)
  7575. return (flags & TQFfirst) != 0;
  7576. if (quantile == numDivisions)
  7577. return (flags & TQFlast) != 0;
  7578. if (rangeIsAll)
  7579. return true;
  7580. //Compare against the list of ranges provided
  7581. //MORE: Since the list is sorted should only need to compare the next (and allow for dups)
  7582. unsigned rangeNum = rangeSize / sizeof(unsigned __int64);
  7583. const unsigned __int64 * ranges = static_cast<const unsigned __int64 *>(rangeValues.getdata());
  7584. for (unsigned i = 0; i < rangeNum; i++)
  7585. {
  7586. if (ranges[i] == quantile)
  7587. return true;
  7588. }
  7589. return false;
  7590. }
  7591. };
  7592. class CRoxieServerQuantileActivityFactory : public CRoxieServerActivityFactory
  7593. {
  7594. unsigned flags;
  7595. public:
  7596. CRoxieServerQuantileActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7597. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  7598. {
  7599. Owned<IHThorQuantileArg> quantileHelper = (IHThorQuantileArg *) helperFactory();
  7600. flags = quantileHelper->getFlags();
  7601. }
  7602. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  7603. {
  7604. return new CRoxieServerQuantileActivity(_ctx, this, _probeManager, flags);
  7605. }
  7606. };
  7607. IRoxieServerActivityFactory *createRoxieServerQuantileActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7608. {
  7609. return new CRoxieServerQuantileActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  7610. }
  7611. //=====================================================================================================
  7612. class CRoxieServerSortedActivity : public CRoxieServerActivity
  7613. {
  7614. IHThorSortedArg &helper;
  7615. ICompare * compare;
  7616. const void *prev;
  7617. IRangeCompare * stepCompare;
  7618. public:
  7619. CRoxieServerSortedActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  7620. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorSortedArg &)basehelper)
  7621. {
  7622. prev = NULL;
  7623. compare = helper.queryCompare();
  7624. stepCompare = NULL;
  7625. }
  7626. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7627. {
  7628. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7629. IInputSteppingMeta * stepMeta = input->querySteppingMeta();
  7630. if (stepMeta)
  7631. stepCompare = stepMeta->queryCompare();
  7632. prev = NULL;
  7633. }
  7634. virtual void reset()
  7635. {
  7636. ReleaseClearRoxieRow(prev);
  7637. CRoxieServerActivity::reset();
  7638. }
  7639. virtual const void * nextRow()
  7640. {
  7641. ActivityTimer t(totalCycles, timeActivities);
  7642. const void *ret = inputStream->nextRow();
  7643. if (ret && prev && compare->docompare(prev, ret) > 0)
  7644. {
  7645. // MORE - better to give mismatching rows that indexes?
  7646. throw MakeStringException(ROXIE_NOT_SORTED, "SORTED(%u) detected incorrectly sorted rows (row %d, %d))", activityId, processed, processed+1);
  7647. }
  7648. ReleaseRoxieRow(prev);
  7649. prev = ret;
  7650. if (ret)
  7651. {
  7652. LinkRoxieRow(prev);
  7653. processed++;
  7654. }
  7655. return ret;
  7656. }
  7657. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  7658. {
  7659. ActivityTimer t(totalCycles, timeActivities);
  7660. const void *ret = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  7661. if (ret && prev && compare->docompare(prev, ret) > 0)
  7662. {
  7663. // MORE - better to give mismatching rows that indexes?
  7664. throw MakeStringException(ROXIE_NOT_SORTED, "SORTED(%u) detected incorrectly sorted rows (row %d, %d))", activityId, processed, processed+1);
  7665. }
  7666. ReleaseRoxieRow(prev);
  7667. prev = ret;
  7668. if (ret)
  7669. {
  7670. LinkRoxieRow(prev);
  7671. processed++;
  7672. }
  7673. return ret;
  7674. }
  7675. IInputSteppingMeta * querySteppingMeta()
  7676. {
  7677. return input->querySteppingMeta();
  7678. }
  7679. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  7680. {
  7681. return input->gatherConjunctions(collector);
  7682. }
  7683. virtual void resetEOF()
  7684. {
  7685. inputStream->resetEOF();
  7686. }
  7687. };
  7688. class CRoxieServerSortedActivityFactory : public CRoxieServerActivityFactory
  7689. {
  7690. public:
  7691. CRoxieServerSortedActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7692. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  7693. {
  7694. }
  7695. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  7696. {
  7697. return new CRoxieServerSortedActivity(_ctx, this, _probeManager);
  7698. }
  7699. };
  7700. IRoxieServerActivityFactory *createRoxieServerSortedActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7701. {
  7702. return new CRoxieServerSortedActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  7703. }
  7704. //=====================================================================================================
  7705. class CRoxieServerThroughSpillActivity : public CRoxieServerActivity
  7706. {
  7707. /*
  7708. BE VERY CAREFUL - this code is tricky.
  7709. Note that starts and stops (and resets) can occur in strange orders
  7710. The FIRST start OR stop must initialize the activity but only the first START should call the upstream start.
  7711. The last stop should call the upstream stop.
  7712. The first reset should call the upstream reset.
  7713. 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
  7714. not yet had start or stop called - for this to happen init() is called on all outputs on the first start or stop.
  7715. Some outputs may be completely pruned away when used in a GRAPH - these outputs should not receive any start/stop/reset and should be
  7716. ignored in the minIndex calculation
  7717. */
  7718. public:
  7719. IHThorArg &helper;
  7720. unsigned activeOutputs;
  7721. unsigned numOutputs;
  7722. unsigned numOriginalOutputs;
  7723. QueueOf<const void, true> buffer;
  7724. CriticalSection crit;
  7725. CriticalSection crit2;
  7726. unsigned tailIdx;
  7727. unsigned headIdx;
  7728. Owned<IException> error;
  7729. class OutputAdaptor : implements IEngineRowStream, implements IFinalRoxieInput, public CInterface
  7730. {
  7731. bool eof, eofpending, stopped;
  7732. public:
  7733. CRoxieServerThroughSpillActivity *parent;
  7734. unsigned idx;
  7735. unsigned oid;
  7736. unsigned processed;
  7737. cycle_t totalCycles; // We track this per output so that the pullers get a meaningful value to use when calculating their localtime
  7738. public:
  7739. IMPLEMENT_IINTERFACE;
  7740. OutputAdaptor()
  7741. {
  7742. parent = NULL;
  7743. oid = 0;
  7744. idx = 0;
  7745. processed = 0;
  7746. totalCycles = 0;
  7747. eofpending = false;
  7748. eof = false;
  7749. stopped = false;
  7750. }
  7751. ~OutputAdaptor()
  7752. {
  7753. if (traceStartStop)
  7754. DBGLOG("%p ~OutputAdaptor %d", this, oid);
  7755. if (processed && parent && parent->factory)
  7756. {
  7757. parent->factory->noteProcessed(oid, processed);
  7758. if (parent->ctx)
  7759. parent->ctx->noteProcessed(parent->querySubgraphId(), parent->activityId, oid, processed, 0);
  7760. }
  7761. }
  7762. void init()
  7763. {
  7764. if (traceStartStop)
  7765. DBGLOG("%p init Input adaptor %d", this, oid);
  7766. idx = 0;
  7767. processed = 0;
  7768. eofpending = false;
  7769. eof = false;
  7770. stopped = false;
  7771. }
  7772. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { assertex(idx==0); return this; }
  7773. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { assertex(idx==0); return nullptr; }
  7774. virtual IRoxieServerActivity *queryActivity()
  7775. {
  7776. return parent;
  7777. }
  7778. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  7779. {
  7780. return parent->queryIndexReadActivity();
  7781. }
  7782. virtual unsigned __int64 queryTotalCycles() const
  7783. {
  7784. return totalCycles;
  7785. }
  7786. virtual const void * nextRow()
  7787. {
  7788. SimpleActivityTimer t(totalCycles, parent->timeActivities);
  7789. if (eof)
  7790. return NULL;
  7791. const void *ret = parent->readBuffered(idx, oid);
  7792. #ifdef TRACE_SPLIT
  7793. parent->CTXLOG("Adaptor %d got back %p for record %d", oid, ret, idx);
  7794. #endif
  7795. if (ret)
  7796. {
  7797. processed++;
  7798. eofpending = false;
  7799. }
  7800. else if (eofpending)
  7801. eof = true;
  7802. else
  7803. eofpending = true;
  7804. return ret;
  7805. }
  7806. virtual IOutputMetaData * queryOutputMeta() const
  7807. {
  7808. return parent->queryOutputMeta();
  7809. }
  7810. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7811. {
  7812. // NOTE: it is tempting to move the init() of all output adaptors here. However that is not a good idea,
  7813. // since adaptors that have not yet started or stopped (but are going to) still need to have been init()'ed
  7814. // for minIndex to give the correct answers
  7815. // therefore, we call init() on all adaptors on receipt of the first start() or stop()
  7816. if (traceStartStop)
  7817. parent->CTXLOG("%p start Input adaptor %d stopped = %d", this, oid, stopped);
  7818. parent->start(oid, parentExtractSize, parentExtract, paused);
  7819. }
  7820. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  7821. {
  7822. parent->connectInputStreams(consumerOrdered);
  7823. streams.append(this);
  7824. return NULL;
  7825. }
  7826. virtual void stop()
  7827. {
  7828. if (traceStartStop)
  7829. parent->CTXLOG("%p stop Input adaptor %d stopped = %d", this, oid, stopped);
  7830. if (!stopped)
  7831. {
  7832. parent->stop(oid, idx); // NOTE - may call init()
  7833. stopped = true; // parent code relies on stop being called exactly once per adaptor, so make sure it is!
  7834. }
  7835. };
  7836. virtual void reset()
  7837. {
  7838. if (traceStartStop)
  7839. parent->CTXLOG("%p reset Input adaptor %d stopped = %d", this, oid, stopped);
  7840. parent->reset(oid);
  7841. idx = 0; // value should not be relevant really but this is the safest...
  7842. stopped = false;
  7843. };
  7844. virtual void resetEOF()
  7845. {
  7846. parent->resetEOF();
  7847. }
  7848. virtual void checkAbort()
  7849. {
  7850. parent->checkAbort();
  7851. }
  7852. } *adaptors;
  7853. bool *used;
  7854. unsigned nextFreeOutput()
  7855. {
  7856. unsigned i = numOutputs;
  7857. while (i)
  7858. {
  7859. i--;
  7860. if (!used[i])
  7861. return i;
  7862. }
  7863. throwUnexpected();
  7864. }
  7865. unsigned minIndex(unsigned exceptOid)
  7866. {
  7867. // MORE - yukky code (and slow). Could keep them heapsorted by idx or something
  7868. // this is trying to determine whether any of the adaptors will in the future read a given record
  7869. unsigned minIdx = (unsigned) -1;
  7870. for (unsigned i = 0; i < numOutputs; i++)
  7871. {
  7872. if (i != exceptOid && used[i] && adaptors[i].idx < minIdx)
  7873. minIdx = adaptors[i].idx;
  7874. }
  7875. return minIdx;
  7876. }
  7877. inline bool isLastTailReader(unsigned exceptOid)
  7878. {
  7879. for (unsigned i = 0; i < numOutputs; i++)
  7880. {
  7881. if (i != exceptOid && adaptors[i].idx == tailIdx && used[i])
  7882. return false;
  7883. }
  7884. return true;
  7885. }
  7886. void initOutputs()
  7887. {
  7888. activeOutputs = numOutputs;
  7889. for (unsigned i = 0; i < numOriginalOutputs; i++)
  7890. if (used[i])
  7891. adaptors[i].init();
  7892. state = STATEstarting;
  7893. }
  7894. public:
  7895. CRoxieServerThroughSpillActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  7896. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper(basehelper), numOutputs(_numOutputs)
  7897. {
  7898. numOriginalOutputs = numOutputs;
  7899. adaptors = new OutputAdaptor[numOutputs];
  7900. used = new bool[numOutputs];
  7901. for (unsigned i = 0; i < numOutputs; i++)
  7902. {
  7903. adaptors[i].parent = this;
  7904. adaptors[i].oid = i;
  7905. used[i] = false;
  7906. }
  7907. tailIdx = 0;
  7908. headIdx = 0;
  7909. activeOutputs = numOutputs;
  7910. }
  7911. ~CRoxieServerThroughSpillActivity()
  7912. {
  7913. delete [] adaptors;
  7914. delete [] used;
  7915. }
  7916. const void *readBuffered(unsigned &idx, unsigned oid)
  7917. {
  7918. //False positives are fine, false negatives are not.. so headIdx must only be updated when a row will be available.
  7919. const unsigned curIdx = idx;
  7920. if (curIdx == headIdx) // test once without getting the crit2 sec
  7921. {
  7922. CriticalBlock b2(crit2); // but only one puller gets to read the head
  7923. if (curIdx == headIdx) // test again now that we have it
  7924. {
  7925. 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
  7926. if (error)
  7927. throw error.getLink();
  7928. try
  7929. {
  7930. const void *row = inputStream->nextRow();
  7931. if (activeOutputs==1)
  7932. {
  7933. #ifdef TRACE_SPLIT
  7934. CTXLOG("spill %d optimised return of %p", activityId, row);
  7935. #endif
  7936. headIdx++;
  7937. idx++;
  7938. return row; // optimization for the case where only one output still active.
  7939. }
  7940. CriticalBlock b(crit);
  7941. headIdx++;
  7942. idx++;
  7943. if (activeOutputs==1)
  7944. return row; // optimization for the case where only one output still active.
  7945. buffer.enqueue(row);
  7946. if (row) LinkRoxieRow(row);
  7947. return row;
  7948. }
  7949. catch (IException *E)
  7950. {
  7951. #ifdef TRACE_SPLIT
  7952. CTXLOG("spill %d caught exception", activityId);
  7953. #endif
  7954. error.set(E);
  7955. throw;
  7956. }
  7957. catch (...)
  7958. {
  7959. IException *E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught in CRoxieServerThroughSpillActivity::readBuffered");
  7960. error.set(E);
  7961. throw E;
  7962. }
  7963. }
  7964. }
  7965. CriticalBlock b(crit);
  7966. 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
  7967. unsigned lidx = curIdx - tailIdx;
  7968. idx++;
  7969. if (!lidx)
  7970. {
  7971. // The numOutputs <= 2 check optimizes slightly the common case of 2-way splitters.
  7972. // 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
  7973. if (numOutputs <= 2 || isLastTailReader(oid)) // NOTE - this includes the case where minIndex returns (unsigned) -1, meaning no other active pullers
  7974. {
  7975. tailIdx++;
  7976. const void *ret = buffer.dequeue(); // no need to link - last puller
  7977. #ifdef TRACE_SPLIT
  7978. CTXLOG("last puller return of %p", ret);
  7979. #endif
  7980. return ret;
  7981. }
  7982. }
  7983. const void *ret = buffer.item(lidx);
  7984. if (ret) LinkRoxieRow(ret);
  7985. #ifdef TRACE_SPLIT
  7986. CTXLOG("standard return of %p", ret);
  7987. #endif
  7988. return ret;
  7989. }
  7990. virtual void start(unsigned oid, unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7991. {
  7992. CriticalBlock b(crit);
  7993. if (error)
  7994. throw error.getLink();
  7995. if (factory)
  7996. factory->noteStarted(oid);
  7997. if (traceStartStop)
  7998. CTXLOG("SPLIT %p: start %d child %d activeOutputs %d numOutputs %d numOriginalOutputs %d state %s", this, activityId, oid, activeOutputs, numOutputs, numOriginalOutputs, queryStateText(state));
  7999. if (state != STATEstarted)
  8000. {
  8001. if (state != STATEstarting)
  8002. initOutputs();
  8003. tailIdx = 0;
  8004. headIdx = 0;
  8005. error.clear();
  8006. try
  8007. {
  8008. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8009. }
  8010. catch (IException *E)
  8011. {
  8012. #ifdef TRACE_SPLIT
  8013. CTXLOG("spill %d caught exception in start", activityId);
  8014. #endif
  8015. error.set(E);
  8016. throw;
  8017. }
  8018. catch (...)
  8019. {
  8020. IException *E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught in CRoxieServerThroughSpillActivity::start");
  8021. error.set(E);
  8022. throw E;
  8023. }
  8024. }
  8025. }
  8026. void stop(unsigned oid, unsigned & idx)
  8027. {
  8028. // Note that OutputAdaptor code ensures that stop is not called more than once per adaptor
  8029. CriticalBlock b(crit);
  8030. #ifdef TRACE_STARTSTOP
  8031. if (traceStartStop)
  8032. {
  8033. CTXLOG("SPLIT %p: stop %d child %d activeOutputs %d numOutputs %d numOriginalOutputs %d state %s", this, activityId, oid, activeOutputs, numOutputs, numOriginalOutputs, queryStateText(state));
  8034. if (watchActivityId && watchActivityId==activityId)
  8035. {
  8036. CTXLOG("WATCH: stop %d", activityId);
  8037. }
  8038. }
  8039. #endif
  8040. if (state != STATEstarting && state != STATEstarted)
  8041. initOutputs();
  8042. if (activeOutputs > 1)
  8043. {
  8044. if (tailIdx==idx)
  8045. {
  8046. // Discard all buffered rows that are there purely for this adaptor to read them
  8047. unsigned min = minIndex(oid);
  8048. if (min != (unsigned) -1)
  8049. // what does -1 signify?? No-one wants anything? In which case can't we kill all rows??
  8050. // Should never happen though if there are still some active.
  8051. // there may be a small window where adaptors are blocked on the semaphore...
  8052. {
  8053. #ifdef TRACE_SPLIT
  8054. CTXLOG("%p: Discarding buffered rows from %d to %d for oid %x (%d outputs active)", this, idx, min, oid, activeOutputs);
  8055. #endif
  8056. while (tailIdx < min)
  8057. {
  8058. ReleaseRoxieRow(buffer.dequeue());
  8059. tailIdx++;
  8060. }
  8061. }
  8062. }
  8063. activeOutputs--;
  8064. idx = (unsigned) -1; // causes minIndex not to save rows for me...
  8065. return;
  8066. }
  8067. #ifdef TRACE_SPLIT
  8068. CTXLOG("%p: All outputs done", this);
  8069. #endif
  8070. activeOutputs = numOutputs;
  8071. CRoxieServerActivity::stop();
  8072. };
  8073. void reset(unsigned oid)
  8074. {
  8075. if (traceStartStop)
  8076. CTXLOG("SPLIT %p: reset %d child %d activeOutputs %d numOutputs %d numOriginalOutputs %d state %s", this, activityId, oid, activeOutputs, numOutputs, numOriginalOutputs, queryStateText(state));
  8077. activeOutputs = numOutputs;
  8078. while (buffer.ordinality())
  8079. ReleaseRoxieRow(buffer.dequeue());
  8080. error.clear();
  8081. if (state != STATEreset) // make sure input is only reset once
  8082. CRoxieServerActivity::reset();
  8083. };
  8084. void connectInputStreams(bool consumerOrdered)
  8085. {
  8086. if (!inputStream)
  8087. CRoxieServerActivity::connectInputStreams(consumerOrdered);
  8088. }
  8089. virtual const void *nextRow()
  8090. {
  8091. throwUnexpected(); // Internal logic error - we are not anybody's input
  8092. }
  8093. virtual IOutputMetaData * queryOutputMeta() const
  8094. {
  8095. // if (outputMeta)
  8096. // return outputMeta;
  8097. // else
  8098. return input->queryOutputMeta(); // not always known (e.g. disk write - though Gavin _could_ fill it in)
  8099. }
  8100. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  8101. {
  8102. if (idx==(unsigned)-1)
  8103. idx = nextFreeOutput(); // MORE - what is this used for?
  8104. assertex(idx < numOriginalOutputs);
  8105. assertex(!used[idx]);
  8106. used[idx] = true;
  8107. return &adaptors[idx];
  8108. }
  8109. virtual void resetOutputsUsed()
  8110. {
  8111. numOutputs = 1;
  8112. activeOutputs = 1;
  8113. // MORE RKC->GH should we be clearing the used array here? anywhere?
  8114. }
  8115. virtual void noteOutputUsed()
  8116. {
  8117. assertex(numOutputs < numOriginalOutputs);
  8118. numOutputs++;
  8119. activeOutputs = numOutputs;
  8120. }
  8121. virtual bool isPassThrough()
  8122. {
  8123. return numOutputs==1;
  8124. }
  8125. };
  8126. class CRoxieServerThroughSpillActivityFactory : public CRoxieServerMultiOutputFactory
  8127. {
  8128. public:
  8129. CRoxieServerThroughSpillActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8130. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  8131. {
  8132. Owned<IHThorSpillArg> helper = (IHThorSpillArg *) helperFactory();
  8133. setNumOutputs(helper->getTempUsageCount() + 1);
  8134. }
  8135. CRoxieServerThroughSpillActivityFactory(IQueryFactory &_queryFactory, HelperFactory *_helperFactory, unsigned _numOutputs, IPropertyTree &_graphNode)
  8136. : CRoxieServerMultiOutputFactory(0, 0, _queryFactory, _helperFactory, TAKsplit, _graphNode)
  8137. {
  8138. setNumOutputs(_numOutputs);
  8139. }
  8140. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  8141. {
  8142. return new CRoxieServerThroughSpillActivity(_ctx, this, _probeManager, numOutputs);
  8143. }
  8144. };
  8145. IRoxieServerActivityFactory *createRoxieServerThroughSpillActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8146. {
  8147. return new CRoxieServerThroughSpillActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  8148. }
  8149. IRoxieServerActivityFactory *createRoxieServerThroughSpillActivityFactory(IQueryFactory &_queryFactory, HelperFactory *_factory, unsigned _numOutputs, IPropertyTree &_graphNode)
  8150. {
  8151. return new CRoxieServerThroughSpillActivityFactory(_queryFactory, _factory, _numOutputs, _graphNode);
  8152. }
  8153. //----------------------------------------------------------------------------------------------
  8154. class CRoxieServerSplitActivityFactory : public CRoxieServerMultiOutputFactory
  8155. {
  8156. public:
  8157. CRoxieServerSplitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8158. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  8159. {
  8160. Owned<IHThorSplitArg> helper = (IHThorSplitArg *) helperFactory();
  8161. setNumOutputs(helper->numBranches());
  8162. }
  8163. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  8164. {
  8165. return new CRoxieServerThroughSpillActivity(_ctx, this, _probeManager, numOutputs);
  8166. }
  8167. };
  8168. IRoxieServerActivityFactory *createRoxieServerSplitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8169. {
  8170. return new CRoxieServerSplitActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  8171. }
  8172. //=====================================================================================================
  8173. #define PIPE_BUFSIZE 0x8000
  8174. static IException *createPipeFailureException(const char *cmd, unsigned retcode, IPipeProcess *pipe)
  8175. {
  8176. StringBuffer msg;
  8177. if(pipe->hasError())
  8178. {
  8179. try
  8180. {
  8181. char error[512];
  8182. size32_t sz = pipe->readError(sizeof(error), error);
  8183. if(sz && sz!=(size32_t)-1)
  8184. msg.append(", stderr: '").append(sz, error).append("'");
  8185. }
  8186. catch (IException *e)
  8187. {
  8188. EXCLOG(e, "Error reading pipe stderr");
  8189. e->Release();
  8190. }
  8191. }
  8192. return MakeStringException(ROXIE_PIPE_ERROR, "Pipe process %s returned error %u%s", cmd, retcode, msg.str());
  8193. }
  8194. class CRoxieServerPipeReadActivity : public CRoxieServerActivity
  8195. {
  8196. IHThorPipeReadArg &helper;
  8197. Owned<IPipeProcess> pipe;
  8198. StringAttr pipeCommand;
  8199. Owned<IOutputRowDeserializer> rowDeserializer;
  8200. Owned<IReadRowStream> readTransformer;
  8201. bool groupSignalled;
  8202. public:
  8203. CRoxieServerPipeReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8204. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorPipeReadArg &)basehelper)
  8205. {
  8206. groupSignalled = true;
  8207. }
  8208. virtual bool needsAllocator() const { return true; }
  8209. virtual void onCreate(IHThorArg *_colocalParent)
  8210. {
  8211. CRoxieServerActivity::onCreate(_colocalParent);
  8212. rowDeserializer.setown(rowAllocator->createDiskDeserializer(ctx->queryCodeContext()));
  8213. }
  8214. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8215. {
  8216. groupSignalled = true; // i.e. don't start with a NULL row
  8217. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8218. if (!readTransformer)
  8219. {
  8220. OwnedRoxieString xmlIteratorPath(helper.getXmlIteratorPath());
  8221. readTransformer.setown(createReadRowStream(rowAllocator, rowDeserializer, helper.queryXmlTransformer(), helper.queryCsvTransformer(), xmlIteratorPath, helper.getPipeFlags()));
  8222. }
  8223. OwnedRoxieString pipeProgram(helper.getPipeProgram());
  8224. openPipe(pipeProgram);
  8225. }
  8226. virtual void stop()
  8227. {
  8228. CRoxieServerActivity::stop();
  8229. pipe.clear();
  8230. readTransformer->setStream(NULL);
  8231. }
  8232. virtual const void *nextRow()
  8233. {
  8234. ActivityTimer t(totalCycles, timeActivities);
  8235. while (!waitForPipe())
  8236. {
  8237. if (!pipe)
  8238. return NULL;
  8239. if (helper.getPipeFlags() & TPFgroupeachrow)
  8240. {
  8241. if (!groupSignalled)
  8242. {
  8243. groupSignalled = true;
  8244. return NULL;
  8245. }
  8246. }
  8247. }
  8248. const void *ret = readTransformer->next();
  8249. assertex(ret != NULL); // if ret can ever be NULL then we need to recode this logic
  8250. processed++;
  8251. groupSignalled = false;
  8252. return ret;
  8253. }
  8254. protected:
  8255. bool waitForPipe()
  8256. {
  8257. if (!pipe)
  8258. return false; // done
  8259. if (!readTransformer->eos())
  8260. return true;
  8261. verifyPipe();
  8262. return false;
  8263. }
  8264. void openPipe(char const * cmd)
  8265. {
  8266. pipeCommand.setown(cmd);
  8267. pipe.setown(createPipeProcess());
  8268. if(!pipe->run(NULL, cmd, ".", false, true, true, 0x10000))
  8269. throw MakeStringException(ROXIE_PIPE_ERROR, "Could not run pipe process %s", cmd);
  8270. Owned<ISimpleReadStream> pipeReader = pipe->getOutputStream();
  8271. readTransformer->setStream(pipeReader.get());
  8272. }
  8273. void verifyPipe()
  8274. {
  8275. if (pipe)
  8276. {
  8277. unsigned err = pipe->wait();
  8278. if(err && !(helper.getPipeFlags() & TPFnofail))
  8279. {
  8280. throw createPipeFailureException(pipeCommand.get(), err, pipe);
  8281. }
  8282. pipe.clear();
  8283. }
  8284. }
  8285. };
  8286. class CRoxieServerPipeThroughActivity : public CRoxieServerActivity, implements IRecordPullerCallback
  8287. {
  8288. IHThorPipeThroughArg &helper;
  8289. RecordPullerThread puller;
  8290. Owned<IPipeProcess> pipe;
  8291. StringAttr pipeCommand;
  8292. InterruptableSemaphore pipeVerified;
  8293. InterruptableSemaphore pipeOpened;
  8294. CachedOutputMetaData inputMeta;
  8295. Owned<IOutputRowSerializer> rowSerializer;
  8296. Owned<IOutputRowDeserializer> rowDeserializer;
  8297. Owned<IPipeWriteXformHelper> writeTransformer;
  8298. Owned<IReadRowStream> readTransformer;
  8299. bool firstRead;
  8300. bool recreate;
  8301. bool inputExhausted;
  8302. bool groupSignalled;
  8303. public:
  8304. CRoxieServerPipeThroughActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8305. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorPipeThroughArg &)basehelper), puller(false)
  8306. {
  8307. recreate = helper.recreateEachRow();
  8308. groupSignalled = true;
  8309. firstRead = false;
  8310. inputExhausted = false;
  8311. }
  8312. virtual bool needsAllocator() const { return true; }
  8313. virtual void onCreate(IHThorArg *_colocalParent)
  8314. {
  8315. CRoxieServerActivity::onCreate(_colocalParent);
  8316. rowSerializer.setown(inputMeta.createDiskSerializer(ctx->queryCodeContext(), activityId));
  8317. rowDeserializer.setown(rowAllocator->createDiskDeserializer(ctx->queryCodeContext()));
  8318. writeTransformer.setown(createPipeWriteXformHelper(helper.getPipeFlags(), helper.queryXmlOutput(), helper.queryCsvOutput(), rowSerializer));
  8319. }
  8320. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8321. {
  8322. firstRead = true;
  8323. inputExhausted = false;
  8324. groupSignalled = true; // i.e. don't start with a NULL row
  8325. pipeVerified.reinit();
  8326. pipeOpened.reinit();
  8327. writeTransformer->ready();
  8328. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8329. if (!readTransformer)
  8330. {
  8331. OwnedRoxieString xmlIterator(helper.getXmlIteratorPath());
  8332. readTransformer.setown(createReadRowStream(rowAllocator, rowDeserializer, helper.queryXmlTransformer(), helper.queryCsvTransformer(), xmlIterator, helper.getPipeFlags()));
  8333. }
  8334. if(!recreate)
  8335. {
  8336. OwnedRoxieString pipeProgram(helper.getPipeProgram());
  8337. openPipe(pipeProgram);
  8338. }
  8339. puller.start(parentExtractSize, parentExtract, paused, 0, false, ctx); // Pipe does not support preload presently - locks up
  8340. }
  8341. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  8342. {
  8343. if (idx)
  8344. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  8345. puller.setInput(this, _sourceIdx, _in);
  8346. inputMeta.set(_in->queryOutputMeta());
  8347. }
  8348. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  8349. {
  8350. puller.connectInputStreams(ctx, consumerOrdered);
  8351. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
  8352. }
  8353. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  8354. {
  8355. if (idx==0)
  8356. return puller.queryInput();
  8357. else
  8358. return NULL;
  8359. }
  8360. virtual void stop()
  8361. {
  8362. pipeVerified.interrupt(NULL);
  8363. pipeOpened.interrupt(NULL);
  8364. puller.stop();
  8365. CRoxieServerActivity::stop();
  8366. pipe.clear();
  8367. if (readTransformer)
  8368. readTransformer->setStream(NULL);
  8369. }
  8370. virtual void reset()
  8371. {
  8372. puller.reset();
  8373. CRoxieServerActivity::reset();
  8374. }
  8375. virtual const void *nextRow()
  8376. {
  8377. ActivityTimer t(totalCycles, timeActivities);
  8378. while (!waitForPipe())
  8379. {
  8380. if (!pipe)
  8381. return NULL;
  8382. if (helper.getPipeFlags() & TPFgroupeachrow)
  8383. {
  8384. if (!groupSignalled)
  8385. {
  8386. groupSignalled = true;
  8387. return NULL;
  8388. }
  8389. }
  8390. }
  8391. const void *ret = readTransformer->next();
  8392. assertex(ret != NULL); // if ret can ever be NULL then we need to recode this logic
  8393. processed++;
  8394. groupSignalled = false;
  8395. return ret;
  8396. }
  8397. virtual void processRow(const void *row)
  8398. {
  8399. // called from puller thread
  8400. if(recreate)
  8401. openPipe(helper.getNameFromRow(row));
  8402. writeTransformer->writeTranslatedText(row, pipe);
  8403. ReleaseRoxieRow(row);
  8404. if(recreate)
  8405. {
  8406. closePipe();
  8407. pipeVerified.wait();
  8408. }
  8409. }
  8410. virtual void processDone()
  8411. {
  8412. // called from puller thread
  8413. if(recreate)
  8414. {
  8415. inputExhausted = true;
  8416. pipeOpened.signal();
  8417. }
  8418. else
  8419. {
  8420. closePipe();
  8421. pipeVerified.wait();
  8422. }
  8423. }
  8424. virtual void processEOG()
  8425. {
  8426. }
  8427. void processGroup(const ConstPointerArray &)
  8428. {
  8429. throwUnexpected();
  8430. }
  8431. virtual bool fireException(IException *e)
  8432. {
  8433. pipeOpened.interrupt(LINK(e));
  8434. pipeVerified.interrupt(e);
  8435. return true;
  8436. }
  8437. private:
  8438. bool waitForPipe()
  8439. {
  8440. if (firstRead)
  8441. {
  8442. pipeOpened.wait();
  8443. firstRead = false;
  8444. }
  8445. if (!pipe)
  8446. return false; // done
  8447. if (!readTransformer->eos())
  8448. return true;
  8449. verifyPipe();
  8450. if (recreate && !inputExhausted)
  8451. pipeOpened.wait();
  8452. return false;
  8453. }
  8454. void openPipe(char const * cmd)
  8455. {
  8456. pipeCommand.setown(cmd);
  8457. pipe.setown(createPipeProcess());
  8458. if(!pipe->run(NULL, cmd, ".", true, true, true, 0x10000))
  8459. throw MakeStringException(ROXIE_PIPE_ERROR, "Could not run pipe process %s", cmd);
  8460. writeTransformer->writeHeader(pipe);
  8461. Owned<ISimpleReadStream> pipeReader = pipe->getOutputStream();
  8462. readTransformer->setStream(pipeReader.get());
  8463. pipeOpened.signal();
  8464. }
  8465. void closePipe()
  8466. {
  8467. writeTransformer->writeFooter(pipe);
  8468. pipe->closeInput();
  8469. }
  8470. void verifyPipe()
  8471. {
  8472. if (pipe)
  8473. {
  8474. unsigned err = pipe->wait();
  8475. if(err && !(helper.getPipeFlags() & TPFnofail))
  8476. {
  8477. throw createPipeFailureException(pipeCommand.get(), err, pipe);
  8478. }
  8479. pipe.clear();
  8480. pipeVerified.signal();
  8481. }
  8482. }
  8483. };
  8484. class CRoxieServerPipeWriteActivity : public CRoxieServerInternalSinkActivity
  8485. {
  8486. IHThorPipeWriteArg &helper;
  8487. Owned<IPipeProcess> pipe;
  8488. StringAttr pipeCommand;
  8489. CachedOutputMetaData inputMeta;
  8490. Owned<IOutputRowSerializer> rowSerializer;
  8491. Owned<IPipeWriteXformHelper> writeTransformer;
  8492. bool firstRead;
  8493. bool recreate;
  8494. bool inputExhausted;
  8495. public:
  8496. CRoxieServerPipeWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  8497. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _numOutputs), helper((IHThorPipeWriteArg &)basehelper)
  8498. {
  8499. recreate = helper.recreateEachRow();
  8500. firstRead = false;
  8501. inputExhausted = false;
  8502. }
  8503. virtual bool needsAllocator() const { return true; }
  8504. virtual void onCreate(IHThorArg *_colocalParent)
  8505. {
  8506. CRoxieServerActivity::onCreate(_colocalParent);
  8507. inputMeta.set(input->queryOutputMeta());
  8508. rowSerializer.setown(inputMeta.createDiskSerializer(ctx->queryCodeContext(), activityId));
  8509. writeTransformer.setown(createPipeWriteXformHelper(helper.getPipeFlags(), helper.queryXmlOutput(), helper.queryCsvOutput(), rowSerializer));
  8510. }
  8511. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8512. {
  8513. firstRead = true;
  8514. inputExhausted = false;
  8515. writeTransformer->ready();
  8516. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8517. if(!recreate)
  8518. {
  8519. OwnedRoxieString pipeProgram(helper.getPipeProgram());
  8520. openPipe(pipeProgram);
  8521. }
  8522. }
  8523. virtual void stop()
  8524. {
  8525. if (!aborted && helper.getSequence() >= 0)
  8526. {
  8527. WorkunitUpdate wu = ctx->updateWorkUnit();
  8528. if (wu)
  8529. {
  8530. Owned<IWUResult> result = wu->updateResultBySequence(helper.getSequence());
  8531. if (result)
  8532. {
  8533. result->setResultTotalRowCount(processed);
  8534. result->setResultStatus(ResultStatusCalculated);
  8535. }
  8536. }
  8537. }
  8538. CRoxieServerActivity::stop();
  8539. pipe.clear();
  8540. }
  8541. virtual void onExecute()
  8542. {
  8543. loop
  8544. {
  8545. const void *row = inputStream->ungroupedNextRow();
  8546. if (!row)
  8547. break;
  8548. processed++;
  8549. if(recreate)
  8550. openPipe(helper.getNameFromRow(row));
  8551. writeTransformer->writeTranslatedText(row, pipe);
  8552. ReleaseRoxieRow(row);
  8553. if(recreate)
  8554. closePipe();
  8555. }
  8556. closePipe();
  8557. }
  8558. private:
  8559. void openPipe(char const * cmd)
  8560. {
  8561. pipeCommand.setown(cmd);
  8562. pipe.setown(createPipeProcess());
  8563. if(!pipe->run(NULL, cmd, ".", true, false, true, 0x10000))
  8564. throw MakeStringException(ROXIE_PIPE_ERROR, "Could not run pipe process %s", cmd);
  8565. writeTransformer->writeHeader(pipe);
  8566. }
  8567. void closePipe()
  8568. {
  8569. writeTransformer->writeFooter(pipe);
  8570. pipe->closeInput();
  8571. unsigned err = pipe->wait();
  8572. if(err && !(helper.getPipeFlags() & TPFnofail))
  8573. {
  8574. throw createPipeFailureException(pipeCommand.get(), err, pipe);
  8575. }
  8576. pipe.clear();
  8577. }
  8578. };
  8579. class CRoxieServerPipeReadActivityFactory : public CRoxieServerActivityFactory
  8580. {
  8581. public:
  8582. CRoxieServerPipeReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8583. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  8584. {
  8585. }
  8586. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  8587. {
  8588. return new CRoxieServerPipeReadActivity(_ctx, this, _probeManager);
  8589. }
  8590. };
  8591. class CRoxieServerPipeThroughActivityFactory : public CRoxieServerActivityFactory
  8592. {
  8593. public:
  8594. CRoxieServerPipeThroughActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8595. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  8596. {
  8597. }
  8598. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  8599. {
  8600. return new CRoxieServerPipeThroughActivity(_ctx, this, _probeManager);
  8601. }
  8602. };
  8603. class CRoxieServerPipeWriteActivityFactory : public CRoxieServerInternalSinkFactory
  8604. {
  8605. public:
  8606. CRoxieServerPipeWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  8607. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot)
  8608. {
  8609. }
  8610. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  8611. {
  8612. return new CRoxieServerPipeWriteActivity(_ctx, this, _probeManager, usageCount);
  8613. }
  8614. };
  8615. IRoxieServerActivityFactory *createRoxieServerPipeReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8616. {
  8617. return new CRoxieServerPipeReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  8618. }
  8619. IRoxieServerActivityFactory *createRoxieServerPipeThroughActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8620. {
  8621. return new CRoxieServerPipeThroughActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  8622. }
  8623. IRoxieServerActivityFactory *createRoxieServerPipeWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  8624. {
  8625. return new CRoxieServerPipeWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot);
  8626. }
  8627. //=====================================================================================================
  8628. class CRoxieServerStreamedIteratorActivity : public CRoxieServerActivity
  8629. {
  8630. IHThorStreamedIteratorArg &helper;
  8631. Owned<IRowStream> rows;
  8632. public:
  8633. CRoxieServerStreamedIteratorActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8634. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorStreamedIteratorArg &)basehelper)
  8635. {
  8636. }
  8637. ~CRoxieServerStreamedIteratorActivity()
  8638. {
  8639. }
  8640. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8641. {
  8642. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8643. rows.setown(helper.createInput());
  8644. }
  8645. virtual void stop()
  8646. {
  8647. if (rows)
  8648. {
  8649. rows->stop();
  8650. rows.clear();
  8651. }
  8652. CRoxieServerActivity::stop();
  8653. }
  8654. virtual const void *nextRow()
  8655. {
  8656. ActivityTimer t(totalCycles, timeActivities);
  8657. assertex(rows != NULL);
  8658. const void * next = rows->nextRow();
  8659. if (next)
  8660. processed++;
  8661. return next;
  8662. }
  8663. };
  8664. class CRoxieServerStreamedIteratorActivityFactory : public CRoxieServerActivityFactory
  8665. {
  8666. public:
  8667. CRoxieServerStreamedIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8668. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  8669. {
  8670. }
  8671. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  8672. {
  8673. return new CRoxieServerStreamedIteratorActivity(_ctx, this, _probeManager);
  8674. }
  8675. };
  8676. IRoxieServerActivityFactory *createRoxieServerStreamedIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8677. {
  8678. return new CRoxieServerStreamedIteratorActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  8679. }
  8680. //=====================================================================================================
  8681. class CRoxieServerFilterActivity : public CRoxieServerLateStartActivity
  8682. {
  8683. IHThorFilterArg &helper;
  8684. bool anyThisGroup;
  8685. IRangeCompare * stepCompare;
  8686. public:
  8687. CRoxieServerFilterActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8688. : CRoxieServerLateStartActivity(_ctx, _factory, _probeManager), helper((IHThorFilterArg &)basehelper)
  8689. {
  8690. anyThisGroup = false;
  8691. stepCompare = NULL;
  8692. }
  8693. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8694. {
  8695. anyThisGroup = false;
  8696. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  8697. lateStart(parentExtractSize, parentExtract, helper.canMatchAny());
  8698. stepCompare = NULL;
  8699. if (!eof)
  8700. {
  8701. IInputSteppingMeta * stepMeta = input->querySteppingMeta();
  8702. if (stepMeta)
  8703. stepCompare = stepMeta->queryCompare();
  8704. }
  8705. }
  8706. virtual const void * nextRow()
  8707. {
  8708. ActivityTimer t(totalCycles, timeActivities);
  8709. if (eof)
  8710. return NULL;
  8711. loop
  8712. {
  8713. const void * ret = inputStream->nextRow();
  8714. if (!ret)
  8715. {
  8716. //stop returning two NULLs in a row.
  8717. if (anyThisGroup)
  8718. {
  8719. anyThisGroup = false;
  8720. return NULL;
  8721. }
  8722. ret = inputStream->nextRow();
  8723. if (!ret)
  8724. {
  8725. eof = true;
  8726. return NULL; // eof...
  8727. }
  8728. }
  8729. if (helper.isValid(ret))
  8730. {
  8731. anyThisGroup = true;
  8732. processed++;
  8733. return ret;
  8734. }
  8735. ReleaseRoxieRow(ret);
  8736. }
  8737. }
  8738. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  8739. {
  8740. //Could assert that this isn't grouped
  8741. // MORE - will need rethinking once we rethink the nextRowGE interface for global smart-stepping.
  8742. ActivityTimer t(totalCycles, timeActivities);
  8743. if (eof)
  8744. return NULL;
  8745. loop
  8746. {
  8747. const void * ret = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  8748. if (!ret)
  8749. {
  8750. eof = true;
  8751. return NULL;
  8752. }
  8753. if (!wasCompleteMatch)
  8754. {
  8755. anyThisGroup = false; // RKC->GH - is this right??
  8756. return ret;
  8757. }
  8758. if (helper.isValid(ret))
  8759. {
  8760. anyThisGroup = true;
  8761. processed++;
  8762. return ret;
  8763. }
  8764. if (!stepExtra.returnMismatches())
  8765. {
  8766. ReleaseRoxieRow(ret);
  8767. return nextRow();
  8768. }
  8769. //If asked to return mismatches we are only interested in mismatches that will force the stepped
  8770. //condition to advance
  8771. if (stepCompare->docompare(ret, seek, numFields) != 0)
  8772. {
  8773. wasCompleteMatch = false;
  8774. anyThisGroup = false; // WHY?
  8775. return ret;
  8776. }
  8777. ReleaseRoxieRow(ret);
  8778. }
  8779. }
  8780. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  8781. {
  8782. return input->gatherConjunctions(collector);
  8783. }
  8784. virtual void resetEOF()
  8785. {
  8786. eof = prefiltered;
  8787. anyThisGroup = false;
  8788. inputStream->resetEOF();
  8789. }
  8790. IInputSteppingMeta * querySteppingMeta()
  8791. {
  8792. return input->querySteppingMeta();
  8793. }
  8794. };
  8795. class CRoxieServerFilterActivityFactory : public CRoxieServerActivityFactory
  8796. {
  8797. public:
  8798. CRoxieServerFilterActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8799. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  8800. {
  8801. optStableInput = false;
  8802. }
  8803. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  8804. {
  8805. return new CRoxieServerFilterActivity(_ctx, this, _probeManager);
  8806. }
  8807. };
  8808. IRoxieServerActivityFactory *createRoxieServerFilterActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8809. {
  8810. return new CRoxieServerFilterActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  8811. }
  8812. //=====================================================================================================
  8813. class CRoxieServerFilterGroupActivity : public CRoxieServerLateStartActivity
  8814. {
  8815. IHThorFilterGroupArg &helper;
  8816. unsigned curIndex;
  8817. ConstPointerArray gathered;
  8818. IRangeCompare * stepCompare;
  8819. public:
  8820. CRoxieServerFilterGroupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8821. : CRoxieServerLateStartActivity(_ctx, _factory, _probeManager), helper((IHThorFilterGroupArg &)basehelper)
  8822. {
  8823. curIndex = 0;
  8824. stepCompare = NULL;
  8825. }
  8826. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8827. {
  8828. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  8829. lateStart(parentExtractSize, parentExtract, helper.canMatchAny());//sets eof
  8830. assertex(eof == !helper.canMatchAny());
  8831. curIndex = 0;
  8832. stepCompare = NULL;
  8833. if (!eof)
  8834. {
  8835. IInputSteppingMeta * inputStepping = input->querySteppingMeta();
  8836. if (inputStepping)
  8837. stepCompare = inputStepping->queryCompare();
  8838. }
  8839. }
  8840. virtual void reset()
  8841. {
  8842. releaseGathered();
  8843. CRoxieServerLateStartActivity::reset();
  8844. }
  8845. inline void releaseGathered()
  8846. {
  8847. roxiemem::ReleaseRoxieRowRange(gathered.getArray(), curIndex, gathered.ordinality());
  8848. gathered.kill();
  8849. curIndex = 0;
  8850. }
  8851. virtual const void * nextRow()
  8852. {
  8853. ActivityTimer t(totalCycles, timeActivities);
  8854. loop
  8855. {
  8856. if (eof)
  8857. return NULL;
  8858. if (gathered.ordinality())
  8859. {
  8860. if (gathered.isItem(curIndex))
  8861. {
  8862. const void * ret = gathered.item(curIndex++);
  8863. processed++;
  8864. return ret;
  8865. }
  8866. curIndex = 0;
  8867. gathered.kill();
  8868. return NULL;
  8869. }
  8870. const void * ret = inputStream->nextRow();
  8871. while (ret)
  8872. {
  8873. gathered.append(ret);
  8874. ret = inputStream->nextRow();
  8875. }
  8876. unsigned num = gathered.ordinality();
  8877. if (num != 0)
  8878. {
  8879. if (!helper.isValid(num, (const void * *)gathered.getArray()))
  8880. ReleaseRoxieRows(gathered); // read next group
  8881. }
  8882. else
  8883. eof = true;
  8884. }
  8885. }
  8886. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  8887. {
  8888. ActivityTimer t(totalCycles, timeActivities);
  8889. if (eof)
  8890. return NULL;
  8891. if (gathered.ordinality())
  8892. {
  8893. while (gathered.isItem(curIndex))
  8894. {
  8895. const void * ret = gathered.item(curIndex++);
  8896. if (stepCompare->docompare(ret, seek, numFields) >= 0)
  8897. {
  8898. processed++;
  8899. return ret;
  8900. }
  8901. ReleaseRoxieRow(ret);
  8902. }
  8903. curIndex = 0;
  8904. gathered.kill();
  8905. //nextRowGE never returns an end of group marker.
  8906. }
  8907. //Not completely sure about this - it could lead the the start of a group being skipped,
  8908. //so the group filter could potentially work on a different group. If so, we'd need to check the
  8909. //next fields were a subset of the grouping fields - more an issue for the group activity.
  8910. //MORE: What do we do with wasCompleteMatch? something like the following????
  8911. #if 0
  8912. loop
  8913. {
  8914. const void * ret;
  8915. if (stepExtra.returnMismatches())
  8916. {
  8917. bool matchedCompletely = true;
  8918. ret = input->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  8919. if (!wasCompleteMatch)
  8920. return ret;
  8921. }
  8922. else
  8923. ret = input->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  8924. #endif
  8925. const void * ret = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  8926. while (ret)
  8927. {
  8928. gathered.append(ret);
  8929. ret = inputStream->nextRow();
  8930. }
  8931. unsigned num = gathered.ordinality();
  8932. if (num != 0)
  8933. {
  8934. if (!helper.isValid(num, (const void * *)gathered.getArray()))
  8935. ReleaseRoxieRows(gathered); // read next group
  8936. }
  8937. else
  8938. eof = true;
  8939. return IEngineRowStream::ungroupedNextRow();
  8940. }
  8941. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  8942. {
  8943. return input->gatherConjunctions(collector);
  8944. }
  8945. virtual void resetEOF()
  8946. {
  8947. eof = false;
  8948. releaseGathered();
  8949. inputStream->resetEOF();
  8950. }
  8951. IInputSteppingMeta * querySteppingMeta()
  8952. {
  8953. return input->querySteppingMeta();
  8954. }
  8955. };
  8956. class CRoxieServerFilterGroupActivityFactory : public CRoxieServerActivityFactory
  8957. {
  8958. public:
  8959. CRoxieServerFilterGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8960. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  8961. {
  8962. }
  8963. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  8964. {
  8965. return new CRoxieServerFilterGroupActivity(_ctx, this, _probeManager);
  8966. }
  8967. };
  8968. IRoxieServerActivityFactory *createRoxieServerFilterGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8969. {
  8970. return new CRoxieServerFilterGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  8971. }
  8972. //=================================================================================
  8973. class CRoxieServerSideEffectActivity : public CRoxieServerActivity
  8974. {
  8975. IHThorSideEffectArg &helper;
  8976. CriticalSection ecrit;
  8977. Owned<IException> exception;
  8978. bool executed;
  8979. public:
  8980. CRoxieServerSideEffectActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8981. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorSideEffectArg &)basehelper)
  8982. {
  8983. executed = false;
  8984. }
  8985. virtual const void * nextRow()
  8986. {
  8987. ActivityTimer t(totalCycles, timeActivities);
  8988. CriticalBlock b(ecrit);
  8989. if (exception)
  8990. throw(exception.getLink());
  8991. if (!executed)
  8992. {
  8993. try
  8994. {
  8995. executed = true;
  8996. helper.action();
  8997. }
  8998. catch(IException *E)
  8999. {
  9000. exception.set(E);
  9001. throw;
  9002. }
  9003. }
  9004. return NULL;
  9005. }
  9006. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  9007. {
  9008. CriticalBlock b(ecrit);
  9009. if (exception)
  9010. throw(exception.getLink());
  9011. if (!executed)
  9012. {
  9013. try
  9014. {
  9015. ActivityTimer t(totalCycles, timeActivities);
  9016. executed = true;
  9017. start(parentExtractSize, parentExtract, false);
  9018. helper.action();
  9019. stop();
  9020. }
  9021. catch(IException *E)
  9022. {
  9023. ctx->notifyAbort(E);
  9024. abort();
  9025. exception.set(E);
  9026. throw;
  9027. }
  9028. }
  9029. }
  9030. virtual void reset()
  9031. {
  9032. executed = false;
  9033. exception.clear();
  9034. CRoxieServerActivity::reset();
  9035. }
  9036. };
  9037. class CRoxieServerSideEffectActivityFactory : public CRoxieServerActivityFactory
  9038. {
  9039. bool isRoot;
  9040. public:
  9041. CRoxieServerSideEffectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  9042. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  9043. {
  9044. }
  9045. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9046. {
  9047. return new CRoxieServerSideEffectActivity(_ctx, this, _probeManager);
  9048. }
  9049. virtual bool isSink() const
  9050. {
  9051. return isRoot && !meta.queryOriginal();
  9052. }
  9053. };
  9054. IRoxieServerActivityFactory *createRoxieServerSideEffectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  9055. {
  9056. return new CRoxieServerSideEffectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  9057. }
  9058. //=================================================================================
  9059. class CRoxieServerActionActivity : public CRoxieServerInternalSinkActivity
  9060. {
  9061. IHThorActionArg &helper;
  9062. public:
  9063. CRoxieServerActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  9064. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _numOutputs), helper((IHThorActionArg &)basehelper)
  9065. {
  9066. }
  9067. virtual void onExecute()
  9068. {
  9069. helper.action();
  9070. }
  9071. };
  9072. class CRoxieServerActionActivityFactory : public CRoxieServerInternalSinkFactory
  9073. {
  9074. public:
  9075. CRoxieServerActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  9076. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot)
  9077. {
  9078. }
  9079. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9080. {
  9081. return new CRoxieServerActionActivity(_ctx, this, _probeManager, usageCount);
  9082. }
  9083. };
  9084. IRoxieServerActivityFactory *createRoxieServerActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  9085. {
  9086. return new CRoxieServerActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot);
  9087. }
  9088. //=================================================================================
  9089. class CRoxieServerSampleActivity : public CRoxieServerActivity
  9090. {
  9091. IHThorSampleArg &helper;
  9092. unsigned numSamples;
  9093. unsigned numToSkip;
  9094. unsigned whichSample;
  9095. bool anyThisGroup;
  9096. bool eof;
  9097. public:
  9098. CRoxieServerSampleActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9099. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorSampleArg &)basehelper)
  9100. {
  9101. numSamples = 0;
  9102. numToSkip = 0;
  9103. whichSample = 0;
  9104. anyThisGroup = false;
  9105. eof = false;
  9106. }
  9107. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9108. {
  9109. anyThisGroup = false;
  9110. eof = false;
  9111. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9112. numSamples = helper.getProportion();
  9113. whichSample = helper.getSampleNumber();
  9114. numToSkip = (whichSample ? whichSample-1 : 0);
  9115. }
  9116. virtual const void * nextRow()
  9117. {
  9118. ActivityTimer t(totalCycles, timeActivities);
  9119. if (eof)
  9120. return NULL;
  9121. loop
  9122. {
  9123. const void * ret = inputStream->nextRow();
  9124. if (!ret)
  9125. {
  9126. //this does work with groups - may or may not be useful...
  9127. //reset the sample for each group.... probably best.
  9128. numToSkip = (whichSample ? whichSample-1 : 0);
  9129. if (anyThisGroup)
  9130. {
  9131. anyThisGroup = false;
  9132. return NULL;
  9133. }
  9134. ret = inputStream->nextRow();
  9135. if (!ret)
  9136. {
  9137. eof = true;
  9138. return NULL; // eof...
  9139. }
  9140. }
  9141. if (numToSkip == 0)
  9142. {
  9143. anyThisGroup = true;
  9144. numToSkip = numSamples-1;
  9145. processed++;
  9146. return ret;
  9147. }
  9148. numToSkip--;
  9149. ReleaseRoxieRow(ret);
  9150. }
  9151. }
  9152. };
  9153. class CRoxieServerSampleActivityFactory : public CRoxieServerActivityFactory
  9154. {
  9155. public:
  9156. CRoxieServerSampleActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9157. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  9158. {
  9159. }
  9160. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9161. {
  9162. return new CRoxieServerSampleActivity(_ctx, this, _probeManager);
  9163. }
  9164. };
  9165. IRoxieServerActivityFactory *createRoxieServerSampleActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9166. {
  9167. return new CRoxieServerSampleActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9168. }
  9169. //=================================================================================
  9170. class CRoxieServerChooseSetsActivity : public CRoxieServerActivity
  9171. {
  9172. IHThorChooseSetsArg &helper;
  9173. unsigned numSets;
  9174. unsigned * setCounts;
  9175. bool done;
  9176. public:
  9177. CRoxieServerChooseSetsActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9178. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorChooseSetsArg &)basehelper)
  9179. {
  9180. setCounts = NULL;
  9181. numSets = 0;
  9182. done = false;
  9183. }
  9184. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9185. {
  9186. done = false;
  9187. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9188. numSets = helper.getNumSets();
  9189. setCounts = new unsigned[numSets];
  9190. memset(setCounts, 0, sizeof(unsigned)*numSets);
  9191. helper.setCounts(setCounts);
  9192. }
  9193. virtual void reset()
  9194. {
  9195. delete [] setCounts;
  9196. setCounts = NULL;
  9197. CRoxieServerActivity::reset();
  9198. }
  9199. virtual const void * nextRow()
  9200. {
  9201. ActivityTimer t(totalCycles, timeActivities);
  9202. if (done)
  9203. return NULL;
  9204. loop
  9205. {
  9206. const void * ret = inputStream->ungroupedNextRow();
  9207. if (!ret)
  9208. {
  9209. done = true;
  9210. return NULL;
  9211. }
  9212. processed++;
  9213. switch (helper.getRecordAction(ret))
  9214. {
  9215. case 2:
  9216. done = true;
  9217. return ret;
  9218. case 1:
  9219. return ret;
  9220. }
  9221. ReleaseRoxieRow(ret);
  9222. }
  9223. }
  9224. };
  9225. class CRoxieServerChooseSetsActivityFactory : public CRoxieServerActivityFactory
  9226. {
  9227. public:
  9228. CRoxieServerChooseSetsActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9229. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  9230. {
  9231. }
  9232. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9233. {
  9234. return new CRoxieServerChooseSetsActivity(_ctx, this, _probeManager);
  9235. }
  9236. };
  9237. IRoxieServerActivityFactory *createRoxieServerChooseSetsActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9238. {
  9239. return new CRoxieServerChooseSetsActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9240. }
  9241. //=================================================================================
  9242. class CRoxieServerChooseSetsExActivity : public CRoxieServerActivity
  9243. {
  9244. protected:
  9245. IHThorChooseSetsExArg &helper;
  9246. unsigned numSets;
  9247. unsigned curIndex;
  9248. unsigned * setCounts;
  9249. count_t * limits;
  9250. bool done;
  9251. ConstPointerArray gathered;
  9252. virtual bool includeRow(const void * row) = 0;
  9253. virtual void calculateSelection() = 0;
  9254. public:
  9255. CRoxieServerChooseSetsExActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9256. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorChooseSetsExArg &)basehelper)
  9257. {
  9258. setCounts = NULL;
  9259. limits = NULL;
  9260. done = false;
  9261. curIndex = 0;
  9262. numSets = 0;
  9263. }
  9264. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9265. {
  9266. done = false;
  9267. curIndex = 0;
  9268. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9269. numSets = helper.getNumSets();
  9270. setCounts = new unsigned[numSets];
  9271. memset(setCounts, 0, sizeof(unsigned)*numSets);
  9272. limits = (count_t *)calloc(sizeof(count_t), numSets);
  9273. helper.getLimits(limits);
  9274. }
  9275. virtual void reset()
  9276. {
  9277. delete [] setCounts;
  9278. setCounts = NULL;
  9279. free(limits);
  9280. limits = NULL;
  9281. roxiemem::ReleaseRoxieRowRange(gathered.getArray(), curIndex, gathered.ordinality());
  9282. gathered.kill();
  9283. curIndex = 0;
  9284. CRoxieServerActivity::reset();
  9285. }
  9286. virtual const void * nextRow()
  9287. {
  9288. ActivityTimer t(totalCycles, timeActivities);
  9289. if (gathered.ordinality() == 0)
  9290. {
  9291. curIndex = 0;
  9292. if (!inputStream->nextGroup(gathered))
  9293. {
  9294. done = true;
  9295. return NULL;
  9296. }
  9297. ForEachItemIn(idx1, gathered)
  9298. {
  9299. unsigned category = helper.getCategory(gathered.item(idx1));
  9300. if (category)
  9301. setCounts[category-1]++;
  9302. }
  9303. calculateSelection();
  9304. }
  9305. while (gathered.isItem(curIndex))
  9306. {
  9307. const void * row = gathered.item(curIndex);
  9308. gathered.replace(NULL, curIndex);
  9309. curIndex++;
  9310. if (includeRow(row))
  9311. {
  9312. processed++;
  9313. return row;
  9314. }
  9315. ReleaseRoxieRow(row);
  9316. }
  9317. gathered.kill();
  9318. return NULL;
  9319. }
  9320. };
  9321. class CRoxieServerChooseSetsLastActivity : public CRoxieServerChooseSetsExActivity
  9322. {
  9323. unsigned * numToSkip;
  9324. public:
  9325. CRoxieServerChooseSetsLastActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager) : CRoxieServerChooseSetsExActivity(_ctx, _factory, _probeManager)
  9326. {
  9327. numToSkip = NULL;
  9328. }
  9329. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9330. {
  9331. CRoxieServerChooseSetsExActivity::start(parentExtractSize, parentExtract, paused);
  9332. numToSkip = (unsigned *)calloc(sizeof(unsigned), numSets);
  9333. }
  9334. virtual void reset()
  9335. {
  9336. free(numToSkip);
  9337. numToSkip = NULL;
  9338. CRoxieServerChooseSetsExActivity::reset();
  9339. }
  9340. protected:
  9341. virtual void calculateSelection()
  9342. {
  9343. for (unsigned idx=0; idx < numSets; idx++)
  9344. {
  9345. if (setCounts[idx] < limits[idx])
  9346. numToSkip[idx] = 0;
  9347. else
  9348. numToSkip[idx] = (unsigned)(setCounts[idx] - limits[idx]);
  9349. }
  9350. }
  9351. virtual bool includeRow(const void * row)
  9352. {
  9353. unsigned category = helper.getCategory(row);
  9354. if (category)
  9355. {
  9356. if (numToSkip[category-1] == 0)
  9357. return true;
  9358. numToSkip[category-1]--;
  9359. }
  9360. return false;
  9361. }
  9362. };
  9363. class CRoxieServerChooseSetsEnthActivity : public CRoxieServerChooseSetsExActivity
  9364. {
  9365. count_t * counter;
  9366. public:
  9367. CRoxieServerChooseSetsEnthActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager) : CRoxieServerChooseSetsExActivity(_ctx, _factory, _probeManager)
  9368. {
  9369. counter = NULL;
  9370. }
  9371. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9372. {
  9373. CRoxieServerChooseSetsExActivity::start(parentExtractSize, parentExtract, paused);
  9374. counter = (count_t *)calloc(sizeof(count_t), numSets);
  9375. }
  9376. virtual void reset()
  9377. {
  9378. free(counter);
  9379. counter = NULL;
  9380. CRoxieServerChooseSetsExActivity::reset();
  9381. }
  9382. protected:
  9383. virtual void calculateSelection()
  9384. {
  9385. }
  9386. virtual bool includeRow(const void * row)
  9387. {
  9388. unsigned category = helper.getCategory(row);
  9389. if (category)
  9390. {
  9391. assertex(category <= numSets);
  9392. counter[category-1] += limits[category-1];
  9393. if(counter[category-1] >= setCounts[category-1])
  9394. {
  9395. counter[category-1] -= setCounts[category-1];
  9396. return true;
  9397. }
  9398. }
  9399. return false;
  9400. }
  9401. };
  9402. class CRoxieServerChooseSetsEnthActivityFactory : public CRoxieServerActivityFactory
  9403. {
  9404. public:
  9405. CRoxieServerChooseSetsEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9406. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  9407. {
  9408. }
  9409. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9410. {
  9411. return new CRoxieServerChooseSetsEnthActivity(_ctx, this, _probeManager);
  9412. }
  9413. };
  9414. IRoxieServerActivityFactory *createRoxieServerChooseSetsEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9415. {
  9416. return new CRoxieServerChooseSetsEnthActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9417. }
  9418. class CRoxieServerChooseSetsLastActivityFactory : public CRoxieServerActivityFactory
  9419. {
  9420. public:
  9421. CRoxieServerChooseSetsLastActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9422. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  9423. {
  9424. }
  9425. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9426. {
  9427. return new CRoxieServerChooseSetsLastActivity(_ctx, this, _probeManager);
  9428. }
  9429. };
  9430. IRoxieServerActivityFactory *createRoxieServerChooseSetsLastActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9431. {
  9432. return new CRoxieServerChooseSetsLastActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9433. }
  9434. //=================================================================================
  9435. class CRoxieServerEnthActivity : public CRoxieServerActivity
  9436. {
  9437. IHThorEnthArg &helper;
  9438. unsigned __int64 numerator;
  9439. unsigned __int64 denominator;
  9440. unsigned __int64 counter;
  9441. bool eof;
  9442. public:
  9443. CRoxieServerEnthActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9444. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorEnthArg &)basehelper)
  9445. {
  9446. eof = false;
  9447. numerator = denominator = counter = 0;
  9448. }
  9449. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9450. {
  9451. eof = false;
  9452. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9453. numerator = helper.getProportionNumerator();
  9454. denominator = helper.getProportionDenominator();
  9455. if(denominator == 0) denominator = 1; //MORE: simplest way to avoid disaster in this case
  9456. counter = (helper.getSampleNumber()-1) * greatestCommonDivisor(numerator, denominator);
  9457. if (counter >= denominator)
  9458. counter %= denominator;
  9459. }
  9460. inline bool wanted()
  9461. {
  9462. counter += numerator;
  9463. if(counter >= denominator)
  9464. {
  9465. counter -= denominator;
  9466. return true;
  9467. }
  9468. return false;
  9469. }
  9470. virtual const void * nextRow()
  9471. {
  9472. ActivityTimer t(totalCycles, timeActivities);
  9473. if (eof)
  9474. return NULL;
  9475. const void * ret;
  9476. loop
  9477. {
  9478. ret = inputStream->ungroupedNextRow();
  9479. if (!ret) //eof
  9480. {
  9481. eof = true;
  9482. return ret;
  9483. }
  9484. if (wanted())
  9485. return ret;
  9486. ReleaseRoxieRow(ret);
  9487. }
  9488. }
  9489. };
  9490. class CRoxieServerEnthActivityFactory : public CRoxieServerActivityFactory
  9491. {
  9492. public:
  9493. CRoxieServerEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9494. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  9495. {
  9496. }
  9497. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9498. {
  9499. return new CRoxieServerEnthActivity(_ctx, this, _probeManager);
  9500. }
  9501. };
  9502. IRoxieServerActivityFactory *createRoxieServerEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9503. {
  9504. return new CRoxieServerEnthActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9505. }
  9506. //=================================================================================
  9507. class CRoxieServerAggregateActivity : public CRoxieServerActivity
  9508. {
  9509. IHThorAggregateArg &helper;
  9510. bool eof;
  9511. bool isInputGrouped;
  9512. bool abortEarly;
  9513. public:
  9514. CRoxieServerAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9515. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorAggregateArg &)basehelper)
  9516. {
  9517. eof = false;
  9518. isInputGrouped = false;
  9519. abortEarly = false;
  9520. }
  9521. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9522. {
  9523. eof = false;
  9524. isInputGrouped = input->queryOutputMeta()->isGrouped(); // could be done earlier, in setInput?
  9525. abortEarly = !isInputGrouped && (factory->getKind() == TAKexistsaggregate); // ditto
  9526. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9527. }
  9528. virtual bool needsAllocator() const { return true; }
  9529. virtual const void * nextRow()
  9530. {
  9531. ActivityTimer t(totalCycles, timeActivities);
  9532. if (eof)
  9533. return NULL;
  9534. const void * next = inputStream->nextRow();
  9535. if (!next && isInputGrouped)
  9536. {
  9537. eof = true;
  9538. return NULL;
  9539. }
  9540. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  9541. size32_t finalSize = helper.clearAggregate(rowBuilder);
  9542. if (next)
  9543. {
  9544. finalSize = helper.processFirst(rowBuilder, next);
  9545. ReleaseRoxieRow(next);
  9546. if (!abortEarly)
  9547. {
  9548. loop
  9549. {
  9550. next = inputStream->nextRow();
  9551. if (!next)
  9552. break;
  9553. finalSize = helper.processNext(rowBuilder, next);
  9554. ReleaseRoxieRow(next);
  9555. }
  9556. }
  9557. }
  9558. if (!isInputGrouped) // either read all, or aborted early
  9559. eof = true;
  9560. processed++;
  9561. return rowBuilder.finalizeRowClear(finalSize);
  9562. }
  9563. };
  9564. class CRoxieServerStrandedAggregateActivity : public CRoxieServerStrandedActivity, implements IOrderedCallbackCollection
  9565. {
  9566. class AggregateProcessor : public StrandProcessor, implements IStrandThreaded, implements IOrderedOutputCallback
  9567. {
  9568. protected:
  9569. IHThorAggregateArg &helper;
  9570. OwnedConstRoxieRow result;
  9571. bool eof = false;
  9572. bool isInputGrouped = false;
  9573. bool abortEarly = false;
  9574. public:
  9575. AggregateProcessor(CRoxieServerActivity &_parent, IEngineRowStream *_inputStream, IHThorAggregateArg &_helper, bool _isInputGrouped, bool _abortEarly)
  9576. : StrandProcessor(_parent, _inputStream, true), helper(_helper), isInputGrouped(_isInputGrouped), abortEarly(_abortEarly)
  9577. {
  9578. }
  9579. virtual const void * nextRow() override
  9580. {
  9581. ActivityTimer t(totalCycles, timeActivities);
  9582. if (eof || isAborting())
  9583. return NULL;
  9584. const void * next = inputStream->nextRow();
  9585. if (!next && isInputGrouped)
  9586. {
  9587. eof = true;
  9588. return NULL;
  9589. }
  9590. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  9591. size32_t finalSize = helper.clearAggregate(rowBuilder);
  9592. if (next)
  9593. {
  9594. finalSize = helper.processFirst(rowBuilder, next);
  9595. ReleaseRoxieRow(next);
  9596. if (!abortEarly)
  9597. {
  9598. loop
  9599. {
  9600. next = inputStream->nextRow();
  9601. if (!next)
  9602. break;
  9603. finalSize = helper.processNext(rowBuilder, next);
  9604. ReleaseRoxieRow(next);
  9605. if (isAborting())
  9606. break;
  9607. }
  9608. }
  9609. }
  9610. if (!isInputGrouped) // either read all, or aborted early
  9611. eof = true;
  9612. processed++;
  9613. return rowBuilder.finalizeRowClear(finalSize);
  9614. }
  9615. virtual void main() override
  9616. {
  9617. isInputGrouped = true; // gather no row if there are no input rows.
  9618. result.setown(nextRow());
  9619. queryActivity().noteStrandFinished(inputStream);
  9620. }
  9621. virtual void reset() override
  9622. {
  9623. StrandProcessor::reset();
  9624. result.clear();
  9625. eof = false;
  9626. }
  9627. //interface IOutputOutputCallback
  9628. virtual bool noteEndOfInputChunk() { return true; }
  9629. virtual void noteEndOfInput() {}
  9630. virtual void stopStream()
  9631. {
  9632. inputStream->stop();
  9633. }
  9634. const void * queryResult() const { return result; }
  9635. CRoxieServerStrandedAggregateActivity & queryActivity() { return static_cast<CRoxieServerStrandedAggregateActivity &>(parent); }
  9636. };
  9637. //This class is only used when a single aggregate is being calculated.
  9638. class AggregateCombiner : public CInterfaceOf<IEngineRowStream>
  9639. {
  9640. public:
  9641. explicit AggregateCombiner(CRoxieServerStrandedAggregateActivity & _parent) : parent(_parent)
  9642. {
  9643. }
  9644. virtual const void *nextRow()
  9645. {
  9646. return parent.getCombinedAggregate();
  9647. }
  9648. virtual void stop()
  9649. {
  9650. parent.outputStopped();
  9651. }
  9652. virtual void resetEOF()
  9653. {
  9654. throwUnexpected();
  9655. }
  9656. protected:
  9657. CRoxieServerStrandedAggregateActivity & parent;
  9658. } combiner;
  9659. class NullCallback : implements IOrderedOutputCallback
  9660. {
  9661. public:
  9662. virtual bool noteEndOfInputChunk() { return true; }
  9663. virtual void noteEndOfInput() {}
  9664. } nullCallback;
  9665. public:
  9666. CRoxieServerStrandedAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const StrandOptions &_strandOptions)
  9667. : CRoxieServerStrandedActivity(_ctx, _factory, _probeManager, _strandOptions), helper((IHThorAggregateArg &)basehelper), combiner(*this)
  9668. {
  9669. isInputGrouped = false;
  9670. abortEarly = false;
  9671. }
  9672. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  9673. {
  9674. CRoxieServerStrandedActivity::setInput(idx, _sourceIdx, _in);
  9675. isInputGrouped = input->queryOutputMeta()->isGrouped(); // could be done earlier, in setInput?
  9676. abortEarly = !isInputGrouped && (factory->getKind() == TAKexistsaggregate); // ditto
  9677. //For EXISTS(), and aggregates that rely on the input order, force to execute single threaded
  9678. //MORE: Ordered should be able to process a block at a time and then merge them, similar to disk write processing.
  9679. if (abortEarly || (!isInputGrouped && queryFactory()->isInputOrdered(false, 0)))
  9680. strandOptions.numStrands = 1;
  9681. else if (!isInputGrouped)
  9682. combineStreams = true;
  9683. }
  9684. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  9685. {
  9686. PointerArrayOf<IEngineRowStream> localStreams;
  9687. //If streams are being combined, this class should be notified of end of sections, otherwise grouped aggregates can inform a downstream activity.
  9688. IOrderedCallbackCollection * callbacks = combineStreams ? static_cast<IOrderedCallbackCollection *>(this) : orderedCallbacks;
  9689. Owned<IStrandJunction> outJunction = CRoxieServerStrandedActivity::getOutputStreams(ctx, idx, localStreams, consumerOptions, consumerOrdered, callbacks);
  9690. if (localStreams.ordinality() == 1)
  9691. combineStreams = false; // Select a more efficient/simpler code path
  9692. if (combineStreams)
  9693. {
  9694. assertex(!outJunction); // this needs more thought!
  9695. streams.append(&combiner);
  9696. }
  9697. else
  9698. {
  9699. streams.swapWith(localStreams);
  9700. }
  9701. return outJunction.getClear();
  9702. }
  9703. virtual StrandProcessor *createStrandProcessor(IEngineRowStream *instream)
  9704. {
  9705. DBGLOG("Create aggregate strand processor %u", strandOptions.numStrands);
  9706. return new AggregateProcessor(*this, instream, (IHThorAggregateArg &) basehelper, isInputGrouped && !combineStreams, abortEarly);
  9707. }
  9708. virtual StrandProcessor *createStrandSourceProcessor(bool inputOrdered) { throwUnexpected(); }
  9709. virtual bool needsAllocator() const { return true; }
  9710. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused) override
  9711. {
  9712. CRoxieServerStrandedActivity::start(parentExtractSize, parentExtract, paused);
  9713. if (combineStreams)
  9714. {
  9715. barrier.setown(createStrandBarrier());
  9716. ForEachItemIn(i, strands)
  9717. barrier->startStrand(queryAggregate(i));
  9718. active.store(1);
  9719. }
  9720. else
  9721. active.store(0);
  9722. }
  9723. virtual void reset() override
  9724. {
  9725. CRoxieServerStrandedActivity::reset();
  9726. barrier.clear();
  9727. calculated = false;
  9728. }
  9729. //Helper functions for the single aggregate case
  9730. const void * getCombinedAggregate()
  9731. {
  9732. if (calculated)
  9733. return NULL;
  9734. calculated= true;
  9735. barrier->waitForStrands();
  9736. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  9737. size32_t finalSize = helper.clearAggregate(rowBuilder);
  9738. bool isFirst = true;
  9739. for (unsigned i=0; i < numStrands(); i++)
  9740. {
  9741. const void * next = queryAggregate(i).queryResult();
  9742. if (next)
  9743. {
  9744. if (isFirst)
  9745. {
  9746. finalSize = cloneRow(rowBuilder, next, helper.queryOutputMeta());
  9747. isFirst = false;
  9748. }
  9749. else
  9750. finalSize = helper.mergeAggregate(rowBuilder, next);
  9751. }
  9752. }
  9753. return rowBuilder.finalizeRowClear(finalSize);
  9754. }
  9755. void outputStopped()
  9756. {
  9757. //only called if generating a single result.
  9758. assertex(combineStreams);
  9759. if (barrier)
  9760. {
  9761. requestAbort(); // if strands are still running, abort them
  9762. barrier->waitForStrands();
  9763. }
  9764. else
  9765. {
  9766. ForEachItemIn(i, strands)
  9767. queryAggregate(i).stopStream();
  9768. }
  9769. CRoxieServerStrandedActivity::stop();
  9770. }
  9771. void noteStrandFinished(IRowStream * stream)
  9772. {
  9773. barrier->noteStrandFinished(stream);
  9774. }
  9775. virtual IOrderedOutputCallback * queryCallback(unsigned i)
  9776. {
  9777. //The non-ordered aggregate does not need to process the ordered call back information.
  9778. //If the ordered single aggregate was implemented then it would need to be processed instead of ignored,
  9779. //however it needs some care since the strands are not yet created. So cannot return strand(i).
  9780. return &nullCallback;
  9781. }
  9782. inline AggregateProcessor & queryAggregate(unsigned i)
  9783. {
  9784. return static_cast<AggregateProcessor &>(strands.item(i));
  9785. }
  9786. protected:
  9787. IHThorAggregateArg &helper;
  9788. Owned<IStrandBarrier> barrier;
  9789. IEngineRowStream * combinedStream = nullptr;
  9790. bool isInputGrouped;
  9791. bool abortEarly;
  9792. bool combineStreams = false;
  9793. bool calculated = false;
  9794. };
  9795. class CRoxieServerAggregateActivityFactory : public CRoxieServerActivityFactory
  9796. {
  9797. StrandOptions strandOptions;
  9798. public:
  9799. CRoxieServerAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9800. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), strandOptions(_graphNode)
  9801. {
  9802. Owned<IHThorAggregateArg> helper = (IHThorAggregateArg *) helperFactory();
  9803. if (!(helper->getAggregateFlags() & TAForderedmerge))
  9804. optStableInput = false;
  9805. }
  9806. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9807. {
  9808. return new CRoxieServerStrandedAggregateActivity(_ctx, this, _probeManager, strandOptions);
  9809. }
  9810. };
  9811. IRoxieServerActivityFactory *createRoxieServerAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9812. {
  9813. return new CRoxieServerAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9814. }
  9815. //=================================================================================
  9816. typedef unsigned t_hashPrefix;
  9817. class CRoxieServerHashAggregateActivity : public CRoxieServerActivity
  9818. {
  9819. IHThorHashAggregateArg &helper;
  9820. RowAggregator aggregated;
  9821. bool eof;
  9822. bool gathered;
  9823. bool isGroupedAggregate;
  9824. public:
  9825. CRoxieServerHashAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, bool _isGroupedAggregate, IProbeManager *_probeManager)
  9826. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorHashAggregateArg &)basehelper),
  9827. isGroupedAggregate(_isGroupedAggregate),
  9828. aggregated(helper, helper)
  9829. {
  9830. eof = false;
  9831. gathered = false;
  9832. }
  9833. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9834. {
  9835. eof = false;
  9836. gathered = false;
  9837. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9838. }
  9839. virtual void reset()
  9840. {
  9841. aggregated.reset();
  9842. CRoxieServerActivity::reset();
  9843. }
  9844. virtual bool needsAllocator() const { return true; }
  9845. virtual const void * nextRow()
  9846. {
  9847. ActivityTimer t(totalCycles, timeActivities);
  9848. if (eof)
  9849. return NULL;
  9850. if (!gathered)
  9851. {
  9852. aggregated.start(rowAllocator);
  9853. bool eog = true;
  9854. loop
  9855. {
  9856. const void * next = inputStream->nextRow();
  9857. if (!next)
  9858. {
  9859. if (isGroupedAggregate)
  9860. {
  9861. if (eog)
  9862. eof = true;
  9863. break;
  9864. }
  9865. next = inputStream->nextRow();
  9866. if (!next)
  9867. break;
  9868. }
  9869. eog = false;
  9870. aggregated.addRow(next);
  9871. ReleaseRoxieRow(next);
  9872. }
  9873. gathered = true;
  9874. }
  9875. Owned<AggregateRowBuilder> next = aggregated.nextResult();
  9876. if (next)
  9877. {
  9878. processed++;
  9879. return next->finalizeRowClear();
  9880. }
  9881. if (!isGroupedAggregate)
  9882. eof = true;
  9883. aggregated.reset();
  9884. gathered = false;
  9885. return NULL;
  9886. }
  9887. };
  9888. class CRoxieServerHashAggregateActivityFactory : public CRoxieServerActivityFactory
  9889. {
  9890. public:
  9891. CRoxieServerHashAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9892. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  9893. {
  9894. isGroupedAggregate = _graphNode.getPropBool("att[@name='grouped']/@value");
  9895. }
  9896. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9897. {
  9898. return new CRoxieServerHashAggregateActivity(_ctx, this, isGroupedAggregate, _probeManager);
  9899. }
  9900. protected:
  9901. bool isGroupedAggregate;
  9902. };
  9903. IRoxieServerActivityFactory *createRoxieServerHashAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9904. {
  9905. return new CRoxieServerHashAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9906. }
  9907. //=================================================================================
  9908. class CRoxieServerDegroupActivity : public CRoxieServerActivity
  9909. {
  9910. IHThorDegroupArg &helper;
  9911. bool eof;
  9912. public:
  9913. CRoxieServerDegroupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9914. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorDegroupArg &)basehelper)
  9915. {
  9916. eof = false;
  9917. }
  9918. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9919. {
  9920. eof = false;
  9921. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9922. }
  9923. virtual const void * nextRow()
  9924. {
  9925. ActivityTimer t(totalCycles, timeActivities);
  9926. if (eof)
  9927. return NULL;
  9928. const void * ret = inputStream->ungroupedNextRow();
  9929. if (ret)
  9930. processed++;
  9931. else
  9932. eof = true;
  9933. return ret;
  9934. }
  9935. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  9936. {
  9937. ActivityTimer t(totalCycles, timeActivities);
  9938. if (eof)
  9939. return NULL;
  9940. const void * ret = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  9941. if (ret)
  9942. processed++;
  9943. else
  9944. eof = true;
  9945. return ret;
  9946. }
  9947. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  9948. {
  9949. return input->gatherConjunctions(collector);
  9950. }
  9951. virtual void resetEOF()
  9952. {
  9953. eof = false;
  9954. inputStream->resetEOF();
  9955. }
  9956. IInputSteppingMeta * querySteppingMeta()
  9957. {
  9958. return input->querySteppingMeta();
  9959. }
  9960. };
  9961. class CRoxieServerDegroupActivityFactory : public CRoxieServerActivityFactory
  9962. {
  9963. public:
  9964. CRoxieServerDegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9965. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  9966. {
  9967. }
  9968. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9969. {
  9970. return new CRoxieServerDegroupActivity(_ctx, this, _probeManager);
  9971. }
  9972. };
  9973. IRoxieServerActivityFactory *createRoxieServerDegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9974. {
  9975. return new CRoxieServerDegroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9976. }
  9977. //=================================================================================
  9978. class CRoxieServerSpillReadActivity : public CRoxieServerActivity
  9979. {
  9980. IHThorDiskReadArg &helper;
  9981. bool needTransform;
  9982. bool eof;
  9983. bool anyThisGroup;
  9984. unsigned __int64 rowLimit;
  9985. unsigned __int64 choosenLimit;
  9986. public:
  9987. CRoxieServerSpillReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9988. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorDiskReadArg &)basehelper)
  9989. {
  9990. needTransform = helper.needTransform();
  9991. rowLimit = (unsigned __int64) -1;
  9992. choosenLimit = 0;
  9993. eof = false;
  9994. anyThisGroup = false;
  9995. }
  9996. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9997. {
  9998. anyThisGroup = false;
  9999. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  10000. if (helper.canMatchAny())
  10001. eof = false;
  10002. else
  10003. eof = true;
  10004. choosenLimit = helper.getChooseNLimit();
  10005. rowLimit = helper.getRowLimit();
  10006. helper.setCallback(NULL); // members should not be called - change if they are
  10007. }
  10008. virtual bool needsAllocator() const { return true; }
  10009. virtual const void * nextRow()
  10010. {
  10011. ActivityTimer t(totalCycles, timeActivities);
  10012. if (eof)
  10013. return NULL;
  10014. if (processed==choosenLimit)
  10015. {
  10016. eof = true;
  10017. return NULL;
  10018. }
  10019. if (needTransform)
  10020. {
  10021. loop
  10022. {
  10023. const void *in = inputStream->nextRow();
  10024. if (!in)
  10025. {
  10026. if (anyThisGroup)
  10027. {
  10028. anyThisGroup = false;
  10029. return NULL;
  10030. }
  10031. in = inputStream->nextRow();
  10032. if (!in)
  10033. {
  10034. eof = true;
  10035. return NULL; // eof...
  10036. }
  10037. }
  10038. unsigned outSize;
  10039. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  10040. try
  10041. {
  10042. outSize = helper.transform(rowBuilder, in);
  10043. ReleaseRoxieRow(in);
  10044. }
  10045. catch (IException *E)
  10046. {
  10047. throw makeWrappedException(E);
  10048. }
  10049. if (outSize)
  10050. {
  10051. anyThisGroup = true;
  10052. processed++;
  10053. if (processed==rowLimit)
  10054. {
  10055. if (traceLevel > 4)
  10056. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  10057. helper.onLimitExceeded();
  10058. }
  10059. return rowBuilder.finalizeRowClear(outSize);
  10060. }
  10061. }
  10062. }
  10063. else
  10064. {
  10065. const void *ret = inputStream->nextRow();
  10066. if (ret)
  10067. {
  10068. processed++;
  10069. if (processed==rowLimit)
  10070. {
  10071. if (traceLevel > 4)
  10072. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  10073. ReleaseClearRoxieRow(ret);
  10074. helper.onLimitExceeded(); // should not return
  10075. throwUnexpected();
  10076. }
  10077. }
  10078. return ret;
  10079. }
  10080. }
  10081. };
  10082. class CRoxieServerSpillReadActivityFactory : public CRoxieServerActivityFactory
  10083. {
  10084. public:
  10085. CRoxieServerSpillReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  10086. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  10087. {
  10088. }
  10089. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  10090. {
  10091. return new CRoxieServerSpillReadActivity(_ctx, this, _probeManager);
  10092. }
  10093. virtual void addDependency(unsigned source, ThorActivityKind sourceKind, unsigned sourceIdx, int controlId, const char *edgeId)
  10094. {
  10095. if (sourceKind==TAKspill || sourceKind==TAKdiskwrite) // Bit of a hack - codegen probably should differentiate
  10096. setInput(0, source, sourceIdx);
  10097. else
  10098. CRoxieServerActivityFactory::addDependency(source, kind, sourceIdx, controlId, edgeId);
  10099. }
  10100. };
  10101. IRoxieServerActivityFactory *createRoxieServerSpillReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  10102. {
  10103. return new CRoxieServerSpillReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  10104. }
  10105. //=================================================================================
  10106. class CRoxieServerSpillWriteActivity : public CRoxieServerActivity
  10107. {
  10108. public:
  10109. CRoxieServerSpillWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  10110. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  10111. {
  10112. }
  10113. ~CRoxieServerSpillWriteActivity()
  10114. {
  10115. }
  10116. virtual const void *nextRow()
  10117. {
  10118. ActivityTimer t(totalCycles, timeActivities);
  10119. return inputStream->nextRow();
  10120. }
  10121. };
  10122. //==================================================================================
  10123. class CRoxieServerDiskWriteActivity : public CRoxieServerInternalSinkActivity, implements IRoxiePublishCallback
  10124. {
  10125. protected:
  10126. Owned<IExtRowWriter> outSeq;
  10127. Owned<IOutputRowSerializer> rowSerializer;
  10128. Linked<IFileIOStream> diskout;
  10129. bool blockcompressed;
  10130. bool extend;
  10131. bool overwrite;
  10132. bool encrypted;
  10133. bool grouped;
  10134. IHThorDiskWriteArg &helper;
  10135. CachedOutputMetaData diskmeta;
  10136. Owned<IRoxieWriteHandler> writer;
  10137. bool tallycrc;
  10138. unsigned __int64 uncompressedBytesWritten;
  10139. CRC32 crc;
  10140. void updateWorkUnitResult(unsigned __int64 reccount)
  10141. {
  10142. assertex(writer);
  10143. // MORE - a lot of this is common with hthor
  10144. WorkunitUpdate wu = ctx->updateWorkUnit();
  10145. if (wu)
  10146. {
  10147. OwnedRoxieString rawLogicalName = helper.getFileName();
  10148. StringBuffer lfn; // logical filename
  10149. expandLogicalFilename(lfn, rawLogicalName, wu, false, false);
  10150. if (lfn.length())
  10151. {
  10152. unsigned flags = helper.getFlags();
  10153. WUFileKind fileKind;
  10154. if (TDXtemporary & flags)
  10155. fileKind = WUFileTemporary;
  10156. else if(TDXjobtemp & flags)
  10157. fileKind = WUFileJobOwned;
  10158. else if(TDWowned & flags)
  10159. fileKind = WUFileOwned;
  10160. else
  10161. fileKind = WUFileStandard;
  10162. StringArray clusters;
  10163. writer->getClusters(clusters);
  10164. wu->addFile(lfn.str(), &clusters, helper.getTempUsageCount(), fileKind, NULL);
  10165. if (!(flags & TDXtemporary) && helper.getSequence() >= 0)
  10166. {
  10167. Owned<IWUResult> result = wu->updateResultBySequence(helper.getSequence());
  10168. if (result)
  10169. {
  10170. result->setResultTotalRowCount(reccount);
  10171. result->setResultStatus(ResultStatusCalculated);
  10172. if (helper.getFlags() & TDWresult)
  10173. result->setResultFilename(lfn.str());
  10174. else
  10175. result->setResultLogicalName(lfn.str());
  10176. }
  10177. }
  10178. }
  10179. }
  10180. }
  10181. void resolve()
  10182. {
  10183. OwnedRoxieString rawLogicalName = helper.getFileName();
  10184. assertex(rawLogicalName);
  10185. assertex((helper.getFlags() & TDXtemporary) == 0);
  10186. StringArray clusters;
  10187. unsigned clusterIdx = 0;
  10188. while(true)
  10189. {
  10190. OwnedRoxieString cluster(helper.getCluster(clusterIdx));
  10191. if(!cluster)
  10192. break;
  10193. clusters.append(cluster);
  10194. clusterIdx++;
  10195. }
  10196. if (clusters.length())
  10197. {
  10198. if (extend)
  10199. throw MakeStringException(0, "Cannot combine EXTEND and CLUSTER flags on disk write of file %s", rawLogicalName.get());
  10200. }
  10201. else
  10202. {
  10203. if (roxieName.length())
  10204. clusters.append(roxieName.str());
  10205. else
  10206. clusters.append(".");
  10207. }
  10208. writer.setown(ctx->createLFN(rawLogicalName, overwrite, extend, clusters));
  10209. // MORE - need to check somewhere that single part if it's an existing file or an external one...
  10210. }
  10211. public:
  10212. CRoxieServerDiskWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  10213. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, 0), helper((IHThorDiskWriteArg &)basehelper)
  10214. {
  10215. extend = ((helper.getFlags() & TDWextend) != 0);
  10216. overwrite = ((helper.getFlags() & TDWoverwrite) != 0);
  10217. grouped = false; // don't think we need to support it...
  10218. diskmeta.set(helper.queryDiskRecordSize());
  10219. blockcompressed = (((helper.getFlags() & TDWnewcompress) != 0) || (((helper.getFlags() & TDXcompress) != 0) && (diskmeta.getFixedSize() >= MIN_ROWCOMPRESS_RECSIZE))); //always use new compression
  10220. encrypted = false; // set later
  10221. tallycrc = true;
  10222. uncompressedBytesWritten = 0;
  10223. }
  10224. ~CRoxieServerDiskWriteActivity()
  10225. {
  10226. }
  10227. virtual bool needsAllocator() const
  10228. {
  10229. return true;
  10230. }
  10231. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10232. {
  10233. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  10234. resolve();
  10235. Owned<IFileIO> io;
  10236. void *ekey;
  10237. size32_t ekeylen;
  10238. helper.getEncryptKey(ekeylen, ekey);
  10239. Owned<ICompressor> ecomp;
  10240. if (ekeylen!=0)
  10241. {
  10242. ecomp.setown(createAESCompressor256(ekeylen,ekey));
  10243. memset(ekey,0,ekeylen);
  10244. rtlFree(ekey);
  10245. encrypted = true;
  10246. blockcompressed = true;
  10247. }
  10248. if (blockcompressed)
  10249. io.setown(createCompressedFileWriter(writer->queryFile(), (diskmeta.isFixedSize() ? diskmeta.getFixedSize() : 0), extend, true, ecomp));
  10250. else
  10251. io.setown(writer->queryFile()->open(extend ? IFOwrite : IFOcreate));
  10252. if (!io)
  10253. throw MakeStringException(errno, "Failed to create%s file %s for writing", (encrypted ? " encrypted" : (blockcompressed ? " compressed" : "")), writer->queryFile()->queryFilename());
  10254. diskout.setown(createBufferedIOStream(io));
  10255. if (extend)
  10256. diskout->seek(0, IFSend);
  10257. tallycrc = !factory->queryQueryFactory().queryOptions().skipFileFormatCrcCheck && !(helper.getFlags() & TDRnocrccheck) && !blockcompressed;
  10258. Owned<IRowInterfaces> rowIf = createRowInterfaces(input->queryOutputMeta(), activityId, factory->getHeapFlags(), ctx->queryCodeContext());
  10259. rowSerializer.set(rowIf->queryRowSerializer());
  10260. unsigned rwFlags = rw_autoflush;
  10261. if(grouped)
  10262. rwFlags |= rw_grouped;
  10263. if(tallycrc)
  10264. rwFlags |= rw_crc;
  10265. outSeq.setown(createRowWriter(diskout, rowIf, rwFlags));
  10266. }
  10267. virtual void stop()
  10268. {
  10269. if (aborted)
  10270. {
  10271. if (writer)
  10272. writer->finish(false, this);
  10273. }
  10274. else
  10275. {
  10276. if (outSeq)
  10277. outSeq->flush(&crc);
  10278. if (outSeq)
  10279. uncompressedBytesWritten = outSeq->getPosition();
  10280. outSeq.clear();
  10281. diskout.clear(); // Make sure file is properly closed or date may not match published info
  10282. if (writer)
  10283. {
  10284. updateWorkUnitResult(processed);
  10285. writer->finish(true, this);
  10286. }
  10287. }
  10288. writer.clear();
  10289. CRoxieServerActivity::stop();
  10290. }
  10291. virtual void reset()
  10292. {
  10293. CRoxieServerActivity::reset();
  10294. diskout.clear();
  10295. outSeq.clear();
  10296. writer.clear();
  10297. uncompressedBytesWritten = 0;
  10298. crc.reset();
  10299. }
  10300. virtual void onExecute()
  10301. {
  10302. loop
  10303. {
  10304. const void *nextrec = inputStream->ungroupedNextRow();
  10305. if (!nextrec)
  10306. break;
  10307. processed++;
  10308. outSeq->putRow(nextrec);
  10309. }
  10310. }
  10311. virtual void setFileProperties(IFileDescriptor *desc) const
  10312. {
  10313. IPropertyTree &partProps = desc->queryPart(0)->queryProperties(); //properties of the first file part.
  10314. IPropertyTree &fileProps = desc->queryProperties(); // properties of the logical file
  10315. if (blockcompressed)
  10316. {
  10317. // caller has already set @size from file size...
  10318. fileProps.setPropBool("@blockCompressed", true);
  10319. fileProps.setPropInt64("@compressedSize", partProps.getPropInt64("@size", 0));
  10320. partProps.setPropInt64("@compressedSize", partProps.getPropInt64("@size", 0));
  10321. fileProps.setPropInt64("@size", uncompressedBytesWritten);
  10322. partProps.setPropInt64("@size", uncompressedBytesWritten);
  10323. }
  10324. else if (tallycrc && crc.get())
  10325. partProps.setPropInt64("@fileCrc", crc.get());
  10326. if (encrypted)
  10327. fileProps.setPropBool("@encrypted", true);
  10328. fileProps.setPropInt64("@recordCount", processed);
  10329. unsigned flags = helper.getFlags();
  10330. if (flags & TDWpersist)
  10331. fileProps.setPropBool("@persistent", true);
  10332. if (grouped)
  10333. fileProps.setPropBool("@grouped", true);
  10334. if (flags & (TDWowned|TDXjobtemp|TDXtemporary))
  10335. fileProps.setPropBool("@owned", true);
  10336. if (flags & TDWresult)
  10337. fileProps.setPropBool("@result", true);
  10338. IConstWorkUnit *workUnit = ctx->queryWorkUnit();
  10339. if (workUnit)
  10340. {
  10341. fileProps.setProp("@owner", workUnit->queryUser());
  10342. fileProps.setProp("@workunit", workUnit->queryWuid());
  10343. fileProps.setProp("@job", workUnit->queryJobName());
  10344. }
  10345. if (flags & TDWexpires)
  10346. setExpiryTime(fileProps, helper.getExpiryDays());
  10347. if (flags & TDWupdate)
  10348. {
  10349. unsigned eclCRC;
  10350. unsigned __int64 totalCRC;
  10351. helper.getUpdateCRCs(eclCRC, totalCRC);
  10352. fileProps.setPropInt("@eclCRC", eclCRC);
  10353. fileProps.setPropInt64("@totalCRC", totalCRC);
  10354. }
  10355. fileProps.setPropInt("@formatCrc", helper.getFormatCrc());
  10356. IRecordSize * inputMeta = input->queryOutputMeta();
  10357. if ((inputMeta->isFixedSize()) && !isOutputTransformed())
  10358. fileProps.setPropInt("@recordSize", inputMeta->getFixedSize() + (grouped ? 1 : 0));
  10359. const char *recordECL = helper.queryRecordECL();
  10360. if (recordECL && *recordECL)
  10361. fileProps.setProp("ECL", recordECL);
  10362. fileProps.setProp("@kind", "flat"); // default, derivitives may override
  10363. }
  10364. virtual IUserDescriptor *queryUserDescriptor() const
  10365. {
  10366. IConstWorkUnit *workUnit = ctx->queryWorkUnit();
  10367. if (workUnit)
  10368. return workUnit->queryUserDescriptor();
  10369. else
  10370. return NULL;
  10371. }
  10372. virtual bool isOutputTransformed() const { return false; }
  10373. };
  10374. //=================================================================================
  10375. class CRoxieServerCsvWriteActivity : public CRoxieServerDiskWriteActivity
  10376. {
  10377. IHThorCsvWriteArg &csvHelper;
  10378. CSVOutputStream csvOutput;
  10379. public:
  10380. CRoxieServerCsvWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  10381. : CRoxieServerDiskWriteActivity(_ctx, _factory, _probeManager), csvHelper(static_cast<IHThorCsvWriteArg &>(helper))
  10382. {
  10383. csvOutput.init(csvHelper.queryCsvParameters(), false);
  10384. }
  10385. virtual void onExecute()
  10386. {
  10387. OwnedRoxieString header(csvHelper.queryCsvParameters()->getHeader());
  10388. if (header)
  10389. {
  10390. csvOutput.beginLine();
  10391. csvOutput.writeHeaderLn(strlen(header), header);
  10392. diskout->write(csvOutput.length(), csvOutput.str());
  10393. }
  10394. loop
  10395. {
  10396. const void *nextrec = inputStream->ungroupedNextRow();
  10397. if (!nextrec)
  10398. break;
  10399. processed++;
  10400. csvOutput.beginLine();
  10401. csvHelper.writeRow((const byte *)nextrec, &csvOutput);
  10402. csvOutput.endLine();
  10403. diskout->write(csvOutput.length(), csvOutput.str());
  10404. ReleaseRoxieRow(nextrec);
  10405. }
  10406. OwnedRoxieString footer(csvHelper.queryCsvParameters()->getFooter());
  10407. if (footer)
  10408. {
  10409. csvOutput.beginLine();
  10410. csvOutput.writeHeaderLn(strlen(footer), footer);
  10411. diskout->write(csvOutput.length(), csvOutput.str());
  10412. }
  10413. }
  10414. virtual void setFileProperties(IFileDescriptor *desc) const
  10415. {
  10416. CRoxieServerDiskWriteActivity::setFileProperties(desc);
  10417. IPropertyTree &props = desc->queryProperties();
  10418. props.setProp("@format","utf8n");
  10419. ICsvParameters *csvParameters = csvHelper.queryCsvParameters();
  10420. StringBuffer separator;
  10421. OwnedRoxieString rs(csvParameters->getSeparator(0));
  10422. const char *s = rs;
  10423. while (s && *s)
  10424. {
  10425. if (',' == *s)
  10426. separator.append("\\,");
  10427. else
  10428. separator.append(*s);
  10429. ++s;
  10430. }
  10431. props.setProp("@csvSeparate", separator.str());
  10432. props.setProp("@csvQuote", rs.setown(csvParameters->getQuote(0)));
  10433. props.setProp("@csvTerminate", rs.setown(csvParameters->getTerminator(0)));
  10434. props.setProp("@csvEscape", rs.setown(csvParameters->getEscape(0)));
  10435. props.setProp("@kind", "csv");
  10436. }
  10437. virtual bool isOutputTransformed() const { return true; }
  10438. };
  10439. class CRoxieServerXmlWriteActivity : public CRoxieServerDiskWriteActivity
  10440. {
  10441. IHThorXmlWriteArg &xmlHelper;
  10442. StringAttr rowTag;
  10443. ThorActivityKind kind;
  10444. unsigned headerLength;
  10445. unsigned footerLength;
  10446. public:
  10447. CRoxieServerXmlWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, ThorActivityKind _kind)
  10448. : CRoxieServerDiskWriteActivity(_ctx, _factory, _probeManager), xmlHelper(static_cast<IHThorXmlWriteArg &>(helper)), kind(_kind), headerLength(0), footerLength(0)
  10449. {
  10450. }
  10451. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10452. {
  10453. CRoxieServerDiskWriteActivity::start(parentExtractSize, parentExtract, paused);
  10454. OwnedRoxieString xmlpath(xmlHelper.getXmlIteratorPath());
  10455. if (!xmlpath)
  10456. rowTag.set(DEFAULTXMLROWTAG);
  10457. else
  10458. {
  10459. const char *path = xmlpath;
  10460. if (*path == '/') path++;
  10461. if (strchr(path, '/')) UNIMPLEMENTED; // more what do we do with /mydata/row
  10462. rowTag.set(path);
  10463. }
  10464. }
  10465. virtual void onExecute()
  10466. {
  10467. StringBuffer header;
  10468. OwnedRoxieString suppliedHeader(xmlHelper.getHeader());
  10469. if (kind==TAKjsonwrite)
  10470. buildJsonHeader(header, suppliedHeader, rowTag);
  10471. else if (suppliedHeader)
  10472. header.set(suppliedHeader);
  10473. else
  10474. header.append(DEFAULTXMLHEADER).newline();
  10475. headerLength = header.length();
  10476. diskout->write(header.length(), header.str());
  10477. Owned<IXmlWriterExt> writer = createIXmlWriterExt(xmlHelper.getXmlFlags(), 0, NULL, (kind==TAKjsonwrite) ? WTJSON : WTStandard);
  10478. writer->outputBeginArray(rowTag); //need to set this
  10479. writer->clear(); //but not output it
  10480. loop
  10481. {
  10482. OwnedConstRoxieRow nextrec = inputStream->ungroupedNextRow();
  10483. if (!nextrec)
  10484. break;
  10485. processed++;
  10486. writer->clear().outputBeginNested(rowTag, false);
  10487. xmlHelper.toXML((const byte *)nextrec.get(), *writer);
  10488. writer->outputEndNested(rowTag);
  10489. diskout->write(writer->length(), writer->str());
  10490. }
  10491. OwnedRoxieString suppliedFooter(xmlHelper.getFooter());
  10492. StringBuffer footer;
  10493. if (kind==TAKjsonwrite)
  10494. buildJsonFooter(footer.newline(), suppliedFooter, rowTag);
  10495. else if (suppliedFooter)
  10496. footer.append(suppliedFooter);
  10497. else
  10498. footer.append(DEFAULTXMLFOOTER);
  10499. footerLength=footer.length();
  10500. diskout->write(footer.length(), footer);
  10501. }
  10502. virtual void reset()
  10503. {
  10504. CRoxieServerDiskWriteActivity::reset();
  10505. rowTag.clear();
  10506. }
  10507. virtual void setFileProperties(IFileDescriptor *desc) const
  10508. {
  10509. CRoxieServerDiskWriteActivity::setFileProperties(desc);
  10510. desc->queryProperties().setProp("@format","utf8n");
  10511. desc->queryProperties().setProp("@rowTag",rowTag.get());
  10512. desc->queryProperties().setProp("@kind", (kind==TAKjsonwrite) ? "json" : "xml");
  10513. desc->queryProperties().setPropInt(FPheaderLength, headerLength);
  10514. desc->queryProperties().setPropInt(FPfooterLength, footerLength);
  10515. }
  10516. virtual bool isOutputTransformed() const { return true; }
  10517. };
  10518. class CRoxieServerDiskWriteActivityFactory : public CRoxieServerMultiOutputFactory
  10519. {
  10520. bool isRoot;
  10521. bool isTemp;
  10522. public:
  10523. CRoxieServerDiskWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  10524. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  10525. {
  10526. Owned<IHThorDiskWriteArg> helper = (IHThorDiskWriteArg *) helperFactory();
  10527. isTemp = (helper->getFlags() & TDXtemporary) != 0;
  10528. setNumOutputs(helper->getTempUsageCount());
  10529. if (_kind!=TAKdiskwrite)
  10530. assertex(numOutputs == 0);
  10531. }
  10532. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  10533. {
  10534. switch (numOutputs)
  10535. {
  10536. case 0:
  10537. switch (kind)
  10538. {
  10539. case TAKdiskwrite: return new CRoxieServerDiskWriteActivity(_ctx, this, _probeManager);
  10540. case TAKcsvwrite: return new CRoxieServerCsvWriteActivity(_ctx, this, _probeManager);
  10541. case TAKxmlwrite:
  10542. case TAKjsonwrite:
  10543. return new CRoxieServerXmlWriteActivity(_ctx, this, _probeManager, kind);
  10544. };
  10545. throwUnexpected();
  10546. case 1:
  10547. return new CRoxieServerSpillWriteActivity(_ctx, this, _probeManager);
  10548. default:
  10549. return new CRoxieServerThroughSpillActivity(_ctx, this, _probeManager, numOutputs);
  10550. }
  10551. }
  10552. virtual bool isSink() const
  10553. {
  10554. return numOutputs == 0 && !isTemp; // MORE - check with Gavin if this is right if not a temp but reread in same job...
  10555. }
  10556. };
  10557. IRoxieServerActivityFactory *createRoxieServerDiskWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  10558. {
  10559. return new CRoxieServerDiskWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  10560. }
  10561. //=================================================================================
  10562. class CRoxieServerIndexWriteActivity : public CRoxieServerInternalSinkActivity, implements IRoxiePublishCallback
  10563. {
  10564. IHThorIndexWriteArg &helper;
  10565. bool overwrite;
  10566. Owned<ClusterWriteHandler> clusterHandler;
  10567. Owned<IRoxieWriteHandler> writer;
  10568. unsigned __int64 reccount;
  10569. unsigned int fileCrc;
  10570. StringBuffer filename;
  10571. void updateWorkUnitResult()
  10572. {
  10573. // MORE - a lot of this is common with hthor
  10574. WorkunitUpdate wu = ctx->updateWorkUnit();
  10575. if (wu)
  10576. {
  10577. OwnedRoxieString rawLogicalName = helper.getFileName();
  10578. StringBuffer lfn; // logical filename
  10579. expandLogicalFilename(lfn, rawLogicalName, wu, false, false);
  10580. if (lfn.length())
  10581. {
  10582. if (helper.getSequence() >= 0)
  10583. {
  10584. Owned<IWUResult> result = wu->updateResultBySequence(helper.getSequence());
  10585. if (result)
  10586. {
  10587. result->setResultTotalRowCount(reccount);
  10588. result->setResultStatus(ResultStatusCalculated);
  10589. result->setResultLogicalName(lfn.str());
  10590. }
  10591. }
  10592. if(clusterHandler)
  10593. clusterHandler->finish(writer->queryFile());
  10594. CTXLOG("Created roxie index file %s", lfn.str());
  10595. }
  10596. }
  10597. }
  10598. virtual void resolve()
  10599. {
  10600. StringArray clusters;
  10601. unsigned clusterIdx = 0;
  10602. while(true)
  10603. {
  10604. OwnedRoxieString cluster(helper.getCluster(clusterIdx));
  10605. if(!cluster)
  10606. break;
  10607. clusters.append(cluster);
  10608. clusterIdx++;
  10609. }
  10610. if (roxieName.length())
  10611. clusters.append(roxieName.str());
  10612. else
  10613. clusters.append(".");
  10614. OwnedRoxieString fname(helper.getFileName());
  10615. writer.setown(ctx->createLFN(fname, overwrite, false, clusters)); // MORE - if there's a workunit, use if for scope.
  10616. filename.set(writer->queryFile()->queryFilename());
  10617. if (writer->queryFile()->exists())
  10618. {
  10619. if (overwrite)
  10620. {
  10621. CTXLOG("Removing existing %s from DFS",filename.str());
  10622. writer->queryFile()->remove();
  10623. }
  10624. else
  10625. throw MakeStringException(99, "Cannot write index file %s, file already exists (missing OVERWRITE attribute?)", filename.str());
  10626. }
  10627. }
  10628. void buildUserMetadata(Owned<IPropertyTree> & metadata)
  10629. {
  10630. size32_t nameLen;
  10631. char * nameBuff;
  10632. size32_t valueLen;
  10633. char * valueBuff;
  10634. unsigned idx = 0;
  10635. while(helper.getIndexMeta(nameLen, nameBuff, valueLen, valueBuff, idx++))
  10636. {
  10637. StringBuffer name(nameLen, nameBuff);
  10638. StringBuffer value(valueLen, valueBuff);
  10639. if(*nameBuff == '_' && strcmp(name, "_nodeSize") != 0)
  10640. {
  10641. OwnedRoxieString fname(helper.getFileName());
  10642. throw MakeStringException(0, "Invalid name %s in user metadata for index %s (names beginning with underscore are reserved)", name.str(), fname.get());
  10643. }
  10644. if(!validateXMLTag(name.str()))
  10645. {
  10646. OwnedRoxieString fname(helper.getFileName());
  10647. throw MakeStringException(0, "Invalid name %s in user metadata for index %s (not legal XML element name)", name.str(), fname.get());
  10648. }
  10649. if(!metadata)
  10650. metadata.setown(createPTree("metadata"));
  10651. metadata->setProp(name.str(), value.str());
  10652. }
  10653. }
  10654. void buildLayoutMetadata(Owned<IPropertyTree> & metadata)
  10655. {
  10656. if(!metadata)
  10657. metadata.setown(createPTree("metadata"));
  10658. metadata->setProp("_record_ECL", helper.queryRecordECL());
  10659. void * layoutMetaBuff;
  10660. size32_t layoutMetaSize;
  10661. if(helper.getIndexLayout(layoutMetaSize, layoutMetaBuff))
  10662. {
  10663. metadata->setPropBin("_record_layout", layoutMetaSize, layoutMetaBuff);
  10664. rtlFree(layoutMetaBuff);
  10665. }
  10666. }
  10667. public:
  10668. CRoxieServerIndexWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  10669. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, 0), helper(static_cast<IHThorIndexWriteArg &>(basehelper))
  10670. {
  10671. overwrite = ((helper.getFlags() & TIWoverwrite) != 0);
  10672. reccount = 0;
  10673. fileCrc = 0;
  10674. }
  10675. ~CRoxieServerIndexWriteActivity()
  10676. {
  10677. }
  10678. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10679. {
  10680. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  10681. resolve();
  10682. }
  10683. virtual void onExecute()
  10684. {
  10685. bool isVariable = helper.queryDiskRecordSize()->isVariableSize();
  10686. size32_t maxDiskRecordSize;
  10687. if (isVariable)
  10688. {
  10689. if (helper.getFlags() & TIWmaxlength)
  10690. maxDiskRecordSize = helper.getMaxKeySize();
  10691. else
  10692. maxDiskRecordSize = KEYBUILD_MAXLENGTH; // Current default behaviour, could be improved in the future
  10693. }
  10694. else
  10695. maxDiskRecordSize = helper.queryDiskRecordSize()->getFixedSize();
  10696. if (maxDiskRecordSize > KEYBUILD_MAXLENGTH)
  10697. throw MakeStringException(99, "Index maximum record length (%d) exceeds 32k internal limit", maxDiskRecordSize);
  10698. OwnedMalloc<char> rowBuffer(maxDiskRecordSize, true);
  10699. fileCrc = -1;
  10700. {
  10701. Owned<IFileIO> io;
  10702. try
  10703. {
  10704. io.setown(writer->queryFile()->open(IFOcreate));
  10705. }
  10706. catch(IException * e)
  10707. {
  10708. e->Release();
  10709. clearKeyStoreCache(false);
  10710. io.setown(writer->queryFile()->open(IFOcreate));
  10711. }
  10712. if(!io)
  10713. throw MakeStringException(errno, "Failed to create file %s for writing", filename.str());
  10714. Owned<IFileIOStream> out = createIOStream(io);
  10715. unsigned flags = COL_PREFIX | HTREE_FULLSORT_KEY;
  10716. if (helper.getFlags() & TIWrowcompress)
  10717. flags |= HTREE_COMPRESSED_KEY|HTREE_QUICK_COMPRESSED_KEY;
  10718. else if (!(helper.getFlags() & TIWnolzwcompress))
  10719. flags |= HTREE_COMPRESSED_KEY;
  10720. if (isVariable)
  10721. flags |= HTREE_VARSIZE;
  10722. Owned<IPropertyTree> metadata;
  10723. buildUserMetadata(metadata);
  10724. buildLayoutMetadata(metadata);
  10725. unsigned nodeSize = metadata ? metadata->getPropInt("_nodeSize", NODESIZE) : NODESIZE;
  10726. Owned<IKeyBuilder> builder = createKeyBuilder(out, flags, maxDiskRecordSize, nodeSize, helper.getKeyedSize(), 0);
  10727. class BcWrapper : implements IBlobCreator
  10728. {
  10729. IKeyBuilder *builder;
  10730. public:
  10731. BcWrapper(IKeyBuilder *_builder) : builder(_builder) {}
  10732. virtual unsigned __int64 createBlob(size32_t size, const void * ptr)
  10733. {
  10734. return builder->createBlob(size, (const char *) ptr);
  10735. }
  10736. } bc(builder);
  10737. // Loop thru the results
  10738. loop
  10739. {
  10740. OwnedConstRoxieRow nextrec(inputStream->ungroupedNextRow());
  10741. if (!nextrec)
  10742. break;
  10743. try
  10744. {
  10745. unsigned __int64 fpos=0;
  10746. RtlStaticRowBuilder rowBuilder(rowBuffer, maxDiskRecordSize);
  10747. size32_t thisSize = helper.transform(rowBuilder, nextrec, &bc, fpos);
  10748. builder->processKeyData(rowBuffer, fpos, thisSize);
  10749. }
  10750. catch(IException * e)
  10751. {
  10752. throw makeWrappedException(e);
  10753. }
  10754. reccount++;
  10755. }
  10756. if(metadata)
  10757. builder->finish(metadata,&fileCrc);
  10758. else
  10759. builder->finish(&fileCrc);
  10760. }
  10761. }
  10762. virtual void stop()
  10763. {
  10764. if (writer)
  10765. {
  10766. if (!aborted)
  10767. updateWorkUnitResult();
  10768. writer->finish(!aborted, this);
  10769. writer.clear();
  10770. }
  10771. CRoxieServerActivity::stop();
  10772. }
  10773. virtual void reset()
  10774. {
  10775. CRoxieServerActivity::reset();
  10776. writer.clear();
  10777. }
  10778. //interface IRoxiePublishCallback
  10779. virtual void setFileProperties(IFileDescriptor *desc) const
  10780. {
  10781. IPropertyTree &partProps = desc->queryPart(0)->queryProperties(); //properties of the first file part.
  10782. IPropertyTree &fileProps = desc->queryProperties(); // properties of the logical file
  10783. // Now publish to name services
  10784. StringBuffer dir,base;
  10785. offset_t indexFileSize = writer->queryFile()->size();
  10786. if(clusterHandler)
  10787. clusterHandler->splitPhysicalFilename(dir, base);
  10788. else
  10789. splitFilename(filename.str(), &dir, &dir, &base, &base);
  10790. desc->setDefaultDir(dir.str());
  10791. //properties of the first file part.
  10792. Owned<IPropertyTree> attrs;
  10793. if(clusterHandler)
  10794. attrs.setown(createPTree("Part")); // clusterHandler is going to set attributes
  10795. else
  10796. {
  10797. // add cluster
  10798. StringBuffer mygroupname;
  10799. desc->setNumParts(1);
  10800. desc->setPartMask(base.str());
  10801. attrs.set(&desc->queryPart(0)->queryProperties());
  10802. }
  10803. attrs->setPropInt64("@size", indexFileSize);
  10804. CDateTime createTime, modifiedTime, accessedTime;
  10805. writer->queryFile()->getTime(&createTime, &modifiedTime, &accessedTime);
  10806. // round file time down to nearest sec. Nanosec accurancy is not preserved elsewhere and can lead to mismatch later.
  10807. unsigned hour, min, sec, nanosec;
  10808. modifiedTime.getTime(hour, min, sec, nanosec);
  10809. modifiedTime.setTime(hour, min, sec, 0);
  10810. StringBuffer timestr;
  10811. modifiedTime.getString(timestr);
  10812. if(timestr.length())
  10813. attrs->setProp("@modified", timestr.str());
  10814. if(clusterHandler)
  10815. clusterHandler->setDescriptorParts(desc, base.str(), attrs);
  10816. // properties of the logical file
  10817. IPropertyTree & properties = desc->queryProperties();
  10818. properties.setProp("@kind", "key");
  10819. properties.setPropInt64("@size", indexFileSize);
  10820. properties.setPropInt64("@recordCount", reccount);
  10821. WorkunitUpdate workUnit = ctx->updateWorkUnit();
  10822. if (workUnit)
  10823. {
  10824. properties.setProp("@owner", workUnit->queryUser());
  10825. properties.setProp("@workunit", workUnit->queryWuid());
  10826. properties.setProp("@job", workUnit->queryJobName());
  10827. }
  10828. char const * rececl = helper.queryRecordECL();
  10829. if(rececl && *rececl)
  10830. properties.setProp("ECL", rececl);
  10831. if (helper.getFlags() & TIWexpires)
  10832. setExpiryTime(properties, helper.getExpiryDays());
  10833. if (helper.getFlags() & TIWupdate)
  10834. {
  10835. unsigned eclCRC;
  10836. unsigned __int64 totalCRC;
  10837. helper.getUpdateCRCs(eclCRC, totalCRC);
  10838. properties.setPropInt("@eclCRC", eclCRC);
  10839. properties.setPropInt64("@totalCRC", totalCRC);
  10840. }
  10841. properties.setPropInt("@fileCrc", fileCrc);
  10842. properties.setPropInt("@formatCrc", helper.getFormatCrc());
  10843. void * layoutMetaBuff;
  10844. size32_t layoutMetaSize;
  10845. if(helper.getIndexLayout(layoutMetaSize, layoutMetaBuff))
  10846. {
  10847. properties.setPropBin("_record_layout", layoutMetaSize, layoutMetaBuff);
  10848. rtlFree(layoutMetaBuff);
  10849. }
  10850. }
  10851. IUserDescriptor *queryUserDescriptor() const
  10852. {
  10853. IConstWorkUnit *workUnit = ctx->queryWorkUnit();
  10854. if (workUnit)
  10855. return workUnit->queryUserDescriptor();
  10856. else
  10857. return NULL;
  10858. }
  10859. };
  10860. //=================================================================================
  10861. class CRoxieServerIndexWriteActivityFactory : public CRoxieServerMultiOutputFactory
  10862. {
  10863. public:
  10864. CRoxieServerIndexWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  10865. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  10866. {
  10867. setNumOutputs(0);
  10868. }
  10869. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  10870. {
  10871. return new CRoxieServerIndexWriteActivity(_ctx, this, _probeManager);
  10872. }
  10873. virtual bool isSink() const
  10874. {
  10875. return true;
  10876. }
  10877. };
  10878. IRoxieServerActivityFactory *createRoxieServerIndexWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  10879. {
  10880. return new CRoxieServerIndexWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  10881. }
  10882. //=================================================================================
  10883. static inline void getLimitType(unsigned flags, bool & limitFail, bool & limitOnFail)
  10884. {
  10885. if((flags & JFmatchAbortLimitSkips) != 0)
  10886. {
  10887. limitFail = false;
  10888. limitOnFail = false;
  10889. }
  10890. else
  10891. {
  10892. limitOnFail = ((flags & JFonfail) != 0);
  10893. limitFail = !limitOnFail;
  10894. }
  10895. }
  10896. class CRoxieServerJoinActivity : public CRoxieServerTwoInputActivity
  10897. {
  10898. enum { JSfill, JSfillleft, JSfillright, JScollate, JScompare, JSleftonly, JSrightonly } state;
  10899. IHThorJoinArg &helper;
  10900. ICompare * collate;
  10901. ICompare * collateupper;
  10902. ThorActivityKind activityKind;
  10903. bool leftOuterJoin;
  10904. bool rightOuterJoin;
  10905. bool exclude;
  10906. bool limitFail;
  10907. bool limitOnFail;
  10908. bool forceSpill;
  10909. unsigned keepLimit;
  10910. unsigned joinLimit;
  10911. unsigned atmostLimit;
  10912. unsigned abortLimit;
  10913. unsigned atmostsTriggered;
  10914. bool betweenjoin;
  10915. OwnedRowArray right;
  10916. const void * left;
  10917. const void * pendingRight;
  10918. unsigned rightIndex;
  10919. unsigned joinCounter;
  10920. BoolArray matchedRight;
  10921. bool matchedLeft;
  10922. Owned<IException> failingLimit;
  10923. ConstPointerArray filteredRight;
  10924. Owned<IRHLimitedCompareHelper> limitedhelper;
  10925. OwnedConstRoxieRow defaultLeft;
  10926. OwnedConstRoxieRow defaultRight;
  10927. Owned<IEngineRowAllocator> defaultLeftAllocator;
  10928. Owned<IEngineRowAllocator> defaultRightAllocator;
  10929. Owned<IGroupedInput> sortedLeft;
  10930. Owned<IGroupedInput> groupedSortedRight;
  10931. bool cloneLeft;
  10932. void createDefaultLeft()
  10933. {
  10934. if (!defaultLeft)
  10935. {
  10936. if (!defaultLeftAllocator)
  10937. defaultLeftAllocator.setown(createRowAllocator(input->queryOutputMeta()));
  10938. RtlDynamicRowBuilder rowBuilder(defaultLeftAllocator);
  10939. size32_t thisSize = helper.createDefaultLeft(rowBuilder);
  10940. defaultLeft.setown(rowBuilder.finalizeRowClear(thisSize));
  10941. }
  10942. }
  10943. void createDefaultRight()
  10944. {
  10945. if (!defaultRight)
  10946. {
  10947. if (!defaultRightAllocator)
  10948. defaultRightAllocator.setown(createRowAllocator(input1->queryOutputMeta()));
  10949. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  10950. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  10951. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  10952. }
  10953. }
  10954. public:
  10955. CRoxieServerJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _forceSpill)
  10956. : CRoxieServerTwoInputActivity(_ctx, _factory, _probeManager), helper((IHThorJoinArg &)basehelper), forceSpill(_forceSpill)
  10957. {
  10958. // MORE - some of this should be done in factory
  10959. unsigned joinFlags = helper.getJoinFlags();
  10960. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  10961. rightOuterJoin = (joinFlags & JFrightouter) != 0;
  10962. exclude = (joinFlags & JFexclude) != 0;
  10963. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  10964. getLimitType(joinFlags, limitFail, limitOnFail);
  10965. if (joinFlags & JFslidingmatch)
  10966. {
  10967. betweenjoin = true;
  10968. collate = helper.queryCompareLeftRightLower();
  10969. collateupper = helper.queryCompareLeftRightUpper();
  10970. }
  10971. else
  10972. {
  10973. betweenjoin = false;
  10974. collate = collateupper = helper.queryCompareLeftRight();
  10975. }
  10976. rightIndex = 0;
  10977. joinCounter = 0;
  10978. state = JSfill;
  10979. matchedLeft = false;
  10980. joinLimit = 0;
  10981. keepLimit = 0; // wait until ctx available
  10982. atmostLimit = 0; // wait until ctx available
  10983. abortLimit = 0; // wait until ctx available
  10984. atmostsTriggered = 0;
  10985. assertex((joinFlags & (JFfirst | JFfirstleft | JFfirstright)) == 0);
  10986. left = NULL;
  10987. pendingRight = NULL;
  10988. activityKind = _factory->getKind();
  10989. }
  10990. virtual bool needsAllocator() const { return true; }
  10991. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10992. {
  10993. left = NULL;
  10994. rightIndex = 0;
  10995. joinCounter = 0;
  10996. state = JSfill;
  10997. matchedLeft = false;
  10998. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  10999. keepLimit = helper.getKeepLimit();
  11000. if (keepLimit == 0)
  11001. keepLimit = (unsigned)-1;
  11002. atmostsTriggered = 0;
  11003. atmostLimit = helper.getJoinLimit();
  11004. if(atmostLimit == 0)
  11005. atmostLimit = (unsigned)-1;
  11006. else
  11007. assertex(!rightOuterJoin && !betweenjoin);
  11008. abortLimit = helper.getMatchAbortLimit();
  11009. if (abortLimit == 0)
  11010. abortLimit = (unsigned)-1;
  11011. if (rightOuterJoin)
  11012. createDefaultLeft();
  11013. if ((leftOuterJoin && (activityKind==TAKjoin || activityKind==TAKjoinlight || activityKind==TAKdenormalizegroup)) || limitOnFail)
  11014. createDefaultRight();
  11015. bool isStable = (helper.getJoinFlags() & JFunstable) == 0;
  11016. RoxieSortAlgorithm sortAlgorithm;
  11017. if (forceSpill)
  11018. sortAlgorithm = isStable ? stableSpillingQuickSortAlgorithm : spillingQuickSortAlgorithm;
  11019. else
  11020. sortAlgorithm = isStable ? stableQuickSortAlgorithm : quickSortAlgorithm;
  11021. if (helper.isLeftAlreadySorted())
  11022. sortedLeft.setown(createDegroupedInputReader(inputStream));
  11023. else
  11024. sortedLeft.setown(createSortedInputReader(inputStream, createSortAlgorithm(sortAlgorithm, helper.queryCompareLeft(), ctx->queryRowManager(), input->queryOutputMeta(), ctx->queryCodeContext(), tempDirectory, activityId)));
  11025. ICompare *compareRight = helper.queryCompareRight();
  11026. if (helper.isRightAlreadySorted())
  11027. groupedSortedRight.setown(createGroupedInputReader(inputStream1, compareRight));
  11028. else
  11029. groupedSortedRight.setown(createSortedGroupedInputReader(inputStream1, compareRight, createSortAlgorithm(sortAlgorithm, compareRight, ctx->queryRowManager(), input1->queryOutputMeta(), ctx->queryCodeContext(), tempDirectory, activityId)));
  11030. if ((helper.getJoinFlags() & JFlimitedprefixjoin) && helper.getJoinLimit())
  11031. { //limited match join (s[1..n])
  11032. limitedhelper.setown(createRHLimitedCompareHelper());
  11033. limitedhelper->init( helper.getJoinLimit(), groupedSortedRight, collate, helper.queryPrefixCompare() );
  11034. }
  11035. }
  11036. virtual void reset()
  11037. {
  11038. if (atmostsTriggered)
  11039. noteStatistic(StNumAtmostTriggered, atmostsTriggered);
  11040. right.clear();
  11041. ReleaseClearRoxieRow(left);
  11042. ReleaseClearRoxieRow(pendingRight);
  11043. defaultRight.clear();
  11044. defaultLeft.clear();
  11045. sortedLeft.clear();
  11046. groupedSortedRight.clear();
  11047. CRoxieServerTwoInputActivity::reset();
  11048. }
  11049. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  11050. {
  11051. if (!idx && (helper.getJoinFlags() & JFparallel) != 0)
  11052. {
  11053. puller.setown(new CRoxieServerReadAheadInput(ctx, ctx->queryOptions().parallelJoinPreload));
  11054. puller->setInput(0, _sourceIdx, _in);
  11055. _in = puller;
  11056. _sourceIdx = 0;
  11057. }
  11058. CRoxieServerTwoInputActivity::setInput(idx, _sourceIdx, _in);
  11059. }
  11060. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  11061. {
  11062. if (idx==(unsigned)-1)
  11063. idx = 0;
  11064. return idx ? NULL : this;
  11065. }
  11066. void fillLeft()
  11067. {
  11068. matchedLeft = false;
  11069. left = sortedLeft->nextRow(); // NOTE: already degrouped by the IGroupedInput we attached
  11070. if (betweenjoin && left && pendingRight && (collate->docompare(left, pendingRight) >= 0))
  11071. fillRight();
  11072. if (limitedhelper && 0==rightIndex)
  11073. {
  11074. rightIndex = 0;
  11075. joinCounter = 0;
  11076. right.clear();
  11077. matchedRight.kill();
  11078. if (left)
  11079. {
  11080. limitedhelper->getGroup(right,left);
  11081. ForEachItemIn(idx, right)
  11082. matchedRight.append(false);
  11083. }
  11084. }
  11085. }
  11086. void fillRight()
  11087. {
  11088. if (limitedhelper)
  11089. return;
  11090. failingLimit.clear();
  11091. if(betweenjoin && left)
  11092. {
  11093. aindex_t start = 0;
  11094. while(right.isItem(start) && (collateupper->docompare(left, right.item(start)) > 0))
  11095. start++;
  11096. if(start>0)
  11097. right.clearPart(0, start);
  11098. }
  11099. else
  11100. right.clear();
  11101. rightIndex = 0;
  11102. joinCounter = 0;
  11103. unsigned groupCount = 0;
  11104. const void * next;
  11105. while(true)
  11106. {
  11107. if(pendingRight)
  11108. {
  11109. next = pendingRight;
  11110. pendingRight = NULL;
  11111. }
  11112. else
  11113. {
  11114. next = groupedSortedRight->nextRow();
  11115. }
  11116. if(!rightOuterJoin && next && (!left || (collateupper->docompare(left, next) > 0))) // if right is less than left, and not right outer, can skip group
  11117. {
  11118. while(next)
  11119. {
  11120. ReleaseClearRoxieRow(next);
  11121. next = groupedSortedRight->nextRow();
  11122. }
  11123. continue;
  11124. }
  11125. while(next)
  11126. {
  11127. if(groupCount==abortLimit)
  11128. {
  11129. if(limitFail)
  11130. failLimit();
  11131. if (ctx->queryDebugContext())
  11132. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  11133. if(limitOnFail)
  11134. {
  11135. assertex(!failingLimit);
  11136. try
  11137. {
  11138. failLimit();
  11139. }
  11140. catch(IException * except)
  11141. {
  11142. failingLimit.setown(except);
  11143. }
  11144. assertex(failingLimit != NULL);
  11145. }
  11146. right.append(next);
  11147. do
  11148. {
  11149. next = groupedSortedRight->nextRow();
  11150. ReleaseRoxieRow(next);
  11151. } while(next);
  11152. break;
  11153. }
  11154. else if(groupCount==atmostLimit)
  11155. {
  11156. atmostsTriggered++;
  11157. right.clear();
  11158. groupCount = 0;
  11159. while(next)
  11160. {
  11161. ReleaseRoxieRow(next);
  11162. next = groupedSortedRight->nextRow();
  11163. }
  11164. }
  11165. else
  11166. {
  11167. right.append(next);
  11168. groupCount++;
  11169. }
  11170. next = groupedSortedRight->nextRow();
  11171. }
  11172. // 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
  11173. if(betweenjoin && left)
  11174. {
  11175. pendingRight = groupedSortedRight->nextRow();
  11176. if(!pendingRight || (collate->docompare(left, pendingRight) < 0))
  11177. break;
  11178. }
  11179. else
  11180. break;
  11181. }
  11182. matchedRight.kill();
  11183. ForEachItemIn(idx, right)
  11184. matchedRight.append(false);
  11185. }
  11186. const void * joinRecords(const void * curLeft, const void * curRight, unsigned counter)
  11187. {
  11188. if (cloneLeft)
  11189. {
  11190. LinkRoxieRow(curLeft);
  11191. return curLeft;
  11192. }
  11193. try
  11194. {
  11195. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11196. size32_t thisSize = helper.transform(rowBuilder, curLeft, curRight, counter);
  11197. if (thisSize)
  11198. return rowBuilder.finalizeRowClear(thisSize);
  11199. else
  11200. return NULL;
  11201. }
  11202. catch (IException *E)
  11203. {
  11204. throw makeWrappedException(E);
  11205. }
  11206. }
  11207. const void * denormalizeRecords(const void * curLeft, ConstPointerArray & rows)
  11208. {
  11209. try
  11210. {
  11211. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11212. unsigned numRows = rows.ordinality();
  11213. const void * right = numRows ? rows.item(0) : defaultRight.get();
  11214. size32_t thisSize = helper.transform(rowBuilder, curLeft, right, numRows, (const void * *)rows.getArray());
  11215. if (thisSize)
  11216. return rowBuilder.finalizeRowClear(thisSize);
  11217. else
  11218. return NULL;
  11219. }
  11220. catch (IException *E)
  11221. {
  11222. throw makeWrappedException(E);
  11223. }
  11224. }
  11225. const void * joinException(const void * curLeft, IException * except)
  11226. {
  11227. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11228. size32_t thisSize = helper.onFailTransform(rowBuilder, curLeft, defaultRight, except);
  11229. return rowBuilder.finalizeRowClear(thisSize);
  11230. }
  11231. void failLimit()
  11232. {
  11233. helper.onMatchAbortLimitExceeded();
  11234. CommonXmlWriter xmlwrite(0);
  11235. if (input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  11236. {
  11237. input->queryOutputMeta()->toXML((byte *) left, xmlwrite);
  11238. }
  11239. throw MakeStringException(ROXIE_TOO_MANY_RESULTS, "More than %d match candidates in join %d for row %s", abortLimit, queryId(), xmlwrite.str());
  11240. }
  11241. virtual const void * nextRow()
  11242. {
  11243. ActivityTimer t(totalCycles, timeActivities);
  11244. loop
  11245. {
  11246. switch (state)
  11247. {
  11248. case JSfill:
  11249. fillLeft();
  11250. state = JSfillright;
  11251. break;
  11252. case JSfillright:
  11253. fillRight();
  11254. state = JScollate;
  11255. break;
  11256. case JSfillleft:
  11257. fillLeft();
  11258. state = JScollate;
  11259. break;
  11260. case JScollate:
  11261. if (right.ordinality() == 0)
  11262. {
  11263. if (left == NULL)
  11264. return NULL;
  11265. state = JSleftonly;
  11266. }
  11267. else
  11268. {
  11269. if (!left)
  11270. state = JSrightonly;
  11271. else
  11272. {
  11273. int diff;
  11274. if(betweenjoin)
  11275. diff = ((collate->docompare(left, right.item(0)) < 0) ? -1 : ((collateupper->docompare(left, right.item(right.ordinality()-1)) > 0) ? +1 : 0));
  11276. else
  11277. diff = collate->docompare(left, right.item(0));
  11278. bool limitExceeded = right.ordinality()>abortLimit;
  11279. if (diff == 0)
  11280. {
  11281. if (limitExceeded)
  11282. {
  11283. const void * ret = NULL;
  11284. if(failingLimit)
  11285. ret = joinException(left, failingLimit);
  11286. ReleaseRoxieRow(left);
  11287. left = NULL;
  11288. state = JSfillleft;
  11289. ForEachItemIn(idx, right)
  11290. matchedRight.replace(true, idx);
  11291. if(ret)
  11292. {
  11293. processed++;
  11294. return ret;
  11295. }
  11296. }
  11297. else
  11298. {
  11299. state = JScompare;
  11300. joinLimit = keepLimit;
  11301. }
  11302. }
  11303. else if (diff < 0)
  11304. state = JSleftonly;
  11305. else if (limitExceeded)
  11306. {
  11307. // MORE - Roxie code seems to think there should be a destroyRowset(right) here....
  11308. state = JSfillright;
  11309. }
  11310. else
  11311. state = JSrightonly;
  11312. }
  11313. }
  11314. break;
  11315. case JSrightonly:
  11316. if (rightOuterJoin)
  11317. {
  11318. switch (activityKind)
  11319. {
  11320. case TAKjoin:
  11321. {
  11322. while (right.isItem(rightIndex))
  11323. {
  11324. if (!matchedRight.item(rightIndex))
  11325. {
  11326. const void * rhs = right.item(rightIndex++);
  11327. const void *ret = joinRecords(defaultLeft, rhs, 0);
  11328. if (ret)
  11329. {
  11330. processed++;
  11331. return ret;
  11332. }
  11333. }
  11334. else
  11335. rightIndex++;
  11336. }
  11337. break;
  11338. }
  11339. //Probably excessive to implement the following, but possibly useful
  11340. case TAKdenormalize:
  11341. {
  11342. OwnedConstRoxieRow newLeft;
  11343. newLeft.set(defaultLeft);
  11344. unsigned rowSize = 0;
  11345. unsigned leftCount = 0;
  11346. while (right.isItem(rightIndex))
  11347. {
  11348. if (!matchedRight.item(rightIndex))
  11349. {
  11350. const void * rhs = right.item(rightIndex);
  11351. try
  11352. {
  11353. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11354. unsigned thisSize = helper.transform(rowBuilder, newLeft, rhs, ++leftCount);
  11355. if (thisSize)
  11356. {
  11357. rowSize = thisSize;
  11358. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  11359. }
  11360. }
  11361. catch (IException *E)
  11362. {
  11363. throw makeWrappedException(E);
  11364. }
  11365. }
  11366. rightIndex++;
  11367. }
  11368. state = JSfillright;
  11369. if (rowSize)
  11370. {
  11371. processed++;
  11372. return newLeft.getClear();
  11373. }
  11374. break;
  11375. }
  11376. case TAKdenormalizegroup:
  11377. {
  11378. filteredRight.kill();
  11379. while (right.isItem(rightIndex))
  11380. {
  11381. if (!matchedRight.item(rightIndex))
  11382. filteredRight.append(right.item(rightIndex));
  11383. rightIndex++;
  11384. }
  11385. state = JSfillright;
  11386. if (filteredRight.ordinality())
  11387. {
  11388. const void * ret = denormalizeRecords(defaultLeft, filteredRight);
  11389. filteredRight.kill();
  11390. if (ret)
  11391. {
  11392. processed++;
  11393. return ret;
  11394. }
  11395. }
  11396. break;
  11397. }
  11398. }
  11399. }
  11400. state = JSfillright;
  11401. break;
  11402. case JSleftonly:
  11403. {
  11404. const void * ret = NULL;
  11405. if (!matchedLeft && leftOuterJoin)
  11406. {
  11407. switch (activityKind)
  11408. {
  11409. case TAKjoin:
  11410. ret = joinRecords(left, defaultRight, 0);
  11411. break;
  11412. case TAKdenormalize:
  11413. ret = left;
  11414. left = NULL;
  11415. break;
  11416. case TAKdenormalizegroup:
  11417. filteredRight.kill();
  11418. ret = denormalizeRecords(left, filteredRight);
  11419. break;
  11420. }
  11421. }
  11422. ReleaseRoxieRow(left);
  11423. left = NULL;
  11424. state = JSfillleft;
  11425. if (ret)
  11426. {
  11427. processed++;
  11428. return ret;
  11429. }
  11430. break;
  11431. }
  11432. case JScompare:
  11433. if (joinLimit != 0)
  11434. {
  11435. switch (activityKind)
  11436. {
  11437. case TAKjoin:
  11438. {
  11439. while (right.isItem(rightIndex))
  11440. {
  11441. const void * rhs = right.item(rightIndex++);
  11442. if (helper.match(left, rhs))
  11443. {
  11444. matchedRight.replace(true, rightIndex-1);
  11445. matchedLeft = true;
  11446. if (!exclude)
  11447. {
  11448. const void *ret = joinRecords(left, rhs, ++joinCounter);
  11449. if (ret)
  11450. {
  11451. processed++;
  11452. joinLimit--;
  11453. return ret;
  11454. }
  11455. }
  11456. }
  11457. }
  11458. break;
  11459. }
  11460. case TAKdenormalize:
  11461. {
  11462. OwnedConstRoxieRow newLeft;
  11463. newLeft.set(left);
  11464. unsigned rowSize = 0;
  11465. unsigned leftCount = 0;
  11466. while (right.isItem(rightIndex) && joinLimit)
  11467. {
  11468. try
  11469. {
  11470. const void * rhs = right.item(rightIndex++);
  11471. if (helper.match(left, rhs))
  11472. {
  11473. matchedRight.replace(true, rightIndex-1);
  11474. matchedLeft = true;
  11475. if (!exclude)
  11476. {
  11477. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11478. unsigned thisSize = helper.transform(rowBuilder, newLeft, rhs, ++leftCount);
  11479. if (thisSize)
  11480. {
  11481. rowSize = thisSize;
  11482. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  11483. joinLimit--;
  11484. }
  11485. }
  11486. }
  11487. }
  11488. catch (IException *E)
  11489. {
  11490. throw makeWrappedException(E);
  11491. }
  11492. }
  11493. state = JSleftonly;
  11494. rightIndex = 0;
  11495. if (rowSize)
  11496. {
  11497. processed++;
  11498. return newLeft.getClear();
  11499. }
  11500. break;
  11501. }
  11502. case TAKdenormalizegroup:
  11503. {
  11504. filteredRight.kill();
  11505. while (right.isItem(rightIndex))
  11506. {
  11507. const void * rhs = right.item(rightIndex++);
  11508. if (helper.match(left, rhs))
  11509. {
  11510. matchedRight.replace(true, rightIndex-1);
  11511. filteredRight.append(rhs);
  11512. matchedLeft = true;
  11513. if (filteredRight.ordinality()==joinLimit)
  11514. break;
  11515. }
  11516. }
  11517. state = JSleftonly;
  11518. rightIndex = 0;
  11519. if (!exclude && filteredRight.ordinality())
  11520. {
  11521. const void * ret = denormalizeRecords(left, filteredRight);
  11522. filteredRight.kill();
  11523. if (ret)
  11524. {
  11525. processed++;
  11526. return ret;
  11527. }
  11528. }
  11529. break;
  11530. }
  11531. }
  11532. }
  11533. state = JSleftonly;
  11534. rightIndex = 0;
  11535. joinCounter = 0;
  11536. break;
  11537. }
  11538. }
  11539. }
  11540. };
  11541. class CRoxieServerJoinActivityFactory : public CRoxieServerActivityFactory
  11542. {
  11543. unsigned input2;
  11544. unsigned input2idx;
  11545. bool forceSpill;
  11546. public:
  11547. CRoxieServerJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  11548. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  11549. {
  11550. forceSpill = _graphNode.getPropBool("hint[@name='spill']/@value", _queryFactory.queryOptions().allSortsMaySpill);
  11551. input2 = 0;
  11552. input2idx = 0;
  11553. }
  11554. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  11555. {
  11556. return new CRoxieServerJoinActivity(_ctx, this, _probeManager, forceSpill);
  11557. }
  11558. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  11559. {
  11560. if (idx==1)
  11561. {
  11562. input2 = source;
  11563. input2idx = sourceidx;
  11564. }
  11565. else
  11566. CRoxieServerActivityFactory::setInput(idx, source, sourceidx);
  11567. }
  11568. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  11569. {
  11570. switch (idx)
  11571. {
  11572. case 1:
  11573. sourceidx = input2idx;
  11574. return input2;
  11575. case 0:
  11576. return CRoxieServerActivityFactory::getInput(idx, sourceidx);
  11577. default:
  11578. return (unsigned) -1;
  11579. }
  11580. }
  11581. virtual unsigned numInputs() const { return 2; }
  11582. virtual const StatisticsMapping &queryStatsMapping() const
  11583. {
  11584. return joinStatistics;
  11585. }
  11586. };
  11587. IRoxieServerActivityFactory *createRoxieServerJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  11588. {
  11589. return new CRoxieServerJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  11590. }
  11591. //=================================================================================
  11592. #define CONCAT_READAHEAD 1000
  11593. class CRoxieThreadedConcatReader : implements IRecordPullerCallback, public CInterface
  11594. {
  11595. public:
  11596. IMPLEMENT_IINTERFACE;
  11597. CRoxieThreadedConcatReader(InterruptableSemaphore &_ready, bool _grouped)
  11598. : puller(false), grouped(_grouped), atEog(true), ready(_ready), eof(false)
  11599. {
  11600. }
  11601. void start(unsigned parentExtractSize, const byte *parentExtract, bool paused, IRoxieSlaveContext *ctx)
  11602. {
  11603. space.reinit(CONCAT_READAHEAD);
  11604. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().concatPreload, false, ctx);
  11605. }
  11606. void stop()
  11607. {
  11608. space.interrupt();
  11609. puller.stop();
  11610. }
  11611. IFinalRoxieInput *queryInput() const
  11612. {
  11613. return puller.queryInput();
  11614. }
  11615. void reset()
  11616. {
  11617. puller.reset();
  11618. ForEachItemIn(idx, buffer)
  11619. ReleaseRoxieRow(buffer.item(idx));
  11620. buffer.clear();
  11621. eof = false;
  11622. atEog = true;
  11623. }
  11624. void setInput(unsigned _sourceIdx, IFinalRoxieInput *_in)
  11625. {
  11626. puller.setInput(this, _sourceIdx, _in);
  11627. }
  11628. void connectInputStreams(IRoxieSlaveContext *ctx, bool consumerOrdered)
  11629. {
  11630. puller.connectInputStreams(ctx, consumerOrdered);
  11631. }
  11632. virtual void processRow(const void *row)
  11633. {
  11634. buffer.enqueue(row);
  11635. ready.signal();
  11636. space.wait();
  11637. }
  11638. virtual void processGroup(const ConstPointerArray &rows)
  11639. {
  11640. // We use record-by-record input mode of the puller thread even in grouped mode.
  11641. throwUnexpected();
  11642. }
  11643. virtual void processEOG()
  11644. {
  11645. if (grouped)
  11646. processRow(NULL);
  11647. }
  11648. virtual void processDone()
  11649. {
  11650. processRow(NULL);
  11651. }
  11652. virtual bool fireException(IException *e)
  11653. {
  11654. // called from puller thread on failure
  11655. ready.interrupt(LINK(e));
  11656. space.interrupt(e);
  11657. return true;
  11658. }
  11659. bool peek(const void * &row, bool &anyActive)
  11660. {
  11661. if (!eof)
  11662. {
  11663. if (buffer.ordinality())
  11664. {
  11665. space.signal();
  11666. row = buffer.dequeue();
  11667. if (row==NULL)
  11668. {
  11669. if (atEog)
  11670. {
  11671. eof = true;
  11672. return false;
  11673. }
  11674. else
  11675. atEog = true;
  11676. }
  11677. else if (grouped)
  11678. atEog = false;
  11679. return true;
  11680. }
  11681. anyActive = true;
  11682. }
  11683. return false;
  11684. }
  11685. protected:
  11686. RecordPullerThread puller;
  11687. InterruptableSemaphore space;
  11688. InterruptableSemaphore &ready;
  11689. SafeQueueOf<const void, true> buffer;
  11690. bool atEog;
  11691. bool eof;
  11692. bool grouped;
  11693. };
  11694. typedef CopyReferenceArrayOf<CRoxieThreadedConcatReader> ReaderArray;
  11695. class CRoxieServerThreadedConcatActivity : public CRoxieServerActivity
  11696. {
  11697. InterruptableSemaphore ready;
  11698. ReaderArray pullers;
  11699. unsigned numInputs;
  11700. unsigned nextPuller; // for round robin
  11701. unsigned readyPending;
  11702. bool eof;
  11703. bool inGroup;
  11704. bool grouped;
  11705. public:
  11706. CRoxieServerThreadedConcatActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _grouped, unsigned _numInputs)
  11707. : CRoxieServerActivity(_ctx, _factory, _probeManager), grouped(_grouped)
  11708. {
  11709. numInputs = _numInputs;
  11710. eof = (numInputs==0);
  11711. inGroup = false;
  11712. nextPuller = 0;
  11713. readyPending = 0;
  11714. for (unsigned i = 0; i < numInputs; i++)
  11715. pullers.append(*new CRoxieThreadedConcatReader(ready, _grouped));
  11716. }
  11717. ~CRoxieServerThreadedConcatActivity()
  11718. {
  11719. ForEachItemIn(idx, pullers)
  11720. delete &pullers.item(idx);
  11721. }
  11722. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11723. {
  11724. eof = (numInputs==0);
  11725. inGroup = false;
  11726. nextPuller = 0;
  11727. readyPending = 0;
  11728. ready.reinit();
  11729. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  11730. ForEachItemIn(idx, pullers)
  11731. {
  11732. pullers.item(idx).start(parentExtractSize, parentExtract, paused, ctx);
  11733. // NOTE - it is ok to start the thread running while parts of the subgraph are still being started, since everything
  11734. // in the part of the subgraph that the thread uses has been started.
  11735. // Note that splitters are supposed to cope with being used when only some outputs have been started.
  11736. }
  11737. }
  11738. virtual void stop()
  11739. {
  11740. ready.interrupt();
  11741. ForEachItemIn(idx, pullers)
  11742. pullers.item(idx).stop();
  11743. CRoxieServerActivity::stop();
  11744. }
  11745. virtual unsigned __int64 queryLocalCycles() const
  11746. {
  11747. return 0;
  11748. }
  11749. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  11750. {
  11751. if (pullers.isItem(idx))
  11752. return pullers.item(idx).queryInput();
  11753. else
  11754. return NULL;
  11755. }
  11756. virtual void reset()
  11757. {
  11758. CRoxieServerActivity::reset();
  11759. ForEachItemIn(idx, pullers)
  11760. pullers.item(idx).reset();
  11761. eof = false;
  11762. inGroup = false;
  11763. nextPuller = 0;
  11764. readyPending = 0;
  11765. }
  11766. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  11767. {
  11768. if (pullers.isItem(idx))
  11769. pullers.item(idx).setInput(_sourceIdx, _in);
  11770. else
  11771. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  11772. }
  11773. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  11774. {
  11775. ForEachItemIn(i, pullers)
  11776. pullers.item(i).connectInputStreams(ctx, consumerOrdered);
  11777. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, nullptr, consumerOrdered, nullptr); // No input actually connected
  11778. }
  11779. virtual const void * nextRow()
  11780. {
  11781. ActivityTimer t(totalCycles, timeActivities);
  11782. if (eof)
  11783. return NULL;
  11784. loop
  11785. {
  11786. if (readyPending && !inGroup)
  11787. {
  11788. if (readyPending > 1)
  11789. ready.signal(readyPending-1);
  11790. readyPending = 0;
  11791. }
  11792. else
  11793. ready.wait();
  11794. bool anyActive = false;
  11795. ForEachItemIn(unused_index, pullers)
  11796. {
  11797. // NOTE - we round robin not just because it's more efficient, but because it ensures the preservation of grouping information
  11798. const void *ret;
  11799. bool fetched = pullers.item(nextPuller).peek(ret, anyActive);
  11800. if (fetched)
  11801. {
  11802. inGroup = (ret != NULL);
  11803. return ret;
  11804. }
  11805. if (inGroup && grouped)
  11806. {
  11807. // Some other puller has data, but we can't consume it until the group we are reading is complete.
  11808. readyPending++;
  11809. anyActive = true;
  11810. break;
  11811. }
  11812. nextPuller++;
  11813. if (nextPuller==pullers.ordinality())
  11814. nextPuller = 0;
  11815. }
  11816. if (!anyActive)
  11817. break;
  11818. // A ready signal without anything being ready means someone reached end-of-file.
  11819. }
  11820. eof = true;
  11821. return NULL;
  11822. }
  11823. };
  11824. class CRoxieServerOrderedConcatActivity : public CRoxieServerMultiInputActivity
  11825. {
  11826. IEngineRowStream *curStream;
  11827. bool eogSeen;
  11828. bool anyThisGroup;
  11829. bool grouped;
  11830. unsigned streamIdx;
  11831. public:
  11832. CRoxieServerOrderedConcatActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _grouped, unsigned _numInputs)
  11833. : CRoxieServerMultiInputActivity(_ctx, _factory, _probeManager, _numInputs)
  11834. {
  11835. eogSeen = false;
  11836. anyThisGroup = false;
  11837. grouped = _grouped;
  11838. streamIdx = 0;
  11839. curStream = NULL;
  11840. }
  11841. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11842. {
  11843. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  11844. streamIdx = 0;
  11845. curStream = streamArray[streamIdx];
  11846. eogSeen = false;
  11847. anyThisGroup = false;
  11848. }
  11849. virtual const void * nextRow()
  11850. {
  11851. ActivityTimer t(totalCycles, timeActivities);
  11852. if (!curStream)
  11853. return NULL; // eof
  11854. const void * next = curStream->nextRow();
  11855. if (next)
  11856. {
  11857. anyThisGroup = true;
  11858. eogSeen = false;
  11859. processed++;
  11860. return next;
  11861. }
  11862. else if (!eogSeen)
  11863. {
  11864. eogSeen = true;
  11865. if (grouped)
  11866. {
  11867. if (anyThisGroup)
  11868. {
  11869. anyThisGroup = false;
  11870. return NULL;
  11871. }
  11872. else
  11873. return nextRow();
  11874. }
  11875. else
  11876. return nextRow();
  11877. }
  11878. else if (streamIdx < numStreams-1)
  11879. {
  11880. streamIdx++;
  11881. curStream = streamArray[streamIdx];
  11882. eogSeen = false;
  11883. return nextRow();
  11884. }
  11885. else
  11886. {
  11887. curStream = NULL;
  11888. return NULL;
  11889. }
  11890. }
  11891. };
  11892. class CRoxieServerConcatActivityFactory : public CRoxieServerMultiInputFactory
  11893. {
  11894. bool ordered;
  11895. bool grouped;
  11896. public:
  11897. CRoxieServerConcatActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  11898. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  11899. {
  11900. Owned <IHThorFunnelArg> helper = (IHThorFunnelArg *) helperFactory();
  11901. ordered = helper->isOrdered();
  11902. grouped = helper->queryOutputMeta()->isGrouped();
  11903. }
  11904. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  11905. {
  11906. if (ordered || (_probeManager && _probeManager->queryDebugManager()))
  11907. return new CRoxieServerOrderedConcatActivity(_ctx, this, _probeManager, grouped, numInputs());
  11908. else
  11909. return new CRoxieServerThreadedConcatActivity(_ctx, this, _probeManager, grouped, numInputs());
  11910. }
  11911. };
  11912. IRoxieServerActivityFactory *createRoxieServerConcatActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  11913. {
  11914. return new CRoxieServerConcatActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  11915. }
  11916. //=================================================================================
  11917. class CRoxieServerNonEmptyActivity : public CRoxieServerMultiInputBaseActivity
  11918. {
  11919. IEngineRowStream* selectedStream;
  11920. unsigned savedParentExtractSize;
  11921. const byte * savedParentExtract;
  11922. bool foundInput;
  11923. public:
  11924. CRoxieServerNonEmptyActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  11925. : CRoxieServerMultiInputBaseActivity(_ctx, _factory, _probeManager, _numInputs)
  11926. {
  11927. foundInput = false;
  11928. selectedStream = NULL;
  11929. savedParentExtractSize = 0;;
  11930. savedParentExtract = NULL;
  11931. }
  11932. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11933. {
  11934. //Don't start the inputs yet so we can short-circuit...
  11935. CRoxieServerMultiInputBaseActivity::start(parentExtractSize, parentExtract, paused);
  11936. savedParentExtractSize = parentExtractSize;
  11937. savedParentExtract = parentExtract;
  11938. }
  11939. virtual void stop()
  11940. {
  11941. if (foundInput)
  11942. {
  11943. if (selectedStream)
  11944. selectedStream->stop();
  11945. }
  11946. else
  11947. {
  11948. for (unsigned i = 0; i < numStreams; i++)
  11949. streamArray[i]->stop();
  11950. }
  11951. CRoxieServerMultiInputBaseActivity::stop();
  11952. }
  11953. virtual void reset()
  11954. {
  11955. CRoxieServerMultiInputBaseActivity::reset();
  11956. foundInput = false;
  11957. selectedStream = NULL;
  11958. }
  11959. virtual unsigned __int64 queryLocalCycles() const
  11960. {
  11961. return 0; // Can't easily calculate anything reliable but local processing is negligible
  11962. }
  11963. virtual const void * nextRow()
  11964. {
  11965. ActivityTimer t(totalCycles, timeActivities);
  11966. if (!foundInput)
  11967. {
  11968. foundInput = true;
  11969. assertex(numInputs == numStreams); // If this ceases to be true we will need to rethink some of this
  11970. //If we get an exception in this loop then stop() will stop any started inputs
  11971. for (unsigned i=0; i < numStreams; i++)
  11972. {
  11973. selectedStream = streamArray[i];
  11974. inputArray[i]->start(savedParentExtractSize, savedParentExtract, false); // Assumes 1:1 mapping streams to inputs
  11975. startJunction(junctionArray[i]);
  11976. const void * next = selectedStream->nextRow();
  11977. if (next)
  11978. {
  11979. //Found a row so stop remaining
  11980. for (unsigned j=i+1; j < numInputs; j++)
  11981. streamArray[j]->stop();
  11982. processed++;
  11983. return next;
  11984. }
  11985. selectedStream->stop();
  11986. }
  11987. selectedStream = NULL;
  11988. return NULL;
  11989. }
  11990. if (!selectedStream)
  11991. return NULL;
  11992. const void * next = selectedStream->nextRow();
  11993. if (next)
  11994. processed++;
  11995. return next;
  11996. }
  11997. };
  11998. class CRoxieServerNonEmptyActivityFactory : public CRoxieServerMultiInputFactory
  11999. {
  12000. public:
  12001. CRoxieServerNonEmptyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12002. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12003. {
  12004. }
  12005. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12006. {
  12007. return new CRoxieServerNonEmptyActivity(_ctx, this, _probeManager, numInputs());
  12008. }
  12009. };
  12010. IRoxieServerActivityFactory *createRoxieServerNonEmptyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12011. {
  12012. return new CRoxieServerNonEmptyActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12013. }
  12014. //=================================================================================
  12015. class CRoxieServerMergeActivity : public CRoxieServerMultiInputActivity
  12016. {
  12017. IHThorMergeArg &helper;
  12018. unsigned *mergeheap;
  12019. unsigned activeInputs;
  12020. const void **pending;
  12021. bool first;
  12022. ICompare *compare;
  12023. bool dedup;
  12024. void permute()
  12025. {
  12026. assertex(activeInputs == 0);
  12027. for(unsigned i = 0; i < numStreams; i++)
  12028. if(pullInput(i))
  12029. mergeheap[activeInputs++] = i;
  12030. // the tree structure: element p has children p*2+1 and p*2+2, or element c has parent (unsigned)(c-1)/2
  12031. // the heap property: no element should be smaller than its parent
  12032. // the dedup variant: if(dedup), the top of the heap should also not be equal to either child
  12033. // 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
  12034. if (activeInputs >= 2)
  12035. for(unsigned p = (activeInputs-2)/2; p > 0; --p)
  12036. siftDown(p);
  12037. if(dedup)
  12038. siftDownDedupTop();
  12039. else
  12040. siftDown(0);
  12041. }
  12042. void readNext()
  12043. {
  12044. if(!pullInput(mergeheap[0]))
  12045. if(!promote(0))
  12046. return;
  12047. // we have changed the element at the top of the heap, so need to sift it down to maintain the heap property
  12048. if(dedup)
  12049. siftDownDedupTop();
  12050. else
  12051. siftDown(0);
  12052. }
  12053. bool pullInput(unsigned i)
  12054. {
  12055. const void *next = streamArray[i]->ungroupedNextRow();
  12056. pending[i] = next;
  12057. return (next != NULL);
  12058. }
  12059. bool promote(unsigned p)
  12060. {
  12061. activeInputs--;
  12062. if(activeInputs == p)
  12063. return false;
  12064. mergeheap[p] = mergeheap[activeInputs];
  12065. return true;
  12066. }
  12067. bool siftDown(unsigned p)
  12068. {
  12069. // assuming that all descendants of p form a heap, sift p down to its correct position, and so include it in the heap
  12070. bool nochange = true;
  12071. while(1)
  12072. {
  12073. unsigned c = p*2 + 1;
  12074. if(c >= activeInputs)
  12075. return nochange;
  12076. if(c+1 < activeInputs)
  12077. {
  12078. int childcmp = BuffCompare(c+1, c);
  12079. if((childcmp < 0) || ((childcmp == 0) && (mergeheap[c+1] < mergeheap[c])))
  12080. ++c;
  12081. }
  12082. int cmp = BuffCompare(c, p);
  12083. if((cmp > 0) || ((cmp == 0) && (mergeheap[c] > mergeheap[p])))
  12084. return nochange;
  12085. nochange = false;
  12086. unsigned r = mergeheap[c];
  12087. mergeheap[c] = mergeheap[p];
  12088. mergeheap[p] = r;
  12089. p = c;
  12090. }
  12091. }
  12092. void siftDownDedupTop()
  12093. {
  12094. // same as siftDown(0), except that it also ensures that the top of the heap is not equal to either of its children
  12095. if(activeInputs < 2)
  12096. return;
  12097. unsigned c = 1;
  12098. int childcmp = 1;
  12099. if(activeInputs >= 3)
  12100. {
  12101. childcmp = BuffCompare(2, 1);
  12102. if(childcmp < 0)
  12103. c = 2;
  12104. }
  12105. int cmp = BuffCompare(c, 0);
  12106. if(cmp > 0)
  12107. return;
  12108. // the following loop ensures the correct property holds on the smaller branch, and that childcmp==0 iff the top matches the other branch
  12109. while(cmp <= 0)
  12110. {
  12111. if(cmp == 0)
  12112. {
  12113. if(mergeheap[c] < mergeheap[0])
  12114. {
  12115. unsigned r = mergeheap[c];
  12116. mergeheap[c] = mergeheap[0];
  12117. mergeheap[0] = r;
  12118. }
  12119. ReleaseClearRoxieRow(pending[mergeheap[c]]);
  12120. if(!pullInput(mergeheap[c]))
  12121. if(!promote(c))
  12122. break;
  12123. siftDown(c);
  12124. }
  12125. else
  12126. {
  12127. unsigned r = mergeheap[c];
  12128. mergeheap[c] = mergeheap[0];
  12129. mergeheap[0] = r;
  12130. if(siftDown(c))
  12131. break;
  12132. }
  12133. cmp = BuffCompare(c, 0);
  12134. }
  12135. // the following loop ensures the uniqueness property holds on the other branch too
  12136. c = 3-c;
  12137. if(activeInputs <= c)
  12138. return;
  12139. while(childcmp == 0)
  12140. {
  12141. if(mergeheap[c] < mergeheap[0])
  12142. {
  12143. unsigned r = mergeheap[c];
  12144. mergeheap[c] = mergeheap[0];
  12145. mergeheap[0] = r;
  12146. }
  12147. ReleaseClearRoxieRow(pending[mergeheap[c]]);
  12148. if(!pullInput(mergeheap[c]))
  12149. if(!promote(c))
  12150. break;
  12151. siftDown(c);
  12152. childcmp = BuffCompare(c, 0);
  12153. }
  12154. }
  12155. inline int BuffCompare(unsigned a, unsigned b)
  12156. {
  12157. return compare->docompare(pending[mergeheap[a]], pending[mergeheap[b]]);
  12158. }
  12159. public:
  12160. CRoxieServerMergeActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  12161. : CRoxieServerMultiInputActivity(_ctx, _factory, _probeManager, _numInputs), helper((IHThorMergeArg &)basehelper)
  12162. {
  12163. activeInputs = 0;
  12164. first = true;
  12165. mergeheap = new unsigned[numInputs];
  12166. pending = new const void *[numStreams];
  12167. compare = helper.queryCompare();
  12168. dedup = helper.dedup();
  12169. for (unsigned i = 0; i < numStreams; i++)
  12170. pending[i] = NULL;
  12171. }
  12172. ~CRoxieServerMergeActivity()
  12173. {
  12174. delete [] mergeheap;
  12175. delete [] pending;
  12176. }
  12177. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12178. {
  12179. activeInputs = 0;
  12180. first = true;
  12181. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  12182. }
  12183. virtual void reset()
  12184. {
  12185. for (unsigned i = 0; i < numStreams; i++)
  12186. ReleaseClearRoxieRow(pending[i]);
  12187. CRoxieServerMultiInputActivity::reset();
  12188. }
  12189. virtual const void * nextRow()
  12190. {
  12191. ActivityTimer t(totalCycles, timeActivities);
  12192. if (first)
  12193. {
  12194. permute();
  12195. first = false;
  12196. }
  12197. if (activeInputs)
  12198. {
  12199. const void *next = pending[mergeheap[0]];
  12200. readNext();
  12201. if (next)
  12202. processed++;
  12203. return next;
  12204. }
  12205. else
  12206. return NULL;
  12207. }
  12208. };
  12209. class CRoxieServerMergeActivityFactory : public CRoxieServerMultiInputFactory
  12210. {
  12211. public:
  12212. CRoxieServerMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12213. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12214. {
  12215. }
  12216. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12217. {
  12218. return new CRoxieServerMergeActivity(_ctx, this, _probeManager, numInputs());
  12219. }
  12220. };
  12221. IRoxieServerActivityFactory *createRoxieServerMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12222. {
  12223. return new CRoxieServerMergeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12224. }
  12225. //=================================================================================
  12226. class CRoxieServerRegroupActivity : public CRoxieServerMultiInputActivity
  12227. {
  12228. IHThorRegroupArg &helper;
  12229. unsigned streamIndex;
  12230. bool eof;
  12231. unsigned __int64 numProcessedLastGroup;
  12232. public:
  12233. CRoxieServerRegroupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  12234. : CRoxieServerMultiInputActivity(_ctx, _factory, _probeManager, _numInputs), helper((IHThorRegroupArg &)basehelper)
  12235. {
  12236. streamIndex = 0;
  12237. eof = false;
  12238. numProcessedLastGroup = 0;
  12239. }
  12240. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12241. {
  12242. streamIndex = 0;
  12243. eof = false;
  12244. numProcessedLastGroup = processed;
  12245. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  12246. }
  12247. const void * nextFromInputs()
  12248. {
  12249. unsigned initialStream = streamIndex;
  12250. while (streamIndex < numStreams)
  12251. {
  12252. const void * next = streamArray[streamIndex]->nextRow();
  12253. if (next)
  12254. {
  12255. if ((streamIndex != initialStream) && (streamIndex != initialStream+1))
  12256. {
  12257. ReleaseRoxieRow(next);
  12258. throw MakeStringException(ROXIE_MISMATCH_GROUP_ERROR, "Mismatched groups supplied to Regroup (%d)", factory->queryId());
  12259. }
  12260. return next;
  12261. }
  12262. streamIndex++;
  12263. }
  12264. if ((initialStream != 0) && (initialStream+1 != numStreams))
  12265. throw MakeStringException(ROXIE_MISMATCH_GROUP_ERROR, "Mismatched groups supplied to Regroup (%d)", factory->queryId());
  12266. streamIndex = 0;
  12267. return NULL;
  12268. }
  12269. virtual const void * nextRow()
  12270. {
  12271. ActivityTimer t(totalCycles, timeActivities);
  12272. if (eof)
  12273. return NULL;
  12274. const void * ret = nextFromInputs();
  12275. if (ret)
  12276. {
  12277. processed++;
  12278. return ret;
  12279. }
  12280. if (numProcessedLastGroup != processed)
  12281. {
  12282. numProcessedLastGroup = processed;
  12283. return NULL;
  12284. }
  12285. eof = true;
  12286. return NULL;
  12287. }
  12288. };
  12289. class CRoxieServerRegroupActivityFactory : public CRoxieServerMultiInputFactory
  12290. {
  12291. public:
  12292. CRoxieServerRegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12293. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12294. {
  12295. }
  12296. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12297. {
  12298. return new CRoxieServerRegroupActivity(_ctx, this, _probeManager, numInputs());
  12299. }
  12300. };
  12301. IRoxieServerActivityFactory *createRoxieServerRegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12302. {
  12303. return new CRoxieServerRegroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12304. }
  12305. //=================================================================================
  12306. class CRoxieServerCombineActivity : public CRoxieServerMultiInputActivity
  12307. {
  12308. IHThorCombineArg &helper;
  12309. unsigned __int64 numProcessedLastGroup;
  12310. public:
  12311. CRoxieServerCombineActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  12312. : CRoxieServerMultiInputActivity(_ctx, _factory, _probeManager, _numInputs), helper((IHThorCombineArg &)basehelper)
  12313. {
  12314. numProcessedLastGroup = 0;
  12315. }
  12316. ~CRoxieServerCombineActivity()
  12317. {
  12318. }
  12319. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12320. {
  12321. numProcessedLastGroup = processed;
  12322. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  12323. }
  12324. void nextInputs(ConstPointerArray & out)
  12325. {
  12326. for (unsigned i=0; i < numStreams; i++)
  12327. {
  12328. const void * next = streamArray[i]->nextRow();
  12329. if (next)
  12330. out.append(next);
  12331. }
  12332. }
  12333. virtual bool needsAllocator() const { return true; }
  12334. virtual const void * nextRow()
  12335. {
  12336. ActivityTimer t(totalCycles, timeActivities);
  12337. loop
  12338. {
  12339. ConstPointerArray group;
  12340. nextInputs(group);
  12341. if ((group.ordinality() == 0) && (numProcessedLastGroup == processed))
  12342. nextInputs(group);
  12343. if (group.ordinality() == 0)
  12344. {
  12345. numProcessedLastGroup = processed;
  12346. return NULL;
  12347. }
  12348. else if (group.ordinality() != numInputs)
  12349. {
  12350. ReleaseRoxieRows(group);
  12351. throw MakeStringException(ROXIE_MISMATCH_GROUP_ERROR, "Mismatched group input for Combine Activity(%d)", factory->queryId());
  12352. }
  12353. try
  12354. {
  12355. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12356. size32_t outSize = helper.transform(rowBuilder, group.ordinality(), group.getArray());
  12357. ReleaseRoxieRows(group);
  12358. if (outSize)
  12359. {
  12360. processed++;
  12361. return rowBuilder.finalizeRowClear(outSize);
  12362. }
  12363. }
  12364. catch (IException *E)
  12365. {
  12366. ReleaseRoxieRows(group);
  12367. throw makeWrappedException(E);
  12368. }
  12369. }
  12370. }
  12371. };
  12372. class CRoxieServerCombineActivityFactory : public CRoxieServerMultiInputFactory
  12373. {
  12374. public:
  12375. CRoxieServerCombineActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12376. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12377. {
  12378. }
  12379. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12380. {
  12381. return new CRoxieServerCombineActivity(_ctx, this, _probeManager, numInputs());
  12382. }
  12383. };
  12384. IRoxieServerActivityFactory *createRoxieServerCombineActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12385. {
  12386. return new CRoxieServerCombineActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12387. }
  12388. //=================================================================================
  12389. class CRoxieServerCombineGroupActivity : public CRoxieServerTwoInputActivity
  12390. {
  12391. IHThorCombineGroupArg &helper;
  12392. unsigned __int64 numProcessedLastGroup;
  12393. public:
  12394. CRoxieServerCombineGroupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  12395. : CRoxieServerTwoInputActivity(_ctx, _factory, _probeManager), helper((IHThorCombineGroupArg &)basehelper)
  12396. {
  12397. numProcessedLastGroup = 0;
  12398. }
  12399. ~CRoxieServerCombineGroupActivity()
  12400. {
  12401. }
  12402. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12403. {
  12404. numProcessedLastGroup = processed;
  12405. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  12406. }
  12407. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  12408. {
  12409. if (idx==(unsigned)-1)
  12410. idx = 0;
  12411. return idx ? NULL : this;
  12412. }
  12413. virtual bool needsAllocator() const { return true; }
  12414. virtual const void * nextRow()
  12415. {
  12416. ActivityTimer t(totalCycles, timeActivities);
  12417. loop
  12418. {
  12419. const void * left = inputStream->nextRow();
  12420. if (!left && (numProcessedLastGroup == processed))
  12421. left = inputStream->nextRow();
  12422. if (!left)
  12423. {
  12424. if (numProcessedLastGroup == processed)
  12425. {
  12426. const void * nextRight = inputStream1->nextRow();
  12427. if (nextRight)
  12428. {
  12429. ReleaseRoxieRow(nextRight);
  12430. throw MakeStringException(ROXIE_MISSING_GROUP_ERROR, "Missing LEFT record for Combine Group (%d)", factory->queryId());
  12431. }
  12432. }
  12433. else
  12434. numProcessedLastGroup = processed;
  12435. return NULL;
  12436. }
  12437. ConstPointerArray group;
  12438. loop
  12439. {
  12440. const void * in = inputStream1->nextRow();
  12441. if (!in)
  12442. break;
  12443. group.append(in);
  12444. }
  12445. if (group.ordinality() == 0)
  12446. {
  12447. ReleaseRoxieRow(left);
  12448. ReleaseRoxieRows(group);
  12449. throw MakeStringException(ROXIE_MISSING_GROUP_ERROR, "Missing RIGHT group for Combine Group (%d)", factory->queryId());
  12450. }
  12451. try
  12452. {
  12453. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12454. size32_t outSize = helper.transform(rowBuilder, left, group.ordinality(), (const void * *)group.getArray());
  12455. ReleaseRoxieRow(left);
  12456. ReleaseRoxieRows(group);
  12457. if (outSize)
  12458. {
  12459. processed++;
  12460. return rowBuilder.finalizeRowClear(outSize);
  12461. }
  12462. }
  12463. catch (IException *E)
  12464. {
  12465. ReleaseRoxieRow(left);
  12466. ReleaseRoxieRows(group);
  12467. throw makeWrappedException(E);
  12468. }
  12469. }
  12470. }
  12471. };
  12472. class CRoxieServerCombineGroupActivityFactory : public CRoxieServerActivityFactory
  12473. {
  12474. unsigned input2;
  12475. unsigned input2idx;
  12476. public:
  12477. CRoxieServerCombineGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12478. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12479. {
  12480. input2 = 0;
  12481. input2idx = 0;
  12482. }
  12483. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12484. {
  12485. return new CRoxieServerCombineGroupActivity(_ctx, this, _probeManager);
  12486. }
  12487. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  12488. {
  12489. if (idx==1)
  12490. {
  12491. input2 = source;
  12492. input2idx = sourceidx;
  12493. }
  12494. else
  12495. CRoxieServerActivityFactory::setInput(idx, source, sourceidx);
  12496. }
  12497. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  12498. {
  12499. switch (idx)
  12500. {
  12501. case 1:
  12502. sourceidx = input2idx;
  12503. return input2;
  12504. case 0:
  12505. return CRoxieServerActivityFactory::getInput(idx, sourceidx);
  12506. default:
  12507. return (unsigned) -1;
  12508. }
  12509. }
  12510. virtual unsigned numInputs() const { return 2; }
  12511. };
  12512. IRoxieServerActivityFactory *createRoxieServerCombineGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12513. {
  12514. return new CRoxieServerCombineGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12515. }
  12516. //=================================================================================
  12517. class CRoxieServerRollupGroupActivity : public CRoxieServerActivity
  12518. {
  12519. IHThorRollupGroupArg &helper;
  12520. bool eof;
  12521. public:
  12522. CRoxieServerRollupGroupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  12523. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  12524. helper((IHThorRollupGroupArg &)basehelper)
  12525. {
  12526. eof = false;
  12527. }
  12528. ~CRoxieServerRollupGroupActivity()
  12529. {
  12530. }
  12531. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12532. {
  12533. eof = false;
  12534. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  12535. }
  12536. virtual bool needsAllocator() const { return true; }
  12537. virtual const void * nextRow()
  12538. {
  12539. ActivityTimer t(totalCycles, timeActivities);
  12540. if (eof)
  12541. return NULL;
  12542. loop
  12543. {
  12544. ConstPointerArray group;
  12545. loop
  12546. {
  12547. const void * in = inputStream->nextRow();
  12548. if (!in)
  12549. break;
  12550. group.append(in);
  12551. }
  12552. if (group.ordinality() == 0)
  12553. {
  12554. eof = true;
  12555. return NULL;
  12556. }
  12557. try
  12558. {
  12559. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12560. size32_t outSize = helper.transform(rowBuilder, group.ordinality(), (const void * *)group.getArray());
  12561. ReleaseRoxieRows(group);
  12562. if (outSize)
  12563. {
  12564. processed++;
  12565. return rowBuilder.finalizeRowClear(outSize);
  12566. }
  12567. }
  12568. catch (IException * E)
  12569. {
  12570. ReleaseRoxieRows(group);
  12571. throw makeWrappedException(E);
  12572. }
  12573. }
  12574. }
  12575. };
  12576. class CRoxieServerRollupGroupActivityFactory : public CRoxieServerActivityFactory
  12577. {
  12578. public:
  12579. CRoxieServerRollupGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12580. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12581. {
  12582. }
  12583. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12584. {
  12585. return new CRoxieServerRollupGroupActivity(_ctx, this, _probeManager);
  12586. }
  12587. };
  12588. IRoxieServerActivityFactory *createRoxieServerRollupGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12589. {
  12590. return new CRoxieServerRollupGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12591. }
  12592. //=================================================================================
  12593. class CRoxieServerFilterProjectActivity : public CRoxieServerLateStartActivity
  12594. {
  12595. IHThorFilterProjectArg &helper;
  12596. unsigned numProcessedLastGroup;
  12597. unsigned __int64 recordCount;
  12598. public:
  12599. CRoxieServerFilterProjectActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  12600. : CRoxieServerLateStartActivity(_ctx, _factory, _probeManager), helper((IHThorFilterProjectArg &)basehelper)
  12601. {
  12602. numProcessedLastGroup = 0;
  12603. recordCount = 0;
  12604. }
  12605. ~CRoxieServerFilterProjectActivity()
  12606. {
  12607. }
  12608. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12609. {
  12610. numProcessedLastGroup = 0;
  12611. recordCount = 0;
  12612. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  12613. lateStart(parentExtractSize, parentExtract, helper.canMatchAny()); //sets eof
  12614. }
  12615. virtual bool needsAllocator() const { return true; }
  12616. virtual const void * nextRow()
  12617. {
  12618. ActivityTimer t(totalCycles, timeActivities);
  12619. if (eof)
  12620. return NULL;
  12621. loop
  12622. {
  12623. const void * in = inputStream->nextRow();
  12624. if (!in)
  12625. {
  12626. recordCount = 0;
  12627. if (numProcessedLastGroup == processed)
  12628. in = inputStream->nextRow();
  12629. if (!in)
  12630. {
  12631. numProcessedLastGroup = processed;
  12632. return NULL;
  12633. }
  12634. }
  12635. try
  12636. {
  12637. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12638. size32_t outSize = helper.transform(rowBuilder, in, ++recordCount);
  12639. ReleaseRoxieRow(in);
  12640. if (outSize)
  12641. {
  12642. processed++;
  12643. return rowBuilder.finalizeRowClear(outSize);
  12644. }
  12645. }
  12646. catch (IException *E)
  12647. {
  12648. throw makeWrappedException(E);
  12649. }
  12650. }
  12651. }
  12652. };
  12653. class CRoxieServerFilterProjectActivityFactory : public CRoxieServerActivityFactory
  12654. {
  12655. public:
  12656. CRoxieServerFilterProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12657. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12658. {
  12659. //MORE: Code generator needs to indicate if the count is used.
  12660. //optStableInput = false;
  12661. }
  12662. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12663. {
  12664. return new CRoxieServerFilterProjectActivity(_ctx, this, _probeManager);
  12665. }
  12666. };
  12667. IRoxieServerActivityFactory *createRoxieServerFilterProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12668. {
  12669. return new CRoxieServerFilterProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12670. }
  12671. //=====================================================
  12672. class CRoxieServerStrandedProjectActivity : public CRoxieServerStrandedActivity
  12673. {
  12674. class ProjectProcessor : public StrandProcessor
  12675. {
  12676. protected:
  12677. IHThorProjectArg &helper;
  12678. public:
  12679. ProjectProcessor(CRoxieServerActivity &_parent, IEngineRowStream *_inputStream, IHThorProjectArg &_helper)
  12680. : StrandProcessor(_parent, _inputStream, true), helper(_helper)
  12681. {
  12682. }
  12683. virtual const void * nextRow()
  12684. {
  12685. ActivityTimer t(totalCycles, timeActivities);
  12686. loop
  12687. {
  12688. OwnedConstRoxieRow in = inputStream->nextRow();
  12689. if (!in)
  12690. {
  12691. if (numProcessedLastGroup == processed)
  12692. in.setown(inputStream->nextRow());
  12693. if (!in)
  12694. {
  12695. numProcessedLastGroup = processed;
  12696. return NULL;
  12697. }
  12698. }
  12699. try
  12700. {
  12701. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12702. size32_t outSize;
  12703. outSize = helper.transform(rowBuilder, in);
  12704. if (outSize)
  12705. {
  12706. processed++;
  12707. return rowBuilder.finalizeRowClear(outSize);
  12708. }
  12709. }
  12710. catch (IException *E)
  12711. {
  12712. throw parent.makeWrappedException(E);
  12713. }
  12714. }
  12715. }
  12716. };
  12717. public:
  12718. CRoxieServerStrandedProjectActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const StrandOptions &_strandOptions)
  12719. : CRoxieServerStrandedActivity(_ctx, _factory, _probeManager, _strandOptions)
  12720. {
  12721. }
  12722. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12723. {
  12724. CRoxieServerStrandedActivity::start(parentExtractSize, parentExtract, paused);
  12725. onStartStrands();
  12726. }
  12727. virtual StrandProcessor *createStrandProcessor(IEngineRowStream *instream)
  12728. {
  12729. return new ProjectProcessor(*this, instream, (IHThorProjectArg &) basehelper);
  12730. }
  12731. virtual StrandProcessor *createStrandSourceProcessor(bool inputOrdered) { throwUnexpected(); }
  12732. };
  12733. class CRoxieServerProjectActivity : public CRoxieServerActivity
  12734. {
  12735. unsigned numProcessedLastGroup;
  12736. unsigned __int64 recordCount;
  12737. bool count;
  12738. public:
  12739. CRoxieServerProjectActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _count)
  12740. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  12741. count(_count)
  12742. {
  12743. numProcessedLastGroup = 0;
  12744. recordCount = 0;
  12745. }
  12746. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12747. {
  12748. numProcessedLastGroup = 0;
  12749. recordCount = 0;
  12750. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  12751. }
  12752. virtual bool needsAllocator() const { return true; }
  12753. virtual const void * nextRow()
  12754. {
  12755. ActivityTimer t(totalCycles, timeActivities);
  12756. loop
  12757. {
  12758. OwnedConstRoxieRow in = inputStream->nextRow();
  12759. if (!in)
  12760. {
  12761. recordCount = 0;
  12762. if (numProcessedLastGroup == processed)
  12763. in.setown(inputStream->nextRow());
  12764. if (!in)
  12765. {
  12766. numProcessedLastGroup = processed;
  12767. return NULL;
  12768. }
  12769. }
  12770. try
  12771. {
  12772. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12773. size32_t outSize;
  12774. if (count)
  12775. outSize = ((IHThorCountProjectArg &) basehelper).transform(rowBuilder, in, ++recordCount);
  12776. else
  12777. outSize = ((IHThorProjectArg &) basehelper).transform(rowBuilder, in);
  12778. if (outSize)
  12779. {
  12780. processed++;
  12781. return rowBuilder.finalizeRowClear(outSize);
  12782. }
  12783. }
  12784. catch (IException *E)
  12785. {
  12786. throw makeWrappedException(E);
  12787. }
  12788. }
  12789. }
  12790. };
  12791. class CRoxieServerProjectActivityFactory : public CRoxieServerActivityFactory
  12792. {
  12793. protected:
  12794. StrandOptions strandOptions;
  12795. bool count;
  12796. public:
  12797. CRoxieServerProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12798. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), strandOptions(_graphNode)
  12799. {
  12800. count = (kind==TAKcountproject || kind==TAKprefetchcountproject);
  12801. optStableInput = count;
  12802. }
  12803. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12804. {
  12805. // 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.
  12806. if (kind == TAKproject) // Not supported on prefetch or count projects
  12807. return new CRoxieServerStrandedProjectActivity(_ctx, this, _probeManager, strandOptions);
  12808. else
  12809. return new CRoxieServerProjectActivity(_ctx, this, _probeManager, count);
  12810. }
  12811. };
  12812. IRoxieServerActivityFactory *createRoxieServerProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12813. {
  12814. return new CRoxieServerProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12815. }
  12816. //=================================================================================
  12817. class CRoxieServerPrefetchProjectActivity : public CRoxieServerActivity, implements IRecordPullerCallback
  12818. {
  12819. unsigned numProcessedLastGroup;
  12820. bool count;
  12821. bool eof;
  12822. bool allPulled;
  12823. bool isThreaded;
  12824. unsigned preload;
  12825. unsigned __int64 recordCount;
  12826. IHThorPrefetchProjectArg &helper;
  12827. RecordPullerThread puller;
  12828. InterruptableSemaphore ready;
  12829. InterruptableSemaphore space;
  12830. class PrefetchInfo : public CInterface
  12831. {
  12832. public:
  12833. inline PrefetchInfo(IHThorPrefetchProjectArg &helper, const void *_in, unsigned __int64 _recordCount)
  12834. {
  12835. if (helper.preTransform(extract, _in, _recordCount))
  12836. {
  12837. in.setown(_in);
  12838. recordCount = _recordCount;
  12839. }
  12840. else
  12841. {
  12842. ReleaseRoxieRow(_in);
  12843. recordCount = 0;
  12844. }
  12845. }
  12846. OwnedConstRoxieRow in;
  12847. unsigned __int64 recordCount;
  12848. rtlRowBuilder extract;
  12849. };
  12850. QueueOf<PrefetchInfo, true> pulled;
  12851. CriticalSection pulledCrit;
  12852. public:
  12853. CRoxieServerPrefetchProjectActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _count)
  12854. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  12855. helper((IHThorPrefetchProjectArg &) basehelper),
  12856. puller(false),
  12857. count(_count)
  12858. {
  12859. numProcessedLastGroup = 0;
  12860. recordCount = 0;
  12861. eof = false;
  12862. allPulled = false;
  12863. isThreaded = (helper.getFlags() & PPFparallel) != 0;
  12864. preload = 0;
  12865. }
  12866. ~CRoxieServerPrefetchProjectActivity()
  12867. {
  12868. while (pulled.ordinality())
  12869. ::Release(pulled.dequeue());
  12870. }
  12871. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  12872. {
  12873. if (idx)
  12874. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  12875. puller.setInput(this, _sourceIdx, _in);
  12876. }
  12877. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  12878. {
  12879. puller.connectInputStreams(ctx, consumerOrdered);
  12880. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
  12881. }
  12882. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  12883. {
  12884. if (idx==0)
  12885. return puller.queryInput();
  12886. else
  12887. return NULL;
  12888. }
  12889. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12890. {
  12891. numProcessedLastGroup = 0;
  12892. recordCount = 0;
  12893. eof = false;
  12894. allPulled = false;
  12895. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  12896. preload = helper.getLookahead();
  12897. if (!preload)
  12898. preload = ctx->queryOptions().prefetchProjectPreload;
  12899. space.reinit(preload);
  12900. ready.reinit();
  12901. puller.start(parentExtractSize, parentExtract, paused, preload, !isThreaded, ctx);
  12902. }
  12903. virtual void stop()
  12904. {
  12905. space.interrupt();
  12906. ready.interrupt();
  12907. CRoxieServerActivity::stop();
  12908. puller.stop();
  12909. }
  12910. virtual void reset()
  12911. {
  12912. CRoxieServerActivity::reset();
  12913. puller.reset();
  12914. allPulled = false;
  12915. while (pulled.ordinality())
  12916. ::Release(pulled.dequeue());
  12917. }
  12918. virtual PrefetchInfo *readNextRecord()
  12919. {
  12920. if (!isThreaded)
  12921. {
  12922. if (!allPulled) // This looks like it's thread unsafe but we are inside the if(!isThreaded) so should be ok
  12923. puller.pullRecords(1);
  12924. }
  12925. else
  12926. ready.wait();
  12927. CriticalBlock b(pulledCrit);
  12928. PrefetchInfo *ret = pulled.ordinality() ? pulled.dequeue() : NULL;
  12929. space.signal();
  12930. return ret;
  12931. }
  12932. virtual bool needsAllocator() const { return true; }
  12933. virtual const void * nextRow()
  12934. {
  12935. ActivityTimer t(totalCycles, timeActivities);
  12936. if (eof)
  12937. return NULL;
  12938. loop
  12939. {
  12940. Owned<PrefetchInfo> in = readNextRecord();
  12941. if (!in)
  12942. {
  12943. recordCount = 0;
  12944. if (numProcessedLastGroup == processed)
  12945. in.setown(readNextRecord());
  12946. if (!in)
  12947. {
  12948. numProcessedLastGroup = processed;
  12949. eof = true;
  12950. return NULL;
  12951. }
  12952. }
  12953. try
  12954. {
  12955. if (in->in)
  12956. {
  12957. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12958. size32_t outSize;
  12959. IThorChildGraph *child = helper.queryChild();
  12960. Owned<IEclGraphResults> results;
  12961. if (child)
  12962. results.setown(child->evaluate(in->extract.size(), in->extract.getbytes()));
  12963. outSize = helper.transform(rowBuilder, in->in, results, in->recordCount);
  12964. if (outSize)
  12965. {
  12966. processed++;
  12967. return rowBuilder.finalizeRowClear(outSize);
  12968. }
  12969. }
  12970. }
  12971. catch (IException *E)
  12972. {
  12973. throw makeWrappedException(E);
  12974. }
  12975. }
  12976. }
  12977. // interface IExceptionHandler
  12978. virtual bool fireException(IException *e)
  12979. {
  12980. // called from puller thread on failure
  12981. ready.interrupt(LINK(e));
  12982. space.interrupt(e);
  12983. return true;
  12984. }
  12985. // interface IRecordPullerCallback
  12986. virtual void processRow(const void *row)
  12987. {
  12988. {
  12989. CriticalBlock b(pulledCrit);
  12990. pulled.enqueue(new PrefetchInfo(helper, row, ++recordCount));
  12991. }
  12992. if (isThreaded)
  12993. {
  12994. ready.signal();
  12995. space.wait();
  12996. }
  12997. }
  12998. virtual void processEOG()
  12999. {
  13000. {
  13001. CriticalBlock b(pulledCrit);
  13002. pulled.enqueue(NULL);
  13003. }
  13004. if (isThreaded)
  13005. {
  13006. ready.signal();
  13007. space.wait();
  13008. }
  13009. }
  13010. virtual void processGroup(const ConstPointerArray &rows)
  13011. {
  13012. throwUnexpected();
  13013. }
  13014. virtual void processDone()
  13015. {
  13016. CriticalBlock b(pulledCrit);
  13017. allPulled = true;
  13018. if (isThreaded)
  13019. ready.signal();
  13020. }
  13021. };
  13022. class CRoxieServerPrefetchProjectActivityFactory : public CRoxieServerProjectActivityFactory
  13023. {
  13024. public:
  13025. CRoxieServerPrefetchProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  13026. : CRoxieServerProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  13027. {
  13028. }
  13029. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  13030. {
  13031. return new CRoxieServerPrefetchProjectActivity(_ctx, this, _probeManager, count);
  13032. }
  13033. };
  13034. extern IRoxieServerActivityFactory *createRoxieServerPrefetchProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  13035. {
  13036. return new CRoxieServerPrefetchProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  13037. }
  13038. //=================================================================================
  13039. class CPointerArrayRoxieInput : public CPseudoRoxieInput
  13040. {
  13041. public:
  13042. CPointerArrayRoxieInput()
  13043. {
  13044. rowset = NULL;
  13045. rowcount = 0;
  13046. curRow = 0;
  13047. }
  13048. void init(size32_t _rowcount, byte **_rowset)
  13049. {
  13050. rowset = _rowset;
  13051. rowcount = _rowcount;
  13052. curRow = 0;
  13053. }
  13054. virtual const void * nextRow()
  13055. {
  13056. if (curRow < rowcount)
  13057. {
  13058. const void * ret = rowset[curRow];
  13059. if (ret)
  13060. LinkRoxieRow(ret);
  13061. curRow++;
  13062. return ret;
  13063. }
  13064. return NULL;
  13065. }
  13066. protected:
  13067. byte **rowset;
  13068. size32_t rowcount;
  13069. size32_t curRow;
  13070. };
  13071. class CRoxieServerLoopActivity : public CRoxieServerActivity
  13072. {
  13073. protected:
  13074. IHThorLoopArg &helper;
  13075. ThorActivityKind activityKind;
  13076. unsigned maxIterations;
  13077. bool finishedLooping;
  13078. unsigned flags;
  13079. bool eof;
  13080. rtlRowBuilder loopExtractBuilder;
  13081. unsigned loopGraphId;
  13082. Linked<IOutputMetaData> counterMeta;
  13083. public:
  13084. CRoxieServerLoopActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _loopGraphId, IOutputMetaData * _counterMeta)
  13085. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  13086. helper((IHThorLoopArg &)basehelper), loopGraphId(_loopGraphId), counterMeta(_counterMeta)
  13087. {
  13088. eof = false;
  13089. finishedLooping = false;
  13090. activityKind = factory->getKind();
  13091. flags = helper.getFlags();
  13092. maxIterations = 0;
  13093. }
  13094. virtual bool needsAllocator() const { return true; }
  13095. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13096. {
  13097. eof = false;
  13098. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  13099. int iterations = (int) helper.numIterations();
  13100. maxIterations = (iterations >= 0) ? iterations : 0;
  13101. finishedLooping = ((activityKind == TAKloopcount) && (maxIterations == 0));
  13102. if ((flags & IHThorLoopArg::LFnewloopagain) && !helper.loopFirstTime())
  13103. finishedLooping = true;
  13104. loopExtractBuilder.clear();
  13105. helper.createParentExtract(loopExtractBuilder); // could possibly delay this until execution actually happens
  13106. }
  13107. virtual void stop()
  13108. {
  13109. CRoxieServerActivity::stop();
  13110. loopExtractBuilder.clear();
  13111. }
  13112. void createCounterResult(IRoxieServerChildGraph * graph, unsigned counter)
  13113. {
  13114. if (flags & IHThorLoopArg::LFcounter)
  13115. {
  13116. void * counterRow = ctx->queryRowManager().allocate(sizeof(thor_loop_counter_t), activityId);
  13117. *((thor_loop_counter_t *)counterRow) = counter;
  13118. RtlLinkedDatasetBuilder builder(rowAllocator);
  13119. builder.appendOwn(counterRow);
  13120. Owned<CGraphResult> counterResult = new CGraphResult(builder.getcount(), builder.linkrows());
  13121. graph->setInputResult(2, counterResult);
  13122. }
  13123. }
  13124. };
  13125. //=================================================================================
  13126. class CRoxieServerSequentialLoopActivity : public CRoxieServerLoopActivity
  13127. {
  13128. Owned<IActivityGraph> loopQuery;
  13129. Owned<IRoxieServerChildGraph> loopGraph;
  13130. IEngineRowStream * curStream;
  13131. RtlLinkedDatasetBuilder *loopInputBuilder;
  13132. CPointerArrayRoxieInput arrayInput;
  13133. Linked<IEngineRowStream> resultStream;
  13134. unsigned loopCounter;
  13135. public:
  13136. CRoxieServerSequentialLoopActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _loopGraphId, IOutputMetaData * _counterMeta)
  13137. : CRoxieServerLoopActivity(_ctx, _factory, _probeManager, _loopGraphId, _counterMeta)
  13138. {
  13139. curStream = NULL;
  13140. loopCounter = 0;
  13141. loopInputBuilder = NULL;
  13142. }
  13143. virtual bool needsAllocator() const { return true; }
  13144. virtual void onCreate(IHThorArg *_colocalParent)
  13145. {
  13146. CRoxieServerLoopActivity::onCreate(_colocalParent);
  13147. loopQuery.set(ctx->queryChildGraph(loopGraphId));
  13148. }
  13149. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13150. {
  13151. curStream = inputStream;
  13152. loopCounter = 1;
  13153. CRoxieServerLoopActivity::start(parentExtractSize, parentExtract, paused);
  13154. //MORE: Not sure about this, should IRoxieServerChildGraph be combined with IActivityGraph?
  13155. loopGraph.set(loopQuery->queryLoopGraph());
  13156. loopInputBuilder = new RtlLinkedDatasetBuilder(rowAllocator);
  13157. }
  13158. virtual void stop()
  13159. {
  13160. delete loopInputBuilder;
  13161. loopInputBuilder = NULL;
  13162. CRoxieServerLoopActivity::stop();
  13163. }
  13164. virtual const void * nextRow()
  13165. {
  13166. ActivityTimer t(totalCycles, timeActivities);
  13167. if (eof)
  13168. return NULL;
  13169. unsigned emptyIterations = 0;
  13170. loop
  13171. {
  13172. loop
  13173. {
  13174. const void * ret = curStream->nextRow();
  13175. if (!ret)
  13176. {
  13177. ret = curStream->nextRow(); // more cope with groups somehow....
  13178. if (!ret)
  13179. {
  13180. if (finishedLooping)
  13181. {
  13182. eof = true;
  13183. return NULL;
  13184. }
  13185. break;
  13186. }
  13187. }
  13188. if (finishedLooping ||
  13189. ((flags & IHThorLoopArg::LFfiltered) && !helper.sendToLoop(loopCounter, ret)))
  13190. {
  13191. processed++;
  13192. return ret;
  13193. }
  13194. loopInputBuilder->appendOwn(ret);
  13195. }
  13196. switch (activityKind)
  13197. {
  13198. case TAKloopdataset:
  13199. {
  13200. if (!(flags & IHThorLoopArg::LFnewloopagain))
  13201. {
  13202. if (!helper.loopAgain(loopCounter, loopInputBuilder->getcount(), (const void**) loopInputBuilder->queryrows()))
  13203. {
  13204. if (loopInputBuilder->getcount() == 0)
  13205. {
  13206. eof = true;
  13207. return NULL;
  13208. }
  13209. arrayInput.init(loopInputBuilder->getcount(), loopInputBuilder->linkrows());
  13210. // MORE - should builder be cleared here?
  13211. curStream = &arrayInput;
  13212. finishedLooping = true;
  13213. continue; // back to the input loop again
  13214. }
  13215. }
  13216. break;
  13217. }
  13218. case TAKlooprow:
  13219. if (!loopInputBuilder->getcount())
  13220. {
  13221. finishedLooping = true;
  13222. eof = true;
  13223. return NULL;
  13224. }
  13225. break;
  13226. }
  13227. if (loopInputBuilder->getcount())
  13228. emptyIterations = 0;
  13229. else
  13230. {
  13231. //note: any outputs which didn't go around the loop again, would return the record, reinitializing emptyIterations
  13232. emptyIterations++;
  13233. if (emptyIterations > maxEmptyLoopIterations)
  13234. throw MakeStringException(ROXIE_TOO_MANY_EMPTY_LOOP, "Executed LOOP with empty input and output %u times", emptyIterations);
  13235. if (emptyIterations % 32 == 0)
  13236. CTXLOG("Executing LOOP with empty input and output %u times", emptyIterations);
  13237. }
  13238. checkAbort();
  13239. try
  13240. {
  13241. Owned<IRoxieGraphResults> results = executeIteration(loopExtractBuilder.size(), loopExtractBuilder.getbytes(), loopCounter);
  13242. resultStream.setown(results->createIterator(0));
  13243. if (flags & IHThorLoopArg::LFnewloopagain)
  13244. {
  13245. Owned<IEngineRowStream> againResult = results->createIterator(helper.loopAgainResult());
  13246. OwnedConstRoxieRow row = againResult->nextRow();
  13247. assertex(row);
  13248. //Result is a row which contains a single boolean field.
  13249. if (!((const bool *)row.get())[0])
  13250. finishedLooping = true;
  13251. }
  13252. }
  13253. catch (IException *E)
  13254. {
  13255. throw makeWrappedException(E);
  13256. }
  13257. curStream = resultStream.get();
  13258. loopCounter++;
  13259. if ((activityKind == TAKloopcount) && (loopCounter > maxIterations))
  13260. finishedLooping = true;
  13261. }
  13262. }
  13263. IRoxieGraphResults * executeIteration(unsigned parentExtractSize, const byte *parentExtract, unsigned counter)
  13264. {
  13265. try
  13266. {
  13267. loopGraph->beforeExecute();
  13268. Owned<IGraphResult> inputRowsResult = new CGraphResult(loopInputBuilder->getcount(), loopInputBuilder->linkrows());
  13269. loopInputBuilder->clear();
  13270. loopGraph->setInputResult(1, inputRowsResult);
  13271. createCounterResult(loopGraph, counter);
  13272. Owned<IRoxieGraphResults> ret = loopGraph->execute(parentExtractSize, parentExtract);
  13273. loopGraph->afterExecute();
  13274. return ret.getClear();
  13275. }
  13276. catch (...)
  13277. {
  13278. CTXLOG("Exception thrown in loop body - cleaning up");
  13279. loopGraph->afterExecute();
  13280. throw;
  13281. }
  13282. }
  13283. };
  13284. //=================================================================================
  13285. typedef SafeQueueOf<const void, true> SafeRowQueue;
  13286. class CRowQueuePseudoInput : public CPseudoRoxieInput
  13287. {
  13288. public:
  13289. CRowQueuePseudoInput(SafeRowQueue & _input, IOutputMetaData * _meta)
  13290. : meta(_meta), input(_input)
  13291. {
  13292. eof = false;
  13293. }
  13294. virtual const void * nextRow()
  13295. {
  13296. if (eof)
  13297. return NULL;
  13298. const void * ret = input.dequeue();
  13299. if (!ret)
  13300. eof = true;
  13301. return ret;
  13302. }
  13303. virtual IOutputMetaData * queryOutputMeta() const { return meta; }
  13304. protected:
  13305. SafeRowQueue & input;
  13306. IOutputMetaData * meta;
  13307. bool eof;
  13308. };
  13309. class CRoxieServerParallelLoopActivity;
  13310. class LoopFilterPseudoInput : public CIndirectRoxieInput
  13311. {
  13312. public:
  13313. LoopFilterPseudoInput(CRoxieServerParallelLoopActivity * _activity, unsigned _counter) :
  13314. activity(_activity), counter(_counter)
  13315. {
  13316. }
  13317. virtual const void * nextRow();
  13318. protected:
  13319. CRoxieServerParallelLoopActivity * activity;
  13320. unsigned counter;
  13321. };
  13322. class LoopExecutorThread : public RestartableThread
  13323. {
  13324. protected:
  13325. Owned<CSafeRoxieInput> safeInput;
  13326. CRoxieServerParallelLoopActivity * activity;
  13327. bool eof;
  13328. CriticalSection crit;
  13329. unsigned flags;
  13330. SafeRowQueue tempResults[2];
  13331. unsigned savedParentExtractSize;
  13332. const byte * savedParentExtract;
  13333. IArrayOf<IActivityGraph> cachedGraphs;
  13334. IRoxieSlaveContext *ctx;
  13335. public:
  13336. LoopExecutorThread()
  13337. : RestartableThread("LoopExecutorThread")
  13338. {
  13339. activity = NULL;
  13340. eof = false;
  13341. flags = 0;
  13342. ctx = NULL;
  13343. savedParentExtract = NULL;
  13344. savedParentExtractSize = 0;
  13345. }
  13346. void setInput(CRoxieServerParallelLoopActivity * _activity, unsigned _sourceIdx, IFinalRoxieInput *_input, unsigned _flags)
  13347. {
  13348. activity = _activity;
  13349. flags = _flags;
  13350. // 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.
  13351. safeInput.setown(new CSafeRoxieInput(_sourceIdx, _input));
  13352. }
  13353. void connectInputStreams(bool consumerOrdered)
  13354. {
  13355. safeInput->connectInputStreams(ctx, consumerOrdered);
  13356. }
  13357. IFinalRoxieInput *queryInput() const
  13358. {
  13359. return safeInput;
  13360. }
  13361. void onCreate(IRoxieSlaveContext * _ctx);
  13362. void start(unsigned parentExtractSize, const byte *parentExtract, bool paused);
  13363. void stop();
  13364. void reset();
  13365. virtual int run();
  13366. protected:
  13367. void executeLoop();
  13368. void executeLoopInstance(unsigned counter, unsigned numIterations, unsigned inputIdx, IFinalRoxieInput * input, SafeRowQueue * spillOutput);
  13369. IFinalRoxieInput * createLoopIterationGraph(unsigned i, unsigned inputIdx, IFinalRoxieInput * input, unsigned counter);
  13370. };
  13371. class CRoxieServerParallelLoopActivity : public CRoxieServerLoopActivity
  13372. {
  13373. friend class LoopFilterPseudoInput;
  13374. friend class LoopExecutorThread;
  13375. QueueOf<const void, true> ready;
  13376. CriticalSection helperCS;
  13377. CriticalSection cs;
  13378. unsigned defaultNumParallel;
  13379. LoopExecutorThread executor;
  13380. IProbeManager* probeManager;
  13381. CriticalSection canAccess;
  13382. CriticalSection scrit;
  13383. InterruptableSemaphore readySpace;
  13384. InterruptableSemaphore recordsReady;
  13385. protected:
  13386. bool includeInLoop(unsigned counter, const void * row)
  13387. {
  13388. CriticalBlock b(helperCS);
  13389. return helper.sendToLoop(counter, row);
  13390. }
  13391. public:
  13392. CRoxieServerParallelLoopActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _loopGraphId, IOutputMetaData * _counterMeta)
  13393. : CRoxieServerLoopActivity(_ctx, _factory, _probeManager, _loopGraphId, _counterMeta),
  13394. readySpace(parallelLoopFlowLimit)
  13395. {
  13396. probeManager = _probeManager;
  13397. defaultNumParallel = 0;
  13398. }
  13399. virtual void onCreate(IHThorArg *_colocalParent)
  13400. {
  13401. CRoxieServerActivity::onCreate(_colocalParent);
  13402. executor.onCreate(ctx);
  13403. }
  13404. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13405. {
  13406. CriticalBlock b(scrit); // can stop while still starting, if unlucky...
  13407. readySpace.reinit(parallelLoopFlowLimit);
  13408. recordsReady.reinit();
  13409. CRoxieServerLoopActivity::start(parentExtractSize, parentExtract, paused);
  13410. defaultNumParallel = helper.defaultParallelIterations();
  13411. if (!defaultNumParallel)
  13412. defaultNumParallel = DEFAULT_PARALLEL_LOOP_THREADS;
  13413. //MORE: If numIterations <= number of parallel iterations[1],
  13414. //then we don't need to create a separate thread to do the processing, and the results will also avoid
  13415. //being transferred via a queue
  13416. executor.start(parentExtractSize, parentExtract, paused);
  13417. }
  13418. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  13419. {
  13420. if (idx)
  13421. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  13422. executor.setInput(this, _sourceIdx, _in, flags);
  13423. }
  13424. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  13425. {
  13426. executor.connectInputStreams(consumerOrdered);
  13427. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, nullptr, consumerOrdered, nullptr);
  13428. }
  13429. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  13430. {
  13431. if (idx==0)
  13432. return executor.queryInput();
  13433. else
  13434. return NULL;
  13435. }
  13436. virtual void stop()
  13437. {
  13438. CriticalBlock b(scrit); // can stop while still starting, if unlucky...
  13439. readySpace.interrupt();
  13440. recordsReady.interrupt();
  13441. executor.join(); // MORE - may not be needed given stop/reset split
  13442. CRoxieServerLoopActivity::stop();
  13443. }
  13444. virtual void reset()
  13445. {
  13446. while (ready.ordinality())
  13447. ReleaseRoxieRow(ready.dequeue());
  13448. executor.reset();
  13449. CRoxieServerActivity::reset();
  13450. }
  13451. virtual const void * nextRow()
  13452. {
  13453. ActivityTimer t(totalCycles, timeActivities);
  13454. loop
  13455. {
  13456. if (eof)
  13457. return NULL;
  13458. recordsReady.wait();
  13459. CriticalBlock procedure(canAccess);
  13460. if (ready.ordinality())
  13461. {
  13462. const void *result = ready.dequeue();
  13463. readySpace.signal();
  13464. if (result)
  13465. processed++;
  13466. return result;
  13467. }
  13468. else
  13469. eof = true;
  13470. }
  13471. }
  13472. unsigned getNumParallel(unsigned iter)
  13473. {
  13474. return defaultNumParallel;
  13475. }
  13476. inline void enqueueResult(const void * row)
  13477. {
  13478. try
  13479. {
  13480. while(!readySpace.wait(1000))
  13481. {
  13482. CTXLOG("Blocked waiting for space in loop %p activity id: %d output queue: %d records in queue", this, queryId(), ready.ordinality());
  13483. }
  13484. }
  13485. catch (...)
  13486. {
  13487. ReleaseRoxieRow(row);
  13488. throw;
  13489. }
  13490. CriticalBlock b2(canAccess);
  13491. ready.enqueue(row);
  13492. recordsReady.signal();
  13493. }
  13494. inline void finishResults()
  13495. {
  13496. recordsReady.signal();
  13497. }
  13498. virtual bool fireException(IException *e)
  13499. {
  13500. readySpace.interrupt(LINK(e));
  13501. recordsReady.interrupt(e);
  13502. return true;
  13503. }
  13504. IActivityGraph * createChildGraphInstance()
  13505. {
  13506. return factory->createChildGraph(ctx, &helper, loopGraphId, this, probeManager, *this);
  13507. }
  13508. IActivityGraph * queryChildGraph()
  13509. {
  13510. return ctx->queryChildGraph(loopGraphId);
  13511. }
  13512. };
  13513. //=================================================================================
  13514. const void * LoopFilterPseudoInput::nextRow()
  13515. {
  13516. loop
  13517. {
  13518. const void * next = stream->nextRow();
  13519. if (!next || activity->includeInLoop(counter, next))
  13520. return next;
  13521. activity->enqueueResult(next);
  13522. }
  13523. }
  13524. void LoopExecutorThread::onCreate(IRoxieSlaveContext * _ctx)
  13525. {
  13526. //Initialise the cached graph list with the child instance that will always be created. Other iterations will be created on demand.
  13527. ctx = _ctx;
  13528. cachedGraphs.append(*LINK(activity->queryChildGraph()));
  13529. }
  13530. void LoopExecutorThread::start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13531. {
  13532. savedParentExtractSize = parentExtractSize;
  13533. savedParentExtract = parentExtract;
  13534. eof = false;
  13535. StringBuffer logPrefix("[");
  13536. ctx->getLogPrefix(logPrefix).append("] ");
  13537. RestartableThread::start(logPrefix);
  13538. }
  13539. int LoopExecutorThread::run()
  13540. {
  13541. try
  13542. {
  13543. executeLoop();
  13544. }
  13545. catch (IException *e)
  13546. {
  13547. activity->fireException(e);
  13548. }
  13549. catch (...)
  13550. {
  13551. activity->fireException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unexpected exception caught in LoopExecutorThread::run"));
  13552. }
  13553. return 0;
  13554. }
  13555. void LoopExecutorThread::stop()
  13556. {
  13557. safeInput->stop();
  13558. RestartableThread::join();
  13559. }
  13560. void LoopExecutorThread::reset()
  13561. {
  13562. safeInput->reset();
  13563. }
  13564. void LoopExecutorThread::executeLoop()
  13565. {
  13566. unsigned iterations = 0;
  13567. unsigned counter = 0;
  13568. unsigned outputIndex = 0;
  13569. //Note, activities don't link inputs, so need to be careful that special inputs remain linked while the activity is executing.
  13570. loop
  13571. {
  13572. if (activity->activityKind == TAKloopcount)
  13573. {
  13574. if (counter == activity->maxIterations)
  13575. break;
  13576. }
  13577. else
  13578. {
  13579. //This condition isn't quite right because it needs to be whether the filtered
  13580. //input is empty. May be ok if we include that in the semantics,
  13581. if (tempResults[1-outputIndex].ordinality() == 0)
  13582. break;
  13583. }
  13584. unsigned numParallel = activity->getNumParallel(iterations);
  13585. Linked<IFinalRoxieInput> curInput;
  13586. if (iterations == 0)
  13587. curInput.set(safeInput);
  13588. else
  13589. {
  13590. SafeRowQueue & inputQueue = tempResults[1-outputIndex];
  13591. inputQueue.enqueue(NULL);
  13592. curInput.setown(new CRowQueuePseudoInput(inputQueue, activity->queryOutputMeta()));
  13593. }
  13594. SafeRowQueue * curOutput = NULL;
  13595. if (counter+numParallel > activity->maxIterations)
  13596. numParallel = activity->maxIterations - counter;
  13597. else if (counter+numParallel < activity->maxIterations)
  13598. curOutput = &tempResults[outputIndex];
  13599. executeLoopInstance(counter, numParallel, 0, curInput, curOutput); // CurInput is always SOME sort of proxy so idx always 0
  13600. outputIndex = 1-outputIndex;
  13601. counter += numParallel;
  13602. iterations++;
  13603. }
  13604. //Check for TAKlooprow, where end of loop couldn't be determined ahead of time
  13605. SafeRowQueue & inputQueue = tempResults[1-outputIndex];
  13606. while (inputQueue.ordinality())
  13607. {
  13608. const void * next = inputQueue.dequeue();
  13609. activity->enqueueResult(next);
  13610. }
  13611. activity->finishResults();
  13612. }
  13613. void LoopExecutorThread::executeLoopInstance(unsigned counter, unsigned numIterations, unsigned inputIdx, IFinalRoxieInput * input, SafeRowQueue * spillOutput)
  13614. {
  13615. IArrayOf<IFinalRoxieInput> savedInputs; // activities don't link their inputs, so this list keeps filters alive.
  13616. Linked<IFinalRoxieInput> curInput = input;
  13617. unsigned i;
  13618. for (i= 0; i != numIterations; i++)
  13619. {
  13620. unsigned thisCounter = counter+i+1;
  13621. IFinalRoxieInput * filtered = curInput;
  13622. if (flags & IHThorLoopArg::LFfiltered)
  13623. {
  13624. LoopFilterPseudoInput *newFiltered = new LoopFilterPseudoInput(activity, thisCounter);
  13625. newFiltered->setInput(inputIdx, curInput);
  13626. filtered = newFiltered;
  13627. savedInputs.append(*filtered);
  13628. inputIdx = 0;
  13629. }
  13630. //graph is kept, so new curInput will be guaranteed to exist
  13631. curInput.setown(createLoopIterationGraph(i, inputIdx, filtered, thisCounter));
  13632. inputIdx = 0;
  13633. }
  13634. Owned<IStrandJunction> curJunction;
  13635. IEngineRowStream *curStream = connectSingleStream(ctx, curInput, inputIdx, curJunction, true);
  13636. try
  13637. {
  13638. curInput->start(savedParentExtractSize, savedParentExtract, false);
  13639. if (spillOutput)
  13640. {
  13641. loop
  13642. {
  13643. const void * next = curStream->nextRow();
  13644. if (!next)
  13645. break;
  13646. spillOutput->enqueue(next);
  13647. }
  13648. }
  13649. else
  13650. {
  13651. loop
  13652. {
  13653. const void * next = curStream->nextRow();
  13654. if (!next)
  13655. break;
  13656. activity->enqueueResult(next);
  13657. }
  13658. }
  13659. }
  13660. catch (IException *E)
  13661. {
  13662. ctx->notifyAbort(E);
  13663. for (i= 0; i != numIterations; i++)
  13664. {
  13665. cachedGraphs.item(i).queryLoopGraph()->afterExecute();
  13666. }
  13667. curStream->stop();
  13668. curInput->reset();
  13669. throw;
  13670. }
  13671. for (i= 0; i != numIterations; i++)
  13672. {
  13673. cachedGraphs.item(i).queryLoopGraph()->afterExecute();
  13674. }
  13675. curStream->stop();
  13676. curInput->reset();
  13677. }
  13678. IFinalRoxieInput * LoopExecutorThread::createLoopIterationGraph(unsigned i, unsigned inputIdx, IFinalRoxieInput * input, unsigned counter)
  13679. {
  13680. if (!cachedGraphs.isItem(i))
  13681. cachedGraphs.append(*activity->createChildGraphInstance());
  13682. Linked<IRoxieServerChildGraph> loopGraph = cachedGraphs.item(i).queryLoopGraph();
  13683. loopGraph->beforeExecute();
  13684. if (!loopGraph->querySetInputResult(1, inputIdx, input))
  13685. throwUnexpected(); // a loop which doesn't use the value from the previous iteration. Should probably handle even if daft.
  13686. activity->createCounterResult(loopGraph, counter);
  13687. return loopGraph->selectOutput(0);
  13688. }
  13689. //=================================================================================
  13690. class CCounterRowMetaData : implements IOutputMetaData, public CInterface
  13691. {
  13692. public:
  13693. IMPLEMENT_IINTERFACE
  13694. virtual size32_t getRecordSize(const void *) { return sizeof(thor_loop_counter_t); }
  13695. virtual size32_t getMinRecordSize() const { return sizeof(thor_loop_counter_t); }
  13696. virtual size32_t getFixedSize() const { return sizeof(thor_loop_counter_t); }
  13697. virtual void toXML(const byte * self, IXmlWriter & out) { }
  13698. virtual unsigned getVersion() const { return OUTPUTMETADATA_VERSION; }
  13699. virtual unsigned getMetaFlags() { return 0; }
  13700. virtual void destruct(byte * self) {}
  13701. virtual IOutputRowSerializer * createDiskSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  13702. virtual IOutputRowDeserializer * createDiskDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  13703. virtual ISourceRowPrefetcher * createDiskPrefetcher(ICodeContext * ctx, unsigned activityId) { return NULL; }
  13704. virtual IOutputMetaData * querySerializedDiskMeta() { return this; }
  13705. virtual IOutputRowSerializer * createInternalSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  13706. virtual IOutputRowDeserializer * createInternalDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  13707. virtual void walkIndirectMembers(const byte * self, IIndirectMemberVisitor & visitor) {}
  13708. virtual IOutputMetaData * queryChildMeta(unsigned i) { return NULL; }
  13709. };
  13710. class CRoxieServerLoopActivityFactory : public CRoxieServerActivityFactory
  13711. {
  13712. unsigned loopGraphId;
  13713. unsigned flags;
  13714. Linked<IOutputMetaData> counterMeta;
  13715. public:
  13716. CRoxieServerLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _loopGraphId)
  13717. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), loopGraphId(_loopGraphId)
  13718. {
  13719. Owned<IHThorLoopArg> helper = (IHThorLoopArg *) helperFactory();
  13720. flags = helper->getFlags();
  13721. counterMeta.setown(new CCounterRowMetaData);
  13722. }
  13723. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  13724. {
  13725. if (flags & IHThorLoopArg::LFparallel)
  13726. return new CRoxieServerParallelLoopActivity(_ctx, this, _probeManager, loopGraphId, counterMeta);
  13727. else
  13728. return new CRoxieServerSequentialLoopActivity(_ctx, this, _probeManager, loopGraphId, counterMeta);
  13729. }
  13730. };
  13731. IRoxieServerActivityFactory *createRoxieServerLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _loopGraphId)
  13732. {
  13733. return new CRoxieServerLoopActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _loopGraphId);
  13734. }
  13735. //=================================================================================
  13736. class CRoxieServerGraphLoopActivity : public CRoxieServerActivity
  13737. {
  13738. protected:
  13739. IHThorGraphLoopArg &helper;
  13740. unsigned maxIterations;
  13741. unsigned flags;
  13742. rtlRowBuilder GraphExtractBuilder;
  13743. unsigned loopGraphId;
  13744. Linked<IOutputMetaData> counterMeta;
  13745. public:
  13746. CRoxieServerGraphLoopActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _GraphGraphId, IOutputMetaData * _counterMeta)
  13747. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  13748. helper((IHThorGraphLoopArg &)basehelper), loopGraphId(_GraphGraphId), counterMeta(_counterMeta)
  13749. {
  13750. flags = helper.getFlags();
  13751. maxIterations = 0;
  13752. }
  13753. virtual bool needsAllocator() const { return true; }
  13754. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13755. {
  13756. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  13757. int iterations = (int) helper.numIterations();
  13758. maxIterations = (iterations >= 0) ? iterations : 0;
  13759. if (maxIterations > maxGraphLoopIterations)
  13760. throw MakeStringException(ROXIE_TOO_MANY_GRAPH_LOOP, "Attempt to execute graph %u times", maxIterations);
  13761. if (maxIterations != 0)
  13762. {
  13763. GraphExtractBuilder.clear();
  13764. helper.createParentExtract(GraphExtractBuilder);
  13765. }
  13766. }
  13767. virtual void stop()
  13768. {
  13769. CRoxieServerActivity::stop();
  13770. GraphExtractBuilder.clear();
  13771. }
  13772. void createCounterResult(IRoxieServerChildGraph * graph, unsigned counter)
  13773. {
  13774. if (flags & IHThorGraphLoopArg::GLFcounter)
  13775. {
  13776. void * counterRow = ctx->queryRowManager().allocate(sizeof(thor_loop_counter_t), activityId);
  13777. *((thor_loop_counter_t *)counterRow) = counter;
  13778. RtlLinkedDatasetBuilder builder(rowAllocator);
  13779. builder.appendOwn(counterRow);
  13780. Owned<CGraphResult> counterResult = new CGraphResult(builder.getcount(), builder.linkrows());
  13781. graph->setInputResult(0, counterResult);
  13782. }
  13783. }
  13784. };
  13785. //=================================================================================
  13786. class CRoxieServerSequentialGraphLoopActivity : public CRoxieServerGraphLoopActivity
  13787. {
  13788. Owned<IActivityGraph> GraphQuery;
  13789. Owned<IRoxieServerChildGraph> loopGraph;
  13790. Linked<IEngineRowStream> resultStream;
  13791. bool evaluated;
  13792. public:
  13793. CRoxieServerSequentialGraphLoopActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _GraphGraphId, IOutputMetaData * _counterMeta)
  13794. : CRoxieServerGraphLoopActivity(_ctx, _factory, _probeManager, _GraphGraphId, _counterMeta)
  13795. {
  13796. evaluated = false;
  13797. }
  13798. virtual void onCreate(IHThorArg *_colocalParent)
  13799. {
  13800. CRoxieServerGraphLoopActivity::onCreate(_colocalParent);
  13801. GraphQuery.set(ctx->queryChildGraph(loopGraphId));
  13802. }
  13803. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13804. {
  13805. CRoxieServerGraphLoopActivity::start(parentExtractSize, parentExtract, paused);
  13806. //MORE: Not sure about this, should IRoxieServerChildGraph be combined with IActivityGraph?
  13807. loopGraph.set(GraphQuery->queryLoopGraph());
  13808. evaluated = false;
  13809. }
  13810. virtual void stop()
  13811. {
  13812. if (loopGraph)
  13813. loopGraph->clearGraphLoopResults();
  13814. CRoxieServerGraphLoopActivity::stop();
  13815. }
  13816. virtual const void * nextRow()
  13817. {
  13818. ActivityTimer t(totalCycles, timeActivities);
  13819. if (!evaluated)
  13820. {
  13821. executeEntireGraph();
  13822. evaluated = true;
  13823. }
  13824. const void * ret = resultStream->nextRow();
  13825. if (ret)
  13826. processed++;
  13827. return ret;
  13828. }
  13829. void executeIteration(unsigned parentExtractSize, const byte *parentExtract, unsigned counter)
  13830. {
  13831. try
  13832. {
  13833. loopGraph->beforeExecute();
  13834. createCounterResult(loopGraph, counter);
  13835. loopGraph->executeGraphLoop(parentExtractSize, parentExtract);
  13836. loopGraph->afterExecute();
  13837. }
  13838. catch (...)
  13839. {
  13840. CTXLOG("Exception thrown in graph body - cleaning up");
  13841. loopGraph->afterExecute();
  13842. throw;
  13843. }
  13844. }
  13845. void createInitialGraphInput()
  13846. {
  13847. loopGraph->clearGraphLoopResults();
  13848. RtlLinkedDatasetBuilder builder(rowAllocator);
  13849. inputStream->readAll(builder);
  13850. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  13851. loopGraph->setGraphLoopResult(0, result);
  13852. }
  13853. void executeEntireGraph()
  13854. {
  13855. createInitialGraphInput();
  13856. for (unsigned loopCounter=1; loopCounter <= maxIterations; loopCounter++)
  13857. {
  13858. executeIteration(GraphExtractBuilder.size(), GraphExtractBuilder.getbytes(), loopCounter);
  13859. }
  13860. resultStream.setown(loopGraph->getGraphLoopResult(maxIterations));
  13861. }
  13862. };
  13863. //=================================================================================
  13864. struct GraphOutputSplitterArg : public ccdserver_hqlhelper::CThorSplitArg
  13865. {
  13866. public:
  13867. virtual unsigned numBranches()
  13868. {
  13869. return 0;
  13870. }
  13871. virtual IOutputMetaData * queryOutputMeta()
  13872. {
  13873. return NULL;// get it from the parent..
  13874. }
  13875. };
  13876. extern "C" IHThorArg * createGraphOutputSplitter() { return new GraphOutputSplitterArg; }
  13877. class CGraphIterationInfo : public CInterface
  13878. {
  13879. private:
  13880. Owned<IRoxieServerActivityFactory> factory; // Note - before sourceAct, so destroyed last
  13881. unsigned sourceIdx;
  13882. Linked<IRoxieServerActivity> sourceAct;
  13883. Linked<IFinalRoxieInput> sourceInput;
  13884. unsigned numUses;
  13885. unsigned iteration;
  13886. public:
  13887. CGraphIterationInfo(IRoxieServerActivity * _sourceAct, IFinalRoxieInput *_input, unsigned _sourceIdx, unsigned _iteration)
  13888. : sourceAct(_sourceAct), sourceInput(_input), sourceIdx(_sourceIdx), iteration(_iteration)
  13889. {
  13890. numUses = 0;
  13891. }
  13892. inline void noteUsed()
  13893. {
  13894. numUses++;
  13895. }
  13896. void createSplitter(IRoxieSlaveContext *ctx, IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes)
  13897. {
  13898. if (numUses > 1)
  13899. {
  13900. Owned<IPropertyTree> splitterNode = createPTree();
  13901. factory.setown(createRoxieServerThroughSpillActivityFactory(sourceAct->queryFactory()->queryQueryFactory(), createGraphOutputSplitter, numUses, *splitterNode));
  13902. IRoxieServerActivity *splitter = factory->createActivity(ctx, NULL);
  13903. splitter->onCreate(NULL);
  13904. IFinalRoxieInput *input = sourceAct->queryOutput(sourceIdx);
  13905. if (probeManager)
  13906. {
  13907. IRoxieProbe * inputProbe = probeManager->createProbe(static_cast<IInputBase*>(input), sourceAct, splitter, sourceIdx, 0, iteration);
  13908. probes.append(*LINK(inputProbe));
  13909. input = &dynamic_cast<IFinalRoxieInput &>(inputProbe->queryInput());
  13910. sourceIdx = 0;
  13911. }
  13912. sourceAct.setown(splitter);
  13913. sourceAct->setInput(0, sourceIdx, input);
  13914. sourceIdx = 0;
  13915. sourceInput.clear();
  13916. }
  13917. }
  13918. IFinalRoxieInput *connectOutput(IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes, IRoxieServerActivity *targetAct, unsigned targetIdx)
  13919. {
  13920. // MORE - not really necessary to create splitters in separate pass, is it?
  13921. if (factory) // we created a splitter....
  13922. sourceInput.set(sourceAct->queryOutput(sourceIdx));
  13923. IFinalRoxieInput *ret = sourceInput;
  13924. if (probeManager)
  13925. {
  13926. IRoxieProbe * inputProbe = probeManager->createProbe(sourceInput, sourceAct, targetAct, sourceIdx, targetIdx, iteration);
  13927. probes.append(*LINK(inputProbe));
  13928. ret = &dynamic_cast<IFinalRoxieInput &>(inputProbe->queryInput());
  13929. // MORE - do we need to connect the stream in the probe?
  13930. }
  13931. if (factory) // we created a splitter....
  13932. sourceIdx++;
  13933. return ret;
  13934. }
  13935. };
  13936. class CRoxieServerParallelGraphLoopActivity : public CRoxieServerGraphLoopActivity, implements IRoxieServerLoopResultProcessor
  13937. {
  13938. Owned<IActivityGraph> childGraph;
  13939. IFinalRoxieInput * resultInput;
  13940. IEngineRowStream * resultStream;
  13941. Owned<IStrandJunction> resultJunction;
  13942. CIArrayOf<CGraphIterationInfo> outputs;
  13943. IArrayOf<IRoxieServerChildGraph> iterationGraphs;
  13944. Owned<CExtractMapperInput> inputExtractMapper;
  13945. IProbeManager *probeManager;
  13946. unsigned createLoopCounter;
  13947. IArrayOf<IRoxieProbe> probes;
  13948. public:
  13949. CRoxieServerParallelGraphLoopActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _GraphGraphId, IOutputMetaData * _counterMeta)
  13950. : CRoxieServerGraphLoopActivity(_ctx, _factory, _probeManager, _GraphGraphId, _counterMeta), probeManager(_probeManager)
  13951. {
  13952. inputExtractMapper.setown(new CExtractMapperInput);
  13953. resultInput = NULL;
  13954. resultStream = NULL;
  13955. createLoopCounter = 0;
  13956. }
  13957. virtual void onCreate(IHThorArg *_colocalParent)
  13958. {
  13959. CRoxieServerGraphLoopActivity::onCreate(_colocalParent);
  13960. childGraph.set(ctx->queryChildGraph(loopGraphId));
  13961. }
  13962. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  13963. {
  13964. //Input needs to be handled very carefully.....
  13965. //We don't want to call onStart on the input unless it is actually used, so don't use the base CRoxieServerActivity implementation.
  13966. //This activity's input needs to be started with (parentExtractSize, parentExtract), but the elements in the graph need to be started with the
  13967. //GraphExtractBuilder parent extract. So we need to wrap the input in a pseudo-input (inputExtractMapper) that passes through a different
  13968. //parentExtract. Something very similar will be needed for query library calls with streaming inputs when they are implemented.
  13969. assertex(idx == 0);
  13970. inputExtractMapper->setInput(_sourceIdx, _in);
  13971. }
  13972. virtual void connectInputStreams(bool consumerOrdered)
  13973. {
  13974. //NB: inputExtractMapper is not connected at this point - only if/when it is used from within the graph
  13975. CRoxieServerActivity::connectInputStreams(consumerOrdered);
  13976. }
  13977. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  13978. {
  13979. if (idx==0)
  13980. return inputExtractMapper->queryInput();
  13981. else
  13982. return NULL;
  13983. }
  13984. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13985. {
  13986. CRoxieServerGraphLoopActivity::start(parentExtractSize, parentExtract, paused); // initialises GraphExtractBuilder
  13987. inputExtractMapper->setParentExtract(parentExtractSize, parentExtract);
  13988. createExpandedGraph(GraphExtractBuilder.size(), GraphExtractBuilder.getbytes(), probeManager);
  13989. resultInput->start(GraphExtractBuilder.size(), GraphExtractBuilder.getbytes(), paused);
  13990. startJunction(resultJunction);
  13991. }
  13992. virtual void stop()
  13993. {
  13994. if (resultStream)
  13995. resultStream->stop();
  13996. CRoxieServerGraphLoopActivity::stop();
  13997. }
  13998. virtual void reset()
  13999. {
  14000. if (resultInput)
  14001. resultInput->reset();
  14002. resetJunction(resultJunction);
  14003. resultInput = NULL;
  14004. resultStream = NULL;
  14005. resultJunction.clear();
  14006. outputs.kill();
  14007. iterationGraphs.kill(); // must be done after all activities killed
  14008. if (probeManager)
  14009. {
  14010. probeManager->deleteGraph(NULL, (IArrayOf<IInputBase>*)&probes);
  14011. probes.kill();
  14012. }
  14013. CRoxieServerGraphLoopActivity::reset();
  14014. }
  14015. virtual const void * nextRow()
  14016. {
  14017. ActivityTimer t(totalCycles, timeActivities);
  14018. const void * ret = resultStream->nextRow();
  14019. if (ret)
  14020. processed++;
  14021. return ret;
  14022. }
  14023. void createExpandedGraph(unsigned parentExtractSize, const byte *parentExtract, IProbeManager *probeManager)
  14024. {
  14025. //result(0) is the input to the graph.
  14026. resultInput = inputExtractMapper;
  14027. outputs.append(* new CGraphIterationInfo(resultInput->queryActivity(), resultInput, 0, 1));
  14028. for (createLoopCounter=1; createLoopCounter <= maxIterations; createLoopCounter++)
  14029. {
  14030. IRoxieServerChildGraph * graph = childGraph->createGraphLoopInstance(ctx, createLoopCounter, parentExtractSize, parentExtract, *this);
  14031. graph->beforeExecute();
  14032. iterationGraphs.append(*graph);
  14033. graph->gatherIterationUsage(*this);
  14034. CGraphIterationInfo *iteration = graph->selectGraphLoopOutput();
  14035. outputs.append(*iteration);
  14036. }
  14037. createLoopCounter = 0;
  14038. createSplitters(probeManager, probes);
  14039. ForEachItemIn(i2, iterationGraphs)
  14040. iterationGraphs.item(i2).associateIterationOutputs(*this);
  14041. resultInput = outputs.tos().connectOutput(probeManager, probes, this, 0);
  14042. resultStream = connectSingleStream(ctx, resultInput, 0, resultJunction, true);
  14043. }
  14044. void createSplitters(IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes)
  14045. {
  14046. ForEachItemIn(i, outputs)
  14047. {
  14048. CGraphIterationInfo & next = outputs.item(i);
  14049. next.createSplitter(ctx, probeManager, probes);
  14050. }
  14051. }
  14052. //IRoxieServerLoopResultProcessor
  14053. virtual void noteUseIteration(unsigned _whichIteration)
  14054. {
  14055. int whichIteration = (int) _whichIteration; // May go negative - API is unsigned for historical reasons
  14056. if (whichIteration >= 0)
  14057. {
  14058. if (!outputs.isItem(whichIteration))
  14059. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Error reading graph result %d from iteration %d", whichIteration, createLoopCounter);
  14060. outputs.item(whichIteration).noteUsed();
  14061. }
  14062. }
  14063. virtual IFinalRoxieInput* connectIterationOutput(unsigned whichIteration, IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes, IRoxieServerActivity *targetAct, unsigned targetIdx)
  14064. {
  14065. if (outputs.isItem(whichIteration))
  14066. {
  14067. CGraphIterationInfo & next = outputs.item(whichIteration);
  14068. return next.connectOutput(probeManager, probes, targetAct, targetIdx);
  14069. }
  14070. return NULL;
  14071. }
  14072. };
  14073. //=================================================================================
  14074. class CRoxieServerGraphLoopActivityFactory : public CRoxieServerActivityFactory
  14075. {
  14076. unsigned loopGraphId;
  14077. unsigned flags;
  14078. Linked<IOutputMetaData> counterMeta;
  14079. public:
  14080. CRoxieServerGraphLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _loopGraphId)
  14081. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), loopGraphId(_loopGraphId)
  14082. {
  14083. Owned<IHThorGraphLoopArg> helper = (IHThorGraphLoopArg *) helperFactory();
  14084. flags = helper->getFlags();
  14085. counterMeta.setown(new CCounterRowMetaData);
  14086. }
  14087. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  14088. {
  14089. if (kind == TAKparallelgraphloop)
  14090. return new CRoxieServerParallelGraphLoopActivity(_ctx, this, _probeManager, loopGraphId, counterMeta);
  14091. else
  14092. return new CRoxieServerSequentialGraphLoopActivity(_ctx, this, _probeManager, loopGraphId, counterMeta);
  14093. }
  14094. };
  14095. IRoxieServerActivityFactory *createRoxieServerGraphLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _loopGraphId)
  14096. {
  14097. return new CRoxieServerGraphLoopActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _loopGraphId);
  14098. }
  14099. //=====================================================================================================
  14100. class CRoxieServerLibraryCallActivity : public CRoxieServerActivity
  14101. {
  14102. class OutputAdaptor : public CExtractMapperInput
  14103. {
  14104. bool stopped;
  14105. public:
  14106. CRoxieServerLibraryCallActivity *parent;
  14107. IOutputMetaData * meta = nullptr;
  14108. unsigned oid;
  14109. unsigned processed;
  14110. public:
  14111. OutputAdaptor()
  14112. {
  14113. parent = NULL;
  14114. oid = 0;
  14115. init();
  14116. }
  14117. ~OutputAdaptor()
  14118. {
  14119. if (traceStartStop)
  14120. DBGLOG("%p ~OutputAdaptor %d", this, oid);
  14121. if (processed && parent && parent->factory)
  14122. {
  14123. parent->factory->noteProcessed(oid, processed);
  14124. if (parent->ctx)
  14125. parent->ctx->noteProcessed(parent->querySubgraphId(), parent->activityId, oid, processed, 0);
  14126. }
  14127. }
  14128. void setParent(CRoxieServerLibraryCallActivity * _parent, IOutputMetaData * _meta, unsigned _oid)
  14129. {
  14130. parent = _parent;
  14131. meta = _meta;
  14132. oid = _oid;
  14133. }
  14134. void init()
  14135. {
  14136. processed = 0;
  14137. stopped = false;
  14138. }
  14139. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14140. {
  14141. parent->start(oid, parentExtractSize, parentExtract, paused);
  14142. CExtractMapperInput::start(parentExtractSize, parentExtract, paused);
  14143. }
  14144. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  14145. {
  14146. //MORE value of consumerOrdered depends on whether this activity is marked as ordered.
  14147. if (!oid) // Only need to set up once
  14148. {
  14149. parent->connectInputStreams(true); // To handle dependencies etc
  14150. }
  14151. return CExtractMapperInput::getOutputStreams(ctx, 0, streams, nullptr, true, nullptr);
  14152. }
  14153. //This override should not really be needed, but input is set up too late for the call to connect strands
  14154. virtual IOutputMetaData * queryOutputMeta() const
  14155. {
  14156. return meta;
  14157. }
  14158. virtual void stop()
  14159. {
  14160. if (!stopped)
  14161. {
  14162. stopped = true;
  14163. parent->stop(oid); // parent code relies on stop being called exactly once per adaptor, so make sure it is!
  14164. CExtractMapperInput::stop();
  14165. }
  14166. };
  14167. virtual void reset()
  14168. {
  14169. parent->reset(oid);
  14170. CExtractMapperInput::reset();
  14171. init();
  14172. };
  14173. virtual void checkAbort()
  14174. {
  14175. parent->checkAbort();
  14176. }
  14177. };
  14178. IHThorLibraryCallArg &helper;
  14179. unsigned numInputs;
  14180. unsigned numOutputs;
  14181. unsigned numActiveOutputs;
  14182. bool started;
  14183. OutputAdaptor* outputAdaptors;
  14184. CExtractMapperInput * * inputAdaptors;
  14185. bool * inputUsed;
  14186. bool * outputUsed;
  14187. Owned<IException> error;
  14188. CriticalSection crit;
  14189. rtlRowBuilder libraryExtractBuilder;
  14190. Owned<IActivityGraph> libraryGraph;
  14191. const LibraryCallFactoryExtra & extra;
  14192. public:
  14193. CRoxieServerLibraryCallActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs, unsigned _numOutputs, const LibraryCallFactoryExtra & _extra)
  14194. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  14195. helper((IHThorLibraryCallArg &)basehelper), extra(_extra)
  14196. {
  14197. numInputs = _numInputs;
  14198. numOutputs = _numOutputs;
  14199. numActiveOutputs = numOutputs;
  14200. inputAdaptors = new CExtractMapperInput*[numInputs];
  14201. inputUsed = new bool[numInputs];
  14202. for (unsigned i1 = 0; i1 < numInputs; i1++)
  14203. {
  14204. inputAdaptors[i1] = new CExtractMapperInput;
  14205. inputUsed[i1] = false;
  14206. }
  14207. outputAdaptors = new OutputAdaptor[numOutputs];
  14208. outputUsed = new bool[numOutputs];
  14209. for (unsigned i2 = 0; i2 < numOutputs; i2++)
  14210. {
  14211. outputAdaptors[i2].setParent(this, helper.queryOutputMeta(i2), i2);
  14212. outputUsed[i2] = false;
  14213. }
  14214. started = false;
  14215. }
  14216. ~CRoxieServerLibraryCallActivity()
  14217. {
  14218. for (unsigned i1 = 0; i1 < numInputs; i1++)
  14219. ::Release(inputAdaptors[i1]);
  14220. delete [] inputAdaptors;
  14221. delete [] inputUsed;
  14222. delete [] outputAdaptors;
  14223. delete [] outputUsed;
  14224. }
  14225. virtual void onCreate(IHThorArg *_colocalParent)
  14226. {
  14227. CRoxieServerActivity::onCreate(_colocalParent);
  14228. libraryGraph.setown(ctx->getLibraryGraph(extra, this));
  14229. libraryGraph->onCreate(_colocalParent);
  14230. //Now map the inputs and outputs to the adapters
  14231. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  14232. for (unsigned i1=0; i1<numInputs; i1++)
  14233. inputUsed[i1] = graph->querySetInputResult(i1, 0, inputAdaptors[i1]);
  14234. for (unsigned i2=0; i2<numOutputs; i2++)
  14235. {
  14236. unsigned outputIndex = extra.outputs.item(i2);
  14237. Owned<IFinalRoxieInput> output = graph->selectOutput(numInputs+outputIndex);
  14238. outputAdaptors[i2].setInput(0, output); // MORE - no idea if this 0 is right??
  14239. outputAdaptors[i2].connectInputStreams(ctx, true);
  14240. }
  14241. }
  14242. virtual void start(unsigned oid, unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14243. {
  14244. CriticalBlock b(crit);
  14245. if (error)
  14246. throw error.getLink();
  14247. if (factory)
  14248. factory->noteStarted(oid);
  14249. if (!started)
  14250. {
  14251. // even though it is not complete, we don't want to run this again if it fails.
  14252. started = true;
  14253. //see notes on splitter above
  14254. try
  14255. {
  14256. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14257. }
  14258. catch (IException *E)
  14259. {
  14260. #ifdef TRACE_SPLIT
  14261. CTXLOG("spill %d caught exception in start", activityId);
  14262. #endif
  14263. error.set(E);
  14264. throw;
  14265. }
  14266. catch (...)
  14267. {
  14268. IException *E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught in CRoxieServerLibraryCallActivity::start");
  14269. error.set(E);
  14270. throw E;
  14271. }
  14272. //recreate the parent extract, and use it to reinitialize the graphs...
  14273. libraryExtractBuilder.clear();
  14274. helper.createParentExtract(libraryExtractBuilder);
  14275. // 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
  14276. // some inputs before we see start on others.
  14277. for (unsigned i1 = 0; i1 < numInputs; i1++)
  14278. {
  14279. if (inputUsed[i1])
  14280. inputAdaptors[i1]->setParentExtract(parentExtractSize, parentExtract);
  14281. else
  14282. inputAdaptors[i1]->stop();
  14283. }
  14284. for (unsigned i2 = 0; i2 < numOutputs; i2++)
  14285. outputAdaptors[i2].setParentExtract(libraryExtractBuilder.size(), libraryExtractBuilder.getbytes());
  14286. //call stop on all the unused inputs.
  14287. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  14288. graph->beforeExecute();
  14289. ForEachItemIn(i3, extra.unusedOutputs)
  14290. {
  14291. Owned<IFinalRoxieInput> output = graph->selectOutput(numInputs+extra.unusedOutputs.item(i3));
  14292. // output->queryStream().stop(); Is this needed??
  14293. }
  14294. }
  14295. }
  14296. virtual void stop(unsigned oid)
  14297. {
  14298. CriticalBlock b(crit);
  14299. if (--numActiveOutputs == 0)
  14300. {
  14301. //call stop on all the unused inputs.
  14302. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  14303. graph->beforeExecute();
  14304. ForEachItemIn(i3, extra.unusedOutputs)
  14305. {
  14306. Owned<IFinalRoxieInput> output = graph->selectOutput(numInputs+extra.unusedOutputs.item(i3));
  14307. // Is this needed ?? output->queryStream().stop();
  14308. }
  14309. CRoxieServerActivity::stop();
  14310. }
  14311. }
  14312. void reset(unsigned oid)
  14313. {
  14314. started = false;
  14315. error.clear();
  14316. numActiveOutputs = numOutputs;
  14317. if (state != STATEreset) // make sure input is only reset once
  14318. {
  14319. CRoxieServerActivity::reset();
  14320. libraryGraph->reset();
  14321. //Call reset on all unused inputs/outputs from the graph - no one else will.
  14322. for (unsigned i1 = 0; i1 < numInputs; i1++)
  14323. {
  14324. if (!inputUsed[i1])
  14325. inputAdaptors[i1]->reset();
  14326. }
  14327. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  14328. ForEachItemIn(i3, extra.unusedOutputs)
  14329. {
  14330. Owned<IFinalRoxieInput> output = graph->selectOutput(numInputs+extra.unusedOutputs.item(i3));
  14331. output->reset();
  14332. }
  14333. }
  14334. };
  14335. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  14336. {
  14337. inputAdaptors[idx]->setInput(_sourceIdx, _in);
  14338. }
  14339. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  14340. {
  14341. if (idx < numInputs && inputAdaptors[idx])
  14342. return inputAdaptors[idx]->queryInput();
  14343. else
  14344. return NULL;
  14345. }
  14346. public:
  14347. virtual const void *nextRow()
  14348. {
  14349. throwUnexpected(); // Internal logic error - we are not anybody's input
  14350. }
  14351. virtual IOutputMetaData * queryOutputMeta() const
  14352. {
  14353. throwUnexpected(); // should be called on outputs instead
  14354. }
  14355. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  14356. {
  14357. assertex(idx!=(unsigned)-1);
  14358. assertex(!outputUsed[idx]);
  14359. outputUsed[idx] = true;
  14360. return &outputAdaptors[idx];
  14361. }
  14362. };
  14363. void LibraryCallFactoryExtra::set(const LibraryCallFactoryExtra & _other)
  14364. {
  14365. ForEachItemIn(i1, _other.outputs)
  14366. outputs.append(_other.outputs.item(i1));
  14367. ForEachItemIn(i2, _other.unusedOutputs)
  14368. unusedOutputs.append(_other.unusedOutputs.item(i2));
  14369. maxOutputs = _other.maxOutputs;
  14370. graphid = _other.graphid;
  14371. libraryName.set(_other.libraryName);
  14372. embeddedGraphName.set(_other.embeddedGraphName);
  14373. interfaceHash = _other.interfaceHash;
  14374. embedded = _other.embedded;
  14375. }
  14376. void LibraryCallFactoryExtra::calcUnused()
  14377. {
  14378. for (unsigned i=0; i < maxOutputs; i++)
  14379. if (!outputs.contains(i))
  14380. unusedOutputs.append(i);
  14381. }
  14382. class CRoxieServerLibraryCallActivityFactory : public CRoxieServerMultiOutputFactory
  14383. {
  14384. private:
  14385. CRoxieServerMultiInputInfo inputs;
  14386. LibraryCallFactoryExtra extra;
  14387. public:
  14388. CRoxieServerLibraryCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, LibraryCallFactoryExtra & _extra)
  14389. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  14390. {
  14391. extra.set(_extra);
  14392. extra.calcUnused();
  14393. setNumOutputs(extra.outputs.ordinality());
  14394. }
  14395. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  14396. {
  14397. return new CRoxieServerLibraryCallActivity(_ctx, this, _probeManager, numInputs(), numOutputs, extra);
  14398. }
  14399. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  14400. {
  14401. inputs.set(idx, source, sourceidx);
  14402. }
  14403. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  14404. {
  14405. return inputs.get(idx, sourceidx);
  14406. }
  14407. virtual unsigned numInputs() const { return inputs.ordinality(); }
  14408. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  14409. {
  14410. addXrefLibraryInfo(reply, extra.libraryName);
  14411. }
  14412. };
  14413. IRoxieServerActivityFactory *createRoxieServerLibraryCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, LibraryCallFactoryExtra & _extra)
  14414. {
  14415. return new CRoxieServerLibraryCallActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _extra);
  14416. }
  14417. //=====================================================================================================
  14418. // CRoxieServerNWayInputActivity is a multi-input, multi-output activity, where the outputs are a subset of the inputs
  14419. // Used to implement RANGE(<rowset-expression>, [set-of-indices])
  14420. class CRoxieServerNWayInputBaseActivity : public CRoxieServerMultiInputBaseActivity
  14421. {
  14422. protected:
  14423. PointerArrayOf<IFinalRoxieInput> selectedInputs;
  14424. PointerArrayOf<IEngineRowStream> selectedStreams;
  14425. PointerArrayOf<IStrandJunction> selectedJunctions;
  14426. public:
  14427. CRoxieServerNWayInputBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14428. : CRoxieServerMultiInputBaseActivity(_ctx, _factory, _probeManager, _numInputs)
  14429. {
  14430. }
  14431. virtual void stop()
  14432. {
  14433. ForEachItemIn(i2, selectedStreams)
  14434. selectedStreams.item(i2)->stop();
  14435. CRoxieServerMultiInputBaseActivity::stop();
  14436. }
  14437. virtual unsigned __int64 queryLocalCycles() const
  14438. {
  14439. __int64 localCycles = totalCycles.totalCycles;
  14440. ForEachItemIn(i, selectedInputs)
  14441. {
  14442. localCycles -= selectedInputs.item(i)->queryTotalCycles();
  14443. }
  14444. if (localCycles < 0)
  14445. localCycles = 0;
  14446. return localCycles;
  14447. }
  14448. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  14449. {
  14450. if (selectedInputs.isItem(idx))
  14451. return selectedInputs.item(idx);
  14452. else
  14453. return NULL;
  14454. }
  14455. virtual void reset()
  14456. {
  14457. ForEachItemIn(i, selectedInputs)
  14458. selectedInputs.item(i)->reset();
  14459. selectedInputs.kill();
  14460. selectedStreams.kill();
  14461. selectedJunctions.kill();
  14462. CRoxieServerMultiInputBaseActivity::reset();
  14463. }
  14464. virtual const void * nextRow()
  14465. {
  14466. throwUnexpected();
  14467. }
  14468. virtual unsigned numConcreteOutputs() const
  14469. {
  14470. return selectedInputs.ordinality();
  14471. }
  14472. virtual IFinalRoxieInput * queryConcreteInput(unsigned idx)
  14473. {
  14474. return queryInput(idx);
  14475. }
  14476. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput)
  14477. {
  14478. if (selectedStreams.isItem(whichInput))
  14479. return selectedStreams.item(whichInput);
  14480. return NULL;
  14481. }
  14482. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const
  14483. {
  14484. if (selectedJunctions.isItem(idx))
  14485. return selectedJunctions.item(idx);
  14486. return NULL;
  14487. }
  14488. };
  14489. class CRoxieServerNWayInputActivity : public CRoxieServerNWayInputBaseActivity
  14490. {
  14491. IHThorNWayInputArg & helper;
  14492. public:
  14493. CRoxieServerNWayInputActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14494. : CRoxieServerNWayInputBaseActivity(_ctx, _factory, _probeManager, _numInputs), helper((IHThorNWayInputArg &)basehelper)
  14495. {
  14496. }
  14497. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14498. {
  14499. CRoxieServerNWayInputBaseActivity::start(parentExtractSize, parentExtract, paused);
  14500. bool selectionIsAll;
  14501. size32_t selectionLen;
  14502. rtlDataAttr selection;
  14503. helper.getInputSelection(selectionIsAll, selectionLen, selection.refdata());
  14504. selectedInputs.kill();
  14505. selectedStreams.kill();
  14506. selectedJunctions.kill();
  14507. assertex(numInputs==numStreams); // Will need refactoring when that ceases to be true
  14508. if (selectionIsAll)
  14509. {
  14510. for (unsigned i=0; i < numInputs; i++)
  14511. {
  14512. selectedInputs.append(inputArray[i]);
  14513. selectedStreams.append(streamArray[i]); // Assumes 1:1 relationship - is that good?
  14514. selectedJunctions.append(junctionArray[i]);
  14515. }
  14516. }
  14517. else
  14518. {
  14519. const size32_t * selections = (const size32_t *)selection.getdata();
  14520. unsigned max = selectionLen/sizeof(size32_t);
  14521. for (unsigned i = 0; i < max; i++)
  14522. {
  14523. unsigned nextIndex = selections[i];
  14524. //Check there are no duplicates..... Assumes there are a fairly small number of inputs, so n^2 search is ok.
  14525. for (unsigned j=i+1; j < max; j++)
  14526. {
  14527. if (nextIndex == selections[j])
  14528. throw MakeStringException(ROXIE_NWAY_INPUT_ERROR, "Selection list for nway input can not contain duplicates");
  14529. }
  14530. if (nextIndex > numInputs || nextIndex > numStreams)
  14531. throw MakeStringException(ROXIE_NWAY_INPUT_ERROR, "Index %d in RANGE selection list is out of range", nextIndex);
  14532. selectedInputs.append(inputArray[nextIndex-1]);
  14533. selectedStreams.append(streamArray[nextIndex-1]); // Assumes 1:1 relationship - is that good?
  14534. selectedJunctions.append(junctionArray[nextIndex-1]);
  14535. }
  14536. }
  14537. // NB: Whatever pulls this nwayinput activity, starts and stops the selectedInputs and selectedJunctions
  14538. }
  14539. virtual void stop()
  14540. {
  14541. // NB: Whatever pulls this nwayinput activity, starts and stops the selectedInputs
  14542. }
  14543. };
  14544. class CRoxieServerNWayInputActivityFactory : public CRoxieServerMultiInputFactory
  14545. {
  14546. public:
  14547. CRoxieServerNWayInputActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  14548. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  14549. {
  14550. }
  14551. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  14552. {
  14553. return new CRoxieServerNWayInputActivity(_ctx, this, _probeManager, numInputs());
  14554. }
  14555. };
  14556. IRoxieServerActivityFactory *createRoxieServerNWayInputActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  14557. {
  14558. return new CRoxieServerNWayInputActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  14559. }
  14560. //=====================================================================================================
  14561. class CRoxieServerNWayGraphLoopResultReadActivity : public CRoxieServerNWayInputBaseActivity
  14562. {
  14563. IHThorNWayGraphLoopResultReadArg & helper;
  14564. IArrayOf<IRoxieServerActivity> resultReaders;
  14565. Owned<IStrandJunction> *resultJunctions;
  14566. unsigned graphId;
  14567. bool grouped;
  14568. bool selectionIsAll;
  14569. size32_t selectionLen;
  14570. rtlDataAttr selection;
  14571. public:
  14572. CRoxieServerNWayGraphLoopResultReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId)
  14573. : CRoxieServerNWayInputBaseActivity(_ctx, _factory, _probeManager, 0), helper((IHThorNWayGraphLoopResultReadArg &)basehelper)
  14574. {
  14575. grouped = helper.isGrouped();
  14576. graphId = _graphId;
  14577. selectionIsAll = false;
  14578. selectionLen = 0;
  14579. resultJunctions = NULL;
  14580. }
  14581. ~CRoxieServerNWayGraphLoopResultReadActivity()
  14582. {
  14583. delete [] resultJunctions;
  14584. }
  14585. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14586. {
  14587. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14588. if (selectedInputs.ordinality() == 0)
  14589. {
  14590. initInputSelection();
  14591. unsigned max = selectionLen / sizeof(size32_t);
  14592. const size32_t * selections = (const size32_t *)selection.getdata();
  14593. IProbeManager * probeManager = NULL; // MORE!!
  14594. for (unsigned i = 0; i < max; i++)
  14595. {
  14596. CRoxieServerActivity * resultInput = new CRoxieServerInternalGraphLoopResultReadActivity(ctx, factory, probeManager, graphId, selections[i]);
  14597. resultReaders.append(*resultInput);
  14598. selectedInputs.append(resultInput);
  14599. resultInput->onCreate(colocalParent);
  14600. resultInput->start(parentExtractSize, parentExtract, paused);
  14601. selectedStreams.append(connectSingleStream(ctx, resultInput, 0, resultJunctions[i], true));
  14602. selectedJunctions.append(resultJunctions[i]);
  14603. }
  14604. }
  14605. }
  14606. virtual void reset()
  14607. {
  14608. resultReaders.kill();
  14609. CRoxieServerNWayInputBaseActivity::reset();
  14610. ForEachItemIn(i, selectedStreams)
  14611. resetJunction(resultJunctions[i]);
  14612. }
  14613. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract)
  14614. {
  14615. ensureCreated();
  14616. basehelper.onStart(parentExtract, NULL);
  14617. initInputSelection();
  14618. unsigned max = selectionLen / sizeof(size32_t);
  14619. const size32_t * selections = (const size32_t *)selection.getdata();
  14620. for (unsigned i = 0; i < max; i++)
  14621. processor.noteUseIteration(selections[i]);
  14622. }
  14623. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract, IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes)
  14624. {
  14625. //selection etc. already initialised from the gatherIterationUsage() call.
  14626. unsigned max = selectionLen / sizeof(size32_t);
  14627. const size32_t * selections = (const size32_t *)selection.getdata();
  14628. resultJunctions = new Owned<IStrandJunction> [max];
  14629. for (unsigned i = 0; i < max; i++)
  14630. {
  14631. IFinalRoxieInput *in = processor.connectIterationOutput(selections[i], probeManager, probes, this, i);
  14632. selectedInputs.append(in);
  14633. selectedStreams.append(connectSingleStream(ctx, in, 0, resultJunctions[i], true));
  14634. selectedJunctions.append(resultJunctions[i]);
  14635. }
  14636. }
  14637. protected:
  14638. void initInputSelection()
  14639. {
  14640. helper.getInputSelection(selectionIsAll, selectionLen, selection.refdata());
  14641. if (selectionIsAll)
  14642. throw MakeStringException(ROXIE_NWAY_INPUT_ERROR, "ALL not yet supported for NWay graph inputs");
  14643. }
  14644. };
  14645. class CRoxieServerNWayGraphLoopResultReadActivityFactory : public CRoxieServerActivityFactory
  14646. {
  14647. unsigned graphId;
  14648. public:
  14649. CRoxieServerNWayGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _graphId)
  14650. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), graphId(_graphId)
  14651. {
  14652. }
  14653. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  14654. {
  14655. return new CRoxieServerNWayGraphLoopResultReadActivity(_ctx, this, _probeManager, graphId);
  14656. }
  14657. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  14658. {
  14659. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for NWay GraphLoopResultRead activity");
  14660. }
  14661. };
  14662. IRoxieServerActivityFactory *createRoxieServerNWayGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned graphId)
  14663. {
  14664. return new CRoxieServerNWayGraphLoopResultReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, graphId);
  14665. }
  14666. //=================================================================================
  14667. class RoxieSteppedInput : implements ISteppedInput, public CInterface
  14668. {
  14669. public:
  14670. RoxieSteppedInput(IFinalRoxieInput * _input, IEngineRowStream *_stream) { input = _input; inputStream = _stream; }
  14671. IMPLEMENT_IINTERFACE
  14672. protected:
  14673. virtual const void * nextInputRow()
  14674. {
  14675. #ifdef TRACE_SEEK_REQUESTS
  14676. IRoxieContextLogger * logger = input->queryActivity();
  14677. const void * ret = doNextInputRow();
  14678. {
  14679. CommonXmlWriter xmlwrite(XWFtrim|XWFopt|XWFnoindent);
  14680. if (!ret)
  14681. xmlwrite.outputBool(true,"eof");
  14682. else if (input->queryOutputMeta()->hasXML())
  14683. input->queryOutputMeta()->toXML((byte *) ret, xmlwrite);
  14684. logger->CTXLOG("next() returns (%s)", xmlwrite.str());
  14685. }
  14686. return ret;
  14687. #else
  14688. return inputStream->ungroupedNextRow();
  14689. #endif
  14690. }
  14691. virtual const void * nextInputRowGE(const void * seek, unsigned numFields, bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  14692. {
  14693. #ifdef TRACE_SEEK_REQUESTS
  14694. IRoxieContextLogger * logger = input->queryActivity();
  14695. {
  14696. CommonXmlWriter xmlwrite(XWFtrim|XWFopt|XWFnoindent);
  14697. if (input->queryOutputMeta()->hasXML())
  14698. input->queryOutputMeta()->toXML((byte *) seek, xmlwrite);
  14699. logger->CTXLOG("nextInputRowGE(%d, %s%s%s, %s) seek(%s)",
  14700. numFields,
  14701. stepExtra.readAheadManyResults() ? "readahead " : "",
  14702. stepExtra.returnMismatches() ? "mismatch" : "exact",
  14703. stepExtra.onlyReturnFirstSeekMatch() ? " single-match" : "",
  14704. stepExtra.queryExtraSeeks() ? "multi-seek":"",
  14705. xmlwrite.str());
  14706. }
  14707. const void * ret = doNextInputRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  14708. {
  14709. CommonXmlWriter xmlwrite(XWFtrim|XWFopt|XWFnoindent);
  14710. if (!ret)
  14711. xmlwrite.outputBool(true,"eof");
  14712. else if (input->queryOutputMeta()->hasXML())
  14713. input->queryOutputMeta()->toXML((byte *) ret, xmlwrite);
  14714. logger->CTXLOG("nextInputRowGE(%d, %s%s%s, %s) result(%s)",
  14715. numFields,
  14716. stepExtra.readAheadManyResults() ? "readahead " : "",
  14717. stepExtra.returnMismatches() ? "mismatch" : "exact",
  14718. stepExtra.onlyReturnFirstSeekMatch() ? " single-match" : "",
  14719. stepExtra.queryExtraSeeks() ? "multi-seek":"",
  14720. xmlwrite.str());
  14721. }
  14722. return ret;
  14723. #else
  14724. return doNextInputRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  14725. #endif
  14726. }
  14727. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  14728. {
  14729. return input->gatherConjunctions(collector);
  14730. }
  14731. virtual void resetEOF()
  14732. {
  14733. inputStream->resetEOF();
  14734. }
  14735. virtual IInputSteppingMeta * queryInputSteppingMeta()
  14736. {
  14737. return input->querySteppingMeta();
  14738. }
  14739. inline const void * doNextInputRowGE(const void * seek, unsigned numFields, bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  14740. {
  14741. assertex(wasCompleteMatch);
  14742. return inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  14743. }
  14744. protected:
  14745. IFinalRoxieInput * input;
  14746. IEngineRowStream * inputStream;
  14747. };
  14748. //=================================================================================
  14749. class CRoxieServerNWayBaseActivity : public CRoxieServerMultiInputBaseActivity
  14750. {
  14751. public:
  14752. CRoxieServerNWayBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14753. : CRoxieServerMultiInputBaseActivity(_ctx, _factory, _probeManager, _numInputs)
  14754. {
  14755. }
  14756. void startExpandedInputs(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14757. {
  14758. ForEachItemIn(ei, expandedInputs)
  14759. expandedInputs.item(ei)->start(parentExtractSize, parentExtract, paused);
  14760. ForEachItemIn(idx, expandedInputs)
  14761. startJunction(expandedJunctions.item(idx));
  14762. }
  14763. virtual void stop()
  14764. {
  14765. ForEachItemIn(i, expandedStreams)
  14766. expandedStreams.item(i)->stop();
  14767. CRoxieServerMultiInputBaseActivity::stop();
  14768. }
  14769. virtual void reset()
  14770. {
  14771. ForEachItemIn(idx, expandedInputs)
  14772. resetJunction(expandedJunctions.item(idx));
  14773. expandedInputs.kill();
  14774. expandedStreams.kill();
  14775. expandedJunctions.kill();
  14776. CRoxieServerMultiInputBaseActivity::reset();
  14777. }
  14778. protected:
  14779. PointerArrayOf<IFinalRoxieInput> expandedInputs;
  14780. PointerArrayOf<IEngineRowStream> expandedStreams;
  14781. PointerArrayOf<IStrandJunction> expandedJunctions;
  14782. };
  14783. //=================================================================================
  14784. class CRoxieServerNaryActivity : public CRoxieServerNWayBaseActivity
  14785. {
  14786. public:
  14787. CRoxieServerNaryActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14788. : CRoxieServerNWayBaseActivity(_ctx, _factory, _probeManager, _numInputs)
  14789. {
  14790. }
  14791. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14792. {
  14793. CRoxieServerNWayBaseActivity::start(parentExtractSize, parentExtract, paused);
  14794. for (unsigned i=0; i < numInputs; i++)
  14795. {
  14796. IFinalRoxieInput * cur = inputArray[i];
  14797. CRoxieServerNWayInputBaseActivity *nWayInput = dynamic_cast<CRoxieServerNWayInputBaseActivity *>(cur);
  14798. if (nWayInput)
  14799. {
  14800. nWayInput->start(parentExtractSize, parentExtract, paused);
  14801. unsigned numRealInputs = cur->numConcreteOutputs();
  14802. for (unsigned j = 0; j < numRealInputs; j++)
  14803. {
  14804. expandedInputs.append(cur->queryConcreteInput(j));
  14805. expandedStreams.append(cur->queryConcreteOutputStream(j));
  14806. expandedJunctions.append(cur->queryConcreteOutputJunction(j));
  14807. }
  14808. }
  14809. else
  14810. {
  14811. expandedInputs.append(cur);
  14812. // NB: this activities input streams + junction have been setup and held in CRoxieServerMultiInputActivity base
  14813. expandedStreams.append(queryConcreteOutputStream(i));
  14814. expandedJunctions.append(queryConcreteOutputJunction(i));
  14815. }
  14816. }
  14817. startExpandedInputs(parentExtractSize, parentExtract, paused);
  14818. }
  14819. };
  14820. //=================================================================================
  14821. class CRoxieStreamMerger : public CStreamMerger
  14822. {
  14823. public:
  14824. CRoxieStreamMerger() : CStreamMerger(true)
  14825. {
  14826. streamArray = NULL;
  14827. }
  14828. void initInputs(unsigned _numInputs, IEngineRowStream ** _streamArray)
  14829. {
  14830. CStreamMerger::initInputs(_numInputs);
  14831. streamArray = _streamArray;
  14832. }
  14833. virtual bool pullInput(unsigned i, const void * seek, unsigned numFields, const SmartStepExtra * stepExtra)
  14834. {
  14835. const void * next;
  14836. bool matches = true;
  14837. if (seek)
  14838. next = streamArray[i]->nextRowGE(seek, numFields, matches, *stepExtra);
  14839. else
  14840. next = streamArray[i]->ungroupedNextRow();
  14841. pending[i] = next;
  14842. pendingMatches[i] = matches;
  14843. return (next != NULL);
  14844. }
  14845. virtual void releaseRow(const void * row)
  14846. {
  14847. ReleaseRoxieRow(row);
  14848. }
  14849. protected:
  14850. IEngineRowStream **streamArray;
  14851. };
  14852. class CRoxieServerNWayMergeActivity : public CRoxieServerNaryActivity
  14853. {
  14854. public:
  14855. CRoxieServerNWayMergeActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14856. : CRoxieServerNaryActivity(_ctx, _factory, _probeManager, _numInputs),
  14857. helper((IHThorNWayMergeArg &)basehelper)
  14858. {
  14859. initializedMeta = false;
  14860. }
  14861. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14862. {
  14863. CRoxieServerNaryActivity::start(parentExtractSize, parentExtract, paused);
  14864. merger.init(helper.queryCompare(), helper.dedup(), helper.querySteppingMeta()->queryCompare());
  14865. merger.initInputs(expandedStreams.length(), expandedStreams.getArray());
  14866. }
  14867. virtual void stop()
  14868. {
  14869. merger.done();
  14870. CRoxieServerNaryActivity::stop();
  14871. }
  14872. virtual void reset()
  14873. {
  14874. merger.cleanup();
  14875. CRoxieServerNaryActivity::reset();
  14876. initializedMeta = false;
  14877. }
  14878. virtual const void * nextRow()
  14879. {
  14880. ActivityTimer t(totalCycles, timeActivities);
  14881. const void * next = merger.nextRow();
  14882. if (next)
  14883. processed++;
  14884. return next;
  14885. }
  14886. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  14887. {
  14888. ActivityTimer t(totalCycles, timeActivities);
  14889. const void * next = merger.nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  14890. if (next)
  14891. processed++;
  14892. return next;
  14893. }
  14894. virtual IInputSteppingMeta * querySteppingMeta()
  14895. {
  14896. if (expandedStreams.ordinality() == 0)
  14897. return NULL;
  14898. if (!initializedMeta)
  14899. {
  14900. meta.init(helper.querySteppingMeta(), false);
  14901. ForEachItemIn(i, expandedStreams)
  14902. {
  14903. if (meta.getNumFields() == 0)
  14904. break;
  14905. IInputSteppingMeta * inputMeta = expandedInputs.item(i)->querySteppingMeta();
  14906. meta.intersect(inputMeta);
  14907. }
  14908. initializedMeta = true;
  14909. }
  14910. if (meta.getNumFields() == 0)
  14911. return NULL;
  14912. return &meta;
  14913. }
  14914. protected:
  14915. IHThorNWayMergeArg &helper;
  14916. CRoxieStreamMerger merger;
  14917. CSteppingMeta meta;
  14918. bool initializedMeta;
  14919. };
  14920. class CRoxieServerNWayMergeActivityFactory : public CRoxieServerMultiInputFactory
  14921. {
  14922. public:
  14923. CRoxieServerNWayMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  14924. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  14925. {
  14926. }
  14927. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  14928. {
  14929. return new CRoxieServerNWayMergeActivity(_ctx, this, _probeManager, numInputs());
  14930. }
  14931. };
  14932. IRoxieServerActivityFactory *createRoxieServerNWayMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  14933. {
  14934. return new CRoxieServerNWayMergeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  14935. }
  14936. //=================================================================================
  14937. class CRoxieServerNWayMergeJoinActivity : public CRoxieServerNaryActivity
  14938. {
  14939. public:
  14940. CRoxieServerNWayMergeJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs, CMergeJoinProcessor & _processor)
  14941. : CRoxieServerNaryActivity(_ctx, _factory, _probeManager, _numInputs),processor(_processor),
  14942. helper((IHThorNWayMergeJoinArg &)basehelper)
  14943. {
  14944. }
  14945. virtual void onCreate(IHThorArg *_colocalParent)
  14946. {
  14947. CRoxieServerNaryActivity::onCreate(_colocalParent);
  14948. ICodeContext * codectx = ctx->queryCodeContext();
  14949. inputAllocator.setown(createRowAllocator(helper.queryInputMeta()));
  14950. outputAllocator.setown(createRowAllocator(helper.queryOutputMeta()));
  14951. }
  14952. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14953. {
  14954. CRoxieServerNaryActivity::start(parentExtractSize, parentExtract, paused);
  14955. ForEachItemIn(i1, expandedInputs)
  14956. {
  14957. Owned<RoxieSteppedInput> stepInput = new RoxieSteppedInput(expandedInputs.item(i1), expandedStreams.item(i1));
  14958. processor.addInput(stepInput);
  14959. }
  14960. processor.beforeProcessing(inputAllocator, outputAllocator);
  14961. }
  14962. virtual void stop()
  14963. {
  14964. processor.afterProcessing();
  14965. CRoxieServerNaryActivity::stop();
  14966. }
  14967. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  14968. {
  14969. return processor.gatherConjunctions(collector);
  14970. }
  14971. virtual void resetEOF()
  14972. {
  14973. processor.queryResetEOF();
  14974. }
  14975. virtual const void * nextRow()
  14976. {
  14977. ActivityTimer t(totalCycles, timeActivities);
  14978. const void * next = processor.nextRow();
  14979. if (next)
  14980. processed++;
  14981. return next;
  14982. }
  14983. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  14984. {
  14985. ActivityTimer t(totalCycles, timeActivities);
  14986. const void * next = processor.nextGE(seek, numFields, wasCompleteMatch, stepExtra);
  14987. if (next)
  14988. processed++;
  14989. return next;
  14990. }
  14991. virtual IInputSteppingMeta * querySteppingMeta()
  14992. {
  14993. return processor.queryInputSteppingMeta();
  14994. }
  14995. protected:
  14996. IHThorNWayMergeJoinArg & helper;
  14997. CMergeJoinProcessor & processor;
  14998. Owned<IEngineRowAllocator> inputAllocator;
  14999. Owned<IEngineRowAllocator> outputAllocator;
  15000. };
  15001. class CRoxieServerAndMergeJoinActivity : public CRoxieServerNWayMergeJoinActivity
  15002. {
  15003. public:
  15004. CRoxieServerAndMergeJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  15005. : CRoxieServerNWayMergeJoinActivity(_ctx, _factory, _probeManager, _numInputs, andProcessor), andProcessor(helper)
  15006. {
  15007. }
  15008. protected:
  15009. CAndMergeJoinProcessor andProcessor;
  15010. };
  15011. class CRoxieServerAndLeftMergeJoinActivity : public CRoxieServerNWayMergeJoinActivity
  15012. {
  15013. public:
  15014. CRoxieServerAndLeftMergeJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  15015. : CRoxieServerNWayMergeJoinActivity(_ctx, _factory, _probeManager, _numInputs, andLeftProcessor), andLeftProcessor(helper)
  15016. {
  15017. }
  15018. protected:
  15019. CAndLeftMergeJoinProcessor andLeftProcessor;
  15020. };
  15021. class CRoxieServerMofNMergeJoinActivity : public CRoxieServerNWayMergeJoinActivity
  15022. {
  15023. public:
  15024. CRoxieServerMofNMergeJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  15025. : CRoxieServerNWayMergeJoinActivity(_ctx, _factory, _probeManager, _numInputs, mofnProcessor), mofnProcessor(helper)
  15026. {
  15027. }
  15028. protected:
  15029. CMofNMergeJoinProcessor mofnProcessor;
  15030. };
  15031. class CRoxieServerProximityJoinActivity : public CRoxieServerNWayMergeJoinActivity
  15032. {
  15033. public:
  15034. CRoxieServerProximityJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  15035. : CRoxieServerNWayMergeJoinActivity(_ctx, _factory, _probeManager, _numInputs, proximityProcessor), proximityProcessor(helper)
  15036. {
  15037. }
  15038. protected:
  15039. CProximityJoinProcessor proximityProcessor;
  15040. };
  15041. class CRoxieServerNWayMergeJoinActivityFactory : public CRoxieServerMultiInputFactory
  15042. {
  15043. unsigned flags;
  15044. public:
  15045. CRoxieServerNWayMergeJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15046. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15047. {
  15048. Owned<IHThorNWayMergeJoinArg> helper = (IHThorNWayMergeJoinArg *) helperFactory();
  15049. flags = helper->getJoinFlags();
  15050. }
  15051. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15052. {
  15053. if (flags & IHThorNWayMergeJoinArg::MJFhasrange)
  15054. return new CRoxieServerProximityJoinActivity(_ctx, this, _probeManager, numInputs());
  15055. switch (flags & IHThorNWayMergeJoinArg::MJFkindmask)
  15056. {
  15057. case IHThorNWayMergeJoinArg::MJFinner:
  15058. return new CRoxieServerAndMergeJoinActivity(_ctx, this, _probeManager, numInputs());
  15059. case IHThorNWayMergeJoinArg::MJFleftonly:
  15060. case IHThorNWayMergeJoinArg::MJFleftouter:
  15061. return new CRoxieServerAndLeftMergeJoinActivity(_ctx, this, _probeManager, numInputs());
  15062. case IHThorNWayMergeJoinArg::MJFmofn:
  15063. return new CRoxieServerMofNMergeJoinActivity(_ctx, this, _probeManager, numInputs());
  15064. default:
  15065. throwUnexpected();
  15066. }
  15067. }
  15068. };
  15069. IRoxieServerActivityFactory *createRoxieServerNWayMergeJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15070. {
  15071. return new CRoxieServerNWayMergeJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15072. }
  15073. //=================================================================================
  15074. class CRoxieServerNWaySelectActivity : public CRoxieServerNWayBaseActivity
  15075. {
  15076. IHThorNWaySelectArg &helper;
  15077. public:
  15078. CRoxieServerNWaySelectActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  15079. : CRoxieServerNWayBaseActivity(_ctx, _factory, _probeManager, _numInputs),
  15080. helper((IHThorNWaySelectArg &)basehelper)
  15081. {
  15082. }
  15083. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15084. {
  15085. CRoxieServerNWayBaseActivity::start(parentExtractSize, parentExtract, paused);
  15086. unsigned whichInput = helper.getInputIndex();
  15087. selectedInput = nullptr;
  15088. selectedStream = nullptr;
  15089. if (whichInput--)
  15090. {
  15091. for (unsigned i=0; i < numInputs; i++)
  15092. {
  15093. IFinalRoxieInput * cur = inputArray[i];
  15094. CRoxieServerNWayInputBaseActivity *nWayInput = dynamic_cast<CRoxieServerNWayInputBaseActivity *>(cur);
  15095. if (nWayInput)
  15096. {
  15097. nWayInput->start(parentExtractSize, parentExtract, paused);
  15098. unsigned numRealInputs = cur->numConcreteOutputs();
  15099. if (whichInput < numRealInputs)
  15100. {
  15101. expandedInputs.append(cur->queryConcreteInput(whichInput));
  15102. expandedStreams.append(cur->queryConcreteOutputStream(whichInput));
  15103. expandedJunctions.append(cur->queryConcreteOutputJunction(whichInput));
  15104. break;
  15105. }
  15106. whichInput -= numRealInputs;
  15107. }
  15108. else
  15109. {
  15110. if (whichInput == 0)
  15111. {
  15112. expandedInputs.append(cur);
  15113. // NB: this activities input streams + junction have been setup and held in CRoxieServerMultiInputActivity base
  15114. expandedStreams.append(queryConcreteOutputStream(i));
  15115. expandedJunctions.append(queryConcreteOutputJunction(i));
  15116. break;
  15117. }
  15118. whichInput -= 1;
  15119. }
  15120. }
  15121. }
  15122. if (expandedInputs.ordinality())
  15123. {
  15124. startExpandedInputs(parentExtractSize, parentExtract, paused);
  15125. selectedInput = expandedInputs.item(0);
  15126. selectedStream = expandedStreams.item(0);
  15127. }
  15128. }
  15129. const void * nextRow()
  15130. {
  15131. ActivityTimer t(totalCycles, timeActivities);
  15132. if (!selectedStream)
  15133. return NULL;
  15134. return selectedStream->nextRow();
  15135. }
  15136. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  15137. {
  15138. if (!selectedInput)
  15139. return false;
  15140. return selectedInput->gatherConjunctions(collector);
  15141. }
  15142. virtual void resetEOF()
  15143. {
  15144. if (selectedStream)
  15145. selectedStream->resetEOF();
  15146. }
  15147. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  15148. {
  15149. ActivityTimer t(totalCycles, timeActivities);
  15150. if (!selectedStream)
  15151. return NULL;
  15152. return selectedStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  15153. }
  15154. IInputSteppingMeta * querySteppingMeta()
  15155. {
  15156. if (selectedInput)
  15157. return selectedInput->querySteppingMeta();
  15158. return NULL;
  15159. }
  15160. protected:
  15161. IFinalRoxieInput * selectedInput = nullptr;
  15162. IEngineRowStream * selectedStream = nullptr;
  15163. Owned<IStrandJunction> selectedJunction;
  15164. };
  15165. class CRoxieServerNWaySelectActivityFactory : public CRoxieServerMultiInputFactory
  15166. {
  15167. public:
  15168. CRoxieServerNWaySelectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15169. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15170. {
  15171. }
  15172. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15173. {
  15174. return new CRoxieServerNWaySelectActivity(_ctx, this, _probeManager, numInputs());
  15175. }
  15176. };
  15177. IRoxieServerActivityFactory *createRoxieServerNWaySelectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15178. {
  15179. return new CRoxieServerNWaySelectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15180. }
  15181. //=================================================================================
  15182. class CRoxieServerRemoteActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler
  15183. {
  15184. protected:
  15185. IHThorRemoteArg &helper;
  15186. CRemoteResultAdaptor remote;
  15187. public:
  15188. CRoxieServerRemoteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteID)
  15189. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  15190. helper((IHThorRemoteArg &)basehelper),
  15191. remote(_ctx, this, _remoteID, meta.queryOriginal(), helper, *this, false, false) // MORE - if they need it stable we'll have to think!
  15192. {
  15193. }
  15194. virtual const IResolvedFile *queryVarFileInfo() const
  15195. {
  15196. return NULL;
  15197. }
  15198. virtual void onCreate(IHThorArg *_colocalParent)
  15199. {
  15200. CRoxieServerActivity::onCreate(_colocalParent);
  15201. remote.onCreate(_colocalParent);
  15202. }
  15203. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15204. {
  15205. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  15206. remote.onStart(parentExtractSize, parentExtract);
  15207. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  15208. unsigned fileNo = 0; // MORE - superfiles require us to do this per file part... maybe (needs thought)
  15209. remote.getMem(0, fileNo, 0); // the cached context is all we need to send
  15210. remote.flush();
  15211. remote.senddone();
  15212. }
  15213. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  15214. {
  15215. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  15216. }
  15217. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  15218. {
  15219. if (idx==(unsigned)-1)
  15220. idx = 0;
  15221. return idx ? NULL: &remote;
  15222. }
  15223. virtual void reset()
  15224. {
  15225. processed = remote.processed;
  15226. remote.processed = 0;
  15227. CRoxieServerActivity::reset();
  15228. }
  15229. virtual void onLimitExceeded(bool isKeyed)
  15230. {
  15231. if (traceLevel > 4)
  15232. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  15233. helper.onLimitExceeded();
  15234. }
  15235. virtual const void *createLimitFailRow(bool isKeyed)
  15236. {
  15237. UNIMPLEMENTED; // MORE - is there an ONFAIL for a limit folded into a remote?
  15238. }
  15239. virtual const void *nextRow()
  15240. {
  15241. throwUnexpected(); // I am nobody's input
  15242. }
  15243. };
  15244. class CRoxieServerRemoteActivityFactory : public CRoxieServerActivityFactory
  15245. {
  15246. public:
  15247. RemoteActivityId remoteId;
  15248. bool isRoot;
  15249. CRoxieServerRemoteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId, bool _isRoot)
  15250. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), remoteId(_remoteId), isRoot(_isRoot)
  15251. {
  15252. }
  15253. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15254. {
  15255. return new CRoxieServerRemoteActivity(_ctx, this, _probeManager, remoteId);
  15256. }
  15257. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  15258. {
  15259. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  15260. }
  15261. virtual bool isSink() const
  15262. {
  15263. //I don't think the action version of this is implemented - but this would be the code
  15264. return isRoot && !meta.queryOriginal();
  15265. }
  15266. virtual const StatisticsMapping &queryStatsMapping() const
  15267. {
  15268. return allStatistics; // Child queries...
  15269. }
  15270. };
  15271. IRoxieServerActivityFactory *createRoxieServerRemoteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId, bool _isRoot)
  15272. {
  15273. return new CRoxieServerRemoteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId, _isRoot);
  15274. }
  15275. //=================================================================================
  15276. class CRoxieServerIterateActivity : public CRoxieServerActivity
  15277. {
  15278. IHThorIterateArg &helper;
  15279. OwnedConstRoxieRow defaultRecord;
  15280. OwnedConstRoxieRow left;
  15281. OwnedConstRoxieRow right;
  15282. unsigned counter;
  15283. public:
  15284. CRoxieServerIterateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  15285. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  15286. helper((IHThorIterateArg &)basehelper)
  15287. {
  15288. counter = 0;
  15289. }
  15290. virtual bool needsAllocator() const { return true; }
  15291. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15292. {
  15293. counter = 0;
  15294. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  15295. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15296. size32_t thisSize = helper.createDefault(rowBuilder);
  15297. defaultRecord.setown(rowBuilder.finalizeRowClear(thisSize));
  15298. }
  15299. virtual void reset()
  15300. {
  15301. defaultRecord.clear();
  15302. right.clear();
  15303. left.clear();
  15304. CRoxieServerActivity::reset();
  15305. }
  15306. virtual const void * nextRow()
  15307. {
  15308. ActivityTimer t(totalCycles, timeActivities);
  15309. loop
  15310. {
  15311. right.setown(inputStream->nextRow());
  15312. if (!right)
  15313. {
  15314. bool skippedGroup = (left == NULL) && (counter > 0); //we have just skipped entire group, but shouldn't output a double null
  15315. left.clear();
  15316. counter = 0;
  15317. if (skippedGroup) continue;
  15318. return NULL;
  15319. }
  15320. try
  15321. {
  15322. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15323. unsigned outSize = helper.transform(rowBuilder, left ? left : defaultRecord, right, ++counter);
  15324. if (outSize)
  15325. {
  15326. left.setown(rowBuilder.finalizeRowClear(outSize));
  15327. processed++;
  15328. return left.getLink();
  15329. }
  15330. }
  15331. catch (IException *E)
  15332. {
  15333. throw makeWrappedException(E);
  15334. }
  15335. }
  15336. }
  15337. };
  15338. class CRoxieServerIterateActivityFactory : public CRoxieServerActivityFactory
  15339. {
  15340. public:
  15341. CRoxieServerIterateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15342. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15343. {
  15344. }
  15345. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15346. {
  15347. return new CRoxieServerIterateActivity(_ctx, this, _probeManager);
  15348. }
  15349. };
  15350. IRoxieServerActivityFactory *createRoxieServerIterateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15351. {
  15352. return new CRoxieServerIterateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15353. }
  15354. //=================================================================================
  15355. class CRoxieServerProcessActivity : public CRoxieServerActivity
  15356. {
  15357. IHThorProcessArg &helper;
  15358. OwnedConstRoxieRow curRight;
  15359. OwnedConstRoxieRow initialRight;
  15360. unsigned counter;
  15361. Owned<IEngineRowAllocator> rightRowAllocator;
  15362. public:
  15363. CRoxieServerProcessActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  15364. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorProcessArg &)basehelper)
  15365. {
  15366. counter = 0;
  15367. }
  15368. virtual bool needsAllocator() const { return true; }
  15369. virtual void onCreate(IHThorArg *_colocalParent)
  15370. {
  15371. CRoxieServerActivity::onCreate(_colocalParent);
  15372. rightRowAllocator.setown(createRowAllocator(helper.queryRightRecordSize()));
  15373. }
  15374. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15375. {
  15376. counter = 0;
  15377. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  15378. RtlDynamicRowBuilder rowBuilder(rightRowAllocator);
  15379. size32_t thisSize = helper.createInitialRight(rowBuilder);
  15380. initialRight.setown(rowBuilder.finalizeRowClear(thisSize));
  15381. curRight.set(initialRight);
  15382. }
  15383. virtual const void * nextRow()
  15384. {
  15385. ActivityTimer t(totalCycles, timeActivities);
  15386. try
  15387. {
  15388. loop
  15389. {
  15390. const void * in = inputStream->nextRow();
  15391. if (!in)
  15392. {
  15393. bool eog = (curRight != initialRight); // processed any records?
  15394. counter = 0;
  15395. curRight.set(initialRight);
  15396. if (eog)
  15397. return NULL;
  15398. in = inputStream->nextRow();
  15399. if (!in)
  15400. return NULL;
  15401. }
  15402. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15403. RtlDynamicRowBuilder rightRowBuilder(rightRowAllocator);
  15404. size32_t outSize = helper.transform(rowBuilder, rightRowBuilder, in, curRight, ++counter);
  15405. ReleaseRoxieRow(in);
  15406. if (outSize)
  15407. {
  15408. //MORE: This should be returned...
  15409. size32_t rightSize = rightRowAllocator->queryOutputMeta()->getRecordSize(rightRowBuilder.getSelf());
  15410. curRight.setown(rightRowBuilder.finalizeRowClear(rightSize));
  15411. processed++;
  15412. return rowBuilder.finalizeRowClear(outSize);
  15413. }
  15414. }
  15415. }
  15416. catch (IException *E)
  15417. {
  15418. throw makeWrappedException(E);
  15419. }
  15420. }
  15421. };
  15422. class CRoxieServerProcessActivityFactory : public CRoxieServerActivityFactory
  15423. {
  15424. public:
  15425. CRoxieServerProcessActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15426. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15427. {
  15428. }
  15429. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15430. {
  15431. return new CRoxieServerProcessActivity(_ctx, this, _probeManager);
  15432. }
  15433. };
  15434. IRoxieServerActivityFactory *createRoxieServerProcessActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15435. {
  15436. return new CRoxieServerProcessActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15437. }
  15438. //=================================================================================
  15439. class CRoxieServerGroupActivity : public CRoxieServerActivity
  15440. {
  15441. IHThorGroupArg &helper;
  15442. bool endPending;
  15443. bool eof;
  15444. bool first;
  15445. unsigned numGroups;
  15446. unsigned numGroupMax;
  15447. unsigned numProcessedLastGroup;
  15448. const void *next;
  15449. public:
  15450. CRoxieServerGroupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  15451. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorGroupArg &)basehelper)
  15452. {
  15453. next = NULL;
  15454. endPending = false;
  15455. eof = false;
  15456. first = true;
  15457. numGroups = 0;
  15458. numGroupMax = 0;
  15459. numProcessedLastGroup = 0;
  15460. }
  15461. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15462. {
  15463. endPending = false;
  15464. eof = false;
  15465. first = true;
  15466. numGroups = 0;
  15467. numGroupMax = 0;
  15468. numProcessedLastGroup = processed;
  15469. assertex(next == NULL);
  15470. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  15471. }
  15472. virtual void reset()
  15473. {
  15474. noteStatistic(StNumGroups, numGroups);
  15475. noteStatistic(StNumGroupMax, numGroupMax);
  15476. ReleaseClearRoxieRow(next);
  15477. CRoxieServerActivity::reset();
  15478. }
  15479. virtual const void * nextRow()
  15480. {
  15481. ActivityTimer t(totalCycles, timeActivities);
  15482. if (first)
  15483. {
  15484. next = inputStream->nextRow();
  15485. first = false;
  15486. }
  15487. if (eof || endPending)
  15488. {
  15489. endPending = false;
  15490. return NULL;
  15491. }
  15492. const void * prev = next;
  15493. next = inputStream->ungroupedNextRow();
  15494. if (next)
  15495. {
  15496. assertex(prev);
  15497. if (!helper.isSameGroup(prev, next))
  15498. {
  15499. noteEndOfGroup();
  15500. endPending = true;
  15501. }
  15502. }
  15503. else
  15504. {
  15505. noteEndOfGroup();
  15506. eof = true;
  15507. }
  15508. if (prev)
  15509. processed++;
  15510. return prev;
  15511. }
  15512. inline void noteEndOfGroup()
  15513. {
  15514. unsigned numThisGroup = processed - numProcessedLastGroup;
  15515. if (numThisGroup == 0)
  15516. return;
  15517. numProcessedLastGroup = processed;
  15518. if (numThisGroup > numGroupMax)
  15519. numGroupMax = numThisGroup;
  15520. numGroups++;
  15521. }
  15522. };
  15523. class CRoxieServerGroupActivityFactory : public CRoxieServerActivityFactory
  15524. {
  15525. public:
  15526. CRoxieServerGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15527. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15528. {
  15529. }
  15530. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15531. {
  15532. return new CRoxieServerGroupActivity(_ctx, this, _probeManager);
  15533. }
  15534. virtual const StatisticsMapping &queryStatsMapping() const
  15535. {
  15536. return groupStatistics;
  15537. }
  15538. };
  15539. IRoxieServerActivityFactory *createRoxieServerGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15540. {
  15541. return new CRoxieServerGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15542. }
  15543. //=================================================================================
  15544. class CRoxieServerFirstNActivity : public CRoxieServerLateStartActivity
  15545. {
  15546. unsigned __int64 limit;
  15547. unsigned __int64 skip;
  15548. unsigned doneThisGroup;
  15549. IHThorFirstNArg &helper;
  15550. public:
  15551. CRoxieServerFirstNActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  15552. : CRoxieServerLateStartActivity(_ctx, _factory, _probeManager), helper((IHThorFirstNArg &)basehelper)
  15553. {
  15554. doneThisGroup = 0;
  15555. limit = 0;
  15556. skip = 0;
  15557. }
  15558. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15559. {
  15560. doneThisGroup = 0;
  15561. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  15562. limit = helper.getLimit();
  15563. skip = helper.numToSkip();
  15564. lateStart(parentExtractSize, parentExtract, limit > 0);
  15565. if (limit + skip >= limit)
  15566. limit += skip;
  15567. }
  15568. const void * nextRow()
  15569. {
  15570. ActivityTimer t(totalCycles, timeActivities);
  15571. if (eof)
  15572. return NULL;
  15573. const void *ret;
  15574. loop
  15575. {
  15576. ret = inputStream->nextRow();
  15577. if (!ret)
  15578. {
  15579. if (meta.isGrouped())
  15580. {
  15581. if (doneThisGroup > skip)
  15582. {
  15583. doneThisGroup = 0;
  15584. return NULL;
  15585. }
  15586. doneThisGroup = 0;
  15587. }
  15588. ret = inputStream->nextRow();
  15589. if (!ret)
  15590. {
  15591. eof = true;
  15592. return NULL;
  15593. }
  15594. }
  15595. doneThisGroup++;
  15596. if (doneThisGroup > skip)
  15597. break;
  15598. ReleaseRoxieRow(ret);
  15599. }
  15600. if (doneThisGroup <= limit)
  15601. {
  15602. processed++;
  15603. return ret;
  15604. }
  15605. ReleaseRoxieRow(ret);
  15606. if (meta.isGrouped())
  15607. {
  15608. while ((ret = inputStream->nextRow()) != NULL)
  15609. ReleaseRoxieRow(ret);
  15610. doneThisGroup = 0;
  15611. }
  15612. else
  15613. eof = true;
  15614. return NULL;
  15615. }
  15616. };
  15617. class CRoxieServerFirstNActivityFactory : public CRoxieServerActivityFactory
  15618. {
  15619. public:
  15620. CRoxieServerFirstNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15621. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15622. {
  15623. }
  15624. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15625. {
  15626. return new CRoxieServerFirstNActivity(_ctx, this, _probeManager);
  15627. }
  15628. };
  15629. IRoxieServerActivityFactory *createRoxieServerFirstNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15630. {
  15631. return new CRoxieServerFirstNActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15632. }
  15633. //=================================================================================
  15634. class CRoxieServerSelectNActivity : public CRoxieServerActivity
  15635. {
  15636. bool done;
  15637. IHThorSelectNArg &helper;
  15638. public:
  15639. CRoxieServerSelectNActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  15640. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorSelectNArg &)basehelper)
  15641. {
  15642. done = false;
  15643. }
  15644. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15645. {
  15646. done = false;
  15647. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  15648. }
  15649. const void *defaultRow()
  15650. {
  15651. if (!rowAllocator)
  15652. ensureRowAllocator(); // We delay as often not needed...
  15653. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15654. size32_t thisSize = helper.createDefault(rowBuilder);
  15655. return rowBuilder.finalizeRowClear(thisSize);
  15656. }
  15657. virtual const void * nextRow()
  15658. {
  15659. ActivityTimer t(totalCycles, timeActivities);
  15660. if (done)
  15661. return NULL;
  15662. done = true;
  15663. processed++; // always going to return a row!
  15664. unsigned __int64 index = helper.getRowToSelect();
  15665. while (--index)
  15666. {
  15667. const void * next = inputStream->ungroupedNextRow();
  15668. if (!next)
  15669. return defaultRow();
  15670. ReleaseRoxieRow(next);
  15671. }
  15672. const void * next = inputStream->ungroupedNextRow();
  15673. if (!next)
  15674. next = defaultRow();
  15675. return next;
  15676. }
  15677. };
  15678. class CRoxieServerSelectNActivityFactory : public CRoxieServerActivityFactory
  15679. {
  15680. public:
  15681. CRoxieServerSelectNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15682. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15683. {
  15684. }
  15685. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15686. {
  15687. return new CRoxieServerSelectNActivity(_ctx, this, _probeManager);
  15688. }
  15689. };
  15690. IRoxieServerActivityFactory *createRoxieServerSelectNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15691. {
  15692. return new CRoxieServerSelectNActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15693. }
  15694. //=================================================================================
  15695. class CRoxieServerSelfJoinActivity : public CRoxieServerActivity
  15696. {
  15697. IHThorJoinArg &helper;
  15698. ICompare *collate;
  15699. OwnedRowArray group;
  15700. bool matchedLeft;
  15701. BoolArray matchedRight;
  15702. bool eof;
  15703. bool first;
  15704. unsigned leftIndex;
  15705. unsigned rightIndex;
  15706. unsigned rightOuterIndex;
  15707. unsigned joinLimit;
  15708. unsigned atmostLimit;
  15709. unsigned atmostsTriggered;
  15710. unsigned abortLimit;
  15711. unsigned keepLimit;
  15712. unsigned joinCounter;
  15713. bool leftOuterJoin;
  15714. bool rightOuterJoin;
  15715. bool exclude;
  15716. bool limitFail;
  15717. bool limitOnFail;
  15718. bool cloneLeft;
  15719. bool forceSpill;
  15720. OwnedConstRoxieRow defaultLeft;
  15721. OwnedConstRoxieRow defaultRight;
  15722. OwnedConstRoxieRow lhs;
  15723. Owned<IException> failingLimit;
  15724. bool failingOuterAtmost;
  15725. Owned<IEngineRowAllocator> defaultAllocator;
  15726. Owned<IRHLimitedCompareHelper> limitedhelper;
  15727. Owned<CRHDualCache> dualcache;
  15728. Owned<IGroupedInput> groupedInput;
  15729. IRowStream *dualCacheInput;
  15730. bool fillGroup()
  15731. {
  15732. group.clear();
  15733. matchedLeft = false;
  15734. matchedRight.kill();
  15735. failingOuterAtmost = false;
  15736. const void * next;
  15737. unsigned groupCount = 0;
  15738. while((next = groupedInput->nextRow()) != NULL)
  15739. {
  15740. if(groupCount==abortLimit)
  15741. {
  15742. if(limitFail)
  15743. failLimit(next);
  15744. if (ctx->queryDebugContext())
  15745. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  15746. if(limitOnFail)
  15747. {
  15748. assertex(!failingLimit);
  15749. try
  15750. {
  15751. failLimit(next);
  15752. }
  15753. catch(IException * except)
  15754. {
  15755. failingLimit.setown(except);
  15756. }
  15757. assertex(failingLimit != NULL);
  15758. group.append(next);
  15759. groupCount++;
  15760. break;
  15761. }
  15762. group.clear();
  15763. groupCount = 0;
  15764. while(next)
  15765. {
  15766. ReleaseRoxieRow(next);
  15767. next = groupedInput->nextRow();
  15768. }
  15769. }
  15770. else if(groupCount==atmostLimit)
  15771. {
  15772. atmostsTriggered++;
  15773. if(leftOuterJoin)
  15774. {
  15775. group.append(next);
  15776. groupCount++;
  15777. failingOuterAtmost = true;
  15778. break;
  15779. }
  15780. else
  15781. {
  15782. group.clear();
  15783. groupCount = 0;
  15784. while (next)
  15785. {
  15786. ReleaseRoxieRow(next);
  15787. next = groupedInput->nextRow();
  15788. }
  15789. }
  15790. }
  15791. else
  15792. {
  15793. group.append(next);
  15794. groupCount++;
  15795. }
  15796. }
  15797. if(group.ordinality()==0)
  15798. {
  15799. eof = true;
  15800. return false;
  15801. }
  15802. leftIndex = 0;
  15803. rightIndex = 0;
  15804. rightOuterIndex = 0;
  15805. joinCounter = 0;
  15806. joinLimit = keepLimit;
  15807. ForEachItemIn(idx, group)
  15808. matchedRight.append(false);
  15809. return true;
  15810. }
  15811. void failLimit(const void * next)
  15812. {
  15813. helper.onMatchAbortLimitExceeded();
  15814. CommonXmlWriter xmlwrite(XWFtrim|XWFopt );
  15815. if (!ctx->isBlind() && input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  15816. {
  15817. input->queryOutputMeta()->toXML((byte *) next, xmlwrite);
  15818. }
  15819. throw MakeStringException(ROXIE_TOO_MANY_RESULTS, "More than %d match candidates in self-join %d for row %s", abortLimit, queryId(), xmlwrite.str());
  15820. }
  15821. virtual bool needsAllocator() const { return true; }
  15822. const void *joinRecords(const void * curLeft, const void * curRight, unsigned counter, IException * except)
  15823. {
  15824. try
  15825. {
  15826. if (cloneLeft && !except)
  15827. {
  15828. LinkRoxieRow(curLeft);
  15829. return curLeft;
  15830. }
  15831. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15832. size32_t outsize = except ? helper.onFailTransform(rowBuilder, curLeft, curRight, except) : helper.transform(rowBuilder, curLeft, curRight, counter);
  15833. if (outsize)
  15834. return rowBuilder.finalizeRowClear(outsize);
  15835. else
  15836. return NULL;
  15837. }
  15838. catch (IException *E)
  15839. {
  15840. throw makeWrappedException(E);
  15841. }
  15842. }
  15843. void createDefaultLeft()
  15844. {
  15845. if (!defaultLeft)
  15846. {
  15847. if (!defaultAllocator)
  15848. defaultAllocator.setown(createRowAllocator(input->queryOutputMeta()));
  15849. RtlDynamicRowBuilder rowBuilder(defaultAllocator);
  15850. size32_t thisSize = helper.createDefaultLeft(rowBuilder);
  15851. defaultLeft.setown(rowBuilder.finalizeRowClear(thisSize));
  15852. }
  15853. }
  15854. void createDefaultRight()
  15855. {
  15856. if (!defaultRight)
  15857. {
  15858. if (!defaultAllocator)
  15859. defaultAllocator.setown(createRowAllocator(input->queryOutputMeta()));
  15860. RtlDynamicRowBuilder rowBuilder(defaultAllocator);
  15861. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  15862. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  15863. }
  15864. }
  15865. public:
  15866. CRoxieServerSelfJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _forceSpill)
  15867. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorJoinArg &)basehelper), forceSpill(_forceSpill)
  15868. {
  15869. collate = helper.queryCompareLeftRight();
  15870. eof = false;
  15871. first = true;
  15872. keepLimit = 0;
  15873. atmostLimit = 0;
  15874. atmostsTriggered = 0;
  15875. unsigned joinFlags = helper.getJoinFlags();
  15876. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  15877. rightOuterJoin = (joinFlags & JFrightouter) != 0;
  15878. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  15879. exclude = (joinFlags & JFexclude) != 0;
  15880. abortLimit = 0;
  15881. joinLimit = 0;
  15882. assertex((joinFlags & (JFfirst | JFfirstleft | JFfirstright)) == 0); // no longer supported
  15883. getLimitType(joinFlags, limitFail, limitOnFail);
  15884. if((joinFlags & JFslidingmatch) != 0)
  15885. throw MakeStringException(ROXIE_UNIMPLEMENTED_ERROR, "Internal Error: Sliding self join not supported");
  15886. failingOuterAtmost = false;
  15887. matchedLeft = false;
  15888. leftIndex = 0;
  15889. rightIndex = 0;
  15890. rightOuterIndex = 0;
  15891. joinCounter = 0;
  15892. dualCacheInput = NULL;
  15893. }
  15894. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15895. {
  15896. eof = false;
  15897. first = true;
  15898. failingLimit.clear();
  15899. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  15900. keepLimit = helper.getKeepLimit();
  15901. if(keepLimit == 0)
  15902. keepLimit = (unsigned)-1;
  15903. atmostsTriggered = 0;
  15904. atmostLimit = helper.getJoinLimit();
  15905. if(atmostLimit == 0)
  15906. atmostLimit = (unsigned)-1;
  15907. else
  15908. assertex(!rightOuterJoin);
  15909. abortLimit = helper.getMatchAbortLimit();
  15910. if (abortLimit == 0)
  15911. abortLimit = (unsigned)-1;
  15912. if (rightOuterJoin)
  15913. createDefaultLeft();
  15914. if (leftOuterJoin || limitOnFail)
  15915. createDefaultRight();
  15916. ICompare *compareLeft = helper.queryCompareLeft();
  15917. if (helper.isLeftAlreadySorted())
  15918. groupedInput.setown(createGroupedInputReader(inputStream, compareLeft));
  15919. else
  15920. {
  15921. bool isStable = (helper.getJoinFlags() & JFunstable) == 0;
  15922. RoxieSortAlgorithm sortAlgorithm;
  15923. if (forceSpill)
  15924. sortAlgorithm = isStable ? stableSpillingQuickSortAlgorithm : spillingQuickSortAlgorithm;
  15925. else
  15926. sortAlgorithm = isStable ? stableQuickSortAlgorithm : quickSortAlgorithm;
  15927. groupedInput.setown(createSortedGroupedInputReader(inputStream, compareLeft, createSortAlgorithm(sortAlgorithm, compareLeft, ctx->queryRowManager(), input->queryOutputMeta(), ctx->queryCodeContext(), tempDirectory, activityId)));
  15928. }
  15929. if ((helper.getJoinFlags() & JFlimitedprefixjoin) && helper.getJoinLimit())
  15930. { //limited match join (s[1..n])
  15931. dualcache.setown(new CRHDualCache());
  15932. dualcache->init(groupedInput);
  15933. dualCacheInput = dualcache->queryOut1();
  15934. failingOuterAtmost = false;
  15935. matchedLeft = false;
  15936. leftIndex = 0;
  15937. rightOuterIndex = 0;
  15938. joinCounter = 0;
  15939. limitedhelper.setown(createRHLimitedCompareHelper());
  15940. limitedhelper->init( helper.getJoinLimit(), dualcache->queryOut2(), collate, helper.queryPrefixCompare() );
  15941. }
  15942. }
  15943. virtual void reset()
  15944. {
  15945. if (atmostsTriggered)
  15946. noteStatistic(StNumAtmostTriggered, atmostsTriggered);
  15947. group.clear();
  15948. groupedInput.clear();
  15949. CRoxieServerActivity::reset();
  15950. defaultLeft.clear();
  15951. defaultRight.clear();
  15952. }
  15953. virtual const void * nextRow()
  15954. {
  15955. ActivityTimer t(totalCycles, timeActivities);
  15956. if (limitedhelper)
  15957. {
  15958. while(!eof) //limited match join
  15959. {
  15960. if (!group.isItem(rightIndex))
  15961. {
  15962. lhs.setown(dualCacheInput->nextRow());
  15963. if (lhs)
  15964. {
  15965. rightIndex = 0;
  15966. joinCounter = 0;
  15967. group.clear();
  15968. limitedhelper->getGroup(group,lhs);
  15969. }
  15970. else
  15971. {
  15972. eof = true;
  15973. }
  15974. }
  15975. if (group.isItem(rightIndex))
  15976. {
  15977. const void * rhs = group.item(rightIndex++);
  15978. if(helper.match(lhs, rhs))
  15979. {
  15980. const void * ret = joinRecords(lhs, rhs, ++joinCounter, NULL);
  15981. if(ret)
  15982. {
  15983. processed++;
  15984. return ret;
  15985. }
  15986. }
  15987. }
  15988. }
  15989. return NULL;
  15990. }
  15991. else
  15992. {
  15993. if (first)
  15994. {
  15995. first = false;
  15996. fillGroup();
  15997. }
  15998. while(!eof)
  15999. {
  16000. if(failingOuterAtmost)
  16001. while(group.isItem(leftIndex))
  16002. {
  16003. const void * ret = joinRecords(group.item(leftIndex++), defaultRight, 0, NULL);
  16004. if(ret)
  16005. {
  16006. processed++;
  16007. return ret;
  16008. }
  16009. }
  16010. if((joinLimit == 0) || !group.isItem(rightIndex))
  16011. {
  16012. if(leftOuterJoin && !matchedLeft && !failingLimit)
  16013. {
  16014. const void * ret = joinRecords(group.item(leftIndex), defaultRight, 0, NULL);
  16015. if(ret)
  16016. {
  16017. matchedLeft = true;
  16018. processed++;
  16019. return ret;
  16020. }
  16021. }
  16022. leftIndex++;
  16023. matchedLeft = false;
  16024. rightIndex = 0;
  16025. joinCounter = 0;
  16026. joinLimit = keepLimit;
  16027. }
  16028. if(!group.isItem(leftIndex))
  16029. {
  16030. if(failingLimit || failingOuterAtmost)
  16031. {
  16032. const void * lhs;
  16033. while((lhs = groupedInput->nextRow()) != NULL) // dualCache never active here
  16034. {
  16035. const void * ret = joinRecords(lhs, defaultRight, 0, failingLimit);
  16036. ReleaseRoxieRow(lhs);
  16037. if(ret)
  16038. {
  16039. processed++;
  16040. return ret;
  16041. }
  16042. }
  16043. failingLimit.clear();
  16044. }
  16045. if(rightOuterJoin && !failingLimit)
  16046. while(group.isItem(rightOuterIndex))
  16047. if(!matchedRight.item(rightOuterIndex++))
  16048. {
  16049. const void * ret = joinRecords(defaultLeft, group.item(rightOuterIndex-1), 0, NULL);
  16050. if(ret)
  16051. {
  16052. processed++;
  16053. return ret;
  16054. }
  16055. }
  16056. if(!fillGroup())
  16057. return NULL;
  16058. continue;
  16059. }
  16060. const void * lhs = group.item(leftIndex);
  16061. if(failingLimit)
  16062. {
  16063. leftIndex++;
  16064. const void * ret = joinRecords(lhs, defaultRight, 0, failingLimit);
  16065. if(ret)
  16066. {
  16067. processed++;
  16068. return ret;
  16069. }
  16070. }
  16071. else
  16072. {
  16073. const void * rhs = group.item(rightIndex++);
  16074. if(helper.match(lhs, rhs))
  16075. {
  16076. matchedLeft = true;
  16077. matchedRight.replace(true, rightIndex-1);
  16078. if(!exclude)
  16079. {
  16080. const void * ret = joinRecords(lhs, rhs, ++joinCounter, NULL);
  16081. if(ret)
  16082. {
  16083. processed++;
  16084. joinLimit--;
  16085. return ret;
  16086. }
  16087. }
  16088. }
  16089. }
  16090. }
  16091. return NULL;
  16092. }
  16093. }
  16094. };
  16095. class CRoxieServerSelfJoinActivityFactory : public CRoxieServerActivityFactory
  16096. {
  16097. bool forceSpill;
  16098. public:
  16099. CRoxieServerSelfJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  16100. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  16101. {
  16102. forceSpill = queryFactory.queryOptions().allSortsMaySpill || _graphNode.getPropBool("hint[@name='spill']/@value", false);;
  16103. }
  16104. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  16105. {
  16106. return new CRoxieServerSelfJoinActivity(_ctx, this, _probeManager, forceSpill);
  16107. }
  16108. virtual const StatisticsMapping &queryStatsMapping() const
  16109. {
  16110. return joinStatistics;
  16111. }
  16112. };
  16113. IRoxieServerActivityFactory *createRoxieServerSelfJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  16114. {
  16115. return new CRoxieServerSelfJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  16116. }
  16117. //=====================================================================================================
  16118. class CRoxieServerLookupJoinActivity : public CRoxieServerTwoInputActivity
  16119. {
  16120. private:
  16121. class LookupTable : public CInterface
  16122. {
  16123. public:
  16124. LookupTable(IHThorHashJoinArg &helper)
  16125. : leftRightCompare(helper.queryCompareLeftRight()), rightCompare(helper.queryCompareRight()),
  16126. leftHash(helper.queryHashLeft()), rightHash(helper.queryHashRight())
  16127. {
  16128. size = 0;
  16129. }
  16130. virtual const void *find(const void * left) const = 0;
  16131. virtual const void *findNext(const void * left) const = 0;
  16132. protected:
  16133. ICompare * leftRightCompare;
  16134. ICompare * rightCompare;
  16135. IHash * leftHash;
  16136. IHash * rightHash;
  16137. unsigned size;
  16138. };
  16139. class DedupLookupTable : public LookupTable
  16140. {
  16141. public:
  16142. DedupLookupTable(ConstPointerArray &rightRows, IHThorHashJoinArg &helper)
  16143. : LookupTable(helper)
  16144. {
  16145. size = (4*rightRows.length())/3 + 1;
  16146. table = (const void * *)calloc(size, sizeof(void *)); // This should probably be allocated from roxiemem (and size rounded up to actual available size)
  16147. ForEachItemIn(idx, rightRows)
  16148. add(rightRows.item(idx));
  16149. }
  16150. ~DedupLookupTable()
  16151. {
  16152. roxiemem::ReleaseRoxieRowArray(size, table);
  16153. free(table);
  16154. }
  16155. virtual const void *find(const void * left) const
  16156. {
  16157. unsigned index = leftHash->hash(left) % size;
  16158. unsigned start = index;
  16159. while (table[index])
  16160. {
  16161. if(leftRightCompare->docompare(left, table[index]) == 0)
  16162. return table[index];
  16163. index++;
  16164. if (index==size)
  16165. index = 0;
  16166. if (index==start)
  16167. throw MakeStringException(ROXIE_JOIN_ERROR, "Internal error in lookup join activity (hash table full on lookup)");
  16168. }
  16169. return NULL;
  16170. }
  16171. virtual const void *findNext(const void * left) const
  16172. {
  16173. return NULL;
  16174. }
  16175. protected:
  16176. void add(const void * right)
  16177. {
  16178. unsigned index = rightHash->hash(right) % size;
  16179. unsigned start = index;
  16180. while (table[index])
  16181. {
  16182. if (rightCompare->docompare(table[index], right) == 0)
  16183. {
  16184. ReleaseRoxieRow(right);
  16185. return;
  16186. }
  16187. index++;
  16188. if (index==size)
  16189. index = 0;
  16190. if (index==start)
  16191. throw MakeStringException(ROXIE_JOIN_ERROR, "Internal error in lookup join activity (hash table full on add)");
  16192. }
  16193. table[index] = right;
  16194. }
  16195. const void * * table;
  16196. };
  16197. class FewLookupTable : public LookupTable
  16198. {
  16199. public:
  16200. FewLookupTable(ConstPointerArray &rightRows, IHThorHashJoinArg &helper)
  16201. : LookupTable(helper)
  16202. {
  16203. size = (4*rightRows.length())/3 + 1;
  16204. table = (const void * *)calloc(size, sizeof(void *)); // This should probably be allocated from roxiemem
  16205. findex = fstart = BadIndex;
  16206. ForEachItemIn(idx, rightRows)
  16207. add(rightRows.item(idx));
  16208. }
  16209. ~FewLookupTable()
  16210. {
  16211. roxiemem::ReleaseRoxieRowArray(size, table);
  16212. free(table);
  16213. }
  16214. virtual const void *find(const void * left) const
  16215. {
  16216. fstart = leftHash->hash(left) % size;
  16217. findex = fstart;
  16218. return doFind(left);
  16219. }
  16220. virtual const void *findNext(const void * left) const
  16221. {
  16222. if (findex == BadIndex)
  16223. return NULL;
  16224. advance();
  16225. return doFind(left);
  16226. }
  16227. protected:
  16228. void add(const void * right)
  16229. {
  16230. unsigned start = rightHash->hash(right) % size;
  16231. unsigned index = start;
  16232. while (table[index])
  16233. {
  16234. index++;
  16235. if (index==size)
  16236. index = 0;
  16237. if (index==start)
  16238. throwUnexpected(); //table is full, should never happen
  16239. }
  16240. table[index] = right;
  16241. }
  16242. void advance() const
  16243. {
  16244. findex++;
  16245. if(findex==size)
  16246. findex = 0;
  16247. if(findex==fstart)
  16248. throw MakeStringException(ROXIE_JOIN_ERROR, "Internal error in lookup join activity (hash table full on lookup)");
  16249. }
  16250. const void *doFind(const void * left) const
  16251. {
  16252. while(table[findex])
  16253. {
  16254. if (leftRightCompare->docompare(left, table[findex]) == 0)
  16255. return table[findex];
  16256. advance();
  16257. }
  16258. findex = BadIndex;
  16259. return NULL;
  16260. }
  16261. const void * * table;
  16262. unsigned mutable fstart;
  16263. unsigned mutable findex;
  16264. static unsigned const BadIndex;
  16265. };
  16266. class ManyLookupTable : public LookupTable
  16267. {
  16268. public:
  16269. ManyLookupTable(ConstPointerArray &rightRows, IHThorHashJoinArg &helper)
  16270. : LookupTable(helper)
  16271. {
  16272. rightRows.swapWith(rowtable);
  16273. UInt64Array groups;
  16274. unsigned numRows = rowtable.length();
  16275. if (numRows)
  16276. {
  16277. unsigned groupStart = 0;
  16278. const void *groupStartRow = rowtable.item(0);
  16279. for (unsigned i=1; i < numRows; i++)
  16280. {
  16281. const void *thisRow = rowtable.item(i);
  16282. if (rightCompare->docompare(groupStartRow, thisRow))
  16283. {
  16284. groups.append(makeint64(groupStart, i-groupStart));
  16285. groupStart = i;
  16286. groupStartRow = thisRow;
  16287. }
  16288. }
  16289. groups.append(makeint64(groupStart, numRows-groupStart));
  16290. }
  16291. size = (4*groups.length())/3 + 1;
  16292. table = (__uint64 *) calloc(size, sizeof(__uint64)); // This should probably be allocated from roxiemem
  16293. ForEachItemIn(idx, groups)
  16294. {
  16295. unsigned __int64 group = groups.item(idx);
  16296. unsigned groupstart = high(group);
  16297. const void *row = rowtable.item(groupstart);
  16298. add(row, group);
  16299. }
  16300. }
  16301. ~ManyLookupTable()
  16302. {
  16303. roxiemem::ReleaseRoxieRows(rowtable);
  16304. free(table);
  16305. }
  16306. void add(const void *row, unsigned __int64 group)
  16307. {
  16308. unsigned start = rightHash->hash(row) % size;
  16309. unsigned index = start;
  16310. while (table[index])
  16311. {
  16312. index++;
  16313. if (index==size)
  16314. index = 0;
  16315. if (index==start)
  16316. throwUnexpected(); //table is full, should never happen
  16317. }
  16318. table[index] = group;
  16319. }
  16320. virtual const void *find(const void * left) const
  16321. {
  16322. unsigned index = leftHash->hash(left) % size;
  16323. unsigned start = index;
  16324. while (table[index])
  16325. {
  16326. __uint64 group = table[index];
  16327. currentMatch = high(group);
  16328. const void *right = rowtable.item(currentMatch);
  16329. if (leftRightCompare->docompare(left, right) == 0)
  16330. {
  16331. currentMatch++;
  16332. matchCount = low(group) - 1;
  16333. return right;
  16334. }
  16335. index++;
  16336. if (index==size)
  16337. index = 0;
  16338. if (index==start)
  16339. throw MakeStringException(ROXIE_JOIN_ERROR, "Internal error in lookup join activity (hash table full on lookup)");
  16340. }
  16341. matchCount = 0;
  16342. return NULL;
  16343. }
  16344. virtual const void *findNext(const void * left) const
  16345. {
  16346. if (!matchCount)
  16347. return NULL;
  16348. matchCount--;
  16349. return rowtable.item(currentMatch++);
  16350. }
  16351. protected:
  16352. __uint64 *table;
  16353. ConstPointerArray rowtable;
  16354. mutable unsigned currentMatch = 0;
  16355. mutable unsigned matchCount = 0;
  16356. };
  16357. IHThorHashJoinArg &helper;
  16358. bool leftOuterJoin;
  16359. bool exclude;
  16360. bool eog;
  16361. bool many;
  16362. bool dedupRHS;
  16363. bool useFewTable;
  16364. bool matchedGroup;
  16365. const void *left;
  16366. OwnedConstRoxieRow defaultRight;
  16367. Owned<LookupTable> table;
  16368. unsigned keepLimit;
  16369. unsigned atmostLimit;
  16370. unsigned atmostsTriggered;
  16371. unsigned limitLimit;
  16372. unsigned joinCounter;
  16373. bool limitFail;
  16374. bool limitOnFail;
  16375. bool hasGroupLimit;
  16376. bool isSmartJoin;
  16377. unsigned keepCount;
  16378. bool gotMatch;
  16379. bool cloneLeft;
  16380. ConstPointerArray rightGroup;
  16381. aindex_t rightGroupIndex;
  16382. Owned<IException> failingLimit;
  16383. ConstPointerArray filteredRight;
  16384. ThorActivityKind activityKind;
  16385. Owned<IEngineRowAllocator> defaultRightAllocator;
  16386. void createDefaultRight()
  16387. {
  16388. if (!defaultRight)
  16389. {
  16390. if (!defaultRightAllocator)
  16391. defaultRightAllocator.setown(createRowAllocator(input1->queryOutputMeta()));
  16392. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  16393. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  16394. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  16395. }
  16396. }
  16397. public:
  16398. CRoxieServerLookupJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _useFewTable)
  16399. : CRoxieServerTwoInputActivity(_ctx, _factory, _probeManager), helper((IHThorHashJoinArg &)basehelper), useFewTable(_useFewTable)
  16400. {
  16401. unsigned joinFlags = helper.getJoinFlags();
  16402. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  16403. assertex((joinFlags & JFrightouter) == 0);
  16404. exclude = (joinFlags & JFexclude) != 0;
  16405. many = (joinFlags & JFmanylookup) != 0;
  16406. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  16407. dedupRHS = (joinFlags & (JFmanylookup | JFmatchrequired | JFtransformMaySkip)) == 0; // optimisation: can implicitly dedup RHS unless is many lookup, or match required, or transform may skip
  16408. left = NULL;
  16409. activityKind = factory->getKind();
  16410. eog = false;
  16411. matchedGroup = false;
  16412. gotMatch = false;
  16413. keepLimit = 0;
  16414. keepCount = 0;
  16415. joinCounter = 0;
  16416. atmostLimit = 0;
  16417. atmostsTriggered = 0;
  16418. limitLimit = 0;
  16419. rightGroupIndex = 0;
  16420. hasGroupLimit = false;
  16421. isSmartJoin = (joinFlags & JFsmart) != 0;
  16422. getLimitType(joinFlags, limitFail, limitOnFail);
  16423. }
  16424. void loadRight()
  16425. {
  16426. ConstPointerArray rightset;
  16427. try
  16428. {
  16429. const void * next;
  16430. while(true)
  16431. {
  16432. next = inputStream1->ungroupedNextRow();
  16433. if(!next)
  16434. break;
  16435. rightset.append(next);
  16436. }
  16437. if (!dedupRHS)
  16438. {
  16439. if (useFewTable)
  16440. {
  16441. table.setown(new FewLookupTable(rightset, helper)); // NOTE - takes ownership of rightset
  16442. }
  16443. else
  16444. {
  16445. if (!helper.isRightAlreadySorted())
  16446. {
  16447. if (helper.getJoinFlags() & JFunstable)
  16448. {
  16449. qsortvec(const_cast<void * *>(rightset.getArray()), rightset.ordinality(), *helper.queryCompareRight());
  16450. }
  16451. else
  16452. {
  16453. unsigned rightord = rightset.ordinality();
  16454. MemoryAttr tempAttr(rightord*sizeof(void **)); // Temp storage for stable sort. This should probably be allocated from roxiemem
  16455. void **temp = (void **) tempAttr.bufferBase();
  16456. void **_rows = const_cast<void * *>(rightset.getArray());
  16457. msortvecstableinplace(_rows, rightord, *helper.queryCompareRight(), temp);
  16458. }
  16459. }
  16460. table.setown(new ManyLookupTable(rightset, helper)); // NOTE - takes ownership of rightset
  16461. }
  16462. }
  16463. else
  16464. {
  16465. table.setown(new DedupLookupTable(rightset, helper)); // NOTE - takes ownership of rightset
  16466. }
  16467. }
  16468. catch (...)
  16469. {
  16470. roxiemem::ReleaseRoxieRows(rightset);
  16471. throw;
  16472. }
  16473. };
  16474. virtual void reset()
  16475. {
  16476. if (atmostsTriggered)
  16477. noteStatistic(StNumAtmostTriggered, atmostsTriggered);
  16478. CRoxieServerTwoInputActivity::reset();
  16479. ReleaseClearRoxieRow(left);
  16480. defaultRight.clear();
  16481. table.clear();
  16482. }
  16483. virtual bool needsAllocator() const { return true; }
  16484. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16485. {
  16486. eog = false;
  16487. matchedGroup = false;
  16488. left = NULL;
  16489. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  16490. keepLimit = helper.getKeepLimit();
  16491. if(keepLimit==0) keepLimit = static_cast<unsigned>(-1);
  16492. atmostsTriggered = 0;
  16493. atmostLimit = helper.getJoinLimit();
  16494. limitLimit = helper.getMatchAbortLimit();
  16495. hasGroupLimit = ((atmostLimit > 0) || (limitLimit > 0));
  16496. if(atmostLimit==0) atmostLimit = static_cast<unsigned>(-1);
  16497. if(limitLimit==0) limitLimit = static_cast<unsigned>(-1);
  16498. getLimitType(helper.getJoinFlags(), limitFail, limitOnFail);
  16499. switch (activityKind)
  16500. {
  16501. case TAKlookupjoin:
  16502. case TAKlookupdenormalizegroup:
  16503. case TAKsmartjoin:
  16504. case TAKsmartdenormalizegroup:
  16505. if (leftOuterJoin)
  16506. createDefaultRight();
  16507. break;
  16508. }
  16509. if (limitOnFail)
  16510. createDefaultRight();
  16511. }
  16512. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  16513. {
  16514. if (!idx && (helper.getJoinFlags() & JFparallel) != 0)
  16515. {
  16516. puller.setown(new CRoxieServerReadAheadInput(ctx, ctx->queryOptions().parallelJoinPreload));
  16517. puller->setInput(0, _sourceIdx, _in);
  16518. _in = puller;
  16519. _sourceIdx = 0;
  16520. }
  16521. CRoxieServerTwoInputActivity::setInput(idx, _sourceIdx, _in);
  16522. }
  16523. virtual const void * nextRow()
  16524. {
  16525. ActivityTimer t(totalCycles, timeActivities);
  16526. if(!table)
  16527. loadRight();
  16528. switch (activityKind)
  16529. {
  16530. case TAKlookupjoin:
  16531. case TAKsmartjoin:
  16532. return nextRowJoin();
  16533. case TAKlookupdenormalize:
  16534. case TAKlookupdenormalizegroup:
  16535. case TAKsmartdenormalize:
  16536. case TAKsmartdenormalizegroup:
  16537. return nextRowDenormalize();
  16538. }
  16539. throwUnexpected();
  16540. }
  16541. private:
  16542. const void * nextRowJoin()
  16543. {
  16544. if(!table)
  16545. loadRight();
  16546. while(true)
  16547. {
  16548. const void * right = NULL;
  16549. if(!left)
  16550. {
  16551. left = inputStream->nextRow();
  16552. keepCount = keepLimit;
  16553. joinCounter = 0;
  16554. if(!left)
  16555. {
  16556. if (isSmartJoin)
  16557. left = inputStream->nextRow();
  16558. if (!left)
  16559. {
  16560. if(matchedGroup || eog)
  16561. {
  16562. matchedGroup = false;
  16563. eog = true;
  16564. return NULL;
  16565. }
  16566. eog = true;
  16567. continue;
  16568. }
  16569. }
  16570. eog = false;
  16571. gotMatch = false;
  16572. right = getRightFirst();
  16573. }
  16574. else
  16575. right = getRightNext();
  16576. const void * ret = NULL;
  16577. if(failingLimit)
  16578. {
  16579. ret = joinException(left, failingLimit);
  16580. }
  16581. else
  16582. {
  16583. while(right)
  16584. {
  16585. if(helper.match(left, right))
  16586. {
  16587. gotMatch = true;
  16588. if(exclude)
  16589. break;
  16590. ret = joinRecords(left, right, ++joinCounter);
  16591. if(ret)
  16592. {
  16593. processed++;
  16594. break;
  16595. }
  16596. }
  16597. right = getRightNext();
  16598. ret = NULL;
  16599. }
  16600. if(leftOuterJoin && !gotMatch)
  16601. {
  16602. ret = joinRecords(left, defaultRight, 0);
  16603. gotMatch = true;
  16604. }
  16605. }
  16606. if(ret)
  16607. {
  16608. matchedGroup = true;
  16609. processed++;
  16610. if(!many || (--keepCount == 0) || failingLimit)
  16611. {
  16612. ReleaseClearRoxieRow(left);
  16613. failingLimit.clear();
  16614. }
  16615. return ret;
  16616. }
  16617. ReleaseClearRoxieRow(left);
  16618. }
  16619. }
  16620. const void * nextRowDenormalize()
  16621. {
  16622. while(true)
  16623. {
  16624. left = inputStream->nextRow();
  16625. if(!left)
  16626. {
  16627. if (!matchedGroup || isSmartJoin)
  16628. left = inputStream->nextRow();
  16629. if (!left)
  16630. {
  16631. matchedGroup = false;
  16632. return NULL;
  16633. }
  16634. }
  16635. gotMatch = false;
  16636. const void * right = getRightFirst();
  16637. const void * ret = NULL;
  16638. if (failingLimit)
  16639. ret = joinException(left, failingLimit);
  16640. else if (activityKind == TAKlookupdenormalize || activityKind == TAKsmartdenormalize)
  16641. {
  16642. OwnedConstRoxieRow newLeft;
  16643. newLeft.set(left);
  16644. unsigned rowSize = 0;
  16645. unsigned leftCount = 0;
  16646. keepCount = keepLimit;
  16647. while (right)
  16648. {
  16649. try
  16650. {
  16651. if (helper.match(left, right))
  16652. {
  16653. gotMatch = true;
  16654. if (exclude)
  16655. break;
  16656. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16657. unsigned thisSize = helper.transform(rowBuilder, newLeft, right, ++leftCount);
  16658. if (thisSize)
  16659. {
  16660. rowSize = thisSize;
  16661. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  16662. }
  16663. if(!many || (--keepCount == 0))
  16664. break;
  16665. }
  16666. right = getRightNext();
  16667. }
  16668. catch (IException *E)
  16669. {
  16670. throw makeWrappedException(E);
  16671. }
  16672. }
  16673. if (rowSize)
  16674. ret = newLeft.getClear();
  16675. else if (leftOuterJoin && !gotMatch)
  16676. {
  16677. ret = left;
  16678. left = NULL;
  16679. }
  16680. }
  16681. else
  16682. {
  16683. filteredRight.kill();
  16684. keepCount = keepLimit;
  16685. while (right)
  16686. {
  16687. if (helper.match(left, right))
  16688. {
  16689. gotMatch = true;
  16690. if(exclude)
  16691. break;
  16692. filteredRight.append(right);
  16693. if(!many || (--keepCount == 0))
  16694. break;
  16695. }
  16696. right = getRightNext();
  16697. }
  16698. if((filteredRight.ordinality() > 0) || (leftOuterJoin && !gotMatch))
  16699. ret = denormalizeRecords(left, filteredRight);
  16700. filteredRight.kill();
  16701. }
  16702. ReleaseRoxieRow(left);
  16703. left = NULL;
  16704. failingLimit.clear();
  16705. if(ret)
  16706. {
  16707. matchedGroup = true;
  16708. processed++;
  16709. return ret;
  16710. }
  16711. }
  16712. }
  16713. const void * joinRecords(const void * left, const void * right, unsigned counter)
  16714. {
  16715. if (cloneLeft)
  16716. {
  16717. LinkRoxieRow(left);
  16718. return left;
  16719. }
  16720. try
  16721. {
  16722. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16723. unsigned outSize = helper.transform(rowBuilder, left, right, counter);
  16724. if (outSize)
  16725. return rowBuilder.finalizeRowClear(outSize);
  16726. else
  16727. return NULL;
  16728. }
  16729. catch (IException *E)
  16730. {
  16731. throw makeWrappedException(E);
  16732. }
  16733. }
  16734. const void * joinException(const void * left, IException * except)
  16735. {
  16736. try
  16737. {
  16738. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16739. unsigned outSize = helper.onFailTransform(rowBuilder, left, defaultRight, except);
  16740. if (outSize)
  16741. return rowBuilder.finalizeRowClear(outSize);
  16742. else
  16743. return NULL;
  16744. }
  16745. catch (IException *E)
  16746. {
  16747. throw makeWrappedException(E);
  16748. }
  16749. }
  16750. const void * denormalizeRecords(const void * left, ConstPointerArray & rows)
  16751. {
  16752. try
  16753. {
  16754. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16755. unsigned numRows = rows.ordinality();
  16756. const void * right = numRows ? rows.item(0) : defaultRight.get();
  16757. unsigned outSize = helper.transform(rowBuilder, left, right, numRows, (const void * *)rows.getArray());
  16758. if (outSize)
  16759. return rowBuilder.finalizeRowClear(outSize);
  16760. else
  16761. return NULL;
  16762. }
  16763. catch (IException *E)
  16764. {
  16765. throw makeWrappedException(E);
  16766. }
  16767. }
  16768. const void * getRightFirst() { if(hasGroupLimit) return fillRightGroup(); else return table->find(left); }
  16769. const void * getRightNext() { if(hasGroupLimit) return readRightGroup(); else return table->findNext(left); }
  16770. const void * readRightGroup() { if(rightGroup.isItem(rightGroupIndex)) return rightGroup.item(rightGroupIndex++); else return NULL; }
  16771. const void *fillRightGroup()
  16772. {
  16773. rightGroup.kill();
  16774. for(const void * right = table->find(left); right; right = table->findNext(left))
  16775. {
  16776. rightGroup.append(right);
  16777. if(rightGroup.ordinality() > limitLimit)
  16778. {
  16779. if(limitFail)
  16780. failLimit();
  16781. gotMatch = true;
  16782. if (ctx->queryDebugContext())
  16783. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  16784. if(limitOnFail)
  16785. {
  16786. assertex(!failingLimit);
  16787. try
  16788. {
  16789. failLimit();
  16790. }
  16791. catch(IException * e)
  16792. {
  16793. failingLimit.setown(e);
  16794. }
  16795. assertex(failingLimit != NULL);
  16796. }
  16797. else
  16798. {
  16799. rightGroup.kill();
  16800. }
  16801. break;
  16802. }
  16803. if(rightGroup.ordinality() > atmostLimit)
  16804. {
  16805. atmostsTriggered++;
  16806. rightGroup.kill();
  16807. break;
  16808. }
  16809. }
  16810. rightGroupIndex = 0;
  16811. return readRightGroup();
  16812. }
  16813. void failLimit()
  16814. {
  16815. helper.onMatchAbortLimitExceeded();
  16816. CommonXmlWriter xmlwrite(XWFtrim|XWFopt );
  16817. if(!ctx->isBlind() && input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  16818. {
  16819. input->queryOutputMeta()->toXML(static_cast<const unsigned char *>(left), xmlwrite);
  16820. }
  16821. throw MakeStringException(ROXIE_TOO_MANY_RESULTS, "More than %u match candidates in join %d for row %s", limitLimit, queryId(), xmlwrite.str());
  16822. }
  16823. };
  16824. unsigned const CRoxieServerLookupJoinActivity::FewLookupTable::BadIndex(static_cast<unsigned>(-1));
  16825. class CRoxieServerLookupJoinActivityFactory : public CRoxieServerJoinActivityFactory
  16826. {
  16827. public:
  16828. CRoxieServerLookupJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  16829. : CRoxieServerJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  16830. {
  16831. Owned<IHThorHashJoinArg> helper = (IHThorHashJoinArg *) helperFactory();
  16832. useFewTable = _graphNode.getPropBool("hint[@name='usefewtable']/@value", false);
  16833. if((helper->getJoinFlags() & (JFfirst | JFfirstleft | JFfirstright | JFslidingmatch)) != 0)
  16834. throw MakeStringException(ROXIE_INVALID_FLAGS, "Invalid flags for lookup join activity"); // code generator should never create such an activity
  16835. }
  16836. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  16837. {
  16838. return new CRoxieServerLookupJoinActivity(_ctx, this, _probeManager, useFewTable);
  16839. }
  16840. virtual const StatisticsMapping &queryStatsMapping() const
  16841. {
  16842. return joinStatistics;
  16843. }
  16844. protected:
  16845. bool useFewTable;
  16846. };
  16847. IRoxieServerActivityFactory *createRoxieServerLookupJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  16848. {
  16849. return new CRoxieServerLookupJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  16850. }
  16851. //=====================================================================================================
  16852. class CRoxieServerAllJoinActivity : public CRoxieServerTwoInputActivity
  16853. {
  16854. private:
  16855. IHThorAllJoinArg &helper;
  16856. bool leftOuterJoin;
  16857. bool rightOuterJoin;
  16858. bool exclude;
  16859. OwnedConstRoxieRow defaultRight;
  16860. OwnedConstRoxieRow defaultLeft;
  16861. Owned<IEngineRowAllocator> defaultRightAllocator;
  16862. Owned<IEngineRowAllocator> defaultLeftAllocator;
  16863. const void *left;
  16864. unsigned countForLeft;
  16865. ConstPointerArray rightset;
  16866. BoolArray matchedRight; // MORE - could use a bitset...
  16867. unsigned keepLimit;
  16868. bool started;
  16869. bool eog;
  16870. bool eos;
  16871. bool matchedLeft;
  16872. bool matchedGroup;
  16873. bool leftIsGrouped;
  16874. bool cloneLeft;
  16875. unsigned rightIndex;
  16876. unsigned joinCounter;
  16877. unsigned rightOrdinality;
  16878. ThorActivityKind activityKind;
  16879. ConstPointerArray filteredRight;
  16880. void createDefaultLeft()
  16881. {
  16882. if (!defaultLeft)
  16883. {
  16884. if (!defaultLeftAllocator)
  16885. defaultLeftAllocator.setown(createRowAllocator(input->queryOutputMeta()));
  16886. RtlDynamicRowBuilder rowBuilder(defaultLeftAllocator);
  16887. size32_t thisSize = helper.createDefaultLeft(rowBuilder);
  16888. defaultLeft.setown(rowBuilder.finalizeRowClear(thisSize));
  16889. }
  16890. }
  16891. void createDefaultRight()
  16892. {
  16893. if (!defaultRight)
  16894. {
  16895. if (!defaultRightAllocator)
  16896. defaultRightAllocator.setown(createRowAllocator(input1->queryOutputMeta()));
  16897. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  16898. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  16899. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  16900. }
  16901. }
  16902. public:
  16903. CRoxieServerAllJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  16904. : CRoxieServerTwoInputActivity(_ctx, _factory, _probeManager), helper((IHThorAllJoinArg &)basehelper)
  16905. {
  16906. unsigned joinFlags = helper.getJoinFlags();
  16907. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  16908. rightOuterJoin = (joinFlags & JFrightouter) != 0;
  16909. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  16910. keepLimit = (unsigned) -1;
  16911. exclude = (joinFlags & JFexclude) != 0;
  16912. left = NULL;
  16913. started = true;
  16914. eog = false;
  16915. eos = false;
  16916. matchedLeft = false;
  16917. matchedGroup = false;
  16918. activityKind = factory->getKind();
  16919. rightIndex = 0;
  16920. rightOrdinality = 0;
  16921. leftIsGrouped = false;
  16922. countForLeft = 0;
  16923. joinCounter = 0;
  16924. }
  16925. virtual void reset()
  16926. {
  16927. defaultRight.clear();
  16928. defaultLeft.clear();
  16929. ReleaseRoxieRows(rightset);
  16930. matchedRight.kill();
  16931. CRoxieServerTwoInputActivity::reset();
  16932. }
  16933. virtual bool needsAllocator() const { return true; }
  16934. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16935. {
  16936. eog = false;
  16937. eos = false;
  16938. matchedLeft = false;
  16939. matchedGroup = false;
  16940. started = false;
  16941. left = NULL;
  16942. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  16943. keepLimit = helper.getKeepLimit();
  16944. if(keepLimit==0)
  16945. keepLimit = (unsigned) -1;
  16946. countForLeft = keepLimit;
  16947. joinCounter = 0;
  16948. leftIsGrouped = input->queryOutputMeta()->isGrouped();
  16949. if((activityKind==TAKalljoin || activityKind==TAKalldenormalizegroup) && leftOuterJoin)
  16950. createDefaultRight();
  16951. if(rightOuterJoin)
  16952. createDefaultLeft();
  16953. }
  16954. void loadRight()
  16955. {
  16956. const void * next;
  16957. while(true)
  16958. {
  16959. next = inputStream1->ungroupedNextRow();
  16960. if(!next)
  16961. break;
  16962. rightset.append(next);
  16963. matchedRight.append(false);
  16964. }
  16965. rightIndex = 0;
  16966. joinCounter = 0;
  16967. rightOrdinality = rightset.ordinality();
  16968. }
  16969. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  16970. {
  16971. if (!idx && (helper.getJoinFlags() & JFparallel) != 0)
  16972. {
  16973. puller.setown(new CRoxieServerReadAheadInput(ctx, ctx->queryOptions().parallelJoinPreload));
  16974. puller->setInput(0, _sourceIdx, _in);
  16975. _in = puller;
  16976. _sourceIdx = 0;
  16977. }
  16978. CRoxieServerTwoInputActivity::setInput(idx, _sourceIdx, _in);
  16979. }
  16980. const void * joinRecords(const void * left, const void * right, unsigned counter)
  16981. {
  16982. // MORE - could share some code with lookup join
  16983. if (cloneLeft)
  16984. {
  16985. LinkRoxieRow(left);
  16986. return left;
  16987. }
  16988. try
  16989. {
  16990. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16991. unsigned outSize = helper.transform(rowBuilder, left, right, counter);
  16992. if (outSize)
  16993. return rowBuilder.finalizeRowClear(outSize);
  16994. else
  16995. return NULL;
  16996. }
  16997. catch (IException *E)
  16998. {
  16999. throw makeWrappedException(E);
  17000. }
  17001. }
  17002. const void * denormalizeRecords(const void * curLeft, ConstPointerArray & rows)
  17003. {
  17004. try
  17005. {
  17006. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17007. unsigned numRows = rows.ordinality();
  17008. const void * right = numRows ? rows.item(0) : defaultRight.get();
  17009. unsigned outSize = helper.transform(rowBuilder, curLeft, right, numRows, rows.getArray());
  17010. if (outSize)
  17011. return rowBuilder.finalizeRowClear(outSize);
  17012. else
  17013. return NULL;
  17014. }
  17015. catch (IException *E)
  17016. {
  17017. throw makeWrappedException(E);
  17018. }
  17019. }
  17020. virtual const void *nextRow()
  17021. {
  17022. ActivityTimer t(totalCycles, timeActivities);
  17023. if(!started)
  17024. {
  17025. started = true;
  17026. left = inputStream->nextRow();
  17027. matchedLeft = false;
  17028. countForLeft = keepLimit;
  17029. joinCounter = 0;
  17030. if(left == NULL)
  17031. {
  17032. eos = true;
  17033. return NULL;
  17034. }
  17035. loadRight();
  17036. }
  17037. const void * ret;
  17038. const void * right;
  17039. if(eos)
  17040. return NULL;
  17041. while(true)
  17042. {
  17043. ret = NULL;
  17044. if((rightIndex == rightOrdinality) || (countForLeft==0))
  17045. {
  17046. if(leftOuterJoin && left && !matchedLeft)
  17047. {
  17048. switch(activityKind)
  17049. {
  17050. case TAKalljoin:
  17051. ret = joinRecords(left, defaultRight, 0);
  17052. break;
  17053. case TAKalldenormalize:
  17054. ret = left;
  17055. left = NULL;
  17056. break;
  17057. case TAKalldenormalizegroup:
  17058. filteredRight.kill();
  17059. ret = denormalizeRecords(left, filteredRight);
  17060. break;
  17061. default:
  17062. throwUnexpected();
  17063. }
  17064. }
  17065. rightIndex = 0;
  17066. joinCounter = 0;
  17067. ReleaseRoxieRow(left);
  17068. left = NULL;
  17069. if(ret)
  17070. {
  17071. matchedGroup = true;
  17072. processed++;
  17073. return ret;
  17074. }
  17075. }
  17076. if(!left)
  17077. {
  17078. left = inputStream->nextRow();
  17079. matchedLeft = false;
  17080. countForLeft = keepLimit;
  17081. joinCounter = 0;
  17082. }
  17083. if(!left)
  17084. {
  17085. if(eog)
  17086. {
  17087. eos = true;
  17088. matchedGroup = false;
  17089. return NULL;
  17090. }
  17091. eog = true;
  17092. if (matchedGroup && leftIsGrouped)
  17093. {
  17094. matchedGroup = false;
  17095. return NULL;
  17096. }
  17097. matchedGroup = false;
  17098. continue;
  17099. }
  17100. eog = false;
  17101. switch(activityKind)
  17102. {
  17103. case TAKalljoin:
  17104. while(rightIndex < rightOrdinality)
  17105. {
  17106. right = rightset.item(rightIndex);
  17107. if(helper.match(left, right))
  17108. {
  17109. matchedLeft = true;
  17110. matchedRight.replace(true, rightIndex);
  17111. if(!exclude)
  17112. ret = joinRecords(left, right, ++joinCounter);
  17113. }
  17114. rightIndex++;
  17115. if(ret)
  17116. {
  17117. countForLeft--;
  17118. matchedGroup = true;
  17119. processed++;
  17120. return ret;
  17121. }
  17122. }
  17123. break;
  17124. case TAKalldenormalize:
  17125. {
  17126. OwnedConstRoxieRow newLeft;
  17127. newLeft.set(left);
  17128. unsigned rowSize = 0;
  17129. unsigned leftCount = 0;
  17130. while((rightIndex < rightOrdinality) && countForLeft)
  17131. {
  17132. right = rightset.item(rightIndex);
  17133. if(helper.match(left, right))
  17134. {
  17135. matchedLeft = true;
  17136. matchedRight.replace(true, rightIndex);
  17137. if(!exclude)
  17138. {
  17139. try
  17140. {
  17141. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17142. unsigned thisSize = helper.transform(rowBuilder, newLeft, right, ++leftCount);
  17143. if(thisSize)
  17144. {
  17145. rowSize = thisSize;
  17146. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  17147. --countForLeft;
  17148. }
  17149. }
  17150. catch (IException *e)
  17151. {
  17152. throw makeWrappedException(e);
  17153. }
  17154. }
  17155. }
  17156. rightIndex++;
  17157. }
  17158. if(rowSize)
  17159. {
  17160. processed++;
  17161. return newLeft.getClear();
  17162. }
  17163. }
  17164. break;
  17165. case TAKalldenormalizegroup:
  17166. filteredRight.kill();
  17167. while((rightIndex < rightOrdinality) && countForLeft)
  17168. {
  17169. right = rightset.item(rightIndex);
  17170. if(helper.match(left, right))
  17171. {
  17172. matchedLeft = true;
  17173. matchedRight.replace(true, rightIndex);
  17174. filteredRight.append(right);
  17175. --countForLeft;
  17176. }
  17177. ++rightIndex;
  17178. }
  17179. if(!exclude && filteredRight.ordinality())
  17180. {
  17181. ret = denormalizeRecords(left, filteredRight);
  17182. filteredRight.kill();
  17183. if(ret)
  17184. {
  17185. processed++;
  17186. return ret;
  17187. }
  17188. }
  17189. break;
  17190. default:
  17191. throwUnexpected();
  17192. }
  17193. }
  17194. }
  17195. };
  17196. class CRoxieServerAllJoinActivityFactory : public CRoxieServerJoinActivityFactory
  17197. {
  17198. public:
  17199. CRoxieServerAllJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17200. : CRoxieServerJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  17201. {
  17202. Owned<IHThorAllJoinArg> helper = (IHThorAllJoinArg *) helperFactory();
  17203. if((helper->getJoinFlags() & (JFfirst | JFfirstleft | JFfirstright)) != 0)
  17204. throw MakeStringException(ROXIE_INVALID_FLAGS, "Invalid flags for join all activity"); // code generator should never create such an activity
  17205. }
  17206. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  17207. {
  17208. return new CRoxieServerAllJoinActivity(_ctx, this, _probeManager);
  17209. }
  17210. virtual const StatisticsMapping &queryStatsMapping() const
  17211. {
  17212. return joinStatistics;
  17213. }
  17214. };
  17215. IRoxieServerActivityFactory *createRoxieServerAllJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17216. {
  17217. return new CRoxieServerAllJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  17218. }
  17219. //=====================================================================================================
  17220. class CRoxieServerTopNActivity : public CRoxieServerLateStartActivity
  17221. {
  17222. unsigned limit;
  17223. bool hasBest;
  17224. bool eoi;
  17225. const void **sorted;
  17226. unsigned sortedCount;
  17227. unsigned curIndex;
  17228. IHThorTopNArg &helper;
  17229. ICompare &compare;
  17230. public:
  17231. CRoxieServerTopNActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17232. : CRoxieServerLateStartActivity(_ctx, _factory, _probeManager), helper((IHThorTopNArg &)basehelper), compare(*helper.queryCompare())
  17233. {
  17234. sorted = NULL;
  17235. sortedCount = 0;
  17236. curIndex = 0;
  17237. limit = 0;
  17238. eoi = false;
  17239. hasBest = false;
  17240. }
  17241. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17242. {
  17243. assertex(sorted == NULL);
  17244. sortedCount = 0;
  17245. curIndex = 0;
  17246. eoi = false;
  17247. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  17248. limit = (unsigned) helper.getLimit();
  17249. hasBest = helper.hasBest();
  17250. lateStart(parentExtractSize, parentExtract, limit > 0);
  17251. // MORE - should we use an expanding array instead?
  17252. if (limit > 0)
  17253. sorted = (const void **) ctx->queryRowManager().allocate((limit+1) * sizeof(const void *), activityId);
  17254. }
  17255. virtual void reset()
  17256. {
  17257. if (sorted)
  17258. {
  17259. roxiemem::ReleaseRoxieRowRange(sorted, curIndex, sortedCount);
  17260. curIndex = 0;
  17261. sortedCount = 0;
  17262. ReleaseRoxieRow(sorted);
  17263. sorted = NULL;
  17264. }
  17265. CRoxieServerLateStartActivity::reset();
  17266. }
  17267. bool abortEarly()
  17268. {
  17269. if (hasBest && (sortedCount == limit))
  17270. {
  17271. int compare = helper.compareBest(sorted[sortedCount-1]);
  17272. if (compare == 0)
  17273. {
  17274. if (meta.isGrouped())
  17275. {
  17276. //MORE: This would be more efficient if we had a away of skipping to the end of the incoming group.
  17277. const void * next;
  17278. while ((next = inputStream->nextRow()) != NULL)
  17279. ReleaseRoxieRow(next);
  17280. }
  17281. else
  17282. eoi = true;
  17283. return true;
  17284. }
  17285. //This only checks the lowest element - we could check all elements inserted, but it would increase the number of compares
  17286. if (compare < 0)
  17287. throw MakeStringException(ROXIE_TOPN_ROW_ERROR, "TOPN: row found that exceeds the best value");
  17288. }
  17289. return false;
  17290. }
  17291. void getSorted()
  17292. {
  17293. curIndex = 0;
  17294. sortedCount = 0;
  17295. if(eoi)
  17296. return;
  17297. const void * next;
  17298. while ((next = inputStream->nextRow()) != NULL)
  17299. {
  17300. if (sortedCount < limit)
  17301. {
  17302. binary_vec_insert_stable(next, sorted, sortedCount, compare);
  17303. sortedCount++;
  17304. if(abortEarly())
  17305. return;
  17306. }
  17307. else
  17308. {
  17309. if(limit && compare.docompare(sorted[sortedCount-1], next) > 0) // MORE - if stability is an issue, need to consider whether this should be > or >=
  17310. {
  17311. binary_vec_insert_stable(next, sorted, sortedCount, compare); // MORE - not sure this is stable!
  17312. ReleaseRoxieRow(sorted[sortedCount]);
  17313. if(abortEarly())
  17314. return;
  17315. }
  17316. else
  17317. {
  17318. ReleaseRoxieRow(next); // do not bother with insertion sort if we know next will fall off the end
  17319. }
  17320. }
  17321. }
  17322. }
  17323. virtual const void * nextRow()
  17324. {
  17325. ActivityTimer t(totalCycles, timeActivities);
  17326. if (eof)
  17327. return NULL;
  17328. if (curIndex >= sortedCount)
  17329. {
  17330. bool eog = sortedCount != 0;
  17331. getSorted();
  17332. if(sortedCount == 0)
  17333. {
  17334. eof = true;
  17335. return NULL;
  17336. }
  17337. if (eog)
  17338. return NULL;
  17339. }
  17340. processed++;
  17341. return sorted[curIndex++];
  17342. }
  17343. };
  17344. class CRoxieServerTopNActivityFactory : public CRoxieServerActivityFactory
  17345. {
  17346. public:
  17347. CRoxieServerTopNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17348. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  17349. {
  17350. }
  17351. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  17352. {
  17353. return new CRoxieServerTopNActivity(_ctx, this, _probeManager);
  17354. }
  17355. };
  17356. IRoxieServerActivityFactory *createRoxieServerTopNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17357. {
  17358. return new CRoxieServerTopNActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  17359. }
  17360. //=================================================================================
  17361. class CRoxieServerLimitActivity : public CRoxieServerActivity
  17362. {
  17363. protected:
  17364. unsigned __int64 rowLimit;
  17365. IHThorLimitArg &helper;
  17366. public:
  17367. CRoxieServerLimitActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17368. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorLimitArg &)basehelper)
  17369. {
  17370. rowLimit = 0;
  17371. }
  17372. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17373. {
  17374. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  17375. rowLimit = helper.getRowLimit(); // could conceivably depend on context so should not compute any earlier than this
  17376. }
  17377. virtual const void *nextRow()
  17378. {
  17379. ActivityTimer t(totalCycles, timeActivities);
  17380. const void * ret = inputStream->nextRow();
  17381. if (ret)
  17382. {
  17383. processed++;
  17384. if (processed > rowLimit)
  17385. {
  17386. ReleaseRoxieRow(ret);
  17387. if (traceLevel > 4)
  17388. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  17389. helper.onLimitExceeded();
  17390. }
  17391. }
  17392. return ret;
  17393. }
  17394. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  17395. {
  17396. ActivityTimer t(totalCycles, timeActivities);
  17397. const void * ret = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  17398. if (ret)
  17399. {
  17400. if (wasCompleteMatch)
  17401. processed++;
  17402. if (processed > rowLimit)
  17403. {
  17404. ReleaseRoxieRow(ret);
  17405. if (traceLevel > 4)
  17406. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  17407. helper.onLimitExceeded();
  17408. }
  17409. }
  17410. return ret;
  17411. }
  17412. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  17413. {
  17414. return input->gatherConjunctions(collector);
  17415. }
  17416. virtual void resetEOF()
  17417. {
  17418. //Do not reset the rowLimit
  17419. inputStream->resetEOF();
  17420. }
  17421. IInputSteppingMeta * querySteppingMeta()
  17422. {
  17423. return input->querySteppingMeta();
  17424. }
  17425. };
  17426. class CRoxieServerLimitActivityFactory : public CRoxieServerActivityFactory
  17427. {
  17428. public:
  17429. CRoxieServerLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17430. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  17431. {
  17432. }
  17433. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  17434. {
  17435. return new CRoxieServerLimitActivity(_ctx, this, _probeManager);
  17436. }
  17437. };
  17438. IRoxieServerActivityFactory *createRoxieServerLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17439. {
  17440. return new CRoxieServerLimitActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  17441. }
  17442. //=====================================================================================================
  17443. class CRoxieServerSkipLimitActivity : public CRoxieServerLimitActivity
  17444. {
  17445. ConstPointerArray buff;
  17446. bool started;
  17447. unsigned index;
  17448. IHThorLimitTransformExtra * transformExtra;
  17449. public:
  17450. CRoxieServerSkipLimitActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _onFail)
  17451. : CRoxieServerLimitActivity(_ctx, _factory, _probeManager)
  17452. {
  17453. transformExtra = NULL;
  17454. started = false;
  17455. index = 0;
  17456. if (_onFail)
  17457. transformExtra = static_cast<IHThorLimitTransformExtra *>(helper.selectInterface(TAIlimittransformextra_1));
  17458. }
  17459. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17460. {
  17461. started = false;
  17462. index = 0;
  17463. CRoxieServerLimitActivity::start(parentExtractSize, parentExtract, paused);
  17464. }
  17465. virtual void reset()
  17466. {
  17467. roxiemem::ReleaseRoxieRowRange(buff.getArray(), index, buff.ordinality());
  17468. buff.kill();
  17469. index = 0;
  17470. started = false;
  17471. CRoxieServerLimitActivity::reset();
  17472. }
  17473. virtual const void *nextRow()
  17474. {
  17475. ActivityTimer t(totalCycles, timeActivities);
  17476. if (!started)
  17477. pullInput();
  17478. if (buff.isItem(index))
  17479. {
  17480. const void * next = buff.item(index++);
  17481. if(next)
  17482. processed++;
  17483. return next;
  17484. }
  17485. return NULL;
  17486. }
  17487. protected:
  17488. void pullInput()
  17489. {
  17490. unsigned count = 0;
  17491. loop
  17492. {
  17493. const void * next = inputStream->nextRow();
  17494. if (next == NULL)
  17495. {
  17496. next = inputStream->nextRow();
  17497. if(next == NULL)
  17498. break;
  17499. buff.append(NULL);
  17500. }
  17501. count++;
  17502. if (count > rowLimit)
  17503. {
  17504. ReleaseRoxieRow(next);
  17505. ReleaseRoxieRows(buff);
  17506. if (ctx->queryDebugContext())
  17507. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  17508. if (transformExtra)
  17509. {
  17510. ensureRowAllocator();
  17511. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17512. size32_t outSize = transformExtra->transformOnLimitExceeded(rowBuilder);
  17513. if (outSize)
  17514. buff.append(rowBuilder.finalizeRowClear(outSize));
  17515. }
  17516. break;
  17517. }
  17518. buff.append(next);
  17519. }
  17520. started = true;
  17521. }
  17522. };
  17523. class CRoxieServerSkipLimitActivityFactory : public CRoxieServerActivityFactory
  17524. {
  17525. public:
  17526. CRoxieServerSkipLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17527. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  17528. {
  17529. }
  17530. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  17531. {
  17532. return new CRoxieServerSkipLimitActivity(_ctx, this, _probeManager, kind==TAKcreaterowlimit);
  17533. }
  17534. };
  17535. IRoxieServerActivityFactory *createRoxieServerSkipLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17536. {
  17537. return new CRoxieServerSkipLimitActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  17538. }
  17539. //=================================================================================
  17540. class CRoxieServerCatchActivity : public CRoxieServerActivity
  17541. {
  17542. IHThorCatchArg &helper;
  17543. public:
  17544. CRoxieServerCatchActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17545. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorCatchArg &)basehelper)
  17546. {
  17547. }
  17548. virtual const void *nextRow()
  17549. {
  17550. ActivityTimer t(totalCycles, timeActivities);
  17551. try
  17552. {
  17553. const void *ret = inputStream->nextRow();
  17554. if (ret)
  17555. processed++;
  17556. return ret;
  17557. }
  17558. catch (IException *E)
  17559. {
  17560. E->Release();
  17561. helper.onExceptionCaught();
  17562. }
  17563. catch (...)
  17564. {
  17565. helper.onExceptionCaught();
  17566. }
  17567. throwUnexpected(); // onExceptionCaught should have thrown something
  17568. }
  17569. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  17570. {
  17571. try
  17572. {
  17573. ActivityTimer t(totalCycles, timeActivities);
  17574. const void * ret = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  17575. if (ret && wasCompleteMatch)
  17576. processed++;
  17577. return ret;
  17578. }
  17579. catch (IException *E)
  17580. {
  17581. E->Release();
  17582. helper.onExceptionCaught();
  17583. }
  17584. catch (...)
  17585. {
  17586. helper.onExceptionCaught();
  17587. }
  17588. throwUnexpected(); // onExceptionCaught should have thrown something
  17589. }
  17590. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  17591. {
  17592. return input->gatherConjunctions(collector);
  17593. }
  17594. virtual void resetEOF()
  17595. {
  17596. inputStream->resetEOF(); // MORE - why not in base class?
  17597. }
  17598. IInputSteppingMeta * querySteppingMeta()
  17599. {
  17600. return input->querySteppingMeta();
  17601. }
  17602. };
  17603. class CRoxieServerSkipCatchActivity : public CRoxieServerActivity
  17604. {
  17605. ConstPointerArray buff;
  17606. bool started;
  17607. unsigned index;
  17608. IHThorCatchArg &helper;
  17609. bool createRow;
  17610. public:
  17611. CRoxieServerSkipCatchActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _createRow)
  17612. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorCatchArg &)basehelper), createRow(_createRow)
  17613. {
  17614. started = false;
  17615. index = 0;
  17616. }
  17617. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17618. {
  17619. started = false;
  17620. index = 0;
  17621. try
  17622. {
  17623. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  17624. }
  17625. catch (IException *E)
  17626. {
  17627. onException(E);
  17628. started = true;
  17629. }
  17630. catch (...)
  17631. {
  17632. onException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught"));
  17633. started = true;
  17634. }
  17635. }
  17636. virtual void reset()
  17637. {
  17638. roxiemem::ReleaseRoxieRowRange(buff.getArray(), index, buff.ordinality());
  17639. buff.kill();
  17640. index = 0;
  17641. started = false;
  17642. CRoxieServerActivity::reset();
  17643. }
  17644. virtual const void *nextRow()
  17645. {
  17646. ActivityTimer t(totalCycles, timeActivities);
  17647. if (!started)
  17648. pullInput();
  17649. if (buff.isItem(index))
  17650. {
  17651. const void * next = buff.item(index++);
  17652. if(next)
  17653. processed++;
  17654. return next;
  17655. }
  17656. return NULL;
  17657. }
  17658. protected:
  17659. void onException(IException *E)
  17660. {
  17661. inputStream->stop();
  17662. ReleaseRoxieRows(buff);
  17663. if (createRow)
  17664. {
  17665. ensureRowAllocator();
  17666. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17667. size32_t outSize = helper.transformOnExceptionCaught(rowBuilder, E);
  17668. if (outSize)
  17669. buff.append(rowBuilder.finalizeRowClear(outSize));
  17670. }
  17671. E->Release();
  17672. }
  17673. void pullInput()
  17674. {
  17675. try
  17676. {
  17677. bool EOGseen = false;
  17678. loop
  17679. {
  17680. const void * next = inputStream->nextRow();
  17681. buff.append(next);
  17682. if (next == NULL)
  17683. {
  17684. if (EOGseen)
  17685. break;
  17686. EOGseen = true;
  17687. }
  17688. else
  17689. EOGseen = false;
  17690. }
  17691. }
  17692. catch (IException *E)
  17693. {
  17694. onException(E);
  17695. }
  17696. catch (...)
  17697. {
  17698. onException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught"));
  17699. }
  17700. started = true;
  17701. }
  17702. };
  17703. class CRoxieServerCatchActivityFactory : public CRoxieServerActivityFactory
  17704. {
  17705. public:
  17706. CRoxieServerCatchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17707. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  17708. {
  17709. }
  17710. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  17711. {
  17712. switch (kind)
  17713. {
  17714. case TAKcatch:
  17715. return new CRoxieServerCatchActivity(_ctx, this, _probeManager);
  17716. case TAKskipcatch:
  17717. return new CRoxieServerSkipCatchActivity(_ctx, this, _probeManager, false);
  17718. case TAKcreaterowcatch:
  17719. return new CRoxieServerSkipCatchActivity(_ctx, this, _probeManager, true);
  17720. default:
  17721. throwUnexpected();
  17722. }
  17723. }
  17724. };
  17725. IRoxieServerActivityFactory *createRoxieServerCatchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17726. {
  17727. return new CRoxieServerCatchActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  17728. }
  17729. //=================================================================================
  17730. class CRoxieServerPullActivity : public CRoxieServerActivity
  17731. {
  17732. ConstPointerArray buff;
  17733. bool started;
  17734. unsigned index;
  17735. public:
  17736. CRoxieServerPullActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17737. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  17738. {
  17739. started = false;
  17740. index = 0;
  17741. }
  17742. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17743. {
  17744. started = false;
  17745. index = 0;
  17746. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  17747. }
  17748. virtual void reset()
  17749. {
  17750. while (buff.isItem(index))
  17751. ReleaseRoxieRow(buff.item(index++));
  17752. buff.kill();
  17753. started = false;
  17754. index = 0;
  17755. CRoxieServerActivity::reset();
  17756. }
  17757. virtual const void *nextRow()
  17758. {
  17759. ActivityTimer t(totalCycles, timeActivities);
  17760. if (!started)
  17761. pullInput();
  17762. if (buff.isItem(index))
  17763. {
  17764. const void * next = buff.item(index++);
  17765. if (next)
  17766. processed++;
  17767. return next;
  17768. }
  17769. return NULL;
  17770. }
  17771. protected:
  17772. void pullInput()
  17773. {
  17774. bool EOGseen = false;
  17775. loop
  17776. {
  17777. const void * next = inputStream->nextRow();
  17778. buff.append(next);
  17779. if (next == NULL)
  17780. {
  17781. if (EOGseen)
  17782. break;
  17783. EOGseen = true;
  17784. }
  17785. else
  17786. EOGseen = false;
  17787. }
  17788. started = true;
  17789. }
  17790. };
  17791. class CRoxieServerPullActivityFactory : public CRoxieServerActivityFactory
  17792. {
  17793. public:
  17794. CRoxieServerPullActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17795. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  17796. {
  17797. }
  17798. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  17799. {
  17800. return new CRoxieServerPullActivity(_ctx, this, _probeManager);
  17801. }
  17802. };
  17803. IRoxieServerActivityFactory *createRoxieServerPullActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17804. {
  17805. return new CRoxieServerPullActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  17806. }
  17807. //=================================================================================
  17808. class CRoxieServerTraceActivity : public CRoxieServerActivity
  17809. {
  17810. public:
  17811. CRoxieServerTraceActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17812. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorTraceArg &) basehelper),
  17813. keepLimit(0), skip(0), sample(0)
  17814. {
  17815. assertex(meta.hasXML());
  17816. traceEnabled = defaultTraceEnabled && !isBlind();
  17817. }
  17818. virtual void onCreate(IHThorArg *_colocalParent)
  17819. {
  17820. CRoxieServerActivity::onCreate(_colocalParent);
  17821. if (ctx)
  17822. traceEnabled = ctx->queryOptions().traceEnabled && !isBlind();
  17823. }
  17824. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17825. {
  17826. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  17827. if (traceEnabled && helper.canMatchAny())
  17828. {
  17829. keepLimit = helper.getKeepLimit();
  17830. if (keepLimit==(unsigned) -1)
  17831. keepLimit = ctx->queryOptions().traceLimit;
  17832. skip = helper.getSkip();
  17833. sample = helper.getSample();
  17834. if (sample)
  17835. sample--;
  17836. name.setown(helper.getName());
  17837. if (!name)
  17838. name.set("Row");
  17839. }
  17840. else
  17841. keepLimit = 0;
  17842. }
  17843. virtual void stop()
  17844. {
  17845. name.clear();
  17846. CRoxieServerActivity::stop();
  17847. }
  17848. virtual bool isPassThrough()
  17849. {
  17850. return true;
  17851. }
  17852. virtual const void *nextRow()
  17853. {
  17854. ActivityTimer t(totalCycles, timeActivities);
  17855. const void *row = inputStream->nextRow();
  17856. if (row)
  17857. {
  17858. onTrace(row);
  17859. processed++;
  17860. }
  17861. return row;
  17862. }
  17863. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  17864. {
  17865. // MORE - will need rethinking once we rethink the nextRowGE interface for global smart-stepping.
  17866. ActivityTimer t(totalCycles, timeActivities);
  17867. const void * row = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  17868. if (row)
  17869. {
  17870. onTrace(row);
  17871. processed++;
  17872. }
  17873. return row;
  17874. }
  17875. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  17876. {
  17877. return input->gatherConjunctions(collector);
  17878. }
  17879. virtual void resetEOF()
  17880. {
  17881. inputStream->resetEOF();
  17882. }
  17883. IInputSteppingMeta * querySteppingMeta()
  17884. {
  17885. return input->querySteppingMeta();
  17886. }
  17887. protected:
  17888. void onTrace(const void *row)
  17889. {
  17890. if (keepLimit && helper.isValid(row))
  17891. {
  17892. if (skip)
  17893. skip--;
  17894. else if (sample)
  17895. sample--;
  17896. else
  17897. {
  17898. CommonXmlWriter xmlwrite(XWFnoindent);
  17899. meta.toXML((const byte *) row, xmlwrite);
  17900. CTXLOG("TRACE: <%s>%s<%s>", name.get(), xmlwrite.str(), name.get());
  17901. keepLimit--;
  17902. sample = helper.getSample();
  17903. if (sample)
  17904. sample--;
  17905. }
  17906. }
  17907. }
  17908. OwnedRoxieString name;
  17909. IHThorTraceArg &helper;
  17910. unsigned keepLimit;
  17911. unsigned skip;
  17912. unsigned sample;
  17913. bool traceEnabled;
  17914. };
  17915. class CRoxieServerTraceActivityFactory : public CRoxieServerActivityFactory
  17916. {
  17917. public:
  17918. CRoxieServerTraceActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17919. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  17920. {
  17921. }
  17922. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  17923. {
  17924. return new CRoxieServerTraceActivity(_ctx, this, _probeManager);
  17925. }
  17926. };
  17927. IRoxieServerActivityFactory *createRoxieServerTraceActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17928. {
  17929. return new CRoxieServerTraceActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  17930. }
  17931. //=================================================================================
  17932. class CRoxieServerCaseActivity : public CRoxieServerMultiInputBaseActivity
  17933. {
  17934. IHThorCaseArg &helper;
  17935. unsigned cond;
  17936. bool unusedStopped;
  17937. IEngineRowStream *active;
  17938. public:
  17939. CRoxieServerCaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  17940. : CRoxieServerMultiInputBaseActivity(_ctx, _factory, _probeManager, _numInputs), helper((IHThorCaseArg &)basehelper)
  17941. {
  17942. unusedStopped = false;
  17943. cond = 0;
  17944. active = NULL;
  17945. }
  17946. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17947. {
  17948. CRoxieServerMultiInputBaseActivity::start(parentExtractSize, parentExtract, paused);
  17949. cond = helper.getBranch();
  17950. //CHOOSE defaults to the last argument if out of range.
  17951. if (cond >= numInputs)
  17952. cond = numInputs - 1;
  17953. inputArray[cond]->start(parentExtractSize, parentExtract, paused);
  17954. startJunction(junctionArray[cond]);
  17955. assertex(numInputs==numStreams);
  17956. for (unsigned idx = 0; idx < numStreams; idx++)
  17957. {
  17958. if (idx!=cond)
  17959. streamArray[idx]->stop(); // Note: stopping unused branches early helps us avoid buffering splits too long.
  17960. }
  17961. active = streamArray[cond];
  17962. unusedStopped = true;
  17963. }
  17964. virtual void stop()
  17965. {
  17966. for (unsigned idx = 0; idx < numStreams; idx++)
  17967. {
  17968. if (idx==cond || !unusedStopped)
  17969. streamArray[idx]->stop();
  17970. }
  17971. CRoxieServerMultiInputBaseActivity::stop();
  17972. }
  17973. virtual void reset()
  17974. {
  17975. unusedStopped = false;
  17976. active = NULL;
  17977. CRoxieServerMultiInputBaseActivity::reset();
  17978. }
  17979. virtual const void *nextRow()
  17980. {
  17981. ActivityTimer t(totalCycles, timeActivities);
  17982. if (active)
  17983. {
  17984. const void *ret = active->nextRow();
  17985. if (ret)
  17986. processed++;
  17987. return ret;
  17988. }
  17989. return NULL;
  17990. }
  17991. };
  17992. class CRoxieServerCaseActivityFactory : public CRoxieServerMultiInputFactory
  17993. {
  17994. bool graphInvariant;
  17995. public:
  17996. CRoxieServerCaseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _graphInvariant)
  17997. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  17998. {
  17999. graphInvariant = _graphInvariant;
  18000. }
  18001. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18002. {
  18003. return new CRoxieServerCaseActivity(_ctx, this, _probeManager, numInputs());
  18004. }
  18005. virtual bool isGraphInvariant() const
  18006. {
  18007. return graphInvariant;
  18008. }
  18009. };
  18010. IRoxieServerActivityFactory *createRoxieServerCaseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _graphInvariant)
  18011. {
  18012. return new CRoxieServerCaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _graphInvariant);
  18013. }
  18014. //=================================================================================
  18015. class CRoxieServerIfActivity : public CRoxieServerActivity
  18016. {
  18017. IHThorIfArg &helper;
  18018. IFinalRoxieInput *inputTrue;
  18019. IFinalRoxieInput *inputFalse;
  18020. IEngineRowStream *streamTrue;
  18021. IEngineRowStream *streamFalse;
  18022. unsigned sourceIdxFalse = 0;
  18023. unsigned sourceIdxTrue = 0;
  18024. Owned<IStrandJunction> junctionTrue;
  18025. Owned<IStrandJunction> junctionFalse;
  18026. bool cond;
  18027. bool unusedStopped;
  18028. public:
  18029. CRoxieServerIfActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18030. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorIfArg &)basehelper)
  18031. {
  18032. inputFalse = NULL;
  18033. inputTrue = NULL;
  18034. streamTrue = NULL;
  18035. streamFalse = NULL;
  18036. unusedStopped = false;
  18037. cond = false;
  18038. }
  18039. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18040. {
  18041. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  18042. cond = helper.getCondition();
  18043. if (cond)
  18044. {
  18045. inputTrue->start(parentExtractSize, parentExtract, paused);
  18046. startJunction(junctionTrue);
  18047. if (streamFalse)
  18048. streamFalse->stop(); // Note: stopping unused branches early helps us avoid buffering splits too long.
  18049. }
  18050. else
  18051. {
  18052. if (inputFalse)
  18053. {
  18054. inputFalse->start(parentExtractSize, parentExtract, paused);
  18055. startJunction(junctionFalse);
  18056. }
  18057. streamTrue->stop();
  18058. }
  18059. unusedStopped = true;
  18060. }
  18061. virtual void stop()
  18062. {
  18063. if (!unusedStopped || cond)
  18064. streamTrue->stop();
  18065. if (streamFalse && (!unusedStopped || !cond))
  18066. streamFalse->stop();
  18067. CRoxieServerActivity::stop();
  18068. }
  18069. virtual unsigned __int64 queryLocalCycles() const
  18070. {
  18071. __int64 localCycles = totalCycles.totalCycles;
  18072. localCycles -= inputTrue->queryTotalCycles();
  18073. if (inputFalse)
  18074. localCycles -= inputFalse->queryTotalCycles();
  18075. if (localCycles < 0)
  18076. localCycles = 0;
  18077. return localCycles;
  18078. }
  18079. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  18080. {
  18081. switch (idx)
  18082. {
  18083. case 0:
  18084. return inputTrue;
  18085. case 1:
  18086. return inputFalse;
  18087. default:
  18088. return NULL;
  18089. }
  18090. }
  18091. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { return this; }
  18092. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { return nullptr; }
  18093. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  18094. {
  18095. IFinalRoxieInput *in = cond ? inputTrue : inputFalse;
  18096. if (in)
  18097. return in->queryIndexReadActivity();
  18098. return NULL;
  18099. }
  18100. virtual void reset()
  18101. {
  18102. CRoxieServerActivity::reset();
  18103. inputTrue->reset();
  18104. if (inputFalse)
  18105. inputFalse->reset();
  18106. resetJunction(junctionTrue);
  18107. resetJunction(junctionFalse);
  18108. unusedStopped = false;
  18109. }
  18110. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  18111. {
  18112. if (idx==1)
  18113. {
  18114. inputFalse = _in;
  18115. sourceIdxFalse = _sourceIdx;
  18116. }
  18117. else
  18118. {
  18119. assertex(!idx);
  18120. inputTrue = _in;
  18121. sourceIdxTrue = _sourceIdx;
  18122. }
  18123. }
  18124. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  18125. {
  18126. //It should be possible to stream IF(), but the number of strands would need to match on the two branches.
  18127. streamTrue = connectSingleStream(ctx, inputTrue, sourceIdxTrue, junctionTrue, consumerOrdered);
  18128. streamFalse = connectSingleStream(ctx, inputFalse, sourceIdxFalse, junctionFalse, consumerOrdered);
  18129. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, nullptr, consumerOrdered, nullptr);
  18130. }
  18131. virtual const void *nextRow()
  18132. {
  18133. ActivityTimer t(totalCycles, timeActivities);
  18134. IEngineRowStream *in = cond ? streamTrue : streamFalse;
  18135. if (in)
  18136. {
  18137. const void * ret;
  18138. if ((ret = in->nextRow()) != NULL)
  18139. processed++;
  18140. return ret;
  18141. }
  18142. return NULL;
  18143. }
  18144. };
  18145. class CRoxieServerIfActivityFactory : public CRoxieServerActivityFactory
  18146. {
  18147. unsigned input2;
  18148. unsigned input2idx;
  18149. bool graphInvariant;
  18150. public:
  18151. CRoxieServerIfActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _graphInvariant)
  18152. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  18153. {
  18154. graphInvariant = _graphInvariant;
  18155. input2 = (unsigned)-1;
  18156. input2idx = (unsigned)-1;
  18157. }
  18158. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18159. {
  18160. return new CRoxieServerIfActivity(_ctx, this, _probeManager);
  18161. }
  18162. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  18163. {
  18164. if (idx==1)
  18165. {
  18166. input2 = source;
  18167. input2idx = sourceidx;
  18168. }
  18169. else
  18170. CRoxieServerActivityFactory::setInput(idx, source, sourceidx);
  18171. }
  18172. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  18173. {
  18174. switch (idx)
  18175. {
  18176. case 1:
  18177. sourceidx = input2idx;
  18178. return input2;
  18179. case 0:
  18180. return CRoxieServerActivityFactory::getInput(idx, sourceidx);
  18181. default:
  18182. return (unsigned) -1;
  18183. }
  18184. }
  18185. virtual unsigned numInputs() const { return (input2 == (unsigned)-1) ? 1 : 2; }
  18186. virtual bool isGraphInvariant() const
  18187. {
  18188. return graphInvariant;
  18189. }
  18190. };
  18191. IRoxieServerActivityFactory *createRoxieServerIfActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _graphInvariant)
  18192. {
  18193. return new CRoxieServerIfActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _graphInvariant);
  18194. }
  18195. //=================================================================================
  18196. class CRoxieServerActionBaseActivity : public CRoxieServerActivity
  18197. {
  18198. CriticalSection ecrit;
  18199. Owned<IException> exception;
  18200. bool executed;
  18201. public:
  18202. CRoxieServerActionBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18203. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  18204. {
  18205. executed = false;
  18206. }
  18207. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract) = 0;
  18208. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  18209. {
  18210. CriticalBlock b(ecrit);
  18211. if (exception)
  18212. throw(exception.getLink());
  18213. if (!executed)
  18214. {
  18215. try
  18216. {
  18217. executed = true;
  18218. start(parentExtractSize, parentExtract, false);
  18219. doExecuteAction(parentExtractSize, parentExtract);
  18220. stop();
  18221. }
  18222. catch (IException * E)
  18223. {
  18224. ctx->notifyAbort(E);
  18225. abort();
  18226. exception.set(E);
  18227. throw;
  18228. }
  18229. }
  18230. }
  18231. virtual void reset()
  18232. {
  18233. executed = false;
  18234. exception.clear();
  18235. CRoxieServerActivity::reset();
  18236. }
  18237. virtual const void *nextRow()
  18238. {
  18239. throwUnexpected(); // I am nobody's input
  18240. }
  18241. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  18242. {
  18243. return NULL;
  18244. }
  18245. };
  18246. class CRoxieServerIfActionActivity : public CRoxieServerActionBaseActivity
  18247. {
  18248. IHThorIfArg &helper;
  18249. public:
  18250. CRoxieServerIfActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18251. : CRoxieServerActionBaseActivity(_ctx, _factory, _probeManager), helper((IHThorIfArg &)basehelper)
  18252. {
  18253. }
  18254. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  18255. {
  18256. bool cond;
  18257. {
  18258. ActivityTimer t(totalCycles, timeActivities);
  18259. cond = helper.getCondition();
  18260. }
  18261. stopDependencies(parentExtractSize, parentExtract, cond ? 2 : 1);
  18262. executeDependencies(parentExtractSize, parentExtract, cond ? 1 : 2);
  18263. }
  18264. };
  18265. class CRoxieServerIfActionActivityFactory : public CRoxieServerActivityFactory
  18266. {
  18267. bool isRoot;
  18268. public:
  18269. CRoxieServerIfActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18270. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  18271. {
  18272. }
  18273. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18274. {
  18275. return new CRoxieServerIfActionActivity(_ctx, this, _probeManager);
  18276. }
  18277. virtual bool isSink() const
  18278. {
  18279. return isRoot;
  18280. }
  18281. };
  18282. IRoxieServerActivityFactory *createRoxieServerIfActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18283. {
  18284. return new CRoxieServerIfActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  18285. }
  18286. //=================================================================================
  18287. class CRoxieServerParallelActionActivity : public CRoxieServerActionBaseActivity
  18288. {
  18289. public:
  18290. CRoxieServerParallelActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18291. : CRoxieServerActionBaseActivity(_ctx, _factory, _probeManager)
  18292. {
  18293. }
  18294. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  18295. {
  18296. #ifdef PARALLEL_EXECUTE
  18297. CParallelActivityExecutor afor(dependencies, parentExtractSize, parentExtract);
  18298. afor.For(dependencies.ordinality(), dependencies.ordinality(), true);
  18299. #else
  18300. ForEachItemIn(idx, dependencies)
  18301. {
  18302. dependencies.item(idx).execute(parentExtractSize, parentExtract);
  18303. }
  18304. #endif
  18305. }
  18306. };
  18307. class CRoxieServerParallelActionActivityFactory : public CRoxieServerActivityFactory
  18308. {
  18309. bool isRoot;
  18310. public:
  18311. CRoxieServerParallelActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18312. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  18313. {
  18314. assertex(!isRoot); // non-internal should be expanded out..
  18315. }
  18316. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18317. {
  18318. return new CRoxieServerParallelActionActivity(_ctx, this, _probeManager);
  18319. }
  18320. virtual bool isSink() const
  18321. {
  18322. return isRoot;
  18323. }
  18324. };
  18325. IRoxieServerActivityFactory *createRoxieServerParallelActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18326. {
  18327. return new CRoxieServerParallelActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  18328. }
  18329. //=================================================================================
  18330. class CRoxieServerSequentialActionActivity : public CRoxieServerActionBaseActivity
  18331. {
  18332. IHThorSequentialArg &helper;
  18333. public:
  18334. CRoxieServerSequentialActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18335. : CRoxieServerActionBaseActivity(_ctx, _factory, _probeManager), helper((IHThorSequentialArg &)basehelper)
  18336. {
  18337. }
  18338. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  18339. {
  18340. unsigned numBranches = helper.numBranches();
  18341. for (unsigned branch=1; branch <= numBranches; branch++)
  18342. executeDependencies(parentExtractSize, parentExtract, branch);
  18343. }
  18344. };
  18345. class CRoxieServerSequentialActionActivityFactory : public CRoxieServerActivityFactory
  18346. {
  18347. bool isRoot;
  18348. public:
  18349. CRoxieServerSequentialActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18350. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  18351. {
  18352. }
  18353. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18354. {
  18355. return new CRoxieServerSequentialActionActivity(_ctx, this, _probeManager);
  18356. }
  18357. virtual bool isSink() const
  18358. {
  18359. return isRoot;
  18360. }
  18361. };
  18362. IRoxieServerActivityFactory *createRoxieServerSequentialActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18363. {
  18364. return new CRoxieServerSequentialActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  18365. }
  18366. //=================================================================================
  18367. class CRoxieServerWhenActivity : public CRoxieServerActivity
  18368. {
  18369. public:
  18370. CRoxieServerWhenActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18371. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  18372. {
  18373. savedExtractSize = 0;
  18374. savedExtract = NULL;
  18375. eofseen = false;
  18376. eogseen = false;
  18377. }
  18378. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18379. {
  18380. savedExtractSize = parentExtractSize;
  18381. savedExtract = parentExtract;
  18382. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  18383. executeDependencies(parentExtractSize, parentExtract, WhenBeforeId);
  18384. executeDependencies(parentExtractSize, parentExtract, WhenParallelId); // MORE: This should probably be done in parallel!
  18385. eofseen = false;
  18386. eogseen = false;
  18387. }
  18388. virtual void stop()
  18389. {
  18390. if (state == STATEreset || (!aborted && !eofseen)) // If someone else aborted, then WHEN clauses don't trigger, whatever
  18391. {
  18392. stopDependencies(savedExtractSize, savedExtract, WhenSuccessId);
  18393. stopDependencies(savedExtractSize, savedExtract, WhenFailureId);
  18394. }
  18395. else if (state != STATEstopped)
  18396. {
  18397. stopDependencies(savedExtractSize, savedExtract, aborted ? WhenSuccessId : WhenFailureId); // These ones don't get executed
  18398. executeDependencies(savedExtractSize, savedExtract, aborted ? WhenFailureId : WhenSuccessId); // These ones do
  18399. }
  18400. CRoxieServerActivity::stop();
  18401. }
  18402. virtual const void *nextRow()
  18403. {
  18404. try
  18405. {
  18406. ActivityTimer t(totalCycles, timeActivities); // bit of a waste of time....
  18407. const void *ret = inputStream->nextRow();
  18408. if (!ret)
  18409. {
  18410. if (eogseen)
  18411. eofseen = true;
  18412. else
  18413. eogseen = true;
  18414. }
  18415. else
  18416. eogseen = false;
  18417. return ret;
  18418. }
  18419. catch (...)
  18420. {
  18421. aborted = true;
  18422. throw;
  18423. }
  18424. }
  18425. protected:
  18426. const byte *savedExtract;
  18427. unsigned savedExtractSize;
  18428. bool eofseen;
  18429. bool eogseen;
  18430. };
  18431. class CRoxieServerWhenActivityFactory : public CRoxieServerActivityFactory
  18432. {
  18433. public:
  18434. CRoxieServerWhenActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  18435. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  18436. {
  18437. }
  18438. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18439. {
  18440. return new CRoxieServerWhenActivity(_ctx, this, _probeManager);
  18441. }
  18442. };
  18443. extern IRoxieServerActivityFactory *createRoxieServerWhenActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  18444. {
  18445. return new CRoxieServerWhenActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  18446. }
  18447. //=================================================================================
  18448. class CRoxieServerWhenActionActivity : public CRoxieServerActionBaseActivity
  18449. {
  18450. public:
  18451. CRoxieServerWhenActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18452. : CRoxieServerActionBaseActivity(_ctx, _factory, _probeManager)
  18453. {
  18454. savedExtractSize = 0;
  18455. savedExtract = NULL;
  18456. }
  18457. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18458. {
  18459. savedExtractSize = parentExtractSize;
  18460. savedExtract = parentExtract;
  18461. CRoxieServerActionBaseActivity::start(parentExtractSize, parentExtract, paused);
  18462. executeDependencies(parentExtractSize, parentExtract, WhenBeforeId);
  18463. executeDependencies(parentExtractSize, parentExtract, WhenParallelId); // MORE: This should probably be done in parallel!
  18464. }
  18465. virtual void stop()
  18466. {
  18467. if (state != STATEstopped)
  18468. {
  18469. stopDependencies(savedExtractSize, savedExtract, aborted ? WhenSuccessId : WhenFailureId); // these are NOT going to execute
  18470. executeDependencies(savedExtractSize, savedExtract, aborted ? WhenFailureId : WhenSuccessId);
  18471. }
  18472. CRoxieServerActionBaseActivity::stop();
  18473. }
  18474. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  18475. {
  18476. executeDependencies(parentExtractSize, parentExtract, 1);
  18477. }
  18478. protected:
  18479. unsigned savedExtractSize;
  18480. const byte *savedExtract;
  18481. };
  18482. class CRoxieServerWhenActionActivityFactory : public CRoxieServerActivityFactory
  18483. {
  18484. public:
  18485. CRoxieServerWhenActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18486. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  18487. {
  18488. }
  18489. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18490. {
  18491. return new CRoxieServerWhenActionActivity(_ctx, this, _probeManager);
  18492. }
  18493. virtual bool isSink() const
  18494. {
  18495. return isRoot;
  18496. }
  18497. private:
  18498. bool isRoot;
  18499. };
  18500. extern IRoxieServerActivityFactory *createRoxieServerWhenActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18501. {
  18502. return new CRoxieServerWhenActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  18503. }
  18504. //=================================================================================
  18505. class CRoxieServerStrandedParseActivity : public CRoxieServerStrandedActivity
  18506. {
  18507. INlpParseAlgorithm * algorithm;
  18508. class ParseProcessor : public StrandProcessor, implements IMatchedAction
  18509. {
  18510. protected:
  18511. IHThorParseArg &helper;
  18512. INlpParser * parser;
  18513. INlpResultIterator * rowIter;
  18514. const void * in;
  18515. char * curSearchText;
  18516. size32_t curSearchTextLen;
  18517. bool processRecord(const void * inRec)
  18518. {
  18519. if (helper.searchTextNeedsFree())
  18520. rtlFree(curSearchText);
  18521. curSearchTextLen = 0;
  18522. curSearchText = NULL;
  18523. helper.getSearchText(curSearchTextLen, curSearchText, inRec);
  18524. return parser->performMatch(*this, in, curSearchTextLen, curSearchText);
  18525. }
  18526. public:
  18527. ParseProcessor(CRoxieServerActivity &_parent, IEngineRowStream *_inputStream, IHThorParseArg &_helper, INlpParseAlgorithm * _algorithm)
  18528. : StrandProcessor(_parent, _inputStream, false), helper(_helper)
  18529. {
  18530. parser = _algorithm->createParser(parent.queryCodeContext(), parent.queryId(), helper.queryHelper(), &helper);
  18531. rowIter = parser->queryResultIter();
  18532. in = NULL;
  18533. curSearchText = NULL;
  18534. curSearchTextLen = 0;
  18535. }
  18536. ~ParseProcessor()
  18537. {
  18538. ::Release(parser);
  18539. }
  18540. virtual void start()
  18541. {
  18542. StrandProcessor::start();
  18543. numProcessedLastGroup = 0;
  18544. curSearchTextLen = 0;
  18545. curSearchText = NULL;
  18546. in = NULL;
  18547. parser->reset();
  18548. }
  18549. virtual void reset()
  18550. {
  18551. if (helper.searchTextNeedsFree())
  18552. rtlFree(curSearchText);
  18553. curSearchText = NULL;
  18554. ReleaseClearRoxieRow(in);
  18555. StrandProcessor::reset();
  18556. }
  18557. virtual const void * nextRow()
  18558. {
  18559. ActivityTimer t(totalCycles, timeActivities);
  18560. loop
  18561. {
  18562. if (rowIter->isValid())
  18563. {
  18564. OwnedConstRoxieRow out = rowIter->getRow();
  18565. rowIter->next();
  18566. processed++;
  18567. return out.getClear();
  18568. }
  18569. ReleaseClearRoxieRow(in);
  18570. in = inputStream->nextRow();
  18571. if (!in)
  18572. {
  18573. if (processed == numProcessedLastGroup)
  18574. in = inputStream->nextRow();
  18575. if (!in)
  18576. {
  18577. processed = numProcessedLastGroup;
  18578. return NULL;
  18579. }
  18580. in = inputStream->nextRow();
  18581. if (!in)
  18582. return NULL;
  18583. }
  18584. processRecord(in);
  18585. rowIter->first();
  18586. }
  18587. }
  18588. virtual unsigned onMatch(ARowBuilder & self, const void * curRecord, IMatchedResults * results, IMatchWalker * walker)
  18589. {
  18590. try
  18591. {
  18592. return helper.transform(self, curRecord, results, walker);
  18593. }
  18594. catch (IException *E)
  18595. {
  18596. throw parent.makeWrappedException(E);
  18597. }
  18598. }
  18599. };
  18600. public:
  18601. CRoxieServerStrandedParseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, INlpParseAlgorithm * _algorithm, const StrandOptions &_strandOptions)
  18602. : CRoxieServerStrandedActivity(_ctx, _factory, _probeManager, _strandOptions), algorithm(_algorithm)
  18603. {
  18604. }
  18605. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18606. {
  18607. CRoxieServerStrandedActivity::start(parentExtractSize, parentExtract, paused);
  18608. onStartStrands();
  18609. }
  18610. virtual StrandProcessor *createStrandProcessor(IEngineRowStream *instream)
  18611. {
  18612. return new ParseProcessor(*this, instream, (IHThorParseArg &) basehelper, algorithm);
  18613. }
  18614. virtual StrandProcessor *createStrandSourceProcessor(bool inputOrdered) { throwUnexpected(); }
  18615. };
  18616. class CRoxieServerParseActivityFactory : public CRoxieServerActivityFactory
  18617. {
  18618. Owned<INlpParseAlgorithm> algorithm;
  18619. Owned<IHThorParseArg> helper;
  18620. StrandOptions strandOptions;
  18621. public:
  18622. CRoxieServerParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, IResourceContext *rc)
  18623. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), strandOptions(_graphNode)
  18624. {
  18625. helper.setown((IHThorParseArg *) helperFactory());
  18626. algorithm.setown(createThorParser(rc, *helper));
  18627. optStableInput = false;
  18628. }
  18629. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18630. {
  18631. return new CRoxieServerStrandedParseActivity(_ctx, this, _probeManager, algorithm, strandOptions);
  18632. }
  18633. };
  18634. IRoxieServerActivityFactory *createRoxieServerParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, IResourceContext *rc)
  18635. {
  18636. return new CRoxieServerParseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, rc);
  18637. }
  18638. //=====================================================================================================
  18639. class CRoxieServerWorkUnitWriteActivity : public CRoxieServerInternalSinkActivity
  18640. {
  18641. IHThorWorkUnitWriteArg &helper;
  18642. bool isReread;
  18643. bool grouped;
  18644. IRoxieServerContext *serverContext;
  18645. public:
  18646. CRoxieServerWorkUnitWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _isReread, unsigned _numOutputs)
  18647. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _numOutputs), helper((IHThorWorkUnitWriteArg &)basehelper), isReread(_isReread)
  18648. {
  18649. grouped = (helper.getFlags() & POFgrouped) != 0;
  18650. serverContext = NULL;
  18651. }
  18652. virtual void onCreate(IHThorArg *_colocalParent)
  18653. {
  18654. CRoxieServerInternalSinkActivity::onCreate(_colocalParent);
  18655. serverContext = ctx->queryServerContext();
  18656. if (!serverContext)
  18657. {
  18658. throw MakeStringException(ROXIE_PIPE_ERROR, "Pipe output activity cannot be executed in slave context");
  18659. }
  18660. }
  18661. virtual bool needsAllocator() const { return true; }
  18662. virtual void onExecute()
  18663. {
  18664. int sequence = helper.getSequence();
  18665. const char *storedName = helper.queryName();
  18666. if (!storedName)
  18667. storedName = "Dataset";
  18668. MemoryBuffer result;
  18669. bool saveInContext = (int) sequence < 0 || isReread;
  18670. if (!meta.queryOriginal()) // this is a bit of a hack - don't know why no meta on an output....
  18671. meta.set(input->queryOutputMeta());
  18672. Owned<IOutputRowSerializer> rowSerializer;
  18673. Owned<IXmlWriter> xmlwriter;
  18674. bool appendRaw = false;
  18675. IHpccProtocolResultsWriter *results = NULL;
  18676. IHpccNativeProtocolResultsWriter *nativeResults = NULL;
  18677. IHpccProtocolResponse *protocol = serverContext->queryProtocol();
  18678. unsigned protocolFlags = (protocol) ? protocol->getFlags() : 0;
  18679. if ((int) sequence >= 0)
  18680. {
  18681. results = (protocol) ? protocol->queryHpccResultsSection() : NULL;
  18682. if (results)
  18683. {
  18684. nativeResults = dynamic_cast<IHpccNativeProtocolResultsWriter*>(results);
  18685. xmlwriter.setown(results->addDataset(helper.queryName(), sequence, "Dataset", appendRaw, serverContext->getXmlFlags(), (helper.getFlags() & POFextend) != 0, serverContext->queryXmlns(sequence))); //xmlwriter only returned if needed
  18686. }
  18687. }
  18688. size32_t outputLimitBytes = 0;
  18689. IConstWorkUnit *workunit = serverContext->queryWorkUnit();
  18690. if (workunit)
  18691. {
  18692. size32_t outputLimit;
  18693. if (helper.getFlags() & POFmaxsize)
  18694. outputLimit = helper.getMaxSize();
  18695. else
  18696. {
  18697. // In absense of OPT_OUTPUTLIMIT check pre 5.2 legacy name OPT_OUTPUTLIMIT_LEGACY
  18698. outputLimit = workunit->getDebugValueInt(OPT_OUTPUTLIMIT, workunit->getDebugValueInt(OPT_OUTPUTLIMIT_LEGACY, defaultDaliResultLimit));
  18699. }
  18700. if (outputLimit>defaultDaliResultOutputMax)
  18701. 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);
  18702. assertex(outputLimit<=0x1000); // 32bit limit because MemoryBuffer/CMessageBuffers involved etc.
  18703. outputLimitBytes = outputLimit * 0x100000;
  18704. }
  18705. if (workunit != NULL || (results && protocol->getFlags() & HPCC_PROTOCOL_NATIVE_RAW))
  18706. {
  18707. ensureRowAllocator();
  18708. rowSerializer.setown(rowAllocator->createDiskSerializer(ctx->queryCodeContext()));
  18709. }
  18710. __int64 initialProcessed = processed;
  18711. RtlLinkedDatasetBuilder builder(rowAllocator);
  18712. loop
  18713. {
  18714. const void *row = inputStream->nextRow();
  18715. if (saveInContext)
  18716. {
  18717. if (row || grouped)
  18718. builder.append(row);
  18719. }
  18720. if (grouped && (processed != initialProcessed))
  18721. {
  18722. if (workunit)
  18723. result.append(row == NULL);
  18724. if (results)
  18725. {
  18726. if (protocolFlags & HPCC_PROTOCOL_NATIVE_RAW && nativeResults)
  18727. {
  18728. char val = (char)(row == NULL);
  18729. nativeResults->appendRaw(sequence, 1, &val);
  18730. }
  18731. else if (xmlwriter)
  18732. {
  18733. xmlwriter->outputBeginNested("Row", false);
  18734. xmlwriter->outputCString("1", "@__GroupBreak__");
  18735. xmlwriter->outputEndNested("Row");
  18736. }
  18737. }
  18738. }
  18739. if (!row)
  18740. {
  18741. row = inputStream->nextRow();
  18742. if (!row)
  18743. break;
  18744. if (saveInContext)
  18745. builder.append(row);
  18746. }
  18747. processed++;
  18748. if (workunit)
  18749. {
  18750. CThorDemoRowSerializer serializerTarget(result);
  18751. rowSerializer->serialize(serializerTarget, (const byte *) row);
  18752. }
  18753. if ((int) sequence >= 0)
  18754. {
  18755. if (appendRaw && nativeResults)
  18756. {
  18757. // MORE - should be able to serialize straight to the response...
  18758. MemoryBuffer rowbuff;
  18759. CThorDemoRowSerializer serializerTarget(rowbuff);
  18760. rowSerializer->serialize(serializerTarget, (const byte *) row);
  18761. nativeResults->appendRawRow(sequence, rowbuff.length(), rowbuff.toByteArray());
  18762. }
  18763. else if (xmlwriter)
  18764. {
  18765. xmlwriter->outputBeginNested(DEFAULTXMLROWTAG, false);
  18766. helper.serializeXml((byte *) row, *xmlwriter);
  18767. xmlwriter->outputEndNested(DEFAULTXMLROWTAG);
  18768. results->finalizeXmlRow(sequence);
  18769. }
  18770. else if (nativeResults)
  18771. {
  18772. SimpleOutputWriter x;
  18773. helper.serializeXml((byte *) row, x);
  18774. x.newline();
  18775. nativeResults->appendSimpleRow(sequence, x.str());
  18776. }
  18777. }
  18778. ReleaseRoxieRow(row);
  18779. if (outputLimitBytes && result.length() > outputLimitBytes)
  18780. {
  18781. StringBuffer errMsg("Dataset too large to output to workunit (limit ");
  18782. errMsg.append(outputLimitBytes/0x100000).append(" megabytes), in result (");
  18783. const char *name = helper.queryName();
  18784. if (name)
  18785. errMsg.append("name=").append(name);
  18786. else
  18787. errMsg.append("sequence=").append(helper.getSequence());
  18788. errMsg.append(")");
  18789. throw MakeStringExceptionDirect(0, errMsg.str());
  18790. }
  18791. }
  18792. if (xmlwriter)
  18793. xmlwriter->outputEndArray(DEFAULTXMLROWTAG);
  18794. if (saveInContext)
  18795. serverContext->appendResultDeserialized(storedName, sequence, builder.getcount(), builder.linkrows(), (helper.getFlags() & POFextend) != 0, LINK(meta.queryOriginal()));
  18796. if (workunit)
  18797. serverContext->appendResultRawContext(storedName, sequence, result.length(), result.toByteArray(), processed, (helper.getFlags() & POFextend) != 0, false); // MORE - shame to do extra copy...
  18798. }
  18799. };
  18800. class CRoxieServerWorkUnitWriteActivityFactory : public CRoxieServerInternalSinkFactory
  18801. {
  18802. bool isReread;
  18803. public:
  18804. CRoxieServerWorkUnitWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  18805. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot)
  18806. {
  18807. isReread = usageCount > 0;
  18808. Owned<IHThorWorkUnitWriteArg> helper = (IHThorWorkUnitWriteArg *) helperFactory();
  18809. isInternal = (helper->getSequence()==ResultSequenceInternal);
  18810. }
  18811. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18812. {
  18813. return new CRoxieServerWorkUnitWriteActivity(_ctx, this, _probeManager, isReread, usageCount);
  18814. }
  18815. };
  18816. IRoxieServerActivityFactory *createRoxieServerWorkUnitWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  18817. {
  18818. return new CRoxieServerWorkUnitWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot);
  18819. }
  18820. //=====================================================================================================
  18821. class CRoxieServerWorkUnitWriteDictActivity : public CRoxieServerInternalSinkActivity
  18822. {
  18823. IHThorDictionaryWorkUnitWriteArg &helper;
  18824. IRoxieServerContext *serverContext;
  18825. public:
  18826. CRoxieServerWorkUnitWriteDictActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _usageCount)
  18827. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _usageCount), helper((IHThorDictionaryWorkUnitWriteArg &)basehelper)
  18828. {
  18829. serverContext = NULL;
  18830. }
  18831. virtual void onCreate(IHThorArg *_colocalParent)
  18832. {
  18833. CRoxieServerInternalSinkActivity::onCreate(_colocalParent);
  18834. serverContext = ctx->queryServerContext();
  18835. if (!serverContext)
  18836. {
  18837. throw MakeStringException(ROXIE_PIPE_ERROR, "Write Dictionary activity cannot be executed in slave context");
  18838. }
  18839. }
  18840. virtual bool needsAllocator() const { return true; }
  18841. virtual void onExecute()
  18842. {
  18843. int sequence = helper.getSequence();
  18844. const char *storedName = helper.queryName();
  18845. assertex(storedName && *storedName);
  18846. assertex(sequence < 0);
  18847. RtlLinkedDictionaryBuilder builder(rowAllocator, helper.queryHashLookupInfo());
  18848. loop
  18849. {
  18850. const void *row = inputStream->ungroupedNextRow();
  18851. if (!row)
  18852. break;
  18853. builder.appendOwn(row);
  18854. processed++;
  18855. }
  18856. serverContext->appendResultDeserialized(storedName, sequence, builder.getcount(), builder.linkrows(), (helper.getFlags() & POFextend) != 0, LINK(meta.queryOriginal()));
  18857. }
  18858. };
  18859. class CRoxieServerWorkUnitWriteDictActivityFactory : public CRoxieServerInternalSinkFactory
  18860. {
  18861. public:
  18862. CRoxieServerWorkUnitWriteDictActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  18863. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot)
  18864. {
  18865. Owned<IHThorDictionaryWorkUnitWriteArg> helper = (IHThorDictionaryWorkUnitWriteArg *) helperFactory();
  18866. isInternal = (helper->getSequence()==ResultSequenceInternal);
  18867. }
  18868. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18869. {
  18870. return new CRoxieServerWorkUnitWriteDictActivity(_ctx, this, _probeManager, usageCount);
  18871. }
  18872. };
  18873. IRoxieServerActivityFactory *createRoxieServerWorkUnitWriteDictActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  18874. {
  18875. return new CRoxieServerWorkUnitWriteDictActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot);
  18876. }
  18877. //=================================================================================
  18878. class CRoxieServerRemoteResultActivity : public CRoxieServerInternalSinkActivity
  18879. {
  18880. IHThorRemoteResultArg &helper;
  18881. public:
  18882. CRoxieServerRemoteResultActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  18883. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _numOutputs), helper((IHThorRemoteResultArg &)basehelper)
  18884. {
  18885. }
  18886. virtual void onExecute()
  18887. {
  18888. OwnedConstRoxieRow row = inputStream->nextRow();
  18889. helper.sendResult(row); // should be only one row or something has gone wrong!
  18890. }
  18891. };
  18892. class CRoxieServerRemoteResultActivityFactory : public CRoxieServerInternalSinkFactory
  18893. {
  18894. public:
  18895. CRoxieServerRemoteResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  18896. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot)
  18897. {
  18898. Owned<IHThorRemoteResultArg> helper = (IHThorRemoteResultArg *) helperFactory();
  18899. isInternal = (helper->getSequence()==ResultSequenceInternal);
  18900. }
  18901. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18902. {
  18903. return new CRoxieServerRemoteResultActivity(_ctx, this, _probeManager, usageCount);
  18904. }
  18905. };
  18906. IRoxieServerActivityFactory *createRoxieServerRemoteResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  18907. {
  18908. return new CRoxieServerRemoteResultActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot);
  18909. }
  18910. //=================================================================================
  18911. class CRoxieServerXmlParseActivity : public CRoxieServerActivity, implements IXMLSelect
  18912. {
  18913. IHThorXmlParseArg &helper;
  18914. Owned<IXMLParse> xmlParser;
  18915. const void * in;
  18916. char * srchStr;
  18917. unsigned numProcessedLastGroup;
  18918. bool srchStrNeedsFree;
  18919. Owned<IColumnProvider> lastMatch;
  18920. public:
  18921. IMPLEMENT_IINTERFACE_USING(CRoxieServerActivity)
  18922. CRoxieServerXmlParseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18923. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  18924. helper((IHThorXmlParseArg &)basehelper)
  18925. {
  18926. srchStrNeedsFree = helper.searchTextNeedsFree();
  18927. numProcessedLastGroup = 0;
  18928. srchStr = NULL;
  18929. in = NULL;
  18930. }
  18931. ~CRoxieServerXmlParseActivity()
  18932. {
  18933. }
  18934. virtual bool needsAllocator() const { return true; }
  18935. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18936. {
  18937. numProcessedLastGroup = 0;
  18938. srchStr = NULL;
  18939. in = NULL;
  18940. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  18941. }
  18942. virtual void reset()
  18943. {
  18944. if (helper.searchTextNeedsFree())
  18945. rtlFree(srchStr);
  18946. srchStr = NULL;
  18947. ReleaseClearRoxieRow(in);
  18948. xmlParser.clear();
  18949. CRoxieServerActivity::reset();
  18950. }
  18951. virtual void match(IColumnProvider &entry, offset_t startOffset, offset_t endOffset)
  18952. {
  18953. lastMatch.set(&entry);
  18954. }
  18955. virtual const void *nextRow()
  18956. {
  18957. ActivityTimer t(totalCycles, timeActivities);
  18958. loop
  18959. {
  18960. if(xmlParser)
  18961. {
  18962. loop
  18963. {
  18964. if(!xmlParser->next())
  18965. {
  18966. if (srchStrNeedsFree)
  18967. {
  18968. rtlFree(srchStr);
  18969. srchStr = NULL;
  18970. }
  18971. xmlParser.clear();
  18972. break;
  18973. }
  18974. if(lastMatch)
  18975. {
  18976. try
  18977. {
  18978. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  18979. size32_t outSize = helper.transform(rowBuilder, in, lastMatch);
  18980. lastMatch.clear();
  18981. if (outSize)
  18982. {
  18983. processed++;
  18984. return rowBuilder.finalizeRowClear(outSize);
  18985. }
  18986. }
  18987. catch (IException *E)
  18988. {
  18989. throw makeWrappedException(E);
  18990. }
  18991. }
  18992. }
  18993. }
  18994. ReleaseClearRoxieRow(in);
  18995. in = inputStream->nextRow();
  18996. if(!in)
  18997. {
  18998. if(numProcessedLastGroup == processed)
  18999. in = inputStream->nextRow();
  19000. if(!in)
  19001. {
  19002. numProcessedLastGroup = processed;
  19003. return NULL;
  19004. }
  19005. }
  19006. size32_t srchLen;
  19007. helper.getSearchText(srchLen, srchStr, in);
  19008. OwnedRoxieString xmlIteratorPath(helper.getXmlIteratorPath());
  19009. xmlParser.setown(createXMLParse(srchStr, srchLen, xmlIteratorPath, *this));
  19010. }
  19011. }
  19012. };
  19013. class CRoxieServerXmlParseActivityFactory : public CRoxieServerActivityFactory
  19014. {
  19015. public:
  19016. CRoxieServerXmlParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  19017. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  19018. {
  19019. }
  19020. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  19021. {
  19022. return new CRoxieServerXmlParseActivity(_ctx, this, _probeManager);
  19023. }
  19024. };
  19025. IRoxieServerActivityFactory *createRoxieServerXmlParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  19026. {
  19027. return new CRoxieServerXmlParseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  19028. }
  19029. //=====================================================================================================
  19030. class CRoxieServerDiskReadBaseActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler, implements IIndexReadContext
  19031. {
  19032. protected:
  19033. IHThorDiskReadBaseArg &helper;
  19034. IHThorCompoundExtra * compoundHelper;
  19035. RemoteActivityId remoteId; // Note we copy it rather than reference
  19036. Owned<CSkippableRemoteResultAdaptor> remote;
  19037. unsigned numParts;
  19038. unsigned __int64 rowLimit;
  19039. unsigned __int64 stopAfter;
  19040. Linked<IInMemoryIndexManager> manager;
  19041. Owned<IInMemoryIndexCursor> cursor;
  19042. Owned<IDirectReader> reader;
  19043. CThorContiguousRowBuffer deserializeSource;
  19044. Owned<ISourceRowPrefetcher> prefetcher;
  19045. bool eof;
  19046. bool isKeyed;
  19047. bool variableFileName;
  19048. bool isOpt;
  19049. bool sorted;
  19050. bool maySkip;
  19051. bool isLocal;
  19052. bool forceRemote;
  19053. CachedOutputMetaData diskSize;
  19054. Owned<const IResolvedFile> varFileInfo;
  19055. Owned<IFileIOArray> varFiles;
  19056. inline bool useRemote()
  19057. {
  19058. return remote != NULL && (forceRemote || numParts > 1);
  19059. }
  19060. public:
  19061. IMPLEMENT_IINTERFACE_USING(CRoxieServerActivity)
  19062. CRoxieServerDiskReadBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager)
  19063. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  19064. helper((IHThorDiskReadBaseArg &)basehelper),
  19065. numParts(_numParts),
  19066. remoteId(_remoteId),
  19067. manager(_manager),
  19068. isLocal(_isLocal),
  19069. sorted(_sorted),
  19070. maySkip(_maySkip),
  19071. deserializeSource(NULL)
  19072. {
  19073. forceRemote = factory->queryQueryFactory().queryOptions().disableLocalOptimizations;
  19074. if ((forceRemote || numParts != 1) && !isLocal) // NOTE : when numParts == 0 (variable case) we create, even though we may not use
  19075. remote.setown(new CSkippableRemoteResultAdaptor(_ctx, this, remoteId, meta.queryOriginal(), helper, *this, sorted, false, _maySkip));
  19076. compoundHelper = NULL;
  19077. eof = false;
  19078. rowLimit = (unsigned __int64) -1;
  19079. isKeyed = false;
  19080. stopAfter = I64C(0x7FFFFFFFFFFFFFFF);
  19081. diskSize.set(helper.queryDiskRecordSize());
  19082. variableFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getFlags() & (TDXvarfilename|TDXdynamicfilename)) != 0);
  19083. isOpt = (helper.getFlags() & TDRoptional) != 0;
  19084. }
  19085. virtual const IResolvedFile *queryVarFileInfo() const
  19086. {
  19087. return varFileInfo;
  19088. }
  19089. virtual void onCreate(IHThorArg *_colocalParent)
  19090. {
  19091. CRoxieServerActivity::onCreate(_colocalParent);
  19092. if (remote)
  19093. remote->onCreate(_colocalParent);
  19094. }
  19095. virtual bool needsAllocator() const { return true; }
  19096. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19097. {
  19098. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  19099. if (compoundHelper)
  19100. {
  19101. rowLimit = compoundHelper->getRowLimit();
  19102. stopAfter = compoundHelper->getChooseNLimit();
  19103. }
  19104. if (!helper.canMatchAny())
  19105. eof = true;
  19106. else
  19107. {
  19108. if (variableFileName)
  19109. {
  19110. OwnedRoxieString fileName(helper.getFileName());
  19111. varFileInfo.setown(resolveLFN(fileName, isOpt));
  19112. numParts = 0;
  19113. if (varFileInfo)
  19114. numParts = varFileInfo->getNumParts();
  19115. }
  19116. if (!numParts)
  19117. {
  19118. eof = true;
  19119. }
  19120. else if (useRemote())
  19121. {
  19122. remote->onStart(parentExtractSize, parentExtract);
  19123. remote->setLimits(rowLimit, (unsigned __int64) -1, stopAfter);
  19124. unsigned fileNo = 0;
  19125. // Translation into a message per channel done elsewhere....
  19126. remote->getMem(0, fileNo, 0);
  19127. remote->flush();
  19128. remote->senddone();
  19129. }
  19130. else
  19131. {
  19132. if (variableFileName)
  19133. {
  19134. unsigned channel = isLocal ? factory->queryQueryFactory().queryChannel() : 0;
  19135. varFiles.setown(varFileInfo->getIFileIOArray(isOpt, channel));
  19136. manager.setown(varFileInfo->getIndexManager(isOpt, channel, varFiles, diskSize, false, 0));
  19137. }
  19138. assertex(manager != NULL);
  19139. helper.createSegmentMonitors(this);
  19140. if (cursor)
  19141. {
  19142. isKeyed = cursor->selectKey();
  19143. cursor->reset();
  19144. }
  19145. if (!isKeyed)
  19146. {
  19147. reader.setown(manager->createReader(0, 0, 1));
  19148. deserializeSource.setStream(reader);
  19149. prefetcher.setown(diskSize.queryOriginal()->createDiskPrefetcher(ctx->queryCodeContext(), activityId));
  19150. }
  19151. helper.setCallback(reader ? reader->queryThorDiskCallback() : cursor);
  19152. }
  19153. }
  19154. }
  19155. virtual void append(IKeySegmentMonitor *segment)
  19156. {
  19157. if (!segment->isWild())
  19158. {
  19159. if (!cursor)
  19160. cursor.setown(manager->createCursor());
  19161. cursor->append(segment);
  19162. }
  19163. }
  19164. virtual unsigned ordinality() const
  19165. {
  19166. return cursor ? cursor->ordinality() : 0;
  19167. }
  19168. virtual IKeySegmentMonitor *item(unsigned idx) const
  19169. {
  19170. return cursor ? cursor->item(idx) : 0;
  19171. }
  19172. virtual void setMergeBarrier(unsigned barrierOffset)
  19173. {
  19174. // no merging so no issue...
  19175. }
  19176. virtual void stop()
  19177. {
  19178. if (useRemote())
  19179. remote->onStop();
  19180. CRoxieServerActivity::stop();
  19181. }
  19182. virtual void reset()
  19183. {
  19184. if (useRemote())
  19185. {
  19186. processed = remote->processed;
  19187. remote->processed = 0;
  19188. remote->onReset();
  19189. }
  19190. varFileInfo.clear();
  19191. eof = false;
  19192. if (cursor)
  19193. cursor->reset();
  19194. deserializeSource.clearStream();
  19195. CRoxieServerActivity::reset();
  19196. }
  19197. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  19198. {
  19199. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  19200. }
  19201. virtual void onLimitExceeded(bool isKeyed)
  19202. {
  19203. if (traceLevel > 4)
  19204. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  19205. assertex(compoundHelper);
  19206. if (isKeyed) // MORE does this exist for diskread? should it?
  19207. {
  19208. if (helper.getFlags() & (TDRkeyedlimitskips|TDRkeyedlimitcreates))
  19209. {
  19210. if (ctx->queryDebugContext())
  19211. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  19212. throw makeLimitSkipException(true);
  19213. }
  19214. else
  19215. {
  19216. UNIMPLEMENTED;
  19217. //compoundHelper->onKeyedLimitExceeded(); Doesn't exist - though the flags do... interesting...
  19218. }
  19219. }
  19220. else
  19221. {
  19222. if (helper.getFlags() & (TDRlimitskips|TDRlimitcreates))
  19223. {
  19224. if (ctx->queryDebugContext())
  19225. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  19226. throw makeLimitSkipException(false);
  19227. }
  19228. else
  19229. compoundHelper->onLimitExceeded();
  19230. }
  19231. }
  19232. virtual const void * createLimitFailRow(bool isKeyed)
  19233. {
  19234. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  19235. IHThorSourceLimitTransformExtra *limitTransformExtra = static_cast<IHThorSourceLimitTransformExtra *>(helper.selectInterface(TAIsourcelimittransformextra_1));
  19236. assertex(limitTransformExtra);
  19237. size32_t outSize = isKeyed ? limitTransformExtra->transformOnKeyedLimitExceeded(rowBuilder) : limitTransformExtra->transformOnLimitExceeded(rowBuilder);
  19238. if (outSize)
  19239. return rowBuilder.finalizeRowClear(outSize);
  19240. return NULL;
  19241. }
  19242. };
  19243. class CRoxieServerDiskReadActivity : public CRoxieServerDiskReadBaseActivity
  19244. {
  19245. IHThorCompoundReadExtra * readHelper;
  19246. ConstPointerArray readrows;
  19247. bool readAheadDone;
  19248. unsigned readIndex;
  19249. public:
  19250. CRoxieServerDiskReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager)
  19251. : CRoxieServerDiskReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, _maySkip, _manager)
  19252. {
  19253. compoundHelper = (IHThorDiskReadArg *)&helper;
  19254. readHelper = (IHThorDiskReadArg *)&helper;
  19255. readAheadDone = false;
  19256. readIndex = 0;
  19257. }
  19258. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19259. {
  19260. rowLimit = compoundHelper->getRowLimit();
  19261. stopAfter = compoundHelper->getChooseNLimit();
  19262. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  19263. readAheadDone = false;
  19264. readIndex = 0;
  19265. }
  19266. virtual void reset()
  19267. {
  19268. roxiemem::ReleaseRoxieRowRange(readrows.getArray(), readIndex, readrows.ordinality());
  19269. readrows.kill();
  19270. readAheadDone = false;
  19271. readIndex = 0;
  19272. CRoxieServerDiskReadBaseActivity::reset();
  19273. }
  19274. virtual const void *nextRow()
  19275. {
  19276. if (eof)
  19277. return NULL;
  19278. else if (useRemote())
  19279. return remote->nextRow();
  19280. else if (maySkip)
  19281. {
  19282. if (!readAheadDone)
  19283. {
  19284. unsigned preprocessed = 0;
  19285. while (!eof)
  19286. {
  19287. const void *row = _nextRow();
  19288. if (row)
  19289. preprocessed++;
  19290. if (preprocessed > rowLimit)
  19291. {
  19292. ReleaseRoxieRow(row);
  19293. roxiemem::ReleaseRoxieRowRange(readrows.getArray(), readIndex, readrows.ordinality());
  19294. readrows.kill();
  19295. readIndex = 0;
  19296. eof = true;
  19297. if (ctx->queryDebugContext())
  19298. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  19299. if (helper.getFlags() & TDRlimitskips)
  19300. return NULL;
  19301. else if (helper.getFlags() & TDRlimitcreates)
  19302. return createLimitFailRow(false);
  19303. else
  19304. throwUnexpected();
  19305. }
  19306. if (preprocessed > stopAfter) // MORE - bit of a strange place to check
  19307. {
  19308. eof = true;
  19309. ReleaseRoxieRow(row);
  19310. break;
  19311. }
  19312. readrows.append(row);
  19313. }
  19314. readAheadDone = true;
  19315. }
  19316. if (readrows.isItem(readIndex))
  19317. {
  19318. const void *ret = readrows.item(readIndex++);
  19319. if (ret)
  19320. processed++;
  19321. return ret;
  19322. }
  19323. else
  19324. {
  19325. eof = true;
  19326. return NULL;
  19327. }
  19328. }
  19329. else
  19330. {
  19331. const void *ret = _nextRow();
  19332. if (ret)
  19333. {
  19334. processed++;
  19335. if (processed > rowLimit)
  19336. {
  19337. if (traceLevel > 4)
  19338. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  19339. ReleaseRoxieRow(ret);
  19340. compoundHelper->onLimitExceeded();
  19341. throwUnexpected(); // onLimitExceeded is not supposed to return
  19342. }
  19343. if (processed > stopAfter) // MORE - bit of a strange place to check
  19344. {
  19345. eof = true;
  19346. ReleaseRoxieRow(ret);
  19347. return NULL;
  19348. }
  19349. }
  19350. return ret;
  19351. }
  19352. }
  19353. const void *_nextRow()
  19354. {
  19355. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  19356. unsigned transformedSize = 0;
  19357. if (isKeyed)
  19358. {
  19359. loop
  19360. {
  19361. const void *nextCandidate = cursor->nextMatch();
  19362. if (!nextCandidate)
  19363. {
  19364. eof = true;
  19365. return NULL;
  19366. }
  19367. transformedSize = readHelper->transform(rowBuilder, nextCandidate);
  19368. if (transformedSize)
  19369. break;
  19370. }
  19371. }
  19372. else // use reader...
  19373. {
  19374. assertex(reader != NULL);
  19375. loop
  19376. {
  19377. if (deserializeSource.eos())
  19378. {
  19379. eof = true;
  19380. return NULL;
  19381. }
  19382. prefetcher->readAhead(deserializeSource);
  19383. const byte *nextRec = deserializeSource.queryRow();
  19384. if (cursor && cursor->isFiltered(nextRec))
  19385. transformedSize = 0;
  19386. else
  19387. transformedSize = readHelper->transform(rowBuilder, nextRec);
  19388. deserializeSource.finishedRow();
  19389. if (transformedSize)
  19390. break;
  19391. }
  19392. }
  19393. return rowBuilder.finalizeRowClear(transformedSize);
  19394. }
  19395. };
  19396. class CRoxieServerXmlReadActivity : public CRoxieServerDiskReadBaseActivity, implements IXMLSelect, implements IThorDiskCallback
  19397. {
  19398. IHThorXmlReadArg * readHelper;
  19399. Owned<IXmlToRowTransformer> rowTransformer;
  19400. Owned<IXMLParse> xmlParser;
  19401. Owned<IColumnProvider> lastMatch;
  19402. unsigned __int64 fileoffset;
  19403. public:
  19404. IMPLEMENT_IINTERFACE_USING(CRoxieServerDiskReadBaseActivity)
  19405. CRoxieServerXmlReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager)
  19406. : CRoxieServerDiskReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, _maySkip, _manager)
  19407. {
  19408. compoundHelper = NULL;
  19409. readHelper = (IHThorXmlReadArg *)&helper;
  19410. fileoffset = 0;
  19411. }
  19412. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19413. {
  19414. rowLimit = readHelper->getRowLimit();
  19415. stopAfter = readHelper->getChooseNLimit();
  19416. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  19417. if (!useRemote())
  19418. {
  19419. rowTransformer.set(readHelper->queryTransformer());
  19420. assertex(reader != NULL);
  19421. OwnedRoxieString xmlIterator(readHelper->getXmlIteratorPath());
  19422. if (factory->getKind()==TAKjsonread)
  19423. xmlParser.setown(createJSONParse(*reader->querySimpleStream(), xmlIterator, *this, (0 != (TDRxmlnoroot & readHelper->getFlags()))?ptr_noRoot:ptr_none, (readHelper->getFlags() & TDRusexmlcontents) != 0));
  19424. else
  19425. xmlParser.setown(createXMLParse(*reader->querySimpleStream(), xmlIterator, *this, (0 != (TDRxmlnoroot & readHelper->getFlags()))?ptr_noRoot:ptr_none, (readHelper->getFlags() & TDRusexmlcontents) != 0));
  19426. }
  19427. }
  19428. virtual void reset()
  19429. {
  19430. CRoxieServerDiskReadBaseActivity::reset();
  19431. rowTransformer.clear();
  19432. xmlParser.clear();
  19433. }
  19434. virtual void match(IColumnProvider &entry, offset_t startOffset, offset_t endOffset)
  19435. {
  19436. fileoffset = startOffset;
  19437. lastMatch.set(&entry);
  19438. }
  19439. //interface IThorDiskCallback
  19440. virtual unsigned __int64 getFilePosition(const void * row)
  19441. {
  19442. return fileoffset;
  19443. }
  19444. virtual unsigned __int64 getLocalFilePosition(const void * row)
  19445. {
  19446. return reader->makeFilePositionLocal(fileoffset);
  19447. }
  19448. virtual const char * queryLogicalFilename(const void * row)
  19449. {
  19450. return reader->queryThorDiskCallback()->queryLogicalFilename(row);
  19451. }
  19452. virtual const void *nextRow()
  19453. {
  19454. if (eof)
  19455. return NULL;
  19456. else if (useRemote())
  19457. return remote->nextRow();
  19458. assertex(xmlParser != NULL);
  19459. try
  19460. {
  19461. while (!eof)
  19462. {
  19463. //call to next() will callback on the IXmlSelect interface
  19464. bool gotNext = false;
  19465. gotNext = xmlParser->next();
  19466. if(!gotNext)
  19467. eof = true;
  19468. else if (lastMatch)
  19469. {
  19470. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  19471. unsigned sizeGot = rowTransformer->transform(rowBuilder, lastMatch, this);
  19472. lastMatch.clear();
  19473. fileoffset = 0;
  19474. if (sizeGot)
  19475. {
  19476. OwnedConstRoxieRow ret = rowBuilder.finalizeRowClear(sizeGot);
  19477. if (processed > rowLimit)
  19478. {
  19479. if (traceLevel > 4)
  19480. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  19481. readHelper->onLimitExceeded();
  19482. throwUnexpected(); // onLimitExceeded is not supposed to return
  19483. }
  19484. processed++;
  19485. if (processed > stopAfter) // MORE - bit of a strange place to check
  19486. {
  19487. eof = true;
  19488. return NULL;
  19489. }
  19490. return ret.getClear();
  19491. }
  19492. }
  19493. }
  19494. return NULL;
  19495. }
  19496. catch(IException *E)
  19497. {
  19498. throw makeWrappedException(E);
  19499. }
  19500. }
  19501. };
  19502. class CRoxieServerCsvReadActivity : public CRoxieServerDiskReadBaseActivity
  19503. {
  19504. IHThorCsvReadArg *readHelper;
  19505. ICsvParameters * csvInfo;
  19506. unsigned headerLines;
  19507. unsigned maxDiskSize;
  19508. CSVSplitter csvSplitter;
  19509. unsigned __int64 localOffset;
  19510. const char *quotes;
  19511. const char *separators;
  19512. const char *terminators;
  19513. const char *escapes;
  19514. size32_t maxRowSize;
  19515. public:
  19516. CRoxieServerCsvReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  19517. unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager,
  19518. const char *_quotes, const char *_separators, const char *_terminators, const char *_escapes, size32_t _maxRowSize)
  19519. : CRoxieServerDiskReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, _maySkip, _manager),
  19520. quotes(_quotes), separators(_separators), terminators(_terminators), escapes(_escapes), maxRowSize(_maxRowSize)
  19521. {
  19522. compoundHelper = NULL;
  19523. readHelper = (IHThorCsvReadArg *)&helper;
  19524. rowLimit = readHelper->getRowLimit();
  19525. stopAfter = readHelper->getChooseNLimit();
  19526. csvInfo = readHelper->queryCsvParameters();
  19527. maxDiskSize = csvInfo->queryMaxSize();
  19528. localOffset = 0;
  19529. headerLines = 0;
  19530. }
  19531. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19532. {
  19533. rowLimit = readHelper->getRowLimit();
  19534. stopAfter = readHelper->getChooseNLimit();
  19535. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  19536. if (!useRemote())
  19537. {
  19538. headerLines = csvInfo->queryHeaderLen();
  19539. if (headerLines && isLocal && reader->queryFilePart() != 1)
  19540. 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...
  19541. if (!eof)
  19542. {
  19543. if (varFileInfo)
  19544. {
  19545. const IPropertyTree *options = varFileInfo->queryProperties();
  19546. if (options)
  19547. {
  19548. quotes = options->queryProp("@csvQuote");
  19549. separators = options->queryProp("@csvSeparate");
  19550. terminators = options->queryProp("@csvTerminate");
  19551. escapes = options->queryProp("@csvEscape");
  19552. }
  19553. }
  19554. csvSplitter.init(readHelper->getMaxColumns(), csvInfo, quotes, separators, terminators, escapes);
  19555. }
  19556. }
  19557. }
  19558. virtual const void *nextRow()
  19559. {
  19560. if (eof)
  19561. return NULL;
  19562. else if (useRemote())
  19563. return remote->nextRow();
  19564. try
  19565. {
  19566. while (!eof)
  19567. {
  19568. if (reader->eos())
  19569. {
  19570. eof = true;
  19571. break;
  19572. }
  19573. // MORE - there are rumours of a csvSplitter that operates on a stream... if/when it exists, this should use it
  19574. size32_t rowSize = 4096; // MORE - make configurable
  19575. size32_t thisLineLength;
  19576. loop
  19577. {
  19578. size32_t avail;
  19579. const void *peek = reader->peek(rowSize, avail);
  19580. thisLineLength = csvSplitter.splitLine(avail, (const byte *)peek);
  19581. if (thisLineLength < rowSize || avail < rowSize)
  19582. break;
  19583. if (rowSize == maxRowSize)
  19584. throw MakeStringException(0, "File contained a line of length greater than %d bytes.", maxRowSize);
  19585. if (rowSize >= maxRowSize/2)
  19586. rowSize = maxRowSize;
  19587. else
  19588. rowSize += rowSize;
  19589. }
  19590. if (headerLines)
  19591. {
  19592. headerLines--;
  19593. reader->skip(thisLineLength);
  19594. }
  19595. else
  19596. {
  19597. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  19598. unsigned transformedSize = readHelper->transform(rowBuilder, csvSplitter.queryLengths(), (const char * *)csvSplitter.queryData());
  19599. reader->skip(thisLineLength);
  19600. if (transformedSize)
  19601. {
  19602. OwnedConstRoxieRow ret = rowBuilder.finalizeRowClear(transformedSize);
  19603. if (processed > rowLimit)
  19604. {
  19605. readHelper->onLimitExceeded();
  19606. throwUnexpected(); // onLimitExceeded is not supposed to return
  19607. }
  19608. processed++;
  19609. if (processed > stopAfter) // MORE - bit of a strange place to check
  19610. {
  19611. eof = true;
  19612. return NULL;
  19613. }
  19614. return ret.getClear();
  19615. }
  19616. }
  19617. }
  19618. return NULL;
  19619. }
  19620. catch(IException *E)
  19621. {
  19622. throw makeWrappedException(E);
  19623. }
  19624. }
  19625. virtual void reset()
  19626. {
  19627. CRoxieServerDiskReadBaseActivity::reset();
  19628. csvSplitter.reset();
  19629. localOffset = 0;
  19630. }
  19631. virtual unsigned __int64 getFilePosition(const void * row)
  19632. {
  19633. UNIMPLEMENTED; // we know offset in the reader but not sure it helps us much
  19634. }
  19635. virtual unsigned __int64 getLocalFilePosition(const void * row)
  19636. {
  19637. UNIMPLEMENTED;
  19638. }
  19639. };
  19640. class CRoxieServerDiskNormalizeActivity : public CRoxieServerDiskReadBaseActivity
  19641. {
  19642. IHThorDiskNormalizeArg *normalizeHelper;
  19643. bool firstPending;
  19644. public:
  19645. CRoxieServerDiskNormalizeActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, IInMemoryIndexManager *_manager)
  19646. : CRoxieServerDiskReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, false, _manager)
  19647. {
  19648. compoundHelper = (IHThorDiskNormalizeArg *)&helper;
  19649. normalizeHelper = (IHThorDiskNormalizeArg *)&helper;
  19650. firstPending = true;
  19651. }
  19652. virtual void reset()
  19653. {
  19654. firstPending = true;
  19655. CRoxieServerDiskReadBaseActivity::reset();
  19656. }
  19657. virtual const void *nextRow()
  19658. {
  19659. if (eof)
  19660. return NULL;
  19661. else if (useRemote())
  19662. return remote->nextRow();
  19663. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  19664. unsigned transformedSize = 0;
  19665. if (isKeyed)
  19666. {
  19667. loop
  19668. {
  19669. while (firstPending)
  19670. {
  19671. const void *nextCandidate = cursor->nextMatch();
  19672. if (!nextCandidate)
  19673. {
  19674. eof = true;
  19675. return NULL;
  19676. }
  19677. if (normalizeHelper->first(nextCandidate))
  19678. {
  19679. firstPending = false;
  19680. break;
  19681. }
  19682. }
  19683. transformedSize = normalizeHelper->transform(rowBuilder);
  19684. firstPending = !normalizeHelper->next();
  19685. if (transformedSize)
  19686. break;
  19687. }
  19688. }
  19689. else
  19690. {
  19691. assertex(reader != NULL);
  19692. loop
  19693. {
  19694. while (firstPending)
  19695. {
  19696. if (deserializeSource.eos())
  19697. {
  19698. eof = true;
  19699. return NULL;
  19700. }
  19701. prefetcher->readAhead(deserializeSource);
  19702. const byte *nextRec = deserializeSource.queryRow();
  19703. if (!cursor || !cursor->isFiltered(nextRec))
  19704. {
  19705. if (normalizeHelper->first(nextRec))
  19706. firstPending = false;
  19707. }
  19708. deserializeSource.finishedRow();
  19709. }
  19710. transformedSize = normalizeHelper->transform(rowBuilder);
  19711. firstPending = !normalizeHelper->next();
  19712. if (transformedSize)
  19713. break;
  19714. }
  19715. }
  19716. OwnedConstRoxieRow recBuffer = rowBuilder.finalizeRowClear(transformedSize);
  19717. processed++;
  19718. if (processed > rowLimit)
  19719. {
  19720. compoundHelper->onLimitExceeded();
  19721. throwUnexpected(); // onLimitExceeded is not supposed to return
  19722. }
  19723. if (processed > stopAfter) // MORE - bit of a strange place to check
  19724. {
  19725. eof = true;
  19726. return NULL;
  19727. }
  19728. return recBuffer.getClear();
  19729. }
  19730. };
  19731. class CRoxieServerDiskAggregateBaseActivity : public CRoxieServerDiskReadBaseActivity
  19732. {
  19733. protected:
  19734. bool done;
  19735. public:
  19736. CRoxieServerDiskAggregateBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager)
  19737. : CRoxieServerDiskReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, false, false, _manager),
  19738. done(false)
  19739. {
  19740. }
  19741. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19742. {
  19743. done = false;
  19744. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  19745. }
  19746. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  19747. {
  19748. if (idx==(unsigned)-1)
  19749. idx = 0;
  19750. return idx ? NULL: this;
  19751. }
  19752. };
  19753. class CRoxieServerDiskCountActivity : public CRoxieServerDiskAggregateBaseActivity
  19754. {
  19755. IHThorDiskCountArg & countHelper;
  19756. unsigned __int64 choosenLimit;
  19757. IHThorSourceCountLimit *limitHelper;
  19758. unsigned __int64 getSkippedCount()
  19759. {
  19760. unsigned flags = countHelper.getFlags();
  19761. if (flags & TDRlimitskips)
  19762. return 0;
  19763. else if (flags & TDRlimitcreates)
  19764. return 1;
  19765. else
  19766. {
  19767. assertex(limitHelper);
  19768. if (traceLevel > 4)
  19769. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  19770. limitHelper->onLimitExceeded();
  19771. throwUnexpected(); // onLimitExceeded should always throw exception
  19772. }
  19773. }
  19774. public:
  19775. CRoxieServerDiskCountActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager)
  19776. : CRoxieServerDiskAggregateBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _manager),
  19777. countHelper((IHThorDiskCountArg &)basehelper)
  19778. {
  19779. limitHelper = static_cast<IHThorSourceCountLimit *>(basehelper.selectInterface(TAIsourcecountlimit_1));
  19780. choosenLimit = 0;
  19781. }
  19782. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19783. {
  19784. choosenLimit = countHelper.getChooseNLimit();
  19785. if (limitHelper)
  19786. {
  19787. rowLimit = limitHelper->getRowLimit();
  19788. // keyedLimit = limitHelper->getKeyedLimit(); // more - should there be one?
  19789. }
  19790. CRoxieServerDiskAggregateBaseActivity::start(parentExtractSize, parentExtract, paused);
  19791. }
  19792. virtual const void *nextRow()
  19793. {
  19794. ActivityTimer t(totalCycles, timeActivities);
  19795. if (done) return NULL;
  19796. done = true;
  19797. unsigned __int64 totalCount = 0;
  19798. if (helper.canMatchAny() && !eof)
  19799. {
  19800. if (useRemote())
  19801. {
  19802. loop
  19803. {
  19804. const void * next = remote->nextRow();
  19805. if (!next)
  19806. break;
  19807. if (meta.getFixedSize() == 1)
  19808. totalCount += *(byte *)next;
  19809. else
  19810. totalCount += *(unsigned __int64 *)next;
  19811. ReleaseRoxieRow(next);
  19812. if (totalCount > rowLimit)
  19813. {
  19814. totalCount = getSkippedCount();
  19815. break;
  19816. }
  19817. else if (totalCount >= choosenLimit)
  19818. {
  19819. totalCount = choosenLimit;
  19820. break;
  19821. }
  19822. }
  19823. }
  19824. else
  19825. {
  19826. if (isKeyed)
  19827. {
  19828. loop
  19829. {
  19830. const void *nextCandidate = cursor->nextMatch();
  19831. if (!nextCandidate)
  19832. break;
  19833. totalCount += countHelper.numValid(nextCandidate);
  19834. if (totalCount > rowLimit)
  19835. {
  19836. totalCount = getSkippedCount();
  19837. break;
  19838. }
  19839. else if (totalCount >= choosenLimit)
  19840. {
  19841. totalCount = choosenLimit;
  19842. break;
  19843. }
  19844. }
  19845. }
  19846. else
  19847. {
  19848. assertex(reader != NULL);
  19849. while (!deserializeSource.eos())
  19850. {
  19851. prefetcher->readAhead(deserializeSource);
  19852. const byte *nextRec = deserializeSource.queryRow();
  19853. if (!cursor || !cursor->isFiltered(nextRec))
  19854. {
  19855. totalCount += countHelper.numValid(nextRec);
  19856. }
  19857. deserializeSource.finishedRow();
  19858. if (totalCount > rowLimit)
  19859. {
  19860. totalCount = getSkippedCount();
  19861. break;
  19862. }
  19863. else if (totalCount >= choosenLimit)
  19864. {
  19865. totalCount = choosenLimit;
  19866. break;
  19867. }
  19868. }
  19869. }
  19870. }
  19871. }
  19872. size32_t rowSize = meta.getFixedSize();
  19873. void * result = rowAllocator->createRow();
  19874. if (rowSize == 1)
  19875. *(byte *)result = (byte)totalCount;
  19876. else
  19877. {
  19878. assertex(rowSize == sizeof(unsigned __int64));
  19879. *(unsigned __int64 *)result = totalCount;
  19880. }
  19881. return rowAllocator->finalizeRow(rowSize, result, rowSize);
  19882. }
  19883. };
  19884. class CRoxieServerDiskAggregateActivity : public CRoxieServerDiskAggregateBaseActivity
  19885. {
  19886. IHThorCompoundAggregateExtra & aggregateHelper;
  19887. public:
  19888. CRoxieServerDiskAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  19889. unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager)
  19890. : CRoxieServerDiskAggregateBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _manager),
  19891. aggregateHelper((IHThorDiskAggregateArg &)basehelper)
  19892. {
  19893. }
  19894. const void * gatherMerged()
  19895. {
  19896. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  19897. size32_t finalSize = 0;
  19898. if (useRemote())
  19899. {
  19900. const void * firstRow = remote->nextRow();
  19901. if (!firstRow)
  19902. {
  19903. rowBuilder.ensureRow();
  19904. finalSize = aggregateHelper.clearAggregate(rowBuilder);
  19905. }
  19906. else
  19907. {
  19908. // NOTE need to clone this because going to modify below, could special case 1 row only
  19909. finalSize = cloneRow(rowBuilder, firstRow, meta);
  19910. ReleaseRoxieRow(firstRow);
  19911. }
  19912. loop
  19913. {
  19914. const void * next = remote->nextRow();
  19915. if (!next)
  19916. break;
  19917. finalSize = aggregateHelper.mergeAggregate(rowBuilder, next);
  19918. ReleaseRoxieRow(next);
  19919. }
  19920. }
  19921. else
  19922. {
  19923. aggregateHelper.clearAggregate(rowBuilder);
  19924. if (helper.canMatchAny() && !eof)
  19925. {
  19926. if (isKeyed)
  19927. {
  19928. loop
  19929. {
  19930. const void *next = cursor->nextMatch();
  19931. if (!next)
  19932. break;
  19933. aggregateHelper.processRow(rowBuilder, next);
  19934. }
  19935. }
  19936. else
  19937. {
  19938. assertex(reader != NULL);
  19939. while (!deserializeSource.eos())
  19940. {
  19941. prefetcher->readAhead(deserializeSource);
  19942. const byte *nextRec = deserializeSource.queryRow();
  19943. if (!cursor || !cursor->isFiltered(nextRec))
  19944. {
  19945. aggregateHelper.processRow(rowBuilder, nextRec);
  19946. }
  19947. deserializeSource.finishedRow();
  19948. }
  19949. }
  19950. }
  19951. finalSize = meta.getRecordSize(rowBuilder.getSelf());
  19952. }
  19953. return rowBuilder.finalizeRowClear(finalSize);
  19954. }
  19955. virtual const void *nextRow()
  19956. {
  19957. ActivityTimer t(totalCycles, timeActivities);
  19958. if (done) return NULL;
  19959. const void * ret = gatherMerged();
  19960. done = true;
  19961. return ret;
  19962. }
  19963. };
  19964. class CRoxieServerDiskGroupAggregateActivity : public CRoxieServerDiskAggregateBaseActivity
  19965. {
  19966. IHThorDiskGroupAggregateArg & aggregateHelper;
  19967. RowAggregator resultAggregator;
  19968. bool gathered;
  19969. public:
  19970. CRoxieServerDiskGroupAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager)
  19971. : CRoxieServerDiskAggregateBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _manager),
  19972. aggregateHelper((IHThorDiskGroupAggregateArg &)basehelper),
  19973. resultAggregator(aggregateHelper, aggregateHelper),
  19974. gathered(false)
  19975. {
  19976. }
  19977. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19978. {
  19979. gathered= false;
  19980. CRoxieServerDiskAggregateBaseActivity::start(parentExtractSize, parentExtract, paused);
  19981. resultAggregator.start(rowAllocator);
  19982. }
  19983. virtual void reset()
  19984. {
  19985. resultAggregator.reset();
  19986. CRoxieServerDiskAggregateBaseActivity::reset();
  19987. }
  19988. void gatherMerged()
  19989. {
  19990. if (useRemote())
  19991. {
  19992. loop
  19993. {
  19994. const void * next = remote->nextRow();
  19995. if (!next)
  19996. break;
  19997. resultAggregator.mergeElement(next);
  19998. ReleaseRoxieRow(next);
  19999. }
  20000. }
  20001. else
  20002. {
  20003. if (helper.canMatchAny() && !eof)
  20004. {
  20005. Owned<IInMemoryFileProcessor> processor = isKeyed ?
  20006. createKeyedGroupAggregateRecordProcessor(cursor, resultAggregator, aggregateHelper) :
  20007. createUnkeyedGroupAggregateRecordProcessor(cursor, resultAggregator, aggregateHelper, manager->createReader(0, 0, 1),
  20008. ctx->queryCodeContext(), activityId);
  20009. processor->doQuery(NULL, 0, 0, 0);
  20010. }
  20011. }
  20012. gathered = true;
  20013. }
  20014. virtual const void *nextRow()
  20015. {
  20016. ActivityTimer t(totalCycles, timeActivities);
  20017. if (done)
  20018. return NULL;
  20019. if (!gathered)
  20020. gatherMerged();
  20021. Owned<AggregateRowBuilder> next = resultAggregator.nextResult();
  20022. if (next)
  20023. {
  20024. processed++;
  20025. return next->finalizeRowClear();
  20026. }
  20027. done = true;
  20028. return NULL;
  20029. }
  20030. };
  20031. class CRoxieServerDiskReadActivityFactory : public CRoxieServerActivityFactory
  20032. {
  20033. public:
  20034. RemoteActivityId remoteId;
  20035. bool isLocal;
  20036. bool sorted;
  20037. bool maySkip;
  20038. bool variableFileName;
  20039. Owned<IFileIOArray> files;
  20040. Owned<IInMemoryIndexManager> manager;
  20041. Owned<const IResolvedFile> datafile;
  20042. const char *quotes;
  20043. const char *separators;
  20044. const char *terminators;
  20045. const char *escapes;
  20046. size32_t maxCsvRowSize;
  20047. CRoxieServerDiskReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  20048. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), remoteId(_remoteId)
  20049. {
  20050. isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  20051. Owned<IHThorDiskReadBaseArg> helper = (IHThorDiskReadBaseArg *) helperFactory();
  20052. sorted = (helper->getFlags() & TDRunsorted) == 0;
  20053. variableFileName = allFilesDynamic || _queryFactory.isDynamic() || ((helper->getFlags() & (TDXvarfilename|TDXdynamicfilename)) != 0);
  20054. maySkip = (helper->getFlags() & (TDRkeyedlimitskips|TDRkeyedlimitcreates|TDRlimitskips|TDRlimitcreates)) != 0;
  20055. quotes = separators = terminators = escapes = NULL;
  20056. if (!variableFileName)
  20057. {
  20058. bool isOpt = (helper->getFlags() & TDRoptional) != 0;
  20059. OwnedRoxieString fileName(helper->getFileName());
  20060. datafile.setown(_queryFactory.queryPackage().lookupFileName(fileName, isOpt, true, true, _queryFactory.queryWorkUnit(), true));
  20061. bool isSimple = (datafile && datafile->getNumParts()==1 && !_queryFactory.queryOptions().disableLocalOptimizations);
  20062. if (isLocal || isSimple)
  20063. {
  20064. if (datafile)
  20065. {
  20066. unsigned channel = isLocal ? queryFactory.queryChannel() : 0;
  20067. files.setown(datafile->getIFileIOArray(isOpt, channel));
  20068. manager.setown(datafile->getIndexManager(isOpt, channel, files, helper->queryDiskRecordSize(), _graphNode.getPropBool("att[@name=\"preload\"]/@value", false), _graphNode.getPropInt("att[@name=\"_preloadSize\"]/@value", 0)));
  20069. const IPropertyTree *options = datafile->queryProperties();
  20070. if (options)
  20071. {
  20072. quotes = options->queryProp("@csvQuote");
  20073. separators = options->queryProp("@csvSeparate");
  20074. terminators = options->queryProp("@csvTerminate");
  20075. escapes = options->queryProp("@csvEscape");
  20076. }
  20077. }
  20078. else
  20079. manager.setown(getEmptyIndexManager());
  20080. }
  20081. }
  20082. switch (kind)
  20083. {
  20084. case TAKcsvread:
  20085. {
  20086. maxCsvRowSize = defaultMaxCsvRowSize * 1024 * 1024;
  20087. IConstWorkUnit *workunit = _queryFactory.queryWorkUnit();
  20088. if (workunit)
  20089. maxCsvRowSize = workunit->getDebugValueInt(OPT_MAXCSVROWSIZE, defaultMaxCsvRowSize) * 1024 * 1024;
  20090. break;
  20091. }
  20092. default:
  20093. maxCsvRowSize = 0; // unused
  20094. }
  20095. }
  20096. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  20097. {
  20098. unsigned numParts = datafile ? datafile->getNumParts() : 0;
  20099. switch (kind)
  20100. {
  20101. case TAKcsvread:
  20102. return new CRoxieServerCsvReadActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, sorted, maySkip, manager,
  20103. quotes, separators, terminators, escapes, maxCsvRowSize);
  20104. case TAKxmlread:
  20105. case TAKjsonread:
  20106. return new CRoxieServerXmlReadActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, sorted, maySkip, manager);
  20107. case TAKdiskread:
  20108. return new CRoxieServerDiskReadActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, sorted, maySkip, manager);
  20109. case TAKdisknormalize:
  20110. return new CRoxieServerDiskNormalizeActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, sorted, manager);
  20111. case TAKdiskcount:
  20112. return new CRoxieServerDiskCountActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, manager);
  20113. case TAKdiskaggregate:
  20114. return new CRoxieServerDiskAggregateActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, manager);
  20115. case TAKdiskgroupaggregate:
  20116. return new CRoxieServerDiskGroupAggregateActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, manager);
  20117. }
  20118. throwUnexpected();
  20119. }
  20120. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  20121. {
  20122. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  20123. }
  20124. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  20125. {
  20126. if (datafile)
  20127. addXrefFileInfo(reply, datafile);
  20128. else
  20129. {
  20130. // Temporarily resolve the file
  20131. Owned<IHThorDiskReadBaseArg> helper = (IHThorDiskReadBaseArg *) helperFactory();
  20132. if ((helper->getFlags() & (TDXvarfilename|TDXdynamicfilename)) == 0)
  20133. {
  20134. OwnedRoxieString fileName(helper->getFileName());
  20135. Owned<const IResolvedFile> temp = queryFactory.queryPackage().lookupFileName(fileName, true, true, false, queryFactory.queryWorkUnit(), true);
  20136. if (temp)
  20137. addXrefFileInfo(reply, temp);
  20138. }
  20139. }
  20140. }
  20141. virtual const StatisticsMapping &queryStatsMapping() const
  20142. {
  20143. return diskStatistics;
  20144. }
  20145. };
  20146. IRoxieServerActivityFactory *createRoxieServerDiskReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  20147. {
  20148. return new CRoxieServerDiskReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  20149. }
  20150. //=================================================================================
  20151. class CRoxieServerIndexActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler
  20152. {
  20153. protected:
  20154. IHThorIndexReadBaseArg &indexHelper;
  20155. IHThorSteppedSourceExtra * steppedExtra;
  20156. Linked<IKeyArray> keySet;
  20157. Linked<TranslatorArray> translators;
  20158. CSkippableRemoteResultAdaptor remote;
  20159. CIndexTransformCallback callback;
  20160. bool sorted;
  20161. bool variableFileName;
  20162. bool variableInfoPending;
  20163. bool isOpt;
  20164. bool isLocal;
  20165. unsigned __int64 rowLimit;
  20166. unsigned __int64 keyedLimit;
  20167. unsigned __int64 choosenLimit;
  20168. unsigned accepted;
  20169. unsigned rejected;
  20170. unsigned seekGEOffset;
  20171. Owned<IKeyManager> tlk;
  20172. Owned<const IResolvedFile> varFileInfo;
  20173. const RemoteActivityId &remoteId;
  20174. void setVariableFileInfo()
  20175. {
  20176. OwnedRoxieString indexName(indexHelper.getFileName());
  20177. varFileInfo.setown(resolveLFN(indexName, isOpt));
  20178. if (varFileInfo)
  20179. {
  20180. translators.setown(new TranslatorArray) ;
  20181. keySet.setown(varFileInfo->getKeyArray(factory->queryActivityMeta(), translators, isOpt, isLocal ? factory->queryQueryFactory().queryChannel() : 0, factory->queryQueryFactory().queryOptions().enableFieldTranslation));
  20182. }
  20183. variableInfoPending = false;
  20184. }
  20185. public:
  20186. CRoxieServerIndexActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  20187. IKeyArray * _keySet, TranslatorArray *_translators, bool _sorted, bool _isLocal, bool _maySkip)
  20188. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  20189. keySet(_keySet),
  20190. translators(_translators),
  20191. indexHelper((IHThorIndexReadBaseArg &)basehelper),
  20192. remote(_ctx, this, _remoteId, meta.queryOriginal(), indexHelper, *this, _sorted, false, _maySkip),
  20193. remoteId(_remoteId),
  20194. sorted(_sorted),
  20195. isLocal(_isLocal)
  20196. {
  20197. indexHelper.setCallback(&callback);
  20198. steppedExtra = static_cast<IHThorSteppedSourceExtra *>(indexHelper.selectInterface(TAIsteppedsourceextra_1));
  20199. variableFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((indexHelper.getFlags() & (TIRvarfilename|TIRdynamicfilename)) != 0);
  20200. variableInfoPending = false;
  20201. isOpt = (indexHelper.getFlags() & TIRoptional) != 0;
  20202. seekGEOffset = 0;
  20203. // started = false;
  20204. rejected = accepted = 0;
  20205. rowLimit = choosenLimit = keyedLimit = 0;
  20206. }
  20207. virtual const IResolvedFile *queryVarFileInfo() const
  20208. {
  20209. return varFileInfo;
  20210. }
  20211. virtual void onCreate(IHThorArg *_colocalParent)
  20212. {
  20213. CRoxieServerActivity::onCreate(_colocalParent);
  20214. remote.onCreate(_colocalParent);
  20215. }
  20216. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20217. {
  20218. accepted = 0;
  20219. rejected = 0;
  20220. rowLimit = (unsigned __int64) -1;
  20221. keyedLimit = (unsigned __int64 ) -1;
  20222. choosenLimit = I64C(0x7fffffffffffffff);
  20223. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  20224. remote.onStart(parentExtractSize, parentExtract);
  20225. variableInfoPending = variableFileName;
  20226. }
  20227. void processAllKeys()
  20228. {
  20229. try
  20230. {
  20231. if (indexHelper.canMatchAny())
  20232. {
  20233. if (variableInfoPending)
  20234. setVariableFileInfo();
  20235. remote.setLimits(rowLimit, keyedLimit, choosenLimit);
  20236. if (keySet)
  20237. {
  20238. // MORE - this recreates the segmonitors per part but not per fileno (which is a little backwards).
  20239. // 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
  20240. // However order is probably better to iterate fileno's inside partnos
  20241. // MORE - also not properly supporting STEPPED I fear.
  20242. // A superkey that mixes single and multipart or tlk and roroot keys might be hard
  20243. for (unsigned partNo = 0; partNo < keySet->length(); partNo++)
  20244. {
  20245. IKeyIndexBase *thisBase = keySet->queryKeyPart(partNo);
  20246. if (thisBase)
  20247. {
  20248. unsigned fileNo = 0;
  20249. IKeyIndex *thisKey = thisBase->queryPart(fileNo);
  20250. if (!thisKey->isTopLevelKey())
  20251. {
  20252. if (keyedLimit != (unsigned __int64) -1)
  20253. {
  20254. if ((indexHelper.getFlags() & TIRcountkeyedlimit) != 0)
  20255. {
  20256. Owned<IKeyManager> countKey;
  20257. countKey.setown(createKeyManager(thisKey, 0, this));
  20258. countKey->setLayoutTranslator(translators->item(fileNo));
  20259. createSegmentMonitors(countKey);
  20260. unsigned __int64 count = countKey->checkCount(keyedLimit);
  20261. if (count > keyedLimit)
  20262. {
  20263. if (traceLevel > 4)
  20264. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  20265. onLimitExceeded(true);
  20266. }
  20267. }
  20268. }
  20269. }
  20270. if (seekGEOffset && !thisKey->isTopLevelKey())
  20271. {
  20272. tlk.setown(createSingleKeyMerger(thisKey, 0, seekGEOffset, this));
  20273. }
  20274. else
  20275. {
  20276. tlk.setown(createKeyManager(thisKey, 0, this));
  20277. tlk->setLayoutTranslator(translators->item(fileNo));
  20278. }
  20279. createSegmentMonitors(tlk);
  20280. if (queryTraceLevel() > 3 || ctx->queryProbeManager())
  20281. {
  20282. StringBuffer out;
  20283. printKeyedValues(out, tlk, indexHelper.queryDiskRecordSize());
  20284. CTXLOG("Using filter %s", out.str());
  20285. if (ctx->queryProbeManager())
  20286. ctx->queryProbeManager()->setNodeProperty(this, "filter", out.str());
  20287. }
  20288. tlk->reset();
  20289. loop // for each file part
  20290. {
  20291. //block for TransformCallbackAssociation
  20292. {
  20293. TransformCallbackAssociation associate(callback, tlk);
  20294. if (thisKey->isTopLevelKey())
  20295. {
  20296. if (thisKey->isFullySorted())
  20297. {
  20298. while (tlk->lookup(false))
  20299. {
  20300. unsigned slavePart = (unsigned) tlk->queryFpos();
  20301. if (slavePart)
  20302. {
  20303. accepted++;
  20304. remote.getMem(slavePart, fileNo, 0); // the cached context is all we need to send
  20305. if (sorted && numChannels>1)
  20306. remote.flush(); // don't combine parts if we need result sorted, except on a 1-way
  20307. }
  20308. }
  20309. }
  20310. else
  20311. {
  20312. // MORE - we could check whether there are any matching parts if we wanted.
  20313. // If people are in the habit of sending null values that would be worthwhile
  20314. remote.getMem(0, fileNo, 0);
  20315. }
  20316. }
  20317. else
  20318. {
  20319. if (processSingleKey(thisKey, translators->item(fileNo)))
  20320. break;
  20321. }
  20322. }
  20323. if (++fileNo < thisBase->numParts())
  20324. {
  20325. thisKey = thisBase->queryPart(fileNo);
  20326. tlk->setKey(thisKey);
  20327. tlk->setLayoutTranslator(translators->item(fileNo));
  20328. tlk->reset();
  20329. }
  20330. else
  20331. break;
  20332. }
  20333. tlk->releaseSegmentMonitors();
  20334. tlk->setKey(NULL);
  20335. }
  20336. }
  20337. }
  20338. }
  20339. remote.flush();
  20340. remote.senddone();
  20341. }
  20342. catch (IException *E)
  20343. {
  20344. remote.setException(E);
  20345. }
  20346. }
  20347. virtual void createSegmentMonitors(IKeyManager *key)
  20348. {
  20349. indexHelper.createSegmentMonitors(key);
  20350. key->finishSegmentMonitors();
  20351. }
  20352. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans) = 0;
  20353. virtual void reset()
  20354. {
  20355. if (accepted)
  20356. noteStatistic(StNumIndexAccepted, accepted);
  20357. if (rejected)
  20358. noteStatistic(StNumIndexRejected, rejected);
  20359. remote.onReset();
  20360. CRoxieServerActivity::reset();
  20361. if (varFileInfo)
  20362. {
  20363. keySet.clear();
  20364. varFileInfo.clear();
  20365. }
  20366. variableInfoPending = false;
  20367. }
  20368. virtual void stop()
  20369. {
  20370. remote.onStop();
  20371. CRoxieServerActivity::stop();
  20372. }
  20373. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  20374. {
  20375. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  20376. }
  20377. };
  20378. class CRoxieServerIndexReadBaseActivity : public CRoxieServerIndexActivity
  20379. {
  20380. IHThorSourceLimitTransformExtra * limitTransformExtra;
  20381. public:
  20382. CRoxieServerIndexReadBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  20383. IKeyArray * _keySet, TranslatorArray *_translators, bool _sorted, bool _isLocal, bool _maySkip)
  20384. : CRoxieServerIndexActivity(_ctx, _factory, _probeManager, _remoteId, _keySet, _translators, _sorted, _isLocal, _maySkip)
  20385. {
  20386. limitTransformExtra = static_cast<IHThorSourceLimitTransformExtra *>(indexHelper.selectInterface(TAIsourcelimittransformextra_1));
  20387. }
  20388. virtual void reset()
  20389. {
  20390. remote.onReset();
  20391. CRoxieServerIndexActivity::reset();
  20392. }
  20393. virtual const void *nextRow()
  20394. {
  20395. ActivityTimer t(totalCycles, timeActivities);
  20396. try
  20397. {
  20398. const void *ret = remote.nextRow();
  20399. if (ret)
  20400. processed++;
  20401. return ret;
  20402. }
  20403. catch (IException *E)
  20404. {
  20405. throw makeWrappedException(E);
  20406. }
  20407. }
  20408. protected:
  20409. virtual const void * createLimitFailRow(bool isKeyed)
  20410. {
  20411. ensureRowAllocator();
  20412. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  20413. size32_t outSize = isKeyed ? limitTransformExtra->transformOnKeyedLimitExceeded(rowBuilder) : limitTransformExtra->transformOnLimitExceeded(rowBuilder);
  20414. if (outSize)
  20415. return rowBuilder.finalizeRowClear(outSize);
  20416. return NULL;
  20417. }
  20418. };
  20419. class CRoxieServerIndexReadActivity : public CRoxieServerIndexReadBaseActivity, implements IIndexReadActivityInfo
  20420. {
  20421. protected:
  20422. IHThorCompoundReadExtra & readHelper;
  20423. ISteppingMeta *rawMeta = nullptr;
  20424. CSteppingMeta steppingMeta;
  20425. unsigned * seekSizes = nullptr;
  20426. bool optimizeSteppedPostFilter;
  20427. ISteppingMeta * projectedMeta = nullptr;
  20428. unsigned maxSeekLookahead;
  20429. public:
  20430. CRoxieServerIndexReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  20431. IKeyArray * _keySet, TranslatorArray *_translators, bool _sorted, bool _isLocal, bool _maySkip, unsigned _maxSeekLookahead)
  20432. : CRoxieServerIndexReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _keySet, _translators, _sorted, _isLocal, _maySkip),
  20433. readHelper((IHThorIndexReadArg &)basehelper)
  20434. {
  20435. rawMeta = readHelper.queryRawSteppingMeta();
  20436. unsigned flags = indexHelper.getFlags();
  20437. optimizeSteppedPostFilter = (flags & TIRunfilteredtransform) != 0;
  20438. seekSizes = NULL;
  20439. maxSeekLookahead = _maxSeekLookahead;
  20440. if (rawMeta)
  20441. {
  20442. const CFieldOffsetSize * fields = rawMeta->queryFields();
  20443. unsigned maxFields = rawMeta->getNumFields();
  20444. seekGEOffset = fields[0].offset;
  20445. seekSizes = new unsigned[maxFields];
  20446. seekSizes[0] = fields[0].size;
  20447. for (unsigned i=1; i < maxFields; i++)
  20448. seekSizes[i] = seekSizes[i-1] + fields[i].size;
  20449. projectedMeta = readHelper.queryProjectedSteppingMeta();
  20450. ISteppingMeta *useMeta = projectedMeta ? projectedMeta : rawMeta;
  20451. remote.setMergeInfo(useMeta); // also need to consider superfile case where there is a mix of multiway and singleparts.. ?
  20452. bool hasPostFilter = readHelper.transformMayFilter() && optimizeSteppedPostFilter;
  20453. steppingMeta.init(useMeta, hasPostFilter);
  20454. }
  20455. }
  20456. ~CRoxieServerIndexReadActivity()
  20457. {
  20458. delete [] seekSizes;
  20459. }
  20460. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20461. {
  20462. CRoxieServerIndexReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  20463. steppingMeta.setDistributed();
  20464. if (steppedExtra)
  20465. steppingMeta.setExtra(steppedExtra);
  20466. rowLimit = readHelper.getRowLimit();
  20467. keyedLimit = readHelper.getKeyedLimit();
  20468. choosenLimit = readHelper.getChooseNLimit();
  20469. if (!paused)
  20470. processAllKeys();
  20471. }
  20472. class LazyLocalKeyReader : implements IMessageUnpackCursor, implements IMessageResult, public CInterface
  20473. {
  20474. public:
  20475. IMPLEMENT_IINTERFACE;
  20476. virtual IMessageUnpackCursor *getCursor(roxiemem::IRowManager *rowMgr) const
  20477. {
  20478. Link();
  20479. return const_cast<LazyLocalKeyReader*> (this);
  20480. }
  20481. virtual const void *getMessageHeader(unsigned &length) const
  20482. {
  20483. length = 0;
  20484. return NULL;
  20485. }
  20486. virtual const void *getMessageMetadata(unsigned &length) const
  20487. {
  20488. length = 0;
  20489. return NULL;
  20490. }
  20491. virtual void discard() const
  20492. {
  20493. // nothing to do.
  20494. }
  20495. unsigned keyedCount;
  20496. unsigned matched;
  20497. bool EOFseen;
  20498. Owned<IKeyIndexSet> keySet;
  20499. Owned<IKeyManager> tlk;
  20500. CRoxieServerIndexReadActivity &owner;
  20501. LazyLocalKeyReader(CRoxieServerIndexReadActivity &_owner, IKeyIndex *key, IRecordLayoutTranslator * trans)
  20502. : owner(_owner)
  20503. {
  20504. keyedCount = 0;
  20505. matched = 0;
  20506. EOFseen = false;
  20507. keySet.setown(createKeyIndexSet());
  20508. keySet->addIndex(LINK(key));
  20509. if (owner.seekGEOffset)
  20510. tlk.setown(createKeyMerger(keySet, 0, owner.seekGEOffset, &owner));
  20511. else
  20512. tlk.setown(createKeyManager(keySet->queryPart(0), 0, &owner));
  20513. tlk->setLayoutTranslator(trans);
  20514. owner.indexHelper.createSegmentMonitors(tlk);
  20515. tlk->finishSegmentMonitors();
  20516. tlk->reset();
  20517. }
  20518. virtual const void *getNext(int length)
  20519. {
  20520. TransformCallbackAssociation associate(owner.callback, tlk);
  20521. while (tlk->lookup(true))
  20522. {
  20523. keyedCount++;
  20524. if (keyedCount > owner.keyedLimit)
  20525. {
  20526. owner.onLimitExceeded(true); // Should throw exception
  20527. throwUnexpected();
  20528. }
  20529. size32_t transformedSize;
  20530. RtlDynamicRowBuilder rowBuilder(owner.rowAllocator);
  20531. byte const * keyRow = tlk->queryKeyBuffer(owner.callback.getFPosRef());
  20532. try
  20533. {
  20534. transformedSize = owner.readHelper.transform(rowBuilder, keyRow);
  20535. owner.callback.finishedRow();
  20536. }
  20537. catch (IException *E)
  20538. {
  20539. throw owner.makeWrappedException(E);
  20540. }
  20541. if (transformedSize)
  20542. {
  20543. OwnedConstRoxieRow result = rowBuilder.finalizeRowClear(transformedSize);
  20544. matched++;
  20545. if (matched > owner.rowLimit)
  20546. {
  20547. owner.onLimitExceeded(false); // Should throw exception
  20548. throwUnexpected();
  20549. }
  20550. if (matched > owner.choosenLimit) // MORE - bit of a strange place to check
  20551. {
  20552. break;
  20553. }
  20554. owner.accepted++;
  20555. return result.getClear();
  20556. }
  20557. else
  20558. owner.rejected++;
  20559. }
  20560. EOFseen = true;
  20561. return NULL;
  20562. }
  20563. virtual bool atEOF() const
  20564. {
  20565. return EOFseen;
  20566. }
  20567. virtual bool isSerialized() const
  20568. {
  20569. return false;
  20570. }
  20571. };
  20572. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
  20573. {
  20574. ensureRowAllocator();
  20575. remote.injectResult(new LazyLocalKeyReader(*this, key, trans));
  20576. return false;
  20577. }
  20578. virtual void onLimitExceeded(bool isKeyed)
  20579. {
  20580. if (traceLevel > 4)
  20581. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  20582. if (isKeyed)
  20583. {
  20584. if (indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates))
  20585. {
  20586. if (ctx->queryDebugContext())
  20587. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  20588. throw makeLimitSkipException(true);
  20589. }
  20590. else
  20591. readHelper.onKeyedLimitExceeded();
  20592. }
  20593. else
  20594. {
  20595. if (indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates))
  20596. {
  20597. if (ctx->queryDebugContext())
  20598. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  20599. throw makeLimitSkipException(false);
  20600. }
  20601. else
  20602. readHelper.onLimitExceeded();
  20603. }
  20604. }
  20605. virtual void serializeSkipInfo(MemoryBuffer &out, unsigned seekLen, const void *rawSeek, unsigned numFields, const void * seek, const SmartStepExtra &stepExtra) const
  20606. {
  20607. out.append((unsigned short) numFields);
  20608. out.append((unsigned short) seekLen);
  20609. out.append((unsigned short) stepExtra.queryFlags());
  20610. IMultipleStepSeekInfo *seeks = stepExtra.queryExtraSeeks();
  20611. if (seeks)
  20612. {
  20613. unsigned lookahead = 40000/seekLen;
  20614. if (maxSeekLookahead && (lookahead > maxSeekLookahead))
  20615. lookahead = maxSeekLookahead;
  20616. seeks->ensureFilled(seek, numFields, lookahead);
  20617. out.append(lookahead != seeks->ordinality()); // seeksAreEof flag
  20618. unsigned serialized = 1; // rawseek is always serialized...
  20619. unsigned patchLength = out.length();
  20620. out.append(serialized); // NOTE - we come back and patch with the actual value...
  20621. out.append(seekLen, rawSeek);
  20622. if (seeks->ordinality())
  20623. {
  20624. const void *lastSeek = rawSeek;
  20625. byte *nextSeek = NULL;
  20626. if (projectedMeta)
  20627. nextSeek = (byte *) alloca(seekLen);
  20628. for (unsigned i = 0; i < seeks->ordinality(); i++)
  20629. {
  20630. if (projectedMeta)
  20631. {
  20632. RtlStaticRowBuilder rowBuilder(nextSeek-seekGEOffset, seekGEOffset+seekLen);
  20633. readHelper.mapOutputToInput(rowBuilder, seeks->querySeek(i), numFields); // NOTE - weird interface to mapOutputToInput means that it STARTS writing at seekGEOffset...
  20634. }
  20635. else
  20636. nextSeek = (byte *) seeks->querySeek(i)+seekGEOffset;
  20637. int diff = memcmp(nextSeek, lastSeek, seekLen);
  20638. if (diff > 0)
  20639. {
  20640. serialized++;
  20641. out.append(seekLen, nextSeek);
  20642. lastSeek = (const byte *) out.reserve(0) - seekLen;
  20643. }
  20644. }
  20645. unsigned length = out.length();
  20646. out.setWritePos(patchLength);
  20647. out.append(serialized);
  20648. out.setWritePos(length);
  20649. }
  20650. }
  20651. else
  20652. {
  20653. out.append(false);
  20654. out.append(1);
  20655. out.append(seekLen, rawSeek);
  20656. }
  20657. }
  20658. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  20659. {
  20660. ActivityTimer t(totalCycles, timeActivities);
  20661. try
  20662. {
  20663. unsigned seeklen = 0;
  20664. const void *rawSeek = NULL;
  20665. if (seek && numFields)
  20666. {
  20667. seeklen = seekSizes[numFields-1];
  20668. rawSeek = (const byte *)seek + seekGEOffset;
  20669. if (projectedMeta)
  20670. {
  20671. byte * temp = (byte *) alloca(seeklen);
  20672. RtlStaticRowBuilder rawBuilder(temp-seekGEOffset, seekGEOffset+seeklen);
  20673. readHelper.mapOutputToInput(rawBuilder, seek, numFields); // NOTE - weird interface to mapOutputToInput means that it STARTS writing at seekGEOffset...
  20674. rawSeek = (byte *)temp;
  20675. }
  20676. }
  20677. const void *ret = remote.nextRowGE(seek, rawSeek, numFields, seeklen, wasCompleteMatch, stepExtra);
  20678. if (ret && wasCompleteMatch) // GH pleas confirm the wasCompleteMatch I just added here is right
  20679. processed++;
  20680. return ret;
  20681. }
  20682. catch (IException *E)
  20683. {
  20684. throw makeWrappedException(E);
  20685. }
  20686. }
  20687. virtual IInputSteppingMeta * querySteppingMeta()
  20688. {
  20689. if (rawMeta && steppingEnabled && ((indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates|TIRkeyedlimitskips|TIRkeyedlimitcreates)) == 0))
  20690. return &steppingMeta;
  20691. return NULL;
  20692. }
  20693. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  20694. {
  20695. if (variableInfoPending)
  20696. setVariableFileInfo();
  20697. return this;
  20698. }
  20699. virtual IKeyArray *getKeySet() const
  20700. {
  20701. return keySet.getLink();
  20702. }
  20703. virtual const IResolvedFile *getVarFileInfo() const
  20704. {
  20705. return varFileInfo.getLink();
  20706. }
  20707. virtual TranslatorArray *getTranslators() const
  20708. {
  20709. return translators.getLink();
  20710. }
  20711. virtual void mergeSegmentMonitors(IIndexReadContext *irc) const
  20712. {
  20713. indexHelper.createSegmentMonitors(irc); // NOTE: they will merge
  20714. }
  20715. virtual IRoxieServerActivity *queryActivity() { return this; }
  20716. virtual const RemoteActivityId& queryRemoteId() const
  20717. {
  20718. return remoteId;
  20719. }
  20720. };
  20721. class CRoxieServerSimpleIndexReadActivity : public CRoxieServerActivity, implements IIndexReadActivityInfo
  20722. {
  20723. IHThorCompoundReadExtra & readHelper;
  20724. IHThorIndexReadBaseArg & indexHelper;
  20725. IHThorSourceLimitTransformExtra * limitTransformExtra;
  20726. IHThorSteppedSourceExtra * steppedExtra;
  20727. bool eof;
  20728. Linked<IKeyArray>keySet;
  20729. Owned<IKeyIndexSet>keyIndexSet;
  20730. Owned<IKeyManager> tlk;
  20731. Linked<TranslatorArray> translators;
  20732. CIndexTransformCallback callback;
  20733. unsigned __int64 keyedLimit;
  20734. unsigned rowLimit;
  20735. unsigned chooseNLimit;
  20736. unsigned accepted;
  20737. unsigned rejected;
  20738. unsigned keyedCount;
  20739. ISteppingMeta * rawMeta;
  20740. ISteppingMeta * projectedMeta;
  20741. size32_t seekGEOffset;
  20742. unsigned * seekSizes;
  20743. CSteppingMeta steppingMeta;
  20744. Owned<const IResolvedFile> varFileInfo;
  20745. const RemoteActivityId &remoteId;
  20746. bool firstRead;
  20747. bool variableFileName;
  20748. bool variableInfoPending;
  20749. bool isOpt;
  20750. bool isLocal;
  20751. bool optimizeSteppedPostFilter;
  20752. // MORE there may be enough in common between this and CRoxieServerIndexActivity to warrant some refactoring
  20753. void initKeySet()
  20754. {
  20755. if ((keySet->length() > 1 || rawMeta != NULL) && translators->needsTranslation())
  20756. {
  20757. throw MakeStringException(ROXIE_UNIMPLEMENTED_ERROR, "Layout translation is not available when merging key parts or smart-stepping, as it may change record order");
  20758. }
  20759. keyIndexSet.setown(createKeyIndexSet());
  20760. for (unsigned part = 0; part < keySet->length(); part++)
  20761. {
  20762. IKeyIndexBase *kib = keySet->queryKeyPart(part);
  20763. if (kib)
  20764. {
  20765. for (unsigned subpart = 0; subpart < kib->numParts(); subpart++)
  20766. {
  20767. IKeyIndex *k = kib->queryPart(subpart);
  20768. if (k)
  20769. {
  20770. assertex(!k->isTopLevelKey());
  20771. keyIndexSet->addIndex(LINK(k));
  20772. }
  20773. }
  20774. }
  20775. }
  20776. }
  20777. void setVariableFileInfo()
  20778. {
  20779. OwnedRoxieString indexName(indexHelper.getFileName());
  20780. varFileInfo.setown(resolveLFN(indexName, isOpt));
  20781. translators.setown(new TranslatorArray) ;
  20782. keySet.setown(varFileInfo->getKeyArray(factory->queryActivityMeta(), translators, isOpt, isLocal ? factory->queryQueryFactory().queryChannel() : 0, factory->queryQueryFactory().queryOptions().enableFieldTranslation));
  20783. initKeySet();
  20784. variableInfoPending = false;
  20785. }
  20786. void onEOF()
  20787. {
  20788. callback.setManager(NULL);
  20789. eof = true;
  20790. tlk.clear();
  20791. }
  20792. public:
  20793. CRoxieServerSimpleIndexReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  20794. IKeyArray *_keyArray, TranslatorArray *_translatorArray, bool _isLocal)
  20795. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  20796. readHelper((IHThorIndexReadArg &)basehelper),
  20797. indexHelper((IHThorIndexReadArg &)basehelper),
  20798. translators(_translatorArray),
  20799. keySet(_keyArray),
  20800. isLocal(_isLocal),
  20801. remoteId(_remoteId)
  20802. {
  20803. rowLimit = 0;
  20804. keyedLimit = 0;
  20805. chooseNLimit = 0;
  20806. indexHelper.setCallback(&callback);
  20807. steppedExtra = static_cast<IHThorSteppedSourceExtra *>(indexHelper.selectInterface(TAIsteppedsourceextra_1));
  20808. limitTransformExtra = static_cast<IHThorSourceLimitTransformExtra *>(indexHelper.selectInterface(TAIsourcelimittransformextra_1));
  20809. unsigned flags = indexHelper.getFlags();
  20810. variableFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((flags & (TIRvarfilename|TIRdynamicfilename)) != 0);
  20811. variableInfoPending = false;
  20812. isOpt = (flags & TIRoptional) != 0;
  20813. optimizeSteppedPostFilter = (flags & TIRunfilteredtransform) != 0;
  20814. firstRead = true;
  20815. accepted = 0;
  20816. rejected = 0;
  20817. keyedCount = 0;
  20818. eof = false;
  20819. rawMeta = readHelper.queryRawSteppingMeta();
  20820. projectedMeta = readHelper.queryProjectedSteppingMeta();
  20821. seekGEOffset = 0;
  20822. seekSizes = NULL;
  20823. if (rawMeta)
  20824. {
  20825. // MORE - should check all keys in maxFields list can actually be keyed.
  20826. const CFieldOffsetSize * fields = rawMeta->queryFields();
  20827. unsigned maxFields = rawMeta->getNumFields();
  20828. seekGEOffset = fields[0].offset;
  20829. seekSizes = new unsigned[maxFields];
  20830. seekSizes[0] = fields[0].size;
  20831. for (unsigned i=1; i < maxFields; i++)
  20832. seekSizes[i] = seekSizes[i-1] + fields[i].size;
  20833. bool hasPostFilter = readHelper.transformMayFilter() && optimizeSteppedPostFilter;
  20834. if (projectedMeta)
  20835. steppingMeta.init(projectedMeta, hasPostFilter);
  20836. else
  20837. steppingMeta.init(rawMeta, hasPostFilter);
  20838. }
  20839. }
  20840. virtual const IResolvedFile *queryVarFileInfo() const
  20841. {
  20842. return varFileInfo;
  20843. }
  20844. ~CRoxieServerSimpleIndexReadActivity()
  20845. {
  20846. delete [] seekSizes;
  20847. }
  20848. virtual bool needsAllocator() const { return true; }
  20849. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20850. {
  20851. firstRead = true;
  20852. accepted = 0;
  20853. rejected = 0;
  20854. keyedCount = 0;
  20855. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  20856. if (steppedExtra)
  20857. steppingMeta.setExtra(steppedExtra);
  20858. eof = !indexHelper.canMatchAny();
  20859. if (variableFileName)
  20860. variableInfoPending = true;
  20861. else
  20862. {
  20863. variableInfoPending = false;
  20864. if (!keyIndexSet)
  20865. initKeySet();
  20866. }
  20867. }
  20868. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  20869. {
  20870. if (variableInfoPending)
  20871. setVariableFileInfo();
  20872. return this;
  20873. }
  20874. virtual IKeyArray *getKeySet() const
  20875. {
  20876. return keySet.getLink();
  20877. }
  20878. virtual const IResolvedFile *getVarFileInfo() const
  20879. {
  20880. return varFileInfo.getLink();
  20881. }
  20882. virtual TranslatorArray *getTranslators() const
  20883. {
  20884. return translators.getLink();
  20885. }
  20886. virtual void mergeSegmentMonitors(IIndexReadContext *irc) const
  20887. {
  20888. indexHelper.createSegmentMonitors(irc); // NOTE: they will merge
  20889. }
  20890. virtual IRoxieServerActivity *queryActivity() { return this; }
  20891. virtual const RemoteActivityId& queryRemoteId() const
  20892. {
  20893. return remoteId;
  20894. }
  20895. const void *nextRow()
  20896. {
  20897. bool matched = true;
  20898. return nextRowGE(NULL, 0, matched, dummySmartStepExtra);
  20899. }
  20900. unsigned __int64 checkCount(unsigned __int64 limit)
  20901. {
  20902. unsigned numParts = keyIndexSet->numParts();
  20903. unsigned __int64 result = 0;
  20904. for (unsigned i = 0; i < numParts; i++)
  20905. {
  20906. Owned<IKeyManager> countTlk = createKeyManager(keyIndexSet->queryPart(i), 0, this);
  20907. countTlk->setLayoutTranslator(translators->item(i));
  20908. indexHelper.createSegmentMonitors(countTlk);
  20909. countTlk->finishSegmentMonitors();
  20910. result += countTlk->checkCount(limit-result);
  20911. if (result > limit)
  20912. break;
  20913. }
  20914. return result;
  20915. }
  20916. virtual const void *nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  20917. {
  20918. ActivityTimer t(totalCycles, timeActivities);
  20919. if (eof)
  20920. return NULL;
  20921. if (firstRead)
  20922. {
  20923. if (variableInfoPending)
  20924. setVariableFileInfo();
  20925. rowLimit = (unsigned) readHelper.getRowLimit();
  20926. chooseNLimit = (unsigned) readHelper.getChooseNLimit();
  20927. unsigned numParts = keyIndexSet->numParts();
  20928. if (!numParts)
  20929. {
  20930. onEOF();
  20931. return NULL;
  20932. }
  20933. if (numParts > 1 || seekGEOffset)
  20934. {
  20935. tlk.setown(createKeyMerger(keyIndexSet, 0, seekGEOffset, this));
  20936. // note that we don't set up translator because we don't support it. If that ever changes...
  20937. }
  20938. else
  20939. {
  20940. tlk.setown(createKeyManager(keyIndexSet->queryPart(0), 0, this));
  20941. tlk->setLayoutTranslator(translators->item(0));
  20942. }
  20943. indexHelper.createSegmentMonitors(tlk);
  20944. tlk->finishSegmentMonitors();
  20945. if (queryTraceLevel() > 3 || ctx->queryProbeManager())
  20946. {
  20947. StringBuffer out;
  20948. printKeyedValues(out, tlk, indexHelper.queryDiskRecordSize());
  20949. CTXLOG("Using filter %s", out.str());
  20950. if (ctx->queryProbeManager())
  20951. ctx->queryProbeManager()->setNodeProperty(this, "filter", out.str());
  20952. }
  20953. tlk->reset();
  20954. callback.setManager(tlk);
  20955. keyedLimit = readHelper.getKeyedLimit();
  20956. if (keyedLimit != (unsigned __int64) -1)
  20957. {
  20958. if ((indexHelper.getFlags() & TIRcountkeyedlimit) != 0)
  20959. {
  20960. unsigned __int64 count = checkCount(keyedLimit);
  20961. if (count > keyedLimit)
  20962. {
  20963. if ((indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates)) == 0)
  20964. readHelper.onKeyedLimitExceeded();
  20965. const void * ret = NULL;
  20966. if (indexHelper.getFlags() & TIRkeyedlimitcreates)
  20967. ret = createKeyedLimitOnFailRow();
  20968. onEOF();
  20969. return ret;
  20970. }
  20971. keyedLimit = (unsigned __int64) -1;
  20972. }
  20973. }
  20974. firstRead = false;
  20975. }
  20976. if (accepted == chooseNLimit)
  20977. {
  20978. onEOF();
  20979. return NULL;
  20980. }
  20981. const byte * rawSeek = NULL;
  20982. unsigned seekSize = 0;
  20983. if (seek)
  20984. {
  20985. seekSize = seekSizes[numFields-1];
  20986. rawSeek = (const byte *)seek + seekGEOffset;
  20987. if (projectedMeta)
  20988. {
  20989. byte *temp = (byte *) alloca(seekSize);
  20990. RtlStaticRowBuilder rawBuilder(temp-seekGEOffset, seekGEOffset+seekSize);
  20991. readHelper.mapOutputToInput(rawBuilder, seek, numFields);// NOTE - weird interface to mapOutputToInput means that it STARTS writing at seekGEOffset...
  20992. rawSeek = (byte *)temp;
  20993. }
  20994. #ifdef _DEBUG
  20995. // StringBuffer seekStr;
  20996. // for (unsigned i = 0; i < seekSize; i++)
  20997. // {
  20998. // seekStr.appendf("%02x ", ((unsigned char *) rawSeek)[i]);
  20999. // }
  21000. // DBGLOG("nextRowGE can skip offset %d size %d value %s", seekGEOffset, seekSize, seekStr.str());
  21001. #endif
  21002. }
  21003. const byte * originalRawSeek = rawSeek;
  21004. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  21005. while (rawSeek ? tlk->lookupSkip(rawSeek, seekGEOffset, seekSize) : tlk->lookup(true))
  21006. {
  21007. checkAbort();
  21008. keyedCount++;
  21009. if (keyedCount > keyedLimit)
  21010. {
  21011. readHelper.onKeyedLimitExceeded();
  21012. break;
  21013. }
  21014. byte const * keyRow = tlk->queryKeyBuffer(callback.getFPosRef());
  21015. #ifdef _DEBUG
  21016. // StringBuffer recstr;
  21017. // unsigned size = (tlk->queryRecordSize()<80) ? tlk->queryRecordSize() : 80;
  21018. // for (unsigned i = 0; i < size; i++)
  21019. // {
  21020. // recstr.appendf("%02x ", ((unsigned char *) keyRow)[i]);
  21021. // }
  21022. // DBGLOG("nextRowGE Got %s", recstr.str());
  21023. if (originalRawSeek && memcmp(keyRow + seekGEOffset, originalRawSeek, seekSize) < 0)
  21024. assertex(!"smart seek failure");
  21025. #endif
  21026. size32_t transformedSize;
  21027. rowBuilder.ensureRow();
  21028. try
  21029. {
  21030. transformedSize = readHelper.transform(rowBuilder, keyRow);
  21031. //if the post filter causes a mismatch, and the stepping condition no longer matches
  21032. //then return a mismatch record - so the join code can start seeking on the other input.
  21033. if (transformedSize == 0 && optimizeSteppedPostFilter && stepExtra.returnMismatches())
  21034. {
  21035. if (memcmp(keyRow + seekGEOffset, originalRawSeek, seekSize) != 0)
  21036. {
  21037. transformedSize = readHelper.unfilteredTransform(rowBuilder, keyRow);
  21038. if (transformedSize != 0)
  21039. wasCompleteMatch = false;
  21040. }
  21041. }
  21042. callback.finishedRow();
  21043. }
  21044. catch (IException *E)
  21045. {
  21046. throw makeWrappedException(E);
  21047. }
  21048. if (transformedSize)
  21049. {
  21050. accepted++;
  21051. if (accepted > rowLimit)
  21052. {
  21053. if ((indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates)) != 0)
  21054. {
  21055. throwUnexpected(); // should not have used simple variant if maySkip set...
  21056. }
  21057. if (traceLevel > 4)
  21058. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  21059. readHelper.onLimitExceeded();
  21060. break;
  21061. }
  21062. processed++;
  21063. #ifdef _DEBUG
  21064. // const byte *ret = (const byte *) out.get();
  21065. // CommonXmlWriter xmlwrite(XWFnoindent|XWFtrim|XWFopt);
  21066. // queryOutputMeta()->toXML(ret, xmlwrite);
  21067. // DBGLOG("ROW: {%p} %s", ret, xmlwrite.str());
  21068. #endif
  21069. return rowBuilder.finalizeRowClear(transformedSize);
  21070. }
  21071. else
  21072. rejected++;
  21073. rawSeek = NULL;
  21074. }
  21075. onEOF();
  21076. return NULL;
  21077. }
  21078. virtual void reset()
  21079. {
  21080. onEOF();
  21081. if (accepted)
  21082. noteStatistic(StNumIndexAccepted, accepted);
  21083. if (rejected)
  21084. noteStatistic(StNumIndexRejected, rejected);
  21085. if (variableFileName)
  21086. {
  21087. varFileInfo.clear();
  21088. translators.clear();
  21089. }
  21090. variableInfoPending = false;
  21091. CRoxieServerActivity::reset();
  21092. }
  21093. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  21094. {
  21095. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  21096. }
  21097. virtual IInputSteppingMeta * querySteppingMeta()
  21098. {
  21099. if (rawMeta && steppingEnabled && ((indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates|TIRkeyedlimitskips|TIRkeyedlimitcreates)) == 0))
  21100. return &steppingMeta;
  21101. return NULL;
  21102. }
  21103. protected:
  21104. const void * createKeyedLimitOnFailRow()
  21105. {
  21106. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  21107. size32_t outSize = limitTransformExtra->transformOnKeyedLimitExceeded(rowBuilder);
  21108. if (outSize)
  21109. return rowBuilder.finalizeRowClear(outSize);
  21110. return NULL;
  21111. }
  21112. };
  21113. class CRoxieServerBaseIndexActivityFactory : public CRoxieServerActivityFactory
  21114. {
  21115. public:
  21116. Owned<IKeyArray> keySet;
  21117. Owned<TranslatorArray> translatorArray;
  21118. Owned<IDefRecordMeta> activityMeta;
  21119. RemoteActivityId remoteId;
  21120. bool isSimple;
  21121. bool isLocal;
  21122. bool maySkip;
  21123. bool sorted;
  21124. bool variableFileName;
  21125. bool enableFieldTranslation;
  21126. unsigned maxSeekLookahead;
  21127. Owned<const IResolvedFile> indexfile;
  21128. CRoxieServerSideCache *cache;
  21129. CRoxieServerBaseIndexActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21130. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), remoteId(_remoteId)
  21131. {
  21132. Owned<IHThorIndexReadBaseArg> indexHelper = (IHThorIndexReadBaseArg *) helperFactory();
  21133. unsigned flags = indexHelper->getFlags();
  21134. sorted = (flags & TIRunordered) == 0;
  21135. isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  21136. rtlDataAttr indexLayoutMeta;
  21137. size32_t indexLayoutSize;
  21138. if(!indexHelper->getIndexLayout(indexLayoutSize, indexLayoutMeta.refdata()))
  21139. assertex(indexLayoutSize==0);
  21140. MemoryBuffer m;
  21141. m.setBuffer(indexLayoutSize, indexLayoutMeta.getdata());
  21142. activityMeta.setown(deserializeRecordMeta(m, true));
  21143. enableFieldTranslation = queryFactory.queryOptions().enableFieldTranslation;
  21144. translatorArray.setown(new TranslatorArray);
  21145. variableFileName = allFilesDynamic || _queryFactory.isDynamic() || ((flags & (TIRvarfilename|TIRdynamicfilename)) != 0);
  21146. if (!variableFileName)
  21147. {
  21148. bool isOpt = (flags & TIRoptional) != 0;
  21149. OwnedRoxieString indexName(indexHelper->getFileName());
  21150. indexfile.setown(queryFactory.queryPackage().lookupFileName(indexName, isOpt, true, true, queryFactory.queryWorkUnit(), true));
  21151. if (indexfile)
  21152. keySet.setown(indexfile->getKeyArray(activityMeta, translatorArray, isOpt, isLocal ? queryFactory.queryChannel() : 0, enableFieldTranslation));
  21153. }
  21154. isSimple = isLocal;
  21155. maySkip = (flags & (TIRkeyedlimitskips|TIRlimitskips|TIRlimitcreates|TIRkeyedlimitcreates)) != 0;
  21156. if (keySet && keySet->length()==1 && !isLocal && (flags & (TIRlimitskips|TIRlimitcreates|TIRkeyedlimitskips|TIRkeyedlimitcreates))==0)
  21157. {
  21158. IKeyIndexBase *thisBase = keySet->queryKeyPart(0);
  21159. if (thisBase->numParts()==1 && !thisBase->queryPart(0)->isTopLevelKey() && !_queryFactory.queryOptions().disableLocalOptimizations)
  21160. isSimple = true;
  21161. }
  21162. int cacheSize = _graphNode.getPropInt("hint[@name='cachehits']/@value", serverSideCacheSize);
  21163. cache = cacheSize ? new CRoxieServerSideCache(cacheSize) : NULL;
  21164. maxSeekLookahead = _graphNode.getPropInt("hint[@name='maxseeklookahead']/@value", 0);
  21165. }
  21166. ~CRoxieServerBaseIndexActivityFactory()
  21167. {
  21168. delete cache;
  21169. }
  21170. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  21171. {
  21172. if (indexfile)
  21173. addXrefFileInfo(reply, indexfile);
  21174. else
  21175. {
  21176. Owned<IHThorIndexReadBaseArg> indexHelper = (IHThorIndexReadBaseArg *) helperFactory();
  21177. if ((indexHelper->getFlags() & (TIRvarfilename|TIRdynamicfilename)) == 0)
  21178. {
  21179. OwnedRoxieString indexName(indexHelper->getFileName());
  21180. Owned<const IResolvedFile> temp = queryFactory.queryPackage().lookupFileName(indexName, true, true, false, queryFactory.queryWorkUnit(), true);
  21181. if (temp)
  21182. addXrefFileInfo(reply, temp);
  21183. }
  21184. }
  21185. }
  21186. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  21187. {
  21188. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for indexread activity");
  21189. }
  21190. virtual IRoxieServerSideCache *queryServerSideCache() const
  21191. {
  21192. return cache;
  21193. }
  21194. virtual bool getEnableFieldTranslation() const
  21195. {
  21196. return enableFieldTranslation;
  21197. }
  21198. virtual IDefRecordMeta *queryActivityMeta() const
  21199. {
  21200. return activityMeta;
  21201. }
  21202. virtual const StatisticsMapping &queryStatsMapping() const
  21203. {
  21204. return indexStatistics;
  21205. }
  21206. };
  21207. class CRoxieServerIndexReadActivityFactory : public CRoxieServerBaseIndexActivityFactory
  21208. {
  21209. public:
  21210. CRoxieServerIndexReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21211. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId)
  21212. {
  21213. }
  21214. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  21215. {
  21216. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  21217. return new CRoxieServerNullActivity(_ctx, this, _probeManager);
  21218. else if (isSimple && !maySkip)
  21219. return new CRoxieServerSimpleIndexReadActivity(_ctx, this, _probeManager, remoteId, keySet, translatorArray, isLocal);
  21220. else
  21221. return new CRoxieServerIndexReadActivity(_ctx, this, _probeManager, remoteId, keySet, translatorArray, sorted, isLocal, maySkip, maxSeekLookahead);
  21222. }
  21223. };
  21224. IRoxieServerActivityFactory *createRoxieServerIndexReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21225. {
  21226. return new CRoxieServerIndexReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  21227. }
  21228. //--------------------------------------------------------------------------------------------------------------------------
  21229. class CRoxieServerNullCountActivity : public CRoxieServerActivity
  21230. {
  21231. bool done;
  21232. public:
  21233. CRoxieServerNullCountActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  21234. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  21235. {
  21236. done = false;
  21237. }
  21238. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21239. {
  21240. done = false;
  21241. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  21242. }
  21243. virtual bool needsAllocator() const { return true; }
  21244. virtual const void *nextRow()
  21245. {
  21246. ActivityTimer t(totalCycles, timeActivities);
  21247. if (done) return NULL;
  21248. done = true;
  21249. size32_t rowSize = meta.getFixedSize();
  21250. void * nullRow = rowAllocator->createRow();
  21251. if (rowSize == 1)
  21252. *(byte *)nullRow = 0;
  21253. else
  21254. {
  21255. assertex(rowSize == sizeof(unsigned __int64));
  21256. *(unsigned __int64 *)nullRow = 0;
  21257. }
  21258. return rowAllocator->finalizeRow(rowSize, nullRow, rowSize);
  21259. }
  21260. };
  21261. class CRoxieServerIndexCountActivity : public CRoxieServerIndexActivity
  21262. {
  21263. IHThorCompoundCountExtra & countHelper;
  21264. IHThorSourceCountLimit * limitHelper;
  21265. bool done;
  21266. public:
  21267. CRoxieServerIndexCountActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IKeyArray * _keySet, TranslatorArray *_translators, bool _isLocal)
  21268. : CRoxieServerIndexActivity(_ctx, _factory, _probeManager, _remoteId, _keySet, _translators, false, _isLocal, false),
  21269. countHelper((IHThorIndexCountArg &)basehelper),
  21270. done(false)
  21271. {
  21272. limitHelper = static_cast<IHThorSourceCountLimit *>(basehelper.selectInterface(TAIsourcecountlimit_1));
  21273. }
  21274. virtual bool needsAllocator() const { return true; }
  21275. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21276. {
  21277. done = false;
  21278. CRoxieServerIndexActivity::start(parentExtractSize, parentExtract, paused);
  21279. choosenLimit = countHelper.getChooseNLimit();
  21280. if (limitHelper)
  21281. {
  21282. rowLimit = limitHelper->getRowLimit();
  21283. keyedLimit = limitHelper->getKeyedLimit();
  21284. }
  21285. if (!paused)
  21286. processAllKeys();
  21287. }
  21288. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
  21289. {
  21290. unsigned __int64 count = 0;
  21291. if (countHelper.hasFilter())
  21292. {
  21293. while (tlk->lookup(true))
  21294. {
  21295. try
  21296. {
  21297. count += countHelper.numValid(tlk->queryKeyBuffer(callback.getFPosRef()));
  21298. callback.finishedRow();
  21299. }
  21300. catch (IException *E)
  21301. {
  21302. throw makeWrappedException(E);
  21303. }
  21304. accepted++;
  21305. if (count >= choosenLimit) // MORE - what about limit?
  21306. break;
  21307. }
  21308. }
  21309. else
  21310. count = tlk->getCount(); //MORE: GH->RKC There should be value in providing a max limit to getCount()
  21311. if (count)
  21312. {
  21313. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), false);
  21314. if (count > choosenLimit)
  21315. count = choosenLimit;
  21316. void * recBuffer = rowAllocator->createRow();
  21317. if (meta.getFixedSize() == 1)
  21318. *(byte *)recBuffer = (byte)count;
  21319. else
  21320. {
  21321. assertex(meta.getFixedSize() == sizeof(unsigned __int64));
  21322. *(unsigned __int64 *)recBuffer = count;
  21323. }
  21324. recBuffer = rowAllocator->finalizeRow(meta.getFixedSize(), recBuffer, meta.getFixedSize());
  21325. result->append(recBuffer);
  21326. remote.injectResult(result.getClear());
  21327. //GH->RKC for count(,choosen)/exists passing in the previous count would short-circuit this much earlier
  21328. if (count >= choosenLimit)
  21329. return true;
  21330. }
  21331. return false;
  21332. }
  21333. virtual void onLimitExceeded(bool isKeyed)
  21334. {
  21335. if (traceLevel > 4)
  21336. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  21337. if (isKeyed)
  21338. {
  21339. if (indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates))
  21340. {
  21341. if (ctx->queryDebugContext())
  21342. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  21343. throw makeLimitSkipException(true);
  21344. }
  21345. else
  21346. {
  21347. assertex(limitHelper); // Should not be able to generate exception if there was not one...
  21348. limitHelper->onKeyedLimitExceeded();
  21349. }
  21350. }
  21351. else
  21352. {
  21353. if (indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates))
  21354. {
  21355. if (ctx->queryDebugContext())
  21356. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  21357. throw makeLimitSkipException(false);
  21358. }
  21359. else
  21360. {
  21361. assertex(limitHelper);
  21362. limitHelper->onLimitExceeded();
  21363. }
  21364. }
  21365. }
  21366. virtual const void *createLimitFailRow(bool isKeyed)
  21367. {
  21368. throwUnexpected();
  21369. }
  21370. virtual const void *nextRow()
  21371. {
  21372. ActivityTimer t(totalCycles, timeActivities);
  21373. if (done) return NULL;
  21374. done = true;
  21375. unsigned __int64 totalCount = 0;
  21376. bool hasLimit = rowLimit != (unsigned __int64) -1;
  21377. try
  21378. {
  21379. loop
  21380. {
  21381. const void * next = remote.nextRow();
  21382. if (!next)
  21383. break;
  21384. if (meta.getFixedSize() == 1)
  21385. totalCount += *(byte *)next;
  21386. else
  21387. totalCount += *(unsigned __int64 *) next;
  21388. ReleaseRoxieRow(next);
  21389. if (totalCount > rowLimit || (totalCount > choosenLimit && !hasLimit)) // can't break out early if there is a possibility of later slave throwing limit exception
  21390. break;
  21391. }
  21392. if (totalCount > rowLimit)
  21393. {
  21394. unsigned flags = indexHelper.getFlags();
  21395. if (flags & TIRlimitskips)
  21396. totalCount = 0;
  21397. else if (flags & TIRlimitcreates)
  21398. totalCount = 1;
  21399. else
  21400. {
  21401. assertex(limitHelper);
  21402. limitHelper->onLimitExceeded();
  21403. }
  21404. }
  21405. else if (totalCount > choosenLimit)
  21406. totalCount = choosenLimit;
  21407. }
  21408. catch (IException *E)
  21409. {
  21410. if (QUERYINTERFACE(E, LimitSkipException))
  21411. {
  21412. totalCount = 0;
  21413. unsigned flags = indexHelper.getFlags();
  21414. if (E->errorCode() == KeyedLimitSkipErrorCode)
  21415. {
  21416. if (flags & TIRkeyedlimitcreates)
  21417. totalCount++;
  21418. }
  21419. else
  21420. {
  21421. if (flags & TIRlimitcreates)
  21422. totalCount++;
  21423. }
  21424. if (totalCount > choosenLimit)
  21425. totalCount = choosenLimit; // would have to be weird code (and escape the optimizer...)
  21426. E->Release();
  21427. }
  21428. else
  21429. throw ;
  21430. }
  21431. void * result = rowAllocator->createRow();
  21432. if (meta.getFixedSize() == 1)
  21433. *(byte *)result = (byte)totalCount;
  21434. else
  21435. {
  21436. assertex(meta.getFixedSize() == sizeof(unsigned __int64));
  21437. *(unsigned __int64 *)result = totalCount;
  21438. }
  21439. return rowAllocator->finalizeRow(meta.getFixedSize(), result, meta.getFixedSize());
  21440. }
  21441. };
  21442. class CRoxieServerIndexCountActivityFactory : public CRoxieServerBaseIndexActivityFactory
  21443. {
  21444. public:
  21445. CRoxieServerIndexCountActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21446. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId)
  21447. {
  21448. }
  21449. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  21450. {
  21451. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  21452. return new CRoxieServerNullCountActivity(_ctx, this, _probeManager);
  21453. // else if (isSimple)
  21454. // return new CRoxieServerSimpleIndexCountActivity(this, keySet->queryKeyPart(0)->queryPart(0));
  21455. else
  21456. return new CRoxieServerIndexCountActivity(_ctx, this, _probeManager, remoteId, keySet, translatorArray, isLocal);
  21457. }
  21458. };
  21459. IRoxieServerActivityFactory *createRoxieServerIndexCountActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21460. {
  21461. return new CRoxieServerIndexCountActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  21462. }
  21463. //--------------------------------------------------------------------------------------------------------------------------
  21464. class CRoxieServerNullIndexAggregateActivity : public CRoxieServerActivity
  21465. {
  21466. IHThorIndexAggregateArg &aggregateHelper;
  21467. bool done;
  21468. public:
  21469. CRoxieServerNullIndexAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  21470. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  21471. aggregateHelper((IHThorIndexAggregateArg &)basehelper)
  21472. {
  21473. done = false;
  21474. }
  21475. virtual bool needsAllocator() const { return true; }
  21476. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21477. {
  21478. done = false;
  21479. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  21480. }
  21481. virtual const void *nextRow()
  21482. {
  21483. ActivityTimer t(totalCycles, timeActivities);
  21484. if (done) return NULL;
  21485. done = true;
  21486. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  21487. size32_t thisSize = aggregateHelper.clearAggregate(rowBuilder);
  21488. return rowBuilder.finalizeRowClear(thisSize);
  21489. }
  21490. };
  21491. class CRoxieServerIndexAggregateActivity : public CRoxieServerIndexActivity
  21492. {
  21493. IHThorCompoundAggregateExtra & aggregateHelper;
  21494. bool done;
  21495. public:
  21496. CRoxieServerIndexAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  21497. IKeyArray * _keySet, TranslatorArray *_translators, bool _isLocal)
  21498. : CRoxieServerIndexActivity(_ctx, _factory, _probeManager, _remoteId, _keySet, _translators, false, _isLocal, false),
  21499. aggregateHelper((IHThorIndexAggregateArg &)basehelper),
  21500. done(false)
  21501. {
  21502. }
  21503. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21504. {
  21505. done = false;
  21506. CRoxieServerIndexActivity::start(parentExtractSize, parentExtract, paused);
  21507. if (!paused)
  21508. processAllKeys();
  21509. }
  21510. virtual bool needsAllocator() const { return true; }
  21511. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
  21512. {
  21513. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  21514. while (tlk->lookup(true))
  21515. {
  21516. if (!rowBuilder.exists())
  21517. {
  21518. rowBuilder.ensureRow();
  21519. aggregateHelper.clearAggregate(rowBuilder);
  21520. }
  21521. try
  21522. {
  21523. aggregateHelper.processRow(rowBuilder, tlk->queryKeyBuffer(callback.getFPosRef()));
  21524. callback.finishedRow();
  21525. }
  21526. catch (IException *E)
  21527. {
  21528. throw makeWrappedException(E);
  21529. }
  21530. accepted++;
  21531. }
  21532. if (aggregateHelper.processedAnyRows())
  21533. {
  21534. size32_t size = meta.getRecordSize(rowBuilder.getSelf());
  21535. const void * recBuffer = rowBuilder.finalizeRowClear(size);
  21536. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), meta.isVariableSize());
  21537. result->append(recBuffer);
  21538. remote.injectResult(result.getClear());
  21539. }
  21540. return false;
  21541. }
  21542. virtual void onLimitExceeded(bool isKeyed)
  21543. {
  21544. if (traceLevel > 4)
  21545. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  21546. throwUnexpected();
  21547. }
  21548. virtual const void *createLimitFailRow(bool isKeyed)
  21549. {
  21550. throwUnexpected();
  21551. }
  21552. const void * gatherMerged()
  21553. {
  21554. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  21555. const void * firstRow = remote.nextRow();
  21556. size32_t finalSize = 0;
  21557. if (!firstRow)
  21558. {
  21559. rowBuilder.ensureRow();
  21560. finalSize = aggregateHelper.clearAggregate(rowBuilder);
  21561. }
  21562. else
  21563. {
  21564. // NOTE need to clone this because going to modify below, could special case 1 row only
  21565. finalSize = cloneRow(rowBuilder, firstRow, meta);
  21566. ReleaseRoxieRow(firstRow);
  21567. }
  21568. loop
  21569. {
  21570. const void * next = remote.nextRow();
  21571. if (!next)
  21572. break;
  21573. finalSize = aggregateHelper.mergeAggregate(rowBuilder, next);
  21574. ReleaseRoxieRow(next);
  21575. }
  21576. return rowBuilder.finalizeRowClear(finalSize);
  21577. }
  21578. virtual const void *nextRow()
  21579. {
  21580. ActivityTimer t(totalCycles, timeActivities);
  21581. if (done) return NULL;
  21582. const void * ret = gatherMerged();
  21583. done = true;
  21584. return ret;
  21585. }
  21586. };
  21587. class CRoxieServerIndexAggregateActivityFactory : public CRoxieServerBaseIndexActivityFactory
  21588. {
  21589. public:
  21590. CRoxieServerIndexAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21591. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId)
  21592. {
  21593. }
  21594. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  21595. {
  21596. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  21597. return new CRoxieServerNullIndexAggregateActivity(_ctx, this, _probeManager);
  21598. // else if (isSimple)
  21599. // return new CRoxieServerSimpleIndexAggregateActivity(this, keySet->queryKeyPart(0)->queryPart(0));
  21600. else
  21601. return new CRoxieServerIndexAggregateActivity(_ctx, this, _probeManager, remoteId, keySet, translatorArray, isLocal);
  21602. }
  21603. };
  21604. IRoxieServerActivityFactory *createRoxieServerIndexAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21605. {
  21606. return new CRoxieServerIndexAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  21607. }
  21608. //--------------------------------------------------------------------------------------------------------------------------
  21609. class CRoxieServerIndexGroupAggregateActivity : public CRoxieServerIndexActivity, implements IHThorGroupAggregateCallback
  21610. {
  21611. IHThorCompoundGroupAggregateExtra & aggregateHelper;
  21612. RowAggregator singleAggregator;
  21613. RowAggregator resultAggregator;
  21614. unsigned groupSegCount;
  21615. bool gathered;
  21616. bool eof;
  21617. public:
  21618. CRoxieServerIndexGroupAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  21619. IKeyArray * _keySet, TranslatorArray *_translators, bool _isLocal)
  21620. : CRoxieServerIndexActivity(_ctx, _factory, _probeManager, _remoteId, _keySet, _translators, false, _isLocal, false),
  21621. aggregateHelper((IHThorIndexGroupAggregateArg &)basehelper),
  21622. singleAggregator(aggregateHelper, aggregateHelper),
  21623. resultAggregator(aggregateHelper, aggregateHelper),
  21624. gathered(false), eof(true)
  21625. {
  21626. groupSegCount = 0;
  21627. }
  21628. IMPLEMENT_IINTERFACE_USING(CRoxieServerIndexActivity)
  21629. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21630. {
  21631. eof = false;
  21632. gathered= false;
  21633. CRoxieServerIndexActivity::start(parentExtractSize, parentExtract, paused);
  21634. groupSegCount = 0;
  21635. if (!paused)
  21636. processAllKeys();
  21637. resultAggregator.start(rowAllocator);
  21638. }
  21639. virtual bool needsAllocator() const { return true; }
  21640. virtual void reset()
  21641. {
  21642. resultAggregator.reset();
  21643. CRoxieServerIndexActivity::reset();
  21644. }
  21645. virtual void processRow(const void * next)
  21646. {
  21647. singleAggregator.addRow(next);
  21648. }
  21649. virtual void createSegmentMonitors(IKeyManager *key)
  21650. {
  21651. unsigned groupSegSize;
  21652. ThorActivityKind kind = factory->getKind();
  21653. if ((kind==TAKindexgroupcount || kind==TAKindexgroupexists))
  21654. groupSegSize = aggregateHelper.getGroupSegmentMonitorsSize();
  21655. else
  21656. groupSegSize = 0;
  21657. if (groupSegSize)
  21658. {
  21659. key->setMergeBarrier(groupSegSize);
  21660. CRoxieServerIndexActivity::createSegmentMonitors(key);
  21661. unsigned numSegs = tlk->ordinality();
  21662. for (unsigned segNo = 0; segNo < numSegs; segNo++)
  21663. {
  21664. IKeySegmentMonitor *seg = tlk->item(segNo);
  21665. if (seg->getOffset()+seg->getSize()==groupSegSize)
  21666. {
  21667. groupSegCount = segNo+1;
  21668. break;
  21669. }
  21670. }
  21671. assertex(groupSegCount);
  21672. }
  21673. else
  21674. CRoxieServerIndexActivity::createSegmentMonitors(key);
  21675. }
  21676. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
  21677. {
  21678. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), meta.isVariableSize());
  21679. singleAggregator.start(rowAllocator);
  21680. ThorActivityKind kind = factory->getKind();
  21681. while (tlk->lookup(true))
  21682. {
  21683. try
  21684. {
  21685. if (groupSegCount && !trans)
  21686. {
  21687. AggregateRowBuilder &rowBuilder = singleAggregator.addRow(tlk->queryKeyBuffer(callback.getFPosRef()));
  21688. callback.finishedRow();
  21689. if (kind==TAKindexgroupcount)
  21690. {
  21691. unsigned __int64 count = tlk->getCurrentRangeCount(groupSegCount);
  21692. aggregateHelper.processCountGrouping(rowBuilder, count-1);
  21693. }
  21694. if (!tlk->nextRange(groupSegCount))
  21695. break;
  21696. }
  21697. else
  21698. {
  21699. aggregateHelper.processRow(tlk->queryKeyBuffer(callback.getFPosRef()), this);
  21700. callback.finishedRow();
  21701. }
  21702. }
  21703. catch (IException *E)
  21704. {
  21705. throw makeWrappedException(E);
  21706. }
  21707. accepted++;
  21708. }
  21709. loop
  21710. {
  21711. Owned<AggregateRowBuilder> next = singleAggregator.nextResult();
  21712. if (!next)
  21713. break;
  21714. size32_t size = next->querySize();
  21715. result->append(next->finalizeRowClear());
  21716. }
  21717. remote.injectResult(result.getClear());
  21718. singleAggregator.reset();
  21719. return false;
  21720. }
  21721. virtual void onLimitExceeded(bool isKeyed)
  21722. {
  21723. if (traceLevel > 4)
  21724. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  21725. throwUnexpected();
  21726. }
  21727. virtual const void *createLimitFailRow(bool isKeyed)
  21728. {
  21729. throwUnexpected();
  21730. }
  21731. void gatherMerged()
  21732. {
  21733. gathered = true;
  21734. loop
  21735. {
  21736. const void * next = remote.nextRow();
  21737. if (!next)
  21738. break;
  21739. resultAggregator.mergeElement(next);
  21740. ReleaseRoxieRow(next);
  21741. }
  21742. }
  21743. virtual const void *nextRow()
  21744. {
  21745. ActivityTimer t(totalCycles, timeActivities);
  21746. if (eof)
  21747. return NULL;
  21748. if (!gathered)
  21749. gatherMerged();
  21750. Owned<AggregateRowBuilder> next = resultAggregator.nextResult();
  21751. if (next)
  21752. {
  21753. processed++;
  21754. return next->finalizeRowClear();
  21755. }
  21756. eof = true;
  21757. return NULL;
  21758. }
  21759. };
  21760. class CRoxieServerIndexGroupAggregateActivityFactory : public CRoxieServerBaseIndexActivityFactory
  21761. {
  21762. public:
  21763. CRoxieServerIndexGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21764. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId)
  21765. {
  21766. }
  21767. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  21768. {
  21769. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  21770. return new CRoxieServerNullActivity(_ctx, this, _probeManager);
  21771. // else if (isSimple)
  21772. // return new CRoxieServerSimpleIndexGroupAggregateActivity(this, keySet->queryKeyPart(0)->queryPart(0));
  21773. else
  21774. return new CRoxieServerIndexGroupAggregateActivity(_ctx, this, _probeManager, remoteId, keySet, translatorArray, isLocal);
  21775. }
  21776. };
  21777. IRoxieServerActivityFactory *createRoxieServerIndexGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21778. {
  21779. return new CRoxieServerIndexGroupAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  21780. }
  21781. //--------------------------------------------------------------------------------------------------------------------------
  21782. class CRoxieServerIndexNormalizeActivity : public CRoxieServerIndexReadBaseActivity
  21783. {
  21784. IHThorCompoundNormalizeExtra & readHelper;
  21785. public:
  21786. CRoxieServerIndexNormalizeActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  21787. IKeyArray * _keySet, TranslatorArray *_translators, bool _sorted, bool _isLocal)
  21788. : CRoxieServerIndexReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _keySet, _translators, _sorted, _isLocal, false),
  21789. readHelper((IHThorIndexNormalizeArg &)basehelper)
  21790. {
  21791. }
  21792. virtual bool needsAllocator() const { return true; }
  21793. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21794. {
  21795. CRoxieServerIndexReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  21796. rowLimit = readHelper.getRowLimit();
  21797. keyedLimit = readHelper.getKeyedLimit();
  21798. choosenLimit = readHelper.getChooseNLimit();
  21799. if (!paused)
  21800. processAllKeys();
  21801. }
  21802. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
  21803. {
  21804. unsigned keyedCount = 0;
  21805. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  21806. while (tlk->lookup(true))
  21807. {
  21808. keyedCount++;
  21809. if (keyedCount > keyedLimit)
  21810. {
  21811. if (traceLevel > 4)
  21812. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  21813. onLimitExceeded(true);
  21814. break;
  21815. }
  21816. size32_t transformedSize;
  21817. if (readHelper.first(tlk->queryKeyBuffer(callback.getFPosRef())))
  21818. {
  21819. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), meta.isVariableSize());
  21820. do
  21821. {
  21822. if (accepted>=choosenLimit)
  21823. break;
  21824. rowBuilder.ensureRow();
  21825. try
  21826. {
  21827. transformedSize = readHelper.transform(rowBuilder);
  21828. }
  21829. catch (IException *E)
  21830. {
  21831. throw makeWrappedException(E);
  21832. }
  21833. if (transformedSize)
  21834. {
  21835. // MORE - would be a good idea to stop these asap if rowlimit exceeded
  21836. result->append(rowBuilder.finalizeRowClear(transformedSize));
  21837. accepted++;
  21838. }
  21839. else
  21840. rejected++;
  21841. } while (readHelper.next());
  21842. remote.injectResult(result.getClear());
  21843. callback.finishedRow();
  21844. if (accepted>=choosenLimit)
  21845. return true;
  21846. }
  21847. }
  21848. return false;
  21849. }
  21850. virtual void onLimitExceeded(bool isKeyed)
  21851. {
  21852. if (traceLevel > 4)
  21853. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  21854. if (isKeyed)
  21855. {
  21856. if (indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates))
  21857. {
  21858. if (ctx->queryDebugContext())
  21859. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  21860. throw makeLimitSkipException(true);
  21861. }
  21862. else
  21863. readHelper.onKeyedLimitExceeded();
  21864. }
  21865. else
  21866. {
  21867. if (indexHelper.getFlags() & (TIRlimitskips||TIRlimitcreates))
  21868. {
  21869. if (ctx->queryDebugContext())
  21870. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  21871. throw makeLimitSkipException(false);
  21872. }
  21873. else
  21874. readHelper.onLimitExceeded();
  21875. }
  21876. }
  21877. virtual const void *createLimitFailRow(bool isKeyed)
  21878. {
  21879. UNIMPLEMENTED;
  21880. }
  21881. };
  21882. class CRoxieServerIndexNormalizeActivityFactory : public CRoxieServerBaseIndexActivityFactory
  21883. {
  21884. public:
  21885. CRoxieServerIndexNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21886. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId)
  21887. {
  21888. }
  21889. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  21890. {
  21891. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  21892. return new CRoxieServerNullActivity(_ctx, this, _probeManager);
  21893. else
  21894. return new CRoxieServerIndexNormalizeActivity(_ctx, this, _probeManager, remoteId, keySet, translatorArray, sorted, isLocal);
  21895. }
  21896. };
  21897. IRoxieServerActivityFactory *createRoxieServerIndexNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21898. {
  21899. return new CRoxieServerIndexNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  21900. }
  21901. //=================================================================================
  21902. class CRoxieServerFetchActivity : public CRoxieServerActivity, implements IRecordPullerCallback, implements IRoxieServerErrorHandler
  21903. {
  21904. IHThorFetchBaseArg &helper;
  21905. IHThorFetchContext * fetchContext;
  21906. Linked<IFilePartMap> map;
  21907. CRemoteResultAdaptor remote;
  21908. RecordPullerThread puller;
  21909. bool needsRHS;
  21910. bool variableFileName;
  21911. bool isOpt;
  21912. Owned<const IResolvedFile> varFileInfo;
  21913. public:
  21914. CRoxieServerFetchActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IFilePartMap *_map)
  21915. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorFetchBaseArg &)basehelper), map(_map), remote(_ctx, this, _remoteId, meta.queryOriginal(), helper, *this, true, true), puller(false)
  21916. {
  21917. fetchContext = static_cast<IHThorFetchContext *>(helper.selectInterface(TAIfetchcontext_1));
  21918. needsRHS = helper.transformNeedsRhs();
  21919. variableFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((fetchContext->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  21920. isOpt = (fetchContext->getFetchFlags() & FFdatafileoptional) != 0;
  21921. }
  21922. virtual const IResolvedFile *queryVarFileInfo() const
  21923. {
  21924. return varFileInfo;
  21925. }
  21926. virtual void onCreate(IHThorArg *_colocalParent)
  21927. {
  21928. CRoxieServerActivity::onCreate(_colocalParent);
  21929. remote.onCreate(_colocalParent);
  21930. }
  21931. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  21932. {
  21933. if (idx)
  21934. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  21935. puller.setInput(this, _sourceIdx, _in);
  21936. }
  21937. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  21938. {
  21939. puller.connectInputStreams(ctx, consumerOrdered);
  21940. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
  21941. }
  21942. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  21943. {
  21944. if (idx==0)
  21945. return puller.queryInput();
  21946. else
  21947. return NULL;
  21948. }
  21949. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21950. {
  21951. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  21952. remote.onStart(parentExtractSize, parentExtract);
  21953. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  21954. if (variableFileName)
  21955. {
  21956. OwnedRoxieString fname(fetchContext->getFileName());
  21957. varFileInfo.setown(resolveLFN(fname, isOpt));
  21958. if (varFileInfo)
  21959. map.setown(varFileInfo->getFileMap());
  21960. }
  21961. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().fetchPreload, false, ctx);
  21962. }
  21963. virtual void stop()
  21964. {
  21965. // Called from remote, so no need to call back to it....
  21966. puller.stop();
  21967. CRoxieServerActivity::stop();
  21968. }
  21969. virtual void reset()
  21970. {
  21971. processed = remote.processed;
  21972. remote.processed = 0;
  21973. puller.reset();
  21974. if (variableFileName)
  21975. {
  21976. varFileInfo.clear();
  21977. map.clear();
  21978. }
  21979. CRoxieServerActivity::reset();
  21980. }
  21981. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  21982. {
  21983. if (idx==(unsigned)-1)
  21984. idx = 0;
  21985. return idx ? NULL : &remote;
  21986. }
  21987. virtual void processRow(const void *row)
  21988. {
  21989. // called from puller thread
  21990. offset_t rp = fetchContext->extractPosition(row);
  21991. unsigned partNo;
  21992. if (isLocalFpos(rp))
  21993. partNo = getLocalFposPart(rp) + 1;
  21994. else
  21995. partNo = map->mapOffset(rp);
  21996. if (needsRHS)
  21997. {
  21998. Owned<IEngineRowAllocator> extractAllocator = createRowAllocator(helper.queryExtractedSize());
  21999. RtlDynamicRowBuilder rb(extractAllocator, true);
  22000. unsigned rhsSize = helper.extractJoinFields(rb, row);
  22001. char * block = (char *) remote.getMem(partNo, 0, sizeof(rp) + sizeof(rhsSize) + rhsSize); // MORE - superfiles
  22002. *(offset_t *) block = rp;
  22003. block += sizeof(rp);
  22004. *(unsigned *) block = rhsSize;
  22005. block += sizeof(rhsSize);
  22006. memcpy(block, rb.row(), rhsSize);
  22007. }
  22008. else
  22009. *(offset_t *) remote.getMem(partNo, 0, sizeof(rp)) = rp; // MORE - superfiles
  22010. ReleaseRoxieRow(row);
  22011. }
  22012. void processEOG()
  22013. {
  22014. #ifdef FETCH_PRESERVES_GROUPING
  22015. UNIMPLEMENTED;
  22016. #endif
  22017. // else discard is correct
  22018. }
  22019. void processGroup(const ConstPointerArray &)
  22020. {
  22021. throwUnexpected();
  22022. }
  22023. void processDone()
  22024. {
  22025. // called from puller thread
  22026. remote.flush();
  22027. remote.senddone();
  22028. }
  22029. virtual bool fireException(IException *e)
  22030. {
  22031. return remote.fireException(e);
  22032. }
  22033. virtual void onLimitExceeded(bool isKeyed)
  22034. {
  22035. if (traceLevel > 4)
  22036. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  22037. if (isKeyed)
  22038. throwUnexpected();
  22039. helper.onLimitExceeded();
  22040. }
  22041. virtual const void *createLimitFailRow(bool isKeyed)
  22042. {
  22043. UNIMPLEMENTED;
  22044. }
  22045. virtual const void *nextRow()
  22046. {
  22047. throwUnexpected(); // I am nobody's input
  22048. }
  22049. };
  22050. class CRoxieServerFetchActivityFactory : public CRoxieServerActivityFactory
  22051. {
  22052. RemoteActivityId remoteId;
  22053. Owned<IFilePartMap> map;
  22054. bool variableFileName;
  22055. Owned<const IResolvedFile> datafile;
  22056. public:
  22057. CRoxieServerFetchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  22058. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), remoteId(_remoteId)
  22059. {
  22060. Owned<IHThorFetchBaseArg> helper = (IHThorFetchBaseArg *) helperFactory();
  22061. IHThorFetchContext *fetchContext = static_cast<IHThorFetchContext *>(helper->selectInterface(TAIfetchcontext_1));
  22062. variableFileName = allFilesDynamic || _queryFactory.isDynamic() || ((fetchContext->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  22063. if (!variableFileName)
  22064. {
  22065. OwnedRoxieString fname(fetchContext->getFileName());
  22066. datafile.setown(_queryFactory.queryPackage().lookupFileName(fname,
  22067. (fetchContext->getFetchFlags() & FFdatafileoptional) != 0,
  22068. true, true,
  22069. _queryFactory.queryWorkUnit(), true));
  22070. if (datafile)
  22071. map.setown(datafile->getFileMap());
  22072. }
  22073. }
  22074. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  22075. {
  22076. return new CRoxieServerFetchActivity(_ctx, this, _probeManager, remoteId, map);
  22077. }
  22078. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  22079. {
  22080. if (datafile)
  22081. addXrefFileInfo(reply, datafile);
  22082. else
  22083. {
  22084. // Temporarily resolve the file
  22085. Owned<IHThorFetchBaseArg> helper = (IHThorFetchBaseArg *) helperFactory();
  22086. IHThorFetchContext *fetchContext = static_cast<IHThorFetchContext *>(helper->selectInterface(TAIfetchcontext_1));
  22087. if ((fetchContext->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) == 0)
  22088. {
  22089. OwnedRoxieString fileName(fetchContext->getFileName());
  22090. Owned<const IResolvedFile> temp = queryFactory.queryPackage().lookupFileName(fileName, true, true, false, queryFactory.queryWorkUnit(), true);
  22091. if (temp)
  22092. addXrefFileInfo(reply, temp);
  22093. }
  22094. }
  22095. }
  22096. virtual const StatisticsMapping &queryStatsMapping() const
  22097. {
  22098. return diskStatistics;
  22099. }
  22100. };
  22101. IRoxieServerActivityFactory *createRoxieServerFetchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  22102. {
  22103. return new CRoxieServerFetchActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  22104. }
  22105. // MORE - is there any point keeping this now?
  22106. class CRoxieServerDummyActivityFactory : public CRoxieServerActivityFactory // not a real activity - just used to properly link files
  22107. {
  22108. public:
  22109. Owned<const IResolvedFile> indexfile;
  22110. Owned<const IResolvedFile> datafile;
  22111. StringAttr fileName;
  22112. StringAttr indexName;
  22113. Owned<IKeyArray> keySet;
  22114. Owned<IFileIOArray> files;
  22115. TranslatorArray layoutTranslators;
  22116. CRoxieServerDummyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool isLoadDataOnly)
  22117. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  22118. {
  22119. try // does not want any missing file errors to be fatal, or throw traps - just log it
  22120. {
  22121. if (_graphNode.getPropBool("att[@name='_isSpill']/@value", false) || _graphNode.getPropBool("att[@name='_isSpillGlobal']/@value", false))
  22122. return; // ignore 'spills'
  22123. bool isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  22124. ThorActivityKind kind = getActivityKind(_graphNode);
  22125. if (kind != TAKdiskwrite && kind != TAKindexwrite && kind != TAKpiperead && kind != TAKpipewrite)
  22126. {
  22127. fileName.set(queryNodeFileName(_graphNode, kind));
  22128. indexName.set(queryNodeIndexName(_graphNode, kind));
  22129. if (indexName && !allFilesDynamic && !queryFactory.isDynamic())
  22130. {
  22131. bool isOpt = pretendAllOpt || _graphNode.getPropBool("att[@name='_isIndexOpt']/@value");
  22132. indexfile.setown(queryFactory.queryPackage().lookupFileName(indexName, isOpt, true, true, queryFactory.queryWorkUnit(), true));
  22133. if (indexfile)
  22134. keySet.setown(indexfile->getKeyArray(NULL, &layoutTranslators, isOpt, isLocal ? queryFactory.queryChannel() : 0, false));
  22135. }
  22136. if (fileName && !allFilesDynamic && !queryFactory.isDynamic())
  22137. {
  22138. bool isOpt = pretendAllOpt || _graphNode.getPropBool("att[@name='_isOpt']/@value");
  22139. datafile.setown(_queryFactory.queryPackage().lookupFileName(fileName, isOpt, true, true, queryFactory.queryWorkUnit(), true));
  22140. if (datafile)
  22141. {
  22142. if (isLocal)
  22143. files.setown(datafile->getIFileIOArray(isOpt, queryFactory.queryChannel()));
  22144. }
  22145. }
  22146. }
  22147. }
  22148. catch(IException *E)
  22149. {
  22150. StringBuffer errors;
  22151. E->errorMessage(errors);
  22152. DBGLOG("%s File error = %s", (isLoadDataOnly) ? "LOADDATAONLY" : "SUSPENDED QUERY", errors.str());
  22153. E->Release();
  22154. }
  22155. }
  22156. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const { throw MakeStringException(ROXIE_INTERNAL_ERROR, "%s query %s is suspended and cannot be executed - error occurred at %s(%d)", (queryFactory.isQueryLibrary()) ? "Library" : " ", queryFactory.queryQueryName(), __FILE__, __LINE__); }
  22157. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  22158. {
  22159. if (!allFilesDynamic)
  22160. {
  22161. if (datafile)
  22162. addXrefFileInfo(reply, datafile);
  22163. if (indexfile)
  22164. addXrefFileInfo(reply, indexfile);
  22165. }
  22166. else
  22167. {
  22168. Owned<const IResolvedFile> temp;
  22169. if (fileName.length())
  22170. {
  22171. temp.setown(queryFactory.queryPackage().lookupFileName(fileName, true, true, false, queryFactory.queryWorkUnit(), true));
  22172. if (temp)
  22173. addXrefFileInfo(reply, temp);
  22174. }
  22175. if (indexName.length())
  22176. {
  22177. temp.setown(queryFactory.queryPackage().lookupFileName(indexName, true, true, false, queryFactory.queryWorkUnit(), true));
  22178. if (temp)
  22179. addXrefFileInfo(reply, temp);
  22180. }
  22181. }
  22182. }
  22183. };
  22184. IRoxieServerActivityFactory *createRoxieServerDummyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool isLoadDataOnly)
  22185. {
  22186. return new CRoxieServerDummyActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, isLoadDataOnly);
  22187. }
  22188. //=====================================================================================================
  22189. // Keyed joins...
  22190. //
  22191. // Input records are pulled by a puller thread, which checks each LHS record to determine which (if any) channels it
  22192. // may have RHS matches on, and sends the relevant fields to the relevant slaves.
  22193. // 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
  22194. // the transform and returns rows that are created.
  22195. // 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)
  22196. //
  22197. //=====================================================================================================
  22198. class CJoinGroup;
  22199. interface IJoinProcessor
  22200. {
  22201. virtual void processEOG() = 0;
  22202. virtual CJoinGroup *createJoinGroup(const void *row) = 0;
  22203. virtual void noteEndReceived(CJoinGroup *jg, unsigned candidateCount) = 0;
  22204. virtual bool fireException(IException *E) = 0;
  22205. virtual void processCompletedGroups() = 0;
  22206. };
  22207. //------------------------------------------------------------------------------------------------------
  22208. // Class CJoinGroup has a record per LHS row, plus (if preserving grouping) a 'head of group' record
  22209. // It gathers all the corresponding RHS rows, keeping track of how may slave transactions are pending in endMarkersPending
  22210. // If preserving groups, the 'head of group' record keeps track of how many LHS records in the group are still incomplete.
  22211. // CJoinGroup records are allocated out of the Roxie row memory manager by overloading operator new, so that they are included in the
  22212. // per-query limits etc (Note that the pointer array block is not though).
  22213. // Because of that, the exact size is significant - especially whether fit just under or just over a chunking threshold...
  22214. //
  22215. // There are two phases to the life of a JoinGroup - it is created by the puller thread that is also firing off slave requests
  22216. // notePending will be called once for every slave request. Puller thread calls noteEndReceived(0) once when done - this corresponds to the
  22217. // initial count when created.
  22218. // Slave replies and are noted by the consumer thread calling addRightMatch() and noteEndReceived(n).
  22219. // Once endMarkersPending reaches 0, JoinGroup is complete. Last thread to call noteEndReceived will process the rows and destroy the group.
  22220. // There is no need for a critsec because although multiple threads will access at different times, only the consumer thread will
  22221. // access any modifiable member variables while endMarkersPending != 0 (i.e. complete() is false). Once complete returns true there is a single
  22222. // remaining reference and the JoinGroup will be processed and destroyed.
  22223. //
  22224. //------------------------------------------------------------------------------------------------------
  22225. class CJoinGroup : public CInterface
  22226. {
  22227. protected:
  22228. const void *left; // LHS row
  22229. PointerArrayOf<KeyedJoinHeader> rows; // matching RHS rows
  22230. atomic_t endMarkersPending; // How many slave responses still waiting for
  22231. CJoinGroup *groupStart; // Head of group, or NULL if not grouping
  22232. unsigned lastPartNo;
  22233. unsigned pos;
  22234. unsigned candidates; // Number of RHS keyed candidates - note this may not be the same as rows.ordinality()
  22235. public:
  22236. #undef new
  22237. void *operator new(size_t size, IRowManager *a, unsigned activityId)
  22238. {
  22239. return a->allocate(size, activityId);
  22240. }
  22241. #if defined(_DEBUG) && defined(_WIN32) && !defined(USING_MPATROL)
  22242. #define new new(_NORMAL_BLOCK, __FILE__, __LINE__)
  22243. #endif
  22244. void operator delete(void *ptr, IRowManager *a, unsigned activityId)
  22245. {
  22246. ReleaseRoxieRow(ptr);
  22247. }
  22248. void operator delete(void *ptr)
  22249. {
  22250. ReleaseRoxieRow(ptr);
  22251. }
  22252. public:
  22253. CJoinGroup(const void *_left, CJoinGroup *_groupStart)
  22254. {
  22255. #ifdef TRACE_JOINGROUPS
  22256. DBGLOG("Creating joinGroup %p, groupstart %p", this, _groupStart);
  22257. #endif
  22258. candidates = 0;
  22259. lastPartNo = 0;
  22260. pos = 0;
  22261. left = _left;
  22262. groupStart = _groupStart;
  22263. if (_groupStart)
  22264. {
  22265. atomic_inc(&_groupStart->endMarkersPending);
  22266. }
  22267. atomic_set(&endMarkersPending, 1);
  22268. }
  22269. ~CJoinGroup()
  22270. {
  22271. #ifdef TRACE_JOINGROUPS
  22272. DBGLOG("Destroying joinGroup %p", this);
  22273. #endif
  22274. if (left)
  22275. {
  22276. ReleaseRoxieRow(left);
  22277. roxiemem::ReleaseRoxieRowArray(rows.ordinality(), (const void * *)rows.getArray());
  22278. rows.kill();
  22279. }
  22280. }
  22281. inline bool isHeadRecord() const
  22282. {
  22283. return left==NULL;
  22284. }
  22285. inline bool complete() const
  22286. {
  22287. return atomic_read(&endMarkersPending) == 0;
  22288. }
  22289. #ifdef TRACE_JOINGROUPS
  22290. inline void notePending(unsigned lineNo)
  22291. #else
  22292. inline void notePending()
  22293. #endif
  22294. {
  22295. assert(!complete());
  22296. atomic_inc(&endMarkersPending);
  22297. #ifdef TRACE_JOINGROUPS
  22298. DBGLOG("CJoinGroup::notePending %p from %d, count became %d group count %d", this, lineNo, atomic_read(&endMarkersPending), groupStart ? atomic_read(&groupStart->endMarkersPending) : 0);
  22299. #endif
  22300. }
  22301. inline bool inGroup(CJoinGroup *leader) const
  22302. {
  22303. return groupStart==leader;
  22304. }
  22305. inline const KeyedJoinHeader *queryRow(unsigned idx) const
  22306. {
  22307. // Single threaded by now
  22308. assert(complete());
  22309. return rows.item(idx);
  22310. }
  22311. #ifdef TRACE_JOINGROUPS
  22312. bool noteEndReceived(unsigned candidateCount, unsigned lineNo)
  22313. #else
  22314. bool noteEndReceived(unsigned candidateCount)
  22315. #endif
  22316. {
  22317. assert(!complete());
  22318. if (candidateCount)
  22319. {
  22320. candidates += candidateCount;
  22321. }
  22322. #ifdef TRACE_JOINGROUPS
  22323. 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);
  22324. #endif
  22325. // NOTE - as soon as endMarkersPending and groupStart->endMarkersPending are decremented to zero this object may get released asynchronously by other threads
  22326. // There must therefore be nothing in this method after them that acceses member variables. Think of it as a delete this...
  22327. // In particular, we can't safely reference groupStart after the dec_and_test of endMarkersPending, hence copy local first
  22328. CJoinGroup *localGroupStart = groupStart;
  22329. if (atomic_dec_and_test(&endMarkersPending))
  22330. {
  22331. if (localGroupStart)
  22332. return atomic_dec_and_test(&localGroupStart->endMarkersPending);
  22333. else
  22334. return true;
  22335. }
  22336. else
  22337. return false;
  22338. }
  22339. inline const void *queryLeft() const
  22340. {
  22341. return left;
  22342. }
  22343. void addRightMatch(KeyedJoinHeader *right)
  22344. {
  22345. assert(!complete());
  22346. unsigned short partNo = right->partNo;
  22347. if (partNo != lastPartNo)
  22348. {
  22349. // MORE - should we binchop? If we did we would need to be careful to find LAST match
  22350. if (partNo > lastPartNo)
  22351. pos = rows.length();
  22352. while (pos>0)
  22353. {
  22354. if (rows.item(pos-1)->partNo <= partNo)
  22355. break;
  22356. pos--;
  22357. }
  22358. lastPartNo = partNo;
  22359. }
  22360. rows.add(right, pos);
  22361. pos++;
  22362. }
  22363. inline unsigned rowsSeen() const
  22364. {
  22365. assert(complete());
  22366. return rows.length();
  22367. }
  22368. inline unsigned candidateCount() const
  22369. {
  22370. assert(complete());
  22371. return candidates;
  22372. }
  22373. };
  22374. #ifdef TRACE_JOINGROUPS
  22375. #define notePending() notePending(__LINE__)
  22376. #define noteEndReceived(a) noteEndReceived(a, __LINE__)
  22377. #endif
  22378. class KeyedJoinRemoteAdaptor : public CRemoteResultAdaptor // MORE - not sure it should be derived from this - makes processed all wrong, for example
  22379. {
  22380. private:
  22381. SafeQueueOf<const void, true> ready;
  22382. public:
  22383. IHThorKeyedJoinArg &helper;
  22384. unsigned joinProcessed;
  22385. bool isFullKey;
  22386. bool eof;
  22387. bool isSimple;
  22388. bool allPulled;
  22389. ActivityTimeAccumulator totalCycles;
  22390. unsigned activityId;
  22391. RecordPullerThread &puller;
  22392. SafeQueueOf<const void, true> injected; // Used in isSimple mode
  22393. Owned<IEngineRowAllocator> ccdRecordAllocator;
  22394. IJoinProcessor &processor;
  22395. KeyedJoinRemoteAdaptor(IRoxieSlaveContext *_ctx, IRoxieServerErrorHandler *_errorHandler, const RemoteActivityId &_remoteId, IHThorKeyedJoinArg &_helper,
  22396. IRoxieServerActivity &_activity, bool _isFullKey, bool _isSimple,
  22397. RecordPullerThread &_puller, IJoinProcessor &_processor)
  22398. : helper(_helper),
  22399. CRemoteResultAdaptor(_ctx, _errorHandler, _remoteId, 0, _helper, _activity, true, true),
  22400. isFullKey(_isFullKey),
  22401. isSimple(_isSimple),
  22402. puller(_puller),
  22403. processor(_processor),
  22404. activityId(_activity.queryId())
  22405. {
  22406. joinProcessed = 0;
  22407. allPulled = false;
  22408. eof = false;
  22409. }
  22410. virtual void onCreate(IHThorArg *_colocalArg)
  22411. {
  22412. CRemoteResultAdaptor::onCreate(_colocalArg);
  22413. ccdRecordAllocator.setown(activity.createRowAllocator(helper.queryJoinFieldsRecordSize()));
  22414. }
  22415. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  22416. {
  22417. eof = false;
  22418. joinProcessed = 0;
  22419. totalCycles.totalCycles = 0;
  22420. allPulled = false;
  22421. assertex(ready.ordinality()==0);
  22422. CRemoteResultAdaptor::start(parentExtractSize, parentExtract, paused);
  22423. }
  22424. virtual void reset()
  22425. {
  22426. CRemoteResultAdaptor::reset();
  22427. while (ready.ordinality())
  22428. {
  22429. const void *goer = ready.dequeue();
  22430. if (goer)
  22431. ReleaseRoxieRow(goer);
  22432. }
  22433. while (injected.ordinality())
  22434. {
  22435. const void *goer = injected.dequeue();
  22436. if (goer)
  22437. ReleaseRoxieRow(goer);
  22438. }
  22439. }
  22440. inline void addResult(const void *row)
  22441. {
  22442. ready.enqueue(row);
  22443. }
  22444. virtual unsigned __int64 queryTotalCycles() const
  22445. {
  22446. return totalCycles.totalCycles;
  22447. }
  22448. virtual const void *nextRow()
  22449. {
  22450. ActivityTimer t(totalCycles, timeActivities);
  22451. loop
  22452. {
  22453. if (eof)
  22454. return NULL;
  22455. processSlaveResults();
  22456. if (ready.ordinality())
  22457. {
  22458. const void *result = ready.dequeue();
  22459. if (result)
  22460. joinProcessed++;
  22461. return result;
  22462. }
  22463. else
  22464. eof = true;
  22465. }
  22466. }
  22467. private:
  22468. void processSlaveResults()
  22469. {
  22470. while (!ready.ordinality())
  22471. {
  22472. KeyedJoinHeader *fetchedData;
  22473. if (isSimple)
  22474. {
  22475. while (!allPulled && !injected.ordinality())
  22476. {
  22477. if (!puller.pullRecords(1))
  22478. {
  22479. puller.done();
  22480. allPulled = true;
  22481. }
  22482. }
  22483. fetchedData = (KeyedJoinHeader *) injected.dequeue();
  22484. }
  22485. else
  22486. fetchedData = (KeyedJoinHeader *) CRemoteResultAdaptor::nextRow();
  22487. if (fetchedData)
  22488. {
  22489. CJoinGroup *thisGroup = fetchedData->thisGroup;
  22490. if (fetchedData->partNo == (unsigned short) -1)
  22491. {
  22492. #ifdef TRACE_JOINGROUPS
  22493. CTXLOG("Got end for group %p", thisGroup);
  22494. #endif
  22495. unsigned candidateCount = (unsigned) fetchedData->fpos;
  22496. ReleaseRoxieRow(fetchedData);
  22497. processor.noteEndReceived(thisGroup, candidateCount); // note - this can throw exception. So release fetchdata before calling
  22498. }
  22499. else
  22500. {
  22501. #ifdef TRACE_JOINGROUPS
  22502. CTXLOG("Reading another %d bytes for group %p data", ccdRecordSize, thisGroup);
  22503. #endif
  22504. thisGroup->addRightMatch(fetchedData);
  22505. if (isFullKey)
  22506. {
  22507. #ifdef TRACE_JOINGROUPS
  22508. CTXLOG("Calling noteEndReceived for record returned from FETCH of full keyed join");
  22509. #endif
  22510. processor.noteEndReceived(thisGroup, 0); // note - this can throw exception. So release fetchdata before calling
  22511. }
  22512. }
  22513. }
  22514. else
  22515. break;
  22516. }
  22517. }
  22518. };
  22519. class CRoxieServerFullKeyedJoinHead: public CRoxieServerActivity, implements IRecordPullerCallback, implements IRoxieServerErrorHandler
  22520. {
  22521. IHThorKeyedJoinArg &helper;
  22522. Owned<IKeyManager> tlk;
  22523. Linked<IKeyArray> keySet;
  22524. Linked<TranslatorArray> translators;
  22525. CRemoteResultAdaptor remote;
  22526. RecordPullerThread puller;
  22527. IOutputMetaData *indexReadMeta;
  22528. IJoinProcessor *joinHandler;
  22529. bool variableIndexFileName;
  22530. bool indexReadInputRecordVariable;
  22531. bool isLocal;
  22532. Owned<IEngineRowAllocator> indexReadAllocator;
  22533. Owned<const IResolvedFile> varFileInfo;
  22534. IFinalRoxieInput *indexReadInput;
  22535. unsigned indexReadIdx = 0;
  22536. IIndexReadActivityInfo *rootIndex;
  22537. public:
  22538. CRoxieServerFullKeyedJoinHead(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IKeyArray * _keySet, TranslatorArray *_translators, IOutputMetaData *_indexReadMeta, IJoinProcessor *_joinHandler, bool _isLocal)
  22539. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  22540. helper((IHThorKeyedJoinArg &)basehelper),
  22541. tlk(createKeyManager(NULL, 0, this)),
  22542. translators(_translators),
  22543. keySet(_keySet),
  22544. remote(_ctx, this, _remoteId, 0, helper, *this, true, true),
  22545. indexReadMeta(_indexReadMeta),
  22546. joinHandler(_joinHandler),
  22547. puller(false),
  22548. isLocal(_isLocal)
  22549. {
  22550. variableIndexFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getJoinFlags() & (JFvarindexfilename|JFdynamicindexfilename|JFindexfromactivity)) != 0);
  22551. indexReadInputRecordVariable = indexReadMeta->isVariableSize();
  22552. indexReadInput = NULL;
  22553. rootIndex = NULL;
  22554. }
  22555. virtual const IResolvedFile *queryVarFileInfo() const
  22556. {
  22557. return varFileInfo;
  22558. }
  22559. virtual void onCreate(IHThorArg *_colocalParent)
  22560. {
  22561. CRoxieServerActivity::onCreate(_colocalParent);
  22562. remote.onCreate(_colocalParent);
  22563. indexReadAllocator.setown(createRowAllocator(indexReadMeta));
  22564. }
  22565. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  22566. {
  22567. if (!idx)
  22568. puller.setInput(this, _sourceIdx, _in);
  22569. else if (idx==1)
  22570. {
  22571. indexReadInput = _in;
  22572. indexReadIdx = _sourceIdx;
  22573. }
  22574. else
  22575. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  22576. }
  22577. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  22578. {
  22579. puller.connectInputStreams(ctx, consumerOrdered);
  22580. //No rows are read from indexReadInput, so no need to extract the streams
  22581. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
  22582. }
  22583. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  22584. {
  22585. switch (idx)
  22586. {
  22587. case 0:
  22588. return puller.queryInput();
  22589. case 1:
  22590. return indexReadInput;
  22591. default:
  22592. return NULL;
  22593. }
  22594. }
  22595. virtual void serializeExtra(MemoryBuffer &out)
  22596. {
  22597. if (helper.getJoinFlags() & JFindexfromactivity)
  22598. {
  22599. assertex(rootIndex);
  22600. const RemoteActivityId& indexId = rootIndex->queryRemoteId();
  22601. indexId.serialize(out);
  22602. // could mess about reserving space for length then patching it again, to avoid copy, but probably not worth it
  22603. MemoryBuffer tmp;
  22604. rootIndex->queryActivity()->serializeCreateStartContext(tmp);
  22605. if (rootIndex->queryActivity()->queryVarFileInfo())
  22606. {
  22607. rootIndex->queryActivity()->queryVarFileInfo()->queryTimeStamp().serialize(tmp);
  22608. tmp.append(rootIndex->queryActivity()->queryVarFileInfo()->queryCheckSum());
  22609. }
  22610. unsigned ctxlen = tmp.length();
  22611. out.append(ctxlen).append(tmp);
  22612. }
  22613. }
  22614. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  22615. {
  22616. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  22617. if (indexReadInput)
  22618. {
  22619. indexReadInput->start(parentExtractSize, parentExtract, true); // paused=true because we don't want to actually run the index read
  22620. rootIndex = indexReadInput->queryIndexReadActivity();
  22621. if (!rootIndex)
  22622. throw MakeStringException(ROXIE_INTERNAL_ERROR,"Index in keyed join %d could not be resolved", queryId());
  22623. }
  22624. remote.onStart(parentExtractSize, parentExtract);
  22625. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  22626. if (rootIndex)
  22627. {
  22628. varFileInfo.setown(rootIndex->getVarFileInfo());
  22629. translators.setown(rootIndex->getTranslators());
  22630. keySet.setown(rootIndex->getKeySet());
  22631. }
  22632. else if (variableIndexFileName)
  22633. {
  22634. OwnedRoxieString indexFileName(helper.getIndexFileName());
  22635. varFileInfo.setown(resolveLFN(indexFileName, (helper.getJoinFlags() & JFindexoptional) != 0));
  22636. if (varFileInfo)
  22637. {
  22638. translators.setown(new TranslatorArray);
  22639. keySet.setown(varFileInfo->getKeyArray(factory->queryActivityMeta(), translators, false, isLocal ? factory->queryQueryFactory().queryChannel() : 0, factory->queryQueryFactory().queryOptions().enableFieldTranslation)); // MORE - isLocal?
  22640. }
  22641. }
  22642. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().fullKeyedJoinPreload, false, ctx);
  22643. }
  22644. virtual void stop()
  22645. {
  22646. puller.stop();
  22647. CRoxieServerActivity::stop();
  22648. }
  22649. virtual void reset()
  22650. {
  22651. CRoxieServerActivity::reset();
  22652. puller.reset();
  22653. if (varFileInfo)
  22654. {
  22655. keySet.clear();
  22656. varFileInfo.clear();
  22657. }
  22658. }
  22659. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  22660. {
  22661. if (idx==(unsigned)-1)
  22662. idx = 0;
  22663. return idx ? NULL : &remote;
  22664. }
  22665. virtual void processRow(const void *row)
  22666. {
  22667. // MORE - this code seems to be pretty much duplicated below in half-keyed....
  22668. // called from front puller thread
  22669. // buffer up an IndexRead request
  22670. if (helper.leftCanMatch(row))
  22671. {
  22672. RtlDynamicRowBuilder extractedBuilder(indexReadAllocator);
  22673. unsigned indexReadSize = helper.extractIndexReadFields(extractedBuilder, row);
  22674. OwnedConstRoxieRow extracted;
  22675. if (indexReadSize)
  22676. extracted.setown(extractedBuilder.finalizeRowClear(indexReadSize));
  22677. CJoinGroup *jg = joinHandler->createJoinGroup(row);
  22678. for (unsigned partNo = 0; partNo < keySet->length(); partNo++)
  22679. {
  22680. IKeyIndexBase *thisBase = keySet->queryKeyPart(partNo);
  22681. if (thisBase)
  22682. {
  22683. unsigned fileNo = 0;
  22684. IKeyIndex *thisKey = thisBase->queryPart(fileNo);
  22685. try
  22686. {
  22687. tlk->setKey(thisKey);
  22688. tlk->setLayoutTranslator(translators->item(fileNo));
  22689. helper.createSegmentMonitors(tlk, extracted);
  22690. if (rootIndex)
  22691. rootIndex->mergeSegmentMonitors(tlk);
  22692. tlk->finishSegmentMonitors();
  22693. tlk->reset();
  22694. loop
  22695. {
  22696. typedef const void * cvp;
  22697. if (thisKey->isTopLevelKey())
  22698. {
  22699. bool locallySorted = !thisKey->isFullySorted();
  22700. while (locallySorted || tlk->lookup(false))
  22701. {
  22702. unsigned slavePart = locallySorted ? 0 : (unsigned) tlk->queryFpos();
  22703. if (locallySorted || slavePart)
  22704. {
  22705. cvp *outputBuffer = (cvp *) remote.getMem(slavePart, fileNo, indexReadSize + sizeof(cvp) + (indexReadInputRecordVariable ? sizeof(unsigned) : 0));
  22706. *outputBuffer++ = jg;
  22707. if (indexReadInputRecordVariable)
  22708. {
  22709. *(unsigned *) outputBuffer = indexReadSize;
  22710. outputBuffer = (cvp*) (((unsigned *) outputBuffer) + 1);
  22711. }
  22712. jg->notePending();
  22713. memcpy(outputBuffer, extracted, indexReadSize);
  22714. if (locallySorted)
  22715. {
  22716. for (unsigned i = 1; i < numChannels; i++)
  22717. jg->notePending();
  22718. break;
  22719. }
  22720. }
  22721. }
  22722. }
  22723. else
  22724. {
  22725. // MORE - this code seems to be duplicated in half keyed
  22726. unsigned accepted = 0;
  22727. unsigned rejected = 0;
  22728. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), true);
  22729. jg->notePending();
  22730. unsigned candidateCount = 0;
  22731. while (tlk->lookup(true))
  22732. {
  22733. candidateCount++;
  22734. atomic_inc(&indexRecordsRead);
  22735. KLBlobProviderAdapter adapter(tlk);
  22736. offset_t recptr;
  22737. const byte *indexRow = tlk->queryKeyBuffer(recptr);
  22738. if (helper.indexReadMatch(extracted, indexRow, recptr, &adapter))
  22739. {
  22740. KeyedJoinHeader *rhs = (KeyedJoinHeader *) ctx->queryRowManager().allocate(KEYEDJOIN_RECORD_SIZE(0), activityId);
  22741. rhs->fpos = recptr;
  22742. rhs->thisGroup = jg;
  22743. rhs->partNo = partNo;
  22744. result->append(rhs);
  22745. }
  22746. else
  22747. {
  22748. rejected++;
  22749. atomic_inc(&postFiltered);
  22750. }
  22751. }
  22752. // output an end marker for the matches to this group
  22753. KeyedJoinHeader *endMarker = (KeyedJoinHeader *) ctx->queryRowManager().allocate(KEYEDJOIN_RECORD_SIZE(0), activityId);
  22754. endMarker->fpos = (offset_t) candidateCount;
  22755. endMarker->thisGroup = jg;
  22756. endMarker->partNo = (unsigned short) -1;
  22757. result->append(endMarker);
  22758. remote.injectResult(result.getClear());
  22759. if (accepted)
  22760. noteStatistic(StNumIndexAccepted, accepted);
  22761. if (rejected)
  22762. noteStatistic(StNumIndexRejected, rejected);
  22763. }
  22764. if (++fileNo < thisBase->numParts())
  22765. {
  22766. thisKey = thisBase->queryPart(fileNo);
  22767. tlk->setKey(thisKey);
  22768. tlk->setLayoutTranslator(translators->item(fileNo));
  22769. tlk->reset();
  22770. }
  22771. else
  22772. break;
  22773. }
  22774. tlk->releaseSegmentMonitors();
  22775. tlk->setKey(NULL);
  22776. }
  22777. catch (...)
  22778. {
  22779. tlk->releaseSegmentMonitors();
  22780. tlk->setKey(NULL);
  22781. throw;
  22782. }
  22783. }
  22784. }
  22785. joinHandler->noteEndReceived(jg, 0);
  22786. }
  22787. else
  22788. {
  22789. joinHandler->noteEndReceived(joinHandler->createJoinGroup(row), 0);
  22790. }
  22791. }
  22792. void processGroup(const ConstPointerArray &)
  22793. {
  22794. throwUnexpected();
  22795. }
  22796. virtual void processEOG()
  22797. {
  22798. joinHandler->processEOG();
  22799. }
  22800. virtual void processDone()
  22801. {
  22802. // called from puller thread
  22803. remote.flush();
  22804. remote.senddone();
  22805. }
  22806. virtual void onLimitExceeded(bool isKeyed)
  22807. {
  22808. if (traceLevel > 4)
  22809. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  22810. if (isKeyed)
  22811. throwUnexpected();
  22812. helper.onLimitExceeded();
  22813. }
  22814. virtual const void *createLimitFailRow(bool isKeyed)
  22815. {
  22816. throwUnexpected();
  22817. }
  22818. virtual bool fireException(IException *e)
  22819. {
  22820. // called from puller thread on failure
  22821. remote.fireException(LINK(e));
  22822. return joinHandler->fireException(e);
  22823. }
  22824. virtual const void *nextRow()
  22825. {
  22826. throwUnexpected(); // I am nobody's input
  22827. }
  22828. };
  22829. class CRoxieServerKeyedJoinBase : public CRoxieServerActivity, implements IRecordPullerCallback, implements IRoxieServerErrorHandler, implements IJoinProcessor
  22830. {
  22831. protected:
  22832. IHThorKeyedJoinArg &helper;
  22833. KeyedJoinRemoteAdaptor remote;
  22834. RecordPullerThread puller;
  22835. OwnedConstRoxieRow defaultRight;
  22836. Owned<IEngineRowAllocator> defaultRightAllocator;
  22837. unsigned joinFlags;
  22838. unsigned atMost;
  22839. unsigned atmostsTriggered;
  22840. unsigned abortLimit;
  22841. unsigned keepLimit;
  22842. bool limitFail;
  22843. bool limitOnFail;
  22844. bool preserveGroups;
  22845. bool cloneLeft;
  22846. bool isSimple;
  22847. bool isLocal;
  22848. ThorActivityKind activityKind;
  22849. CJoinGroup *groupStart;
  22850. CriticalSection groupsCrit;
  22851. QueueOf<CJoinGroup, false> groups;
  22852. IFinalRoxieInput *indexReadInput;
  22853. unsigned indexReadIdx = 0;
  22854. Owned<IStrandJunction> indexReadJunction;
  22855. IEngineRowStream *indexReadStream = NULL; // Never actually pulled
  22856. IIndexReadActivityInfo *rootIndex;
  22857. void createDefaultRight()
  22858. {
  22859. if (!defaultRight)
  22860. {
  22861. if (!defaultRightAllocator)
  22862. defaultRightAllocator.setown(createRowAllocator(helper.queryJoinFieldsRecordSize()));
  22863. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  22864. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  22865. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  22866. }
  22867. }
  22868. public:
  22869. CRoxieServerKeyedJoinBase(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _joinFlags
  22870. , bool isFull, bool _isSimple, bool _isLocal)
  22871. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  22872. helper((IHThorKeyedJoinArg &)basehelper),
  22873. remote(_ctx, this, _remoteId, helper, *this, isFull, _isSimple, puller, *this),
  22874. joinFlags(_joinFlags),
  22875. preserveGroups(meta.isGrouped()),
  22876. puller(false),
  22877. isSimple(_isSimple),
  22878. isLocal(_isLocal),
  22879. abortLimit(0),
  22880. keepLimit(0),
  22881. atMost(0),
  22882. limitFail(false),
  22883. limitOnFail(false),
  22884. cloneLeft(false)
  22885. {
  22886. groupStart = NULL;
  22887. activityKind = _factory->getKind();
  22888. indexReadInput = NULL;
  22889. rootIndex = NULL;
  22890. atmostsTriggered = 0;
  22891. // MORE - code would be easier to read if I got more values from helper rather than passing from factory
  22892. }
  22893. virtual void onCreate(IHThorArg *_colocalParent)
  22894. {
  22895. CRoxieServerActivity::onCreate(_colocalParent);
  22896. remote.onCreate(_colocalParent);
  22897. }
  22898. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  22899. {
  22900. if (!idx)
  22901. puller.setInput(this, _sourceIdx, _in);
  22902. else if (idx==1)
  22903. {
  22904. indexReadInput = _in;
  22905. indexReadIdx = _sourceIdx;
  22906. }
  22907. else
  22908. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  22909. }
  22910. virtual void connectInputStreams(bool consumerOrdered)
  22911. {
  22912. CRoxieServerActivity::connectInputStreams(consumerOrdered);
  22913. puller.connectInputStreams(ctx, consumerOrdered);
  22914. if (indexReadInput)
  22915. indexReadStream = connectSingleStream(ctx, indexReadInput, indexReadIdx, indexReadJunction, consumerOrdered); // We never actually pull the stream
  22916. }
  22917. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  22918. {
  22919. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  22920. if (indexReadInput)
  22921. {
  22922. indexReadInput->start(parentExtractSize, parentExtract, true); // paused=true because we don't want to actually run the index read
  22923. rootIndex = indexReadInput->queryIndexReadActivity();
  22924. if (!rootIndex)
  22925. throw MakeStringException(ROXIE_INTERNAL_ERROR,"Index in keyed join %d could not be resolved", queryId());
  22926. }
  22927. remote.onStart(parentExtractSize, parentExtract);
  22928. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  22929. atmostsTriggered = 0;
  22930. atMost = helper.getJoinLimit();
  22931. if (atMost == 0) atMost = (unsigned)-1;
  22932. abortLimit = helper.getMatchAbortLimit();
  22933. if (abortLimit == 0 || atMost != (unsigned) -1) abortLimit = (unsigned)-1;
  22934. keepLimit = helper.getKeepLimit();
  22935. if (keepLimit == 0) keepLimit = (unsigned)-1;
  22936. getLimitType(joinFlags, limitFail, limitOnFail);
  22937. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  22938. if (joinFlags & JFleftouter || limitOnFail)
  22939. createDefaultRight();
  22940. }
  22941. virtual void stop()
  22942. {
  22943. puller.stop();
  22944. if (indexReadStream)
  22945. indexReadStream->stop(); // Could probably do this as soon as re have fetched rootIndex?
  22946. CRoxieServerActivity::stop();
  22947. }
  22948. virtual unsigned __int64 queryLocalCycles() const
  22949. {
  22950. __int64 localCycles = remote.totalCycles.totalCycles;
  22951. localCycles -= puller.queryTotalCycles(); // MORE - debatable... but probably fair.
  22952. if (localCycles < 0)
  22953. localCycles = 0;
  22954. return localCycles;
  22955. }
  22956. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  22957. {
  22958. if (idx==0)
  22959. return puller.queryInput();
  22960. else if (idx==1)
  22961. return indexReadInput;
  22962. else
  22963. return NULL;
  22964. }
  22965. virtual void reset()
  22966. {
  22967. totalCycles.totalCycles = remote.totalCycles.totalCycles;
  22968. remote.totalCycles.totalCycles = 0;
  22969. processed = remote.joinProcessed;
  22970. remote.joinProcessed = 0;
  22971. defaultRight.clear();
  22972. if (indexReadInput)
  22973. indexReadInput->reset();
  22974. if (atmostsTriggered)
  22975. noteStatistic(StNumAtmostTriggered, atmostsTriggered);
  22976. CRoxieServerActivity::reset();
  22977. puller.reset();
  22978. while (groups.ordinality())
  22979. {
  22980. ::Release(groups.dequeue());
  22981. }
  22982. }
  22983. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  22984. {
  22985. if (idx==(unsigned)-1)
  22986. idx = 0;
  22987. return idx ? NULL : &remote;
  22988. }
  22989. #undef new
  22990. virtual CJoinGroup *createJoinGroup(const void *row)
  22991. {
  22992. // NOTE - we need to protect access to queue, since it's also modified by consumer thread. Groupstart is only modified by puller thread.
  22993. CriticalBlock c(groupsCrit);
  22994. if (preserveGroups && !groupStart)
  22995. {
  22996. groupStart = new (&ctx->queryRowManager(), activityId) CJoinGroup(NULL, NULL);
  22997. groups.enqueue(groupStart);
  22998. }
  22999. CJoinGroup *jg = new (&ctx->queryRowManager(), activityId) CJoinGroup(row, groupStart);
  23000. groups.enqueue(jg);
  23001. return jg;
  23002. }
  23003. #if defined(_DEBUG) && defined(_WIN32) && !defined(USING_MPATROL)
  23004. #define new new(_NORMAL_BLOCK, __FILE__, __LINE__)
  23005. #endif
  23006. void endGroup()
  23007. {
  23008. CriticalBlock c(groupsCrit);
  23009. if (groupStart)
  23010. noteEndReceived(groupStart, 0);
  23011. groupStart = NULL;
  23012. }
  23013. virtual void noteEndReceived(CJoinGroup *jg, unsigned candidateCount)
  23014. {
  23015. if (jg->noteEndReceived(candidateCount))
  23016. processCompletedGroups();
  23017. }
  23018. void processCompletedGroups()
  23019. {
  23020. CriticalBlock c(groupsCrit);
  23021. while (groups.ordinality())
  23022. {
  23023. if (!groups.head()->complete())
  23024. break;
  23025. Owned<CJoinGroup> head = groups.dequeue();
  23026. if (preserveGroups)
  23027. {
  23028. assert(head->isHeadRecord());
  23029. assert(groups.head()->inGroup(head));
  23030. unsigned joinGroupSize = 0;
  23031. while (groups.ordinality() && groups.head()->inGroup(head))
  23032. {
  23033. Owned<CJoinGroup> finger = groups.dequeue();
  23034. joinGroupSize += doJoinGroup(finger);
  23035. }
  23036. if (joinGroupSize)
  23037. remote.addResult(NULL);
  23038. }
  23039. else
  23040. doJoinGroup(head);
  23041. }
  23042. }
  23043. void failLimit(const void * left)
  23044. {
  23045. helper.onMatchAbortLimitExceeded();
  23046. CommonXmlWriter xmlwrite(0);
  23047. if (input && input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  23048. {
  23049. input->queryOutputMeta()->toXML((byte *) left, xmlwrite);
  23050. }
  23051. throw MakeStringException(ROXIE_JOIN_ERROR, "More than %d match candidates in keyed join %d for row %s", abortLimit, queryId(), xmlwrite.str());
  23052. }
  23053. virtual bool needsAllocator() const { return true; }
  23054. unsigned doTransform(const void *left, const void *right, offset_t fpos_or_count, IException *except, const void **group, unsigned counter)
  23055. {
  23056. if (cloneLeft && !except)
  23057. {
  23058. LinkRoxieRow(left);
  23059. remote.addResult((void *) left);
  23060. return 1;
  23061. }
  23062. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  23063. unsigned outSize;
  23064. try
  23065. {
  23066. outSize = except ? helper.onFailTransform(rowBuilder, left, right, fpos_or_count, except) :
  23067. (activityKind == TAKkeyeddenormalizegroup) ? helper.transform(rowBuilder, left, right, (unsigned) fpos_or_count, group) :
  23068. helper.transform(rowBuilder, left, right, fpos_or_count, counter);
  23069. }
  23070. catch (IException *E)
  23071. {
  23072. throw makeWrappedException(E);
  23073. }
  23074. if (outSize)
  23075. {
  23076. const void *shrunk = rowBuilder.finalizeRowClear(outSize);
  23077. remote.addResult(shrunk);
  23078. return 1;
  23079. }
  23080. else
  23081. return 0;
  23082. }
  23083. unsigned doJoinGroup(CJoinGroup *jg)
  23084. {
  23085. unsigned matched = jg->rowsSeen();
  23086. unsigned added = 0;
  23087. const void *left = jg->queryLeft();
  23088. if (jg->candidateCount() > abortLimit)
  23089. {
  23090. if (limitFail)
  23091. failLimit(left);
  23092. if (ctx->queryDebugContext())
  23093. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  23094. if (limitOnFail)
  23095. {
  23096. Owned<IException> except;
  23097. try
  23098. {
  23099. failLimit(left);
  23100. }
  23101. catch(IException * e)
  23102. {
  23103. except.setown(e);
  23104. }
  23105. added = doTransform(left, defaultRight, 0, except, NULL, 0);
  23106. }
  23107. }
  23108. else if (!matched || jg->candidateCount() > atMost)
  23109. {
  23110. if (jg->candidateCount() > atMost)
  23111. atmostsTriggered++;
  23112. switch (joinFlags & JFtypemask)
  23113. {
  23114. case JFleftouter:
  23115. case JFleftonly:
  23116. switch (activityKind)
  23117. {
  23118. case TAKkeyedjoin:
  23119. case TAKkeyeddenormalizegroup:
  23120. added = doTransform(left, defaultRight, 0, NULL, NULL, 0);
  23121. break;
  23122. case TAKkeyeddenormalize:
  23123. LinkRoxieRow(left);
  23124. remote.addResult((void *) left);
  23125. added++;
  23126. break;
  23127. }
  23128. break;
  23129. }
  23130. }
  23131. else if (!(joinFlags & JFexclude))
  23132. {
  23133. unsigned idx = 0;
  23134. switch (activityKind)
  23135. {
  23136. case TAKkeyedjoin:
  23137. while (idx < matched)
  23138. {
  23139. const KeyedJoinHeader *rhs = jg->queryRow(idx);
  23140. added += doTransform(left, &rhs->rhsdata, rhs->fpos, NULL, NULL, idx+1);
  23141. if (added==keepLimit)
  23142. break;
  23143. idx++;
  23144. }
  23145. break;
  23146. case TAKkeyeddenormalize:
  23147. {
  23148. OwnedConstRoxieRow newLeft;
  23149. newLeft.set(left);
  23150. unsigned rowSize = 0;
  23151. unsigned rightAdded = 0;
  23152. while (idx < matched)
  23153. {
  23154. const KeyedJoinHeader *rhs = jg->queryRow(idx);
  23155. try
  23156. {
  23157. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  23158. size32_t transformedSize = helper.transform(rowBuilder, newLeft, &rhs->rhsdata, rhs->fpos, idx+1);
  23159. if (transformedSize)
  23160. {
  23161. rowSize = transformedSize;
  23162. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  23163. rightAdded++;
  23164. if (rightAdded==keepLimit)
  23165. break;
  23166. }
  23167. idx++;
  23168. }
  23169. catch (IException *E)
  23170. {
  23171. throw makeWrappedException(E);
  23172. }
  23173. }
  23174. if (rowSize)
  23175. {
  23176. remote.addResult(newLeft.getClear());
  23177. added++;
  23178. }
  23179. }
  23180. break;
  23181. case TAKkeyeddenormalizegroup:
  23182. {
  23183. ConstPointerArray extractedRows;
  23184. while (idx < matched && idx < keepLimit)
  23185. {
  23186. const KeyedJoinHeader *rhs = jg->queryRow(idx);
  23187. extractedRows.append((void *) &rhs->rhsdata);
  23188. idx++;
  23189. }
  23190. added += doTransform(left, extractedRows.item(0), extractedRows.ordinality(), NULL, (const void * *)extractedRows.getArray(), 0);
  23191. }
  23192. break;
  23193. }
  23194. }
  23195. return added;
  23196. }
  23197. virtual void processDone()
  23198. {
  23199. // called from puller thread
  23200. remote.flush();
  23201. remote.senddone();
  23202. }
  23203. virtual void onLimitExceeded(bool isKeyed)
  23204. {
  23205. if (traceLevel > 4)
  23206. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  23207. if (isKeyed)
  23208. throwUnexpected();
  23209. helper.onLimitExceeded();
  23210. }
  23211. virtual const void *createLimitFailRow(bool isKeyed)
  23212. {
  23213. throwUnexpected();
  23214. }
  23215. virtual bool fireException(IException *e)
  23216. {
  23217. // called from puller thread on failure
  23218. return remote.fireException(e);
  23219. }
  23220. virtual const void *nextRow()
  23221. {
  23222. throwUnexpected(); // I am nobody's input
  23223. }
  23224. };
  23225. #ifdef _MSC_VER
  23226. #pragma warning ( push )
  23227. #pragma warning ( disable: 4355 )
  23228. #endif
  23229. class CRoxieServerKeyedJoinActivity : public CRoxieServerKeyedJoinBase
  23230. {
  23231. CRoxieServerFullKeyedJoinHead head;
  23232. Owned<IEngineRowAllocator> fetchInputAllocator;
  23233. Linked<IFilePartMap> map;
  23234. bool variableFetchFileName;
  23235. Owned<const IResolvedFile> varFetchFileInfo;
  23236. CachedOutputMetaData fetchInputFields;
  23237. public:
  23238. CRoxieServerKeyedJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_headId, IKeyArray * _key, TranslatorArray *_translators, IOutputMetaData *_indexReadMeta,
  23239. const RemoteActivityId &_tailId, IFilePartMap *_map, unsigned _joinFlags, bool _isLocal)
  23240. : CRoxieServerKeyedJoinBase(_ctx, _factory, _probeManager, _tailId, _joinFlags, true, false, _isLocal),
  23241. head(_ctx, _factory, _probeManager, _headId, _key, _translators, _indexReadMeta, this, _isLocal),
  23242. map(_map)
  23243. {
  23244. CRoxieServerKeyedJoinBase::setInput(0, 0, head.queryOutput(0));
  23245. variableFetchFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  23246. }
  23247. virtual const IResolvedFile *queryVarFileInfo() const
  23248. {
  23249. return varFetchFileInfo;
  23250. }
  23251. virtual void onCreate(IHThorArg *_colocalParent)
  23252. {
  23253. CRoxieServerKeyedJoinBase::onCreate(_colocalParent);
  23254. head.onCreate(_colocalParent);
  23255. fetchInputFields.set(helper.queryFetchInputRecordSize());
  23256. fetchInputAllocator.setown(createRowAllocator(helper.queryFetchInputRecordSize()));
  23257. }
  23258. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  23259. {
  23260. CRoxieServerKeyedJoinBase::start(parentExtractSize, parentExtract, paused);
  23261. if (variableFetchFileName)
  23262. {
  23263. bool isFetchOpt = (helper.getFetchFlags() & FFdatafileoptional) != 0;
  23264. OwnedRoxieString fname(helper.getFileName());
  23265. varFetchFileInfo.setown(resolveLFN(fname, isFetchOpt));
  23266. if (varFetchFileInfo)
  23267. map.setown(varFetchFileInfo->getFileMap());
  23268. }
  23269. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().keyedJoinPreload, false, ctx);
  23270. }
  23271. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  23272. {
  23273. head.setInput(idx, _sourceIdx, _in);
  23274. }
  23275. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  23276. {
  23277. connectInputStreams(consumerOrdered);
  23278. return head.getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
  23279. }
  23280. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  23281. {
  23282. return head.queryInput(idx);
  23283. }
  23284. virtual void processRow(const void *_rhs)
  23285. {
  23286. // called from puller thread
  23287. KeyedJoinHeader *rhs = (KeyedJoinHeader *) _rhs;
  23288. CJoinGroup *jg = rhs->thisGroup;
  23289. if (rhs->partNo != (unsigned short) -1)
  23290. {
  23291. unsigned partNo = map->mapOffset(rhs->fpos);
  23292. RtlDynamicRowBuilder fetchBuilder(fetchInputAllocator, true);
  23293. size32_t fisize = helper.extractFetchFields(fetchBuilder, jg->queryLeft());
  23294. if (fetchInputFields.isVariableSize())
  23295. {
  23296. KeyedJoinHeader *outRow = (KeyedJoinHeader *) remote.getMem(partNo, 0, KEYEDJOIN_RECORD_SIZE(fisize + sizeof(fisize)));
  23297. memcpy(outRow, rhs, KEYEDJOIN_RECORD_SIZE(0)); // MORE - copy constructor might be more appropriate....
  23298. ReleaseRoxieRow(rhs);
  23299. jg->notePending();
  23300. memcpy(&outRow->rhsdata, &fisize, sizeof(fisize));
  23301. memcpy((&outRow->rhsdata)+sizeof(fisize), fetchBuilder.row(), fisize);
  23302. }
  23303. else
  23304. {
  23305. KeyedJoinHeader *outRow = (KeyedJoinHeader *) remote.getMem(partNo, 0, KEYEDJOIN_RECORD_SIZE(fisize));
  23306. memcpy(outRow, rhs, KEYEDJOIN_RECORD_SIZE(0)); // MORE - copy constructor might be more appropriate....
  23307. ReleaseRoxieRow(rhs);
  23308. jg->notePending();
  23309. memcpy(&outRow->rhsdata, fetchBuilder.row(), fisize);
  23310. }
  23311. }
  23312. else
  23313. {
  23314. unsigned candidateCount = (unsigned) rhs->fpos;
  23315. // CTXLOG("Full keyed join - all results back from index");
  23316. ReleaseRoxieRow(rhs);
  23317. noteEndReceived(jg, candidateCount); // may throw exception - so release row before calling
  23318. }
  23319. }
  23320. virtual void processEOG()
  23321. {
  23322. // called from front puller thread
  23323. if (preserveGroups)
  23324. endGroup();
  23325. }
  23326. void processGroup(const ConstPointerArray &)
  23327. {
  23328. throwUnexpected();
  23329. }
  23330. };
  23331. #ifdef _MSC_VER
  23332. #pragma warning ( pop )
  23333. #endif
  23334. class CRoxieServerHalfKeyedJoinActivity : public CRoxieServerKeyedJoinBase
  23335. {
  23336. IOutputMetaData *indexReadMeta;
  23337. Owned<IEngineRowAllocator> indexReadAllocator;
  23338. Owned<IKeyManager> tlk;
  23339. bool variableIndexFileName;
  23340. bool indexReadInputRecordVariable;
  23341. Owned<const IResolvedFile> varFileInfo;
  23342. Linked<TranslatorArray> translators;
  23343. Linked<IKeyArray> keySet;
  23344. Owned<IOutputMetaData> joinPrefixedMeta;
  23345. Owned<IEngineRowAllocator> joinFieldsAllocator;
  23346. public:
  23347. CRoxieServerHalfKeyedJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IKeyArray * _keySet, TranslatorArray *_translators,
  23348. IOutputMetaData *_indexReadMeta, unsigned _joinFlags, bool _isSimple, bool _isLocal)
  23349. : CRoxieServerKeyedJoinBase(_ctx, _factory, _probeManager, _remoteId, _joinFlags, false, _isSimple, _isLocal),
  23350. indexReadMeta(_indexReadMeta),
  23351. tlk(createKeyManager(NULL, 0, this)),
  23352. keySet(_keySet),
  23353. translators(_translators)
  23354. {
  23355. variableIndexFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getJoinFlags() & (JFvarindexfilename|JFdynamicindexfilename|JFindexfromactivity)) != 0);
  23356. indexReadInputRecordVariable = indexReadMeta->isVariableSize();
  23357. }
  23358. virtual void serializeExtra(MemoryBuffer &out)
  23359. {
  23360. if (helper.getJoinFlags() & JFindexfromactivity)
  23361. {
  23362. assertex(rootIndex);
  23363. const RemoteActivityId& indexId = rootIndex->queryRemoteId();
  23364. indexId.serialize(out);
  23365. // could mess about reserving space for length then patching it again, to avoid copy, but probably not worth it
  23366. MemoryBuffer tmp;
  23367. rootIndex->queryActivity()->serializeCreateStartContext(tmp);
  23368. if (rootIndex->queryActivity()->queryVarFileInfo())
  23369. {
  23370. rootIndex->queryActivity()->queryVarFileInfo()->queryTimeStamp().serialize(tmp);
  23371. tmp.append(rootIndex->queryActivity()->queryVarFileInfo()->queryCheckSum());
  23372. }
  23373. unsigned ctxlen = tmp.length();
  23374. out.append(ctxlen).append(tmp);
  23375. }
  23376. }
  23377. virtual void onCreate(IHThorArg *_colocalParent)
  23378. {
  23379. CRoxieServerKeyedJoinBase::onCreate(_colocalParent);
  23380. indexReadAllocator.setown(createRowAllocator(indexReadMeta));
  23381. IOutputMetaData *joinFieldsMeta = helper.queryJoinFieldsRecordSize();
  23382. joinPrefixedMeta.setown(new CPrefixedOutputMeta(KEYEDJOIN_RECORD_SIZE(0), joinFieldsMeta)); // MORE - not sure if we really need this
  23383. joinFieldsAllocator.setown(createRowAllocator(joinPrefixedMeta));
  23384. }
  23385. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  23386. {
  23387. CRoxieServerKeyedJoinBase::start(parentExtractSize, parentExtract, paused);
  23388. if (rootIndex)
  23389. {
  23390. varFileInfo.setown(rootIndex->getVarFileInfo());
  23391. translators.setown(rootIndex->getTranslators());
  23392. keySet.setown(rootIndex->getKeySet());
  23393. }
  23394. else if (variableIndexFileName)
  23395. {
  23396. OwnedRoxieString indexFileName(helper.getIndexFileName());
  23397. varFileInfo.setown(resolveLFN(indexFileName, (helper.getJoinFlags() & JFindexoptional) != 0));
  23398. if (varFileInfo)
  23399. {
  23400. translators.setown(new TranslatorArray);
  23401. keySet.setown(varFileInfo->getKeyArray(factory->queryActivityMeta(), translators, false, isLocal ? factory->queryQueryFactory().queryChannel() : 0, factory->queryQueryFactory().queryOptions().enableFieldTranslation));
  23402. }
  23403. }
  23404. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().keyedJoinPreload, isSimple, ctx);
  23405. }
  23406. virtual const IResolvedFile *queryVarFileInfo() const
  23407. {
  23408. return varFileInfo;
  23409. }
  23410. virtual void reset()
  23411. {
  23412. CRoxieServerKeyedJoinBase::reset();
  23413. if (varFileInfo)
  23414. {
  23415. keySet.clear();
  23416. varFileInfo.clear();
  23417. }
  23418. }
  23419. virtual void processRow(const void *row)
  23420. {
  23421. // called from front puller thread
  23422. // buffer up an IndexRead request
  23423. if (helper.leftCanMatch(row) && keySet)
  23424. {
  23425. RtlDynamicRowBuilder extractBuilder(indexReadAllocator);
  23426. unsigned indexReadRecordSize = helper.extractIndexReadFields(extractBuilder, row);
  23427. OwnedConstRoxieRow extracted;
  23428. if (indexReadRecordSize)
  23429. extracted.setown(extractBuilder.finalizeRowClear(indexReadRecordSize));
  23430. CJoinGroup *jg = createJoinGroup(row);
  23431. for (unsigned partNo = 0; partNo < keySet->length(); partNo++)
  23432. {
  23433. IKeyIndexBase *thisBase = keySet->queryKeyPart(partNo);
  23434. if (thisBase)
  23435. {
  23436. unsigned fileNo = 0;
  23437. IKeyIndex *thisKey = thisBase->queryPart(fileNo);
  23438. tlk->setKey(thisKey);
  23439. tlk->setLayoutTranslator(translators->item(fileNo));
  23440. helper.createSegmentMonitors(tlk, extracted);
  23441. if (rootIndex)
  23442. rootIndex->mergeSegmentMonitors(tlk);
  23443. tlk->finishSegmentMonitors();
  23444. try
  23445. {
  23446. tlk->reset();
  23447. loop
  23448. {
  23449. typedef const void * cvp;
  23450. if (thisKey && thisKey->isTopLevelKey())
  23451. {
  23452. bool locallySorted = (!thisKey->isFullySorted());
  23453. while (locallySorted || tlk->lookup(false))
  23454. {
  23455. unsigned slavePart = locallySorted ? 0 : (unsigned) tlk->queryFpos();
  23456. if (locallySorted || slavePart)
  23457. {
  23458. cvp *outputBuffer = (cvp *) remote.getMem(slavePart, fileNo, indexReadRecordSize + sizeof(cvp) + (indexReadInputRecordVariable ? sizeof(unsigned) : 0));
  23459. *outputBuffer++ = jg;
  23460. if (indexReadInputRecordVariable)
  23461. {
  23462. *(unsigned *) outputBuffer = indexReadRecordSize;
  23463. outputBuffer = (cvp *) (((unsigned *) outputBuffer) + 1);
  23464. }
  23465. jg->notePending();
  23466. memcpy(outputBuffer, extracted, indexReadRecordSize);
  23467. if (locallySorted)
  23468. {
  23469. for (unsigned i = 1; i < numChannels; i++)
  23470. jg->notePending();
  23471. break;
  23472. }
  23473. }
  23474. }
  23475. }
  23476. else
  23477. {
  23478. unsigned accepted = 0;
  23479. unsigned rejected = 0;
  23480. Owned<CRowArrayMessageResult> result;
  23481. if (!isSimple)
  23482. result.setown(new CRowArrayMessageResult(ctx->queryRowManager(), true));
  23483. // MORE - This code seems to be duplicated in keyedJoinHead
  23484. jg->notePending();
  23485. unsigned candidateCount = 0;
  23486. while (tlk->lookup(true))
  23487. {
  23488. candidateCount++;
  23489. atomic_inc(&indexRecordsRead);
  23490. KLBlobProviderAdapter adapter(tlk);
  23491. offset_t recptr;
  23492. const byte *indexRow = tlk->queryKeyBuffer(recptr);
  23493. if (helper.indexReadMatch(extracted, indexRow, recptr, &adapter))
  23494. {
  23495. RtlDynamicRowBuilder rb(joinFieldsAllocator, true);
  23496. CPrefixedRowBuilder pb(KEYEDJOIN_RECORD_SIZE(0), rb);
  23497. accepted++;
  23498. KLBlobProviderAdapter adapter(tlk);
  23499. size32_t joinFieldsSize = helper.extractJoinFields(pb, indexRow, recptr, &adapter);
  23500. KeyedJoinHeader *rec = (KeyedJoinHeader *) rb.getUnfinalizedClear(); // lack of finalize ok as unserialized data here.
  23501. rec->fpos = recptr;
  23502. rec->thisGroup = jg;
  23503. rec->partNo = partNo;
  23504. if (isSimple)
  23505. remote.injected.enqueue(rec);
  23506. else
  23507. result->append(rec);
  23508. }
  23509. else
  23510. {
  23511. rejected++;
  23512. atomic_inc(&postFiltered);
  23513. }
  23514. }
  23515. // output an end marker for the matches to this group
  23516. KeyedJoinHeader *rec = (KeyedJoinHeader *) ctx->queryRowManager().allocate(KEYEDJOIN_RECORD_SIZE(0), activityId);
  23517. rec->fpos = (offset_t) candidateCount;
  23518. rec->thisGroup = jg;
  23519. rec->partNo = (unsigned short) -1;
  23520. if (isSimple)
  23521. remote.injected.enqueue(rec);
  23522. else
  23523. {
  23524. result->append(rec);
  23525. remote.injectResult(result.getClear());
  23526. }
  23527. if (accepted)
  23528. noteStatistic(StNumIndexAccepted, accepted);
  23529. if (rejected)
  23530. noteStatistic(StNumIndexRejected, rejected);
  23531. }
  23532. if (++fileNo < thisBase->numParts())
  23533. {
  23534. thisKey = thisBase->queryPart(fileNo);
  23535. tlk->setKey(thisKey);
  23536. tlk->setLayoutTranslator(translators->item(fileNo));
  23537. tlk->reset();
  23538. }
  23539. else
  23540. break;
  23541. }
  23542. tlk->releaseSegmentMonitors();
  23543. tlk->setKey(NULL);
  23544. }
  23545. catch (...)
  23546. {
  23547. tlk->releaseSegmentMonitors();
  23548. tlk->setKey(NULL);
  23549. throw;
  23550. }
  23551. }
  23552. }
  23553. noteEndReceived(jg, 0);
  23554. }
  23555. else
  23556. {
  23557. noteEndReceived(createJoinGroup(row), 0);
  23558. }
  23559. }
  23560. virtual void processEOG()
  23561. {
  23562. // called from front puller thread
  23563. if (preserveGroups)
  23564. endGroup();
  23565. }
  23566. void processGroup(const ConstPointerArray &)
  23567. {
  23568. throwUnexpected();
  23569. }
  23570. };
  23571. class CRoxieServerKeyedJoinActivityFactory : public CRoxieServerMultiInputFactory
  23572. {
  23573. Owned<const IResolvedFile> indexfile;
  23574. Owned<const IResolvedFile> datafile;
  23575. Owned<IKeyArray> keySet;
  23576. Owned<TranslatorArray> translatorArray;
  23577. Owned<IDefRecordMeta> activityMeta;
  23578. RemoteActivityId headId;
  23579. RemoteActivityId tailId;
  23580. IOutputMetaData *indexReadMeta;
  23581. Owned<IFilePartMap> map;
  23582. Owned<IFileIOArray> files;
  23583. unsigned joinFlags;
  23584. bool isHalfKeyed;
  23585. bool isLocal;
  23586. bool enableFieldTranslation;
  23587. bool variableFetchFileName;
  23588. bool variableIndexFileName;
  23589. bool isSimple;
  23590. public:
  23591. CRoxieServerKeyedJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_headId, const RemoteActivityId &_tailId)
  23592. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), headId(_headId), tailId(_tailId)
  23593. {
  23594. Owned<IHThorKeyedJoinArg> helper = (IHThorKeyedJoinArg *) helperFactory();
  23595. isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  23596. isSimple = isLocal;
  23597. rtlDataAttr indexLayoutMeta;
  23598. size32_t indexLayoutSize;
  23599. if(!helper->getIndexLayout(indexLayoutSize, indexLayoutMeta.refdata()))
  23600. assertex(indexLayoutSize== 0);
  23601. MemoryBuffer m;
  23602. m.setBuffer(indexLayoutSize, indexLayoutMeta.getdata());
  23603. activityMeta.setown(deserializeRecordMeta(m, true));
  23604. enableFieldTranslation = queryFactory.queryOptions().enableFieldTranslation;
  23605. translatorArray.setown(new TranslatorArray);
  23606. joinFlags = helper->getJoinFlags();
  23607. variableIndexFileName = allFilesDynamic || _queryFactory.isDynamic() || ((joinFlags & (JFvarindexfilename|JFdynamicindexfilename|JFindexfromactivity)) != 0);
  23608. variableFetchFileName = allFilesDynamic || _queryFactory.isDynamic() || ((helper->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  23609. if (!variableIndexFileName)
  23610. {
  23611. bool isOpt = (joinFlags & JFindexoptional) != 0;
  23612. OwnedRoxieString indexFileName(helper->getIndexFileName());
  23613. indexfile.setown(queryFactory.queryPackage().lookupFileName(indexFileName, isOpt, true, true, queryFactory.queryWorkUnit(), true));
  23614. if (indexfile)
  23615. keySet.setown(indexfile->getKeyArray(activityMeta, translatorArray, isOpt, isLocal ? queryFactory.queryChannel() : 0, enableFieldTranslation));
  23616. }
  23617. if (keySet && keySet->length()==1 && !isSimple)
  23618. {
  23619. IKeyIndexBase *thisBase = keySet->queryKeyPart(0);
  23620. if (thisBase->numParts()==1 && !thisBase->queryPart(0)->isTopLevelKey() && !_queryFactory.queryOptions().disableLocalOptimizations)
  23621. isSimple = true;
  23622. // MORE - if it's a variable filename then it MAY be simple, we don't know. Tough.
  23623. }
  23624. if (!simpleLocalKeyedJoins)
  23625. isSimple = false;
  23626. isHalfKeyed = !helper->diskAccessRequired();
  23627. indexReadMeta = QUERYINTERFACE(helper->queryIndexReadInputRecordSize(), IOutputMetaData);
  23628. if (!isHalfKeyed && !variableFetchFileName)
  23629. {
  23630. bool isFetchOpt = (helper->getFetchFlags() & FFdatafileoptional) != 0;
  23631. datafile.setown(_queryFactory.queryPackage().lookupFileName(queryNodeFileName(_graphNode, _kind), isFetchOpt, true, true, _queryFactory.queryWorkUnit(), true));
  23632. if (datafile)
  23633. {
  23634. if (isLocal)
  23635. files.setown(datafile->getIFileIOArray(isFetchOpt, queryFactory.queryChannel()));
  23636. else
  23637. map.setown(datafile->getFileMap());
  23638. }
  23639. }
  23640. }
  23641. virtual bool getEnableFieldTranslation() const
  23642. {
  23643. return enableFieldTranslation;
  23644. }
  23645. virtual IDefRecordMeta *queryActivityMeta() const
  23646. {
  23647. return activityMeta;
  23648. }
  23649. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  23650. {
  23651. if (isHalfKeyed)
  23652. return new CRoxieServerHalfKeyedJoinActivity(_ctx, this, _probeManager,
  23653. headId, keySet, translatorArray, indexReadMeta, joinFlags, isSimple, isLocal);
  23654. else
  23655. return new CRoxieServerKeyedJoinActivity(_ctx, this, _probeManager,
  23656. headId, keySet, translatorArray, indexReadMeta,
  23657. tailId, map, joinFlags, isLocal);
  23658. }
  23659. virtual const StatisticsMapping &queryStatsMapping() const
  23660. {
  23661. return keyedJoinStatistics;
  23662. }
  23663. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  23664. {
  23665. if (datafile)
  23666. addXrefFileInfo(reply, datafile);
  23667. if (indexfile)
  23668. addXrefFileInfo(reply, indexfile);
  23669. }
  23670. };
  23671. IRoxieServerActivityFactory *createRoxieServerKeyedJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId, const RemoteActivityId &_remoteId2)
  23672. {
  23673. return new CRoxieServerKeyedJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId, _remoteId2);
  23674. }
  23675. //=================================================================================
  23676. class CRoxieServerSoapActivityBase : public CRoxieServerActivity, implements ISoapCallRowProvider, implements IRoxieAbortMonitor
  23677. {
  23678. protected:
  23679. Owned<ISoapCallHelper> soaphelper;
  23680. IHThorSoapActionArg & helper;
  23681. StringBuffer authToken;
  23682. bool eof;
  23683. CriticalSection crit;
  23684. ClientCertificate *pClientCert;
  23685. public:
  23686. IMPLEMENT_IINTERFACE_USING(CRoxieServerActivity)
  23687. CRoxieServerSoapActivityBase(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  23688. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorSoapActionArg &)basehelper)
  23689. {
  23690. eof = false;
  23691. if (clientCert.certificate.length() > 0 && clientCert.privateKey.length() > 0 && clientCert.passphrase.length() > 0)
  23692. pClientCert = &clientCert;
  23693. else
  23694. pClientCert = NULL;
  23695. }
  23696. // ISoapCallRowProvider
  23697. virtual IHThorSoapActionArg * queryActionHelper() { return &helper; };
  23698. virtual IHThorSoapCallArg * queryCallHelper() { return NULL; };
  23699. virtual const void * getNextRow() { return NULL; };
  23700. virtual void releaseRow(const void * r) { ReleaseRoxieRow(r); };
  23701. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  23702. {
  23703. eof = false;
  23704. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  23705. authToken.append(ctx->queryAuthToken());
  23706. }
  23707. virtual void reset()
  23708. {
  23709. // MORE - Shouldn't we make sure thread is stopped etc???
  23710. soaphelper.clear();
  23711. CRoxieServerActivity::reset();
  23712. }
  23713. // IRoxieAbortMonitor
  23714. virtual void checkForAbort() { checkAbort(); }
  23715. };
  23716. //---------------------------------------------------------------------------
  23717. class CRoxieServerSoapRowCallActivity : public CRoxieServerSoapActivityBase
  23718. {
  23719. IHThorSoapCallArg & callHelper;
  23720. public:
  23721. CRoxieServerSoapRowCallActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  23722. : CRoxieServerSoapActivityBase(_ctx, _factory, _probeManager), callHelper((IHThorSoapCallArg &)basehelper)
  23723. {
  23724. }
  23725. virtual IHThorSoapCallArg * queryCallHelper()
  23726. {
  23727. return &callHelper;
  23728. }
  23729. virtual bool needsAllocator() const { return true; }
  23730. virtual const void *nextRow()
  23731. {
  23732. ActivityTimer t(totalCycles, timeActivities);
  23733. if(eof) return NULL;
  23734. if (soaphelper == NULL)
  23735. {
  23736. if (factory->getKind()==TAKhttp_rowdataset)
  23737. soaphelper.setown(createHttpCallHelper(this, rowAllocator, authToken.str(), SCrow, pClientCert, *this, this));
  23738. else
  23739. soaphelper.setown(createSoapCallHelper(this, rowAllocator, authToken.str(), SCrow, pClientCert, *this, this));
  23740. soaphelper->start();
  23741. }
  23742. OwnedConstRoxieRow ret = soaphelper->getRow();
  23743. if (!ret)
  23744. {
  23745. eof = true;
  23746. return NULL;
  23747. }
  23748. ++processed;
  23749. return ret.getClear();
  23750. }
  23751. };
  23752. class CRoxieServerSoapRowCallActivityFactory : public CRoxieServerActivityFactory
  23753. {
  23754. public:
  23755. CRoxieServerSoapRowCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  23756. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  23757. {
  23758. }
  23759. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  23760. {
  23761. return new CRoxieServerSoapRowCallActivity(_ctx, this, _probeManager);
  23762. }
  23763. virtual const StatisticsMapping &queryStatsMapping() const
  23764. {
  23765. return soapStatistics;
  23766. }
  23767. };
  23768. IRoxieServerActivityFactory *createRoxieServerSoapRowCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  23769. {
  23770. return new CRoxieServerSoapRowCallActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  23771. }
  23772. //---------------------------------------------------------------------------
  23773. class CRoxieServerSoapRowActionActivity : public CRoxieServerSoapActivityBase
  23774. {
  23775. public:
  23776. CRoxieServerSoapRowActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  23777. : CRoxieServerSoapActivityBase(_ctx, _factory, _probeManager)
  23778. {}
  23779. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  23780. {
  23781. //MORE: parentExtract not passed to start - although shouldn't be a problem.
  23782. soaphelper.setown(createSoapCallHelper(this, NULL, ctx->queryAuthToken(), SCrow, pClientCert, *this, this));
  23783. soaphelper->start();
  23784. soaphelper->waitUntilDone();
  23785. IException *e = soaphelper->getError();
  23786. soaphelper.clear();
  23787. if (e)
  23788. throw e;
  23789. }
  23790. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  23791. {
  23792. return NULL;
  23793. }
  23794. virtual const void *nextRow()
  23795. {
  23796. throwUnexpected(); // I am nobody's input
  23797. }
  23798. };
  23799. class CRoxieServerSoapRowActionActivityFactory : public CRoxieServerActivityFactory
  23800. {
  23801. bool isRoot;
  23802. public:
  23803. CRoxieServerSoapRowActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  23804. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  23805. {
  23806. }
  23807. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  23808. {
  23809. return new CRoxieServerSoapRowActionActivity(_ctx, this, _probeManager);
  23810. }
  23811. virtual bool isSink() const
  23812. {
  23813. return isRoot;
  23814. }
  23815. virtual const StatisticsMapping &queryStatsMapping() const
  23816. {
  23817. return soapStatistics;
  23818. }
  23819. };
  23820. IRoxieServerActivityFactory *createRoxieServerSoapRowActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  23821. {
  23822. return new CRoxieServerSoapRowActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  23823. }
  23824. //---------------------------------------------------------------------------
  23825. class CRoxieServerSoapDatasetCallActivity : public CRoxieServerSoapActivityBase
  23826. {
  23827. IHThorSoapCallArg & callHelper;
  23828. public:
  23829. CRoxieServerSoapDatasetCallActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  23830. : CRoxieServerSoapActivityBase(_ctx, _factory, _probeManager), callHelper((IHThorSoapCallArg &)basehelper)
  23831. {
  23832. }
  23833. virtual IHThorSoapCallArg * queryCallHelper()
  23834. {
  23835. return &callHelper;
  23836. }
  23837. virtual const void *getNextRow()
  23838. {
  23839. CriticalBlock b(crit); // MORE - why ?
  23840. return inputStream->ungroupedNextRow();
  23841. }
  23842. virtual bool needsAllocator() const { return true; }
  23843. virtual const void *nextRow()
  23844. {
  23845. ActivityTimer t(totalCycles, timeActivities);
  23846. if(eof) return NULL;
  23847. if (soaphelper == NULL)
  23848. {
  23849. soaphelper.setown(createSoapCallHelper(this, rowAllocator, authToken.str(), SCdataset, pClientCert, *this, this));
  23850. soaphelper->start();
  23851. }
  23852. OwnedConstRoxieRow ret = soaphelper->getRow();
  23853. if (!ret)
  23854. {
  23855. eof = true;
  23856. return NULL;
  23857. }
  23858. ++processed;
  23859. return ret.getClear();
  23860. }
  23861. };
  23862. class CRoxieServerSoapDatasetCallActivityFactory : public CRoxieServerActivityFactory
  23863. {
  23864. public:
  23865. CRoxieServerSoapDatasetCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  23866. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  23867. {
  23868. }
  23869. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  23870. {
  23871. return new CRoxieServerSoapDatasetCallActivity(_ctx, this, _probeManager);
  23872. }
  23873. virtual const StatisticsMapping &queryStatsMapping() const
  23874. {
  23875. return soapStatistics;
  23876. }
  23877. };
  23878. IRoxieServerActivityFactory *createRoxieServerSoapDatasetCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  23879. {
  23880. return new CRoxieServerSoapDatasetCallActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  23881. }
  23882. //---------------------------------------------------------------------------
  23883. class CRoxieServerSoapDatasetActionActivity : public CRoxieServerSoapActivityBase
  23884. {
  23885. public:
  23886. CRoxieServerSoapDatasetActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  23887. : CRoxieServerSoapActivityBase(_ctx, _factory, _probeManager)
  23888. {}
  23889. virtual const void *getNextRow()
  23890. {
  23891. CriticalBlock b(crit); // MORE - Why?
  23892. const void *nextrec = inputStream->ungroupedNextRow();
  23893. if (nextrec)
  23894. processed++;
  23895. return nextrec;
  23896. }
  23897. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  23898. {
  23899. try
  23900. {
  23901. start(parentExtractSize, parentExtract, false);
  23902. soaphelper.setown(createSoapCallHelper(this, NULL, ctx->queryAuthToken(), SCdataset, pClientCert, *this, this));
  23903. soaphelper->start();
  23904. soaphelper->waitUntilDone();
  23905. IException *e = soaphelper->getError();
  23906. soaphelper.clear();
  23907. if (e)
  23908. throw e;
  23909. stop();
  23910. }
  23911. catch (IException *E)
  23912. {
  23913. ctx->notifyAbort(E);
  23914. abort();
  23915. throw;
  23916. }
  23917. catch(...)
  23918. {
  23919. Owned<IException> E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught at %s:%d", __FILE__, __LINE__);
  23920. ctx->notifyAbort(E);
  23921. abort();
  23922. throw;
  23923. }
  23924. }
  23925. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  23926. {
  23927. return NULL;
  23928. }
  23929. virtual const void *nextRow()
  23930. {
  23931. throwUnexpected(); // I am nobody's input
  23932. }
  23933. };
  23934. class CRoxieServerSoapDatasetActionActivityFactory : public CRoxieServerActivityFactory
  23935. {
  23936. bool isRoot;
  23937. public:
  23938. CRoxieServerSoapDatasetActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  23939. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  23940. {
  23941. }
  23942. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  23943. {
  23944. return new CRoxieServerSoapDatasetActionActivity(_ctx, this, _probeManager);
  23945. }
  23946. virtual bool isSink() const
  23947. {
  23948. return isRoot;
  23949. }
  23950. virtual const StatisticsMapping &queryStatsMapping() const
  23951. {
  23952. return soapStatistics;
  23953. }
  23954. };
  23955. IRoxieServerActivityFactory *createRoxieServerSoapDatasetActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  23956. {
  23957. return new CRoxieServerSoapDatasetActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  23958. }
  23959. //=====================================================================================================
  23960. class CGraphResults : implements IRoxieGraphResults, public CInterface
  23961. {
  23962. IArrayOf<IGraphResult> results;
  23963. CriticalSection cs;
  23964. IGraphResult & select(unsigned idx)
  23965. {
  23966. CriticalBlock procedure(cs);
  23967. if (idx >= results.ordinality())
  23968. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Error reading graph result %d before it is calculated", idx);
  23969. return results.item(idx);
  23970. }
  23971. public:
  23972. IMPLEMENT_IINTERFACE
  23973. void clear()
  23974. {
  23975. CriticalBlock procedure(cs);
  23976. results.kill();
  23977. }
  23978. virtual IEngineRowStream * createIterator(unsigned id)
  23979. {
  23980. return select(id).createIterator();
  23981. }
  23982. virtual void getLinkedResult(unsigned & count, byte * * & ret, unsigned id)
  23983. {
  23984. select(id).getLinkedResult(count, ret);
  23985. }
  23986. virtual void getDictionaryResult(unsigned & count, byte * * & ret, unsigned id)
  23987. {
  23988. select(id).getLinkedResult(count, ret);
  23989. }
  23990. virtual const void * getLinkedRowResult(unsigned id)
  23991. {
  23992. return select(id).getLinkedRowResult();
  23993. }
  23994. void setResult(unsigned id, IGraphResult * result)
  23995. {
  23996. CriticalBlock procedure(cs);
  23997. if (results.ordinality() <= id)
  23998. {
  23999. while (results.ordinality() < id)
  24000. results.append(*new CGraphResult);
  24001. results.append(*LINK(result));
  24002. }
  24003. else
  24004. results.replace(*LINK(result), id);
  24005. }
  24006. void appendResult(IGraphResult * result)
  24007. {
  24008. CriticalBlock procedure(cs);
  24009. results.append(*LINK(result));
  24010. }
  24011. };
  24012. //===================================================================================================================
  24013. class CPseudoArg : implements IHThorArg, public CInterface
  24014. {
  24015. public:
  24016. IMPLEMENT_IINTERFACE
  24017. virtual IOutputMetaData * queryOutputMeta() { return NULL; }
  24018. };
  24019. class CPseudoActivity : public CRoxieServerActivity
  24020. {
  24021. public:
  24022. CPseudoActivity(IRoxieSlaveContext *_ctx, IHThorArg & _helper) : CRoxieServerActivity(_ctx, _helper) {}
  24023. virtual const void *nextRow()
  24024. {
  24025. throwUnexpected(); // I am nobody's input
  24026. }
  24027. };
  24028. class CActivityGraph : implements IActivityGraph, implements IThorChildGraph, implements ILocalGraphEx, implements IRoxieServerChildGraph, public CInterface
  24029. {
  24030. protected:
  24031. class ActivityGraphSlaveContext : public IndirectSlaveContext
  24032. {
  24033. SpinLock abortLock;
  24034. bool aborted;
  24035. Owned<IException> exception;
  24036. public:
  24037. ActivityGraphSlaveContext(IRoxieSlaveContext *_ctx, const IRoxieContextLogger &_logctx) : IndirectSlaveContext(_ctx), logctx(_logctx), loopCounter(0), codeContext(NULL)
  24038. {
  24039. aborted = false;
  24040. }
  24041. // Note - we must track exceptions at the child level in case there is a CATCH in parent
  24042. virtual void notifyAbort(IException *E)
  24043. {
  24044. SpinBlock b(abortLock);
  24045. if (!aborted && QUERYINTERFACE(E, InterruptedSemaphoreException) == NULL)
  24046. {
  24047. aborted = true;
  24048. exception.set(E);
  24049. }
  24050. }
  24051. virtual void checkAbort()
  24052. {
  24053. if (aborted) // NOTE - don't bother getting lock before reading this (for speed) - a false read is very unlikely and not a problem
  24054. {
  24055. SpinBlock b(abortLock);
  24056. if (!exception)
  24057. exception.setown(MakeStringException(ROXIE_INTERNAL_ERROR, "Query was aborted"));
  24058. throw exception.getLink();
  24059. }
  24060. IndirectSlaveContext::checkAbort();
  24061. }
  24062. virtual ICodeContext *queryCodeContext()
  24063. {
  24064. return codeContext;
  24065. }
  24066. void setCodeContext(ICodeContext * _codeContext)
  24067. {
  24068. codeContext = _codeContext;
  24069. }
  24070. void setLoopCounter(unsigned _loopCounter)
  24071. {
  24072. loopCounter = _loopCounter;
  24073. }
  24074. virtual void noteChildGraph(unsigned id, IActivityGraph *childGraph)
  24075. {
  24076. childGraphs.setValue(id, childGraph);
  24077. }
  24078. virtual IActivityGraph * queryChildGraph(unsigned id)
  24079. {
  24080. if (queryTraceLevel() > 10)
  24081. CTXLOG("resolveChildGraph %d", id);
  24082. IActivityGraph *childGraph = childGraphs.getValue(id);
  24083. assertex(childGraph);
  24084. return childGraph;
  24085. }
  24086. // 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
  24087. virtual StringBuffer &getLogPrefix(StringBuffer &ret) const
  24088. {
  24089. logctx.getLogPrefix(ret);
  24090. if (loopCounter)
  24091. ret.appendf("{%u}", loopCounter);
  24092. return ret;
  24093. }
  24094. protected:
  24095. const IRoxieContextLogger &logctx;
  24096. unsigned loopCounter;
  24097. ICodeContext * codeContext;
  24098. MapXToMyClass<unsigned, unsigned, IActivityGraph> childGraphs;
  24099. } graphSlaveContext;
  24100. class ActivityGraphCodeContext : public IndirectCodeContext
  24101. {
  24102. public:
  24103. virtual IEclGraphResults * resolveLocalQuery(__int64 activityId)
  24104. {
  24105. if ((unsigned) activityId == container->queryId())
  24106. return container;
  24107. IActivityGraph * match = slaveContext->queryChildGraph((unsigned) activityId);
  24108. if (match)
  24109. return match->queryLocalGraph();
  24110. return IndirectCodeContext::resolveLocalQuery(activityId);
  24111. }
  24112. virtual IThorChildGraph * resolveChildQuery(__int64 activityId, IHThorArg * colocal)
  24113. {
  24114. IActivityGraph * match = slaveContext->queryChildGraph((unsigned) activityId);
  24115. return LINK(match->queryChildGraph());
  24116. }
  24117. virtual unsigned getGraphLoopCounter() const
  24118. {
  24119. return container->queryLoopCounter(); // only called if value is valid
  24120. }
  24121. void setContainer(IRoxieSlaveContext * _slaveContext, CActivityGraph * _container)
  24122. {
  24123. slaveContext = _slaveContext;
  24124. container = _container;
  24125. }
  24126. protected:
  24127. IRoxieSlaveContext * slaveContext;
  24128. CActivityGraph * container;
  24129. } graphCodeContext;
  24130. // NOTE - destructor order is significant - need to destroy graphCodeContext and graphSlaveContext last
  24131. IArrayOf<IRoxieServerActivity> activities;
  24132. IArrayOf<IRoxieProbe> probes;
  24133. IRoxieServerActivityCopyArray sinks;
  24134. StringAttr graphName;
  24135. Owned<CGraphResults> results;
  24136. CGraphResults graphLoopResults;
  24137. ActivityArray & graphDefinition;
  24138. CriticalSection evaluateCrit;
  24139. IProbeManager *probeManager;
  24140. unsigned id;
  24141. unsigned loopCounter;
  24142. public:
  24143. IMPLEMENT_IINTERFACE;
  24144. CActivityGraph(IRoxieSlaveContext *_ctx, const char *_graphName, unsigned _id, ActivityArray &x, IProbeManager *_probeManager, const IRoxieContextLogger &_logctx)
  24145. : probeManager(_probeManager), graphDefinition(x), graphName(_graphName), graphSlaveContext(_ctx, _logctx)
  24146. {
  24147. id = x.getLibraryGraphId();
  24148. if (!id)
  24149. id = _id;
  24150. loopCounter = 0;
  24151. graphSlaveContext.setCodeContext(&graphCodeContext);
  24152. graphCodeContext.setContainer(&graphSlaveContext, this);
  24153. }
  24154. ~CActivityGraph()
  24155. {
  24156. if (probeManager)
  24157. probeManager->deleteGraph((IArrayOf<IActivityBase>*)&activities, (IArrayOf<IInputBase>*)&probes);
  24158. }
  24159. virtual const char *queryName() const
  24160. {
  24161. return graphName.get();
  24162. }
  24163. virtual IRoxieServerActivity *queryActivity(unsigned _activityId)
  24164. {
  24165. unsigned idx = graphDefinition.recursiveFindActivityIndex(_activityId);
  24166. if (idx==NotFound)
  24167. return nullptr;
  24168. assertex(activities.isItem(idx));
  24169. IRoxieServerActivity *activity = &activities.item(idx);
  24170. if (activity->queryId() == _activityId)
  24171. return activity;
  24172. return activity->queryChildActivity(_activityId);
  24173. }
  24174. void createGraph(IRoxieSlaveContext *_ctx)
  24175. {
  24176. if (graphDefinition.isMultiInstance())
  24177. {
  24178. graphCodeContext.set(_ctx->queryCodeContext());
  24179. _ctx = &graphSlaveContext;
  24180. }
  24181. ForEachItemIn(idx, graphDefinition)
  24182. {
  24183. IRoxieServerActivityFactory &donor = graphDefinition.serverItem(idx);
  24184. IRoxieServerActivity &activity = *donor.createActivity(_ctx, probeManager);
  24185. activities.append(activity);
  24186. if (donor.isSink())
  24187. {
  24188. sinks.append(activity);
  24189. if (probeManager)
  24190. probeManager->noteSink(&activity);
  24191. }
  24192. }
  24193. ForEachItemIn(idx1, graphDefinition)
  24194. {
  24195. IRoxieServerActivityFactory &donor = graphDefinition.serverItem(idx1);
  24196. IRoxieServerActivity &activity = activities.item(idx1);
  24197. unsigned inputidx = 0;
  24198. loop
  24199. {
  24200. unsigned outputidx;
  24201. unsigned source = donor.getInput(inputidx, outputidx);
  24202. if (source==(unsigned) -1)
  24203. break;
  24204. connectInput(idx1, inputidx, source, outputidx, 0);
  24205. inputidx++;
  24206. }
  24207. IntArray &dependencies = donor.queryDependencies();
  24208. IntArray &dependencyIndexes = donor.queryDependencyIndexes();
  24209. IntArray &dependencyControlIds = donor.queryDependencyControlIds();
  24210. StringArray &dependencyEdgeIds = donor.queryDependencyEdgeIds();
  24211. ForEachItemIn(idx2, dependencies)
  24212. {
  24213. IRoxieServerActivity &dependencySourceActivity = activities.item(dependencies.item(idx2));
  24214. unsigned dependencySourceIndex = dependencyIndexes.item(idx2);
  24215. unsigned dependencyControlId = dependencyControlIds.item(idx2);
  24216. activity.addDependency(dependencySourceActivity, dependencySourceIndex, dependencyControlId);
  24217. if (probeManager)
  24218. probeManager->noteDependency( &dependencySourceActivity, dependencySourceIndex, dependencyControlId, dependencyEdgeIds.item(idx2), &activity);
  24219. }
  24220. }
  24221. ForEachItemIn(idx2, sinks)
  24222. {
  24223. IRoxieServerActivity &sink = sinks.item(idx2);
  24224. sink.connectInputStreams(true);
  24225. }
  24226. }
  24227. void connectInput(unsigned target, unsigned targetIdx, unsigned source, unsigned sourceIdx, unsigned iteration)
  24228. {
  24229. IRoxieServerActivity &targetActivity = activities.item(target);
  24230. IRoxieServerActivity &sourceActivity = activities.item(source);
  24231. IFinalRoxieInput * output = sourceActivity.queryOutput(sourceIdx);
  24232. if (probeManager)
  24233. {
  24234. IRoxieProbe * inputProbe = probeManager->createProbe(static_cast<IInputBase*>(output), &sourceActivity, &targetActivity, sourceIdx, targetIdx, iteration);
  24235. probes.append(*LINK(inputProbe));
  24236. output = &dynamic_cast<IFinalRoxieInput &>(inputProbe->queryInput());
  24237. }
  24238. targetActivity.setInput(targetIdx, sourceIdx, output);
  24239. }
  24240. virtual void onCreate(IHThorArg *_colocalParent)
  24241. {
  24242. ForEachItemIn(idx, activities)
  24243. {
  24244. IRoxieServerActivity *activity = &activities.item(idx);
  24245. if (activity)
  24246. activity->onCreate(_colocalParent);
  24247. }
  24248. }
  24249. virtual void abort()
  24250. {
  24251. ForEachItemIn(idx, sinks)
  24252. {
  24253. IRoxieServerActivity &sink = sinks.item(idx);
  24254. sink.abort();
  24255. }
  24256. }
  24257. virtual void reset()
  24258. {
  24259. ForEachItemIn(idx, sinks)
  24260. {
  24261. IRoxieServerActivity &sink = sinks.item(idx);
  24262. sink.reset();
  24263. }
  24264. }
  24265. Linked<IException> exception;
  24266. CriticalSection eCrit;
  24267. virtual void noteException(IException *E)
  24268. {
  24269. CriticalBlock b(eCrit);
  24270. if (!exception)
  24271. {
  24272. if (graphSlaveContext.queryDebugContext())
  24273. {
  24274. graphSlaveContext.queryDebugContext()->checkBreakpoint(DebugStateException, NULL, exception);
  24275. }
  24276. exception.set(E);
  24277. }
  24278. }
  24279. virtual void checkAbort()
  24280. {
  24281. CriticalBlock b(eCrit);
  24282. if (exception)
  24283. throw exception.getLink();
  24284. }
  24285. virtual void execute()
  24286. {
  24287. results.setown(new CGraphResults);
  24288. doExecute(0, NULL);
  24289. }
  24290. //New child query code...
  24291. virtual IThorChildGraph * queryChildGraph()
  24292. {
  24293. return this;
  24294. }
  24295. virtual IEclGraphResults * queryLocalGraph()
  24296. {
  24297. return this;
  24298. }
  24299. virtual IRoxieServerChildGraph * queryLoopGraph()
  24300. {
  24301. return this;
  24302. }
  24303. inline unsigned queryId() const
  24304. {
  24305. return id;
  24306. }
  24307. inline unsigned queryLoopCounter() const
  24308. {
  24309. return loopCounter;
  24310. }
  24311. void doExecute(unsigned parentExtractSize, const byte * parentExtract)
  24312. {
  24313. if (sinks.ordinality()==1)
  24314. sinks.item(0).execute(parentExtractSize, parentExtract);
  24315. #ifdef PARALLEL_EXECUTE
  24316. else if (!probeManager && !graphDefinition.isSequential())
  24317. {
  24318. class casyncfor: public CAsyncFor
  24319. {
  24320. public:
  24321. IActivityGraph &parent;
  24322. unsigned parentExtractSize;
  24323. const byte * parentExtract;
  24324. casyncfor(IRoxieServerActivityCopyArray &_sinks, IActivityGraph &_parent, unsigned _parentExtractSize, const byte * _parentExtract) :
  24325. sinks(_sinks), parent(_parent), parentExtractSize(_parentExtractSize), parentExtract(_parentExtract) { }
  24326. void Do(unsigned i)
  24327. {
  24328. try
  24329. {
  24330. sinks.item(i).execute(parentExtractSize, parentExtract);
  24331. }
  24332. catch (IException *E)
  24333. {
  24334. parent.noteException(E);
  24335. throw;
  24336. }
  24337. }
  24338. private:
  24339. IRoxieServerActivityCopyArray &sinks;
  24340. } afor(sinks, *this, parentExtractSize, parentExtract);
  24341. afor.For(sinks.ordinality(), sinks.ordinality());
  24342. }
  24343. #endif
  24344. else
  24345. {
  24346. ForEachItemIn(idx, sinks)
  24347. {
  24348. IRoxieServerActivity &sink = sinks.item(idx);
  24349. sink.execute(parentExtractSize, parentExtract);
  24350. }
  24351. }
  24352. }
  24353. virtual IEclGraphResults *evaluate(unsigned parentExtractSize, const byte * parentExtract)
  24354. {
  24355. CriticalBlock block(evaluateCrit);
  24356. results.setown(new CGraphResults);
  24357. try
  24358. {
  24359. doExecute(parentExtractSize, parentExtract);
  24360. }
  24361. catch (...)
  24362. {
  24363. DBGLOG("Exception thrown in child query - cleaning up");
  24364. reset();
  24365. throw;
  24366. }
  24367. reset();
  24368. return results.getClear();
  24369. }
  24370. //interface IRoxieServerChildGraph
  24371. virtual void beforeExecute()
  24372. {
  24373. results.setown(new CGraphResults);
  24374. }
  24375. virtual IFinalRoxieInput * startOutput(unsigned id, unsigned parentExtractSize, const byte *parentExtract, bool paused)
  24376. {
  24377. IFinalRoxieInput * ret = selectOutput(id);
  24378. ret->start(parentExtractSize, parentExtract, paused);
  24379. return ret;
  24380. }
  24381. virtual IFinalRoxieInput * selectOutput(unsigned id)
  24382. {
  24383. ForEachItemIn(i, sinks)
  24384. {
  24385. IFinalRoxieInput * ret = sinks.item(i).querySelectOutput(id);
  24386. if (ret)
  24387. return ret;
  24388. }
  24389. throwUnexpected();
  24390. return NULL;
  24391. }
  24392. virtual void setInputResult(unsigned id, IGraphResult * result)
  24393. {
  24394. results->setResult(id, result);
  24395. }
  24396. virtual bool querySetInputResult(unsigned id, unsigned _sourceIdx, IFinalRoxieInput * input)
  24397. {
  24398. ForEachItemIn(i, activities)
  24399. {
  24400. if (activities.item(i).querySetStreamInput(id, _sourceIdx, input))
  24401. return true;
  24402. }
  24403. return false;
  24404. }
  24405. virtual void stopUnusedOutputs()
  24406. {
  24407. //Hmm not sure how to do this...
  24408. }
  24409. virtual void afterExecute()
  24410. {
  24411. ForEachItemIn(i, sinks)
  24412. {
  24413. sinks.item(i).stop();
  24414. }
  24415. if (graphSlaveContext.queryDebugContext())
  24416. {
  24417. graphSlaveContext.queryDebugContext()->checkBreakpoint(DebugStateGraphFinished, NULL, NULL);
  24418. }
  24419. reset();
  24420. }
  24421. virtual IRoxieGraphResults * execute(size32_t parentExtractSize, const byte *parentExtract)
  24422. {
  24423. doExecute(parentExtractSize, parentExtract);
  24424. return LINK(results);
  24425. }
  24426. virtual void getLinkedResult(unsigned & count, byte * * & ret, unsigned id)
  24427. {
  24428. results->getLinkedResult(count, ret, id);
  24429. }
  24430. virtual void getDictionaryResult(unsigned & count, byte * * & ret, unsigned id)
  24431. {
  24432. results->getLinkedResult(count, ret, id);
  24433. }
  24434. virtual const void * getLinkedRowResult(unsigned id)
  24435. {
  24436. return results->getLinkedRowResult(id);
  24437. }
  24438. virtual void setResult(unsigned id, IGraphResult * result)
  24439. {
  24440. results->setResult(id, result);
  24441. }
  24442. virtual IEngineRowStream * createResultIterator(unsigned id)
  24443. {
  24444. return results->createIterator(id);
  24445. }
  24446. virtual void setGraphLoopResult(IGraphResult * result)
  24447. {
  24448. graphLoopResults.appendResult(result);
  24449. }
  24450. virtual IEngineRowStream * createGraphLoopResultIterator(unsigned id)
  24451. {
  24452. try
  24453. {
  24454. return graphLoopResults.createIterator(id);
  24455. }
  24456. catch (IException * e)
  24457. {
  24458. e->Release();
  24459. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Error reading graph result %d before it is calculated", id);
  24460. }
  24461. }
  24462. virtual void clearGraphLoopResults()
  24463. {
  24464. graphLoopResults.clear();
  24465. }
  24466. virtual void executeGraphLoop(size32_t parentExtractSize, const byte *parentExtract)
  24467. {
  24468. doExecute(parentExtractSize, parentExtract);
  24469. }
  24470. virtual void setGraphLoopResult(unsigned id, IGraphResult * result)
  24471. {
  24472. graphLoopResults.setResult(id, result);
  24473. }
  24474. virtual IEngineRowStream * getGraphLoopResult(unsigned id)
  24475. {
  24476. return graphLoopResults.createIterator(id);
  24477. }
  24478. virtual void getProbeResponse(IPropertyTree *query)
  24479. {
  24480. if (probeManager)
  24481. probeManager->getProbeResponse(query);
  24482. }
  24483. virtual IRoxieServerChildGraph * createGraphLoopInstance(IRoxieSlaveContext *ctx, unsigned loopCounter, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &logctx)
  24484. {
  24485. throwUnexpected();
  24486. }
  24487. virtual CGraphIterationInfo *selectGraphLoopOutput()
  24488. {
  24489. return NULL;
  24490. }
  24491. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor)
  24492. {
  24493. throwUnexpected();
  24494. }
  24495. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor)
  24496. {
  24497. throwUnexpected();
  24498. }
  24499. };
  24500. class CProxyActivityGraph : implements IActivityGraph, implements IThorChildGraph, public CInterface
  24501. {
  24502. public:
  24503. IMPLEMENT_IINTERFACE;
  24504. CProxyActivityGraph(IRoxieSlaveContext *_ctx, const char *_graphName, unsigned _id, ActivityArray &_graphDefinition, const IRoxieContextLogger &_logctx, unsigned _numParallel)
  24505. : ctx(_ctx), graphName(_graphName), id(_id), graphDefinition(_graphDefinition), logctx(_logctx), numParallel(_numParallel)
  24506. {
  24507. }
  24508. virtual void abort() { throwUnexpected(); }
  24509. virtual void reset() { throwUnexpected(); }
  24510. virtual void execute() { throwUnexpected(); }
  24511. virtual void getProbeResponse(IPropertyTree *query) { throwUnexpected(); }
  24512. virtual void onCreate(IHThorArg *_colocalArg)
  24513. {
  24514. colocalArg = _colocalArg;
  24515. }
  24516. virtual void noteException(IException *E) { throwUnexpected(); }
  24517. virtual void checkAbort() { throwUnexpected(); }
  24518. virtual IThorChildGraph * queryChildGraph() { return this; }
  24519. virtual IEclGraphResults * queryLocalGraph() { throwUnexpected(); }
  24520. virtual IRoxieServerChildGraph * queryLoopGraph() { throwUnexpected(); }
  24521. virtual IRoxieServerChildGraph * createGraphLoopInstance(IRoxieSlaveContext *ctx, unsigned loopCounter, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &logctx) { throwUnexpected(); }
  24522. virtual const char *queryName() const { throwUnexpected(); }
  24523. virtual IRoxieServerActivity *queryActivity(unsigned _activityId) { return nullptr; } // MORE - may need something here!?
  24524. virtual IEclGraphResults * evaluate(unsigned parentExtractSize, const byte * parentExtract)
  24525. {
  24526. Owned<CActivityGraph> realGraph;
  24527. {
  24528. CriticalBlock b(graphCrit);
  24529. if (stack.length())
  24530. realGraph.setown(&stack.popGet());
  24531. }
  24532. if (!realGraph)
  24533. {
  24534. realGraph.setown(new CActivityGraph(ctx, graphName, id, graphDefinition, NULL, logctx));
  24535. realGraph->createGraph(ctx);
  24536. realGraph->onCreate(colocalArg);
  24537. }
  24538. Owned<IEclGraphResults> results = realGraph->evaluate(parentExtractSize, parentExtract);
  24539. {
  24540. CriticalBlock b(graphCrit);
  24541. stack.append(*realGraph.getClear());
  24542. }
  24543. return results.getClear();
  24544. }
  24545. protected:
  24546. IRoxieSlaveContext *ctx;
  24547. StringAttr graphName;
  24548. unsigned id;
  24549. ActivityArray &graphDefinition;
  24550. const IRoxieContextLogger &logctx;
  24551. unsigned numParallel;
  24552. IHThorArg *colocalArg = nullptr;
  24553. CriticalSection graphCrit;
  24554. CIArrayOf<CActivityGraph> stack;
  24555. };
  24556. class CIterationActivityGraph : public CActivityGraph
  24557. {
  24558. IHThorArg * colocalParent;
  24559. unsigned fixedParentExtractSize;
  24560. const byte * fixedParentExtract;
  24561. unsigned graphOutputActivityIndex;
  24562. public:
  24563. CIterationActivityGraph(const char *_graphName, unsigned _id, ActivityArray &x, IProbeManager *_probeManager,
  24564. unsigned _loopCounter, IRoxieSlaveContext *_ctx, IHThorArg * _colocalParent, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &_logctx)
  24565. : CActivityGraph(_ctx, _graphName, _id, x, _probeManager, _logctx)
  24566. {
  24567. graphOutputActivityIndex = 0;
  24568. loopCounter = _loopCounter;
  24569. colocalParent = _colocalParent;
  24570. graphSlaveContext.setLoopCounter(loopCounter);
  24571. graphCodeContext.set(_ctx->queryCodeContext());
  24572. fixedParentExtractSize = parentExtractSize;
  24573. fixedParentExtract = parentExtract;
  24574. }
  24575. void createIterationGraph(IRoxieSlaveContext *_ctx)
  24576. {
  24577. Owned<IRoxieServerActivity> pseudoActivity = new CPseudoActivity(_ctx, *new CPseudoArg);
  24578. ForEachItemIn(idx1, graphDefinition)
  24579. activities.append(*LINK(pseudoActivity));
  24580. graphOutputActivityIndex = queryGraphOutputIndex();
  24581. recursiveCreateGraph(_ctx, graphOutputActivityIndex);
  24582. }
  24583. unsigned queryGraphOutputIndex() const
  24584. {
  24585. ForEachItemIn(i, graphDefinition)
  24586. if (graphDefinition.serverItem(i).getKind() == TAKgraphloopresultwrite)
  24587. return i;
  24588. throwUnexpected();
  24589. }
  24590. void recursiveCreateGraph(IRoxieSlaveContext *_ctx, unsigned whichActivity)
  24591. {
  24592. //Check to see if already created
  24593. IRoxieServerActivity & prevActivity = activities.item(whichActivity);
  24594. if (prevActivity.queryId() != 0)
  24595. {
  24596. prevActivity.noteOutputUsed(); //We need to patch up the number of outputs for splitters.
  24597. return;
  24598. }
  24599. IRoxieServerActivityFactory &donor = graphDefinition.serverItem(whichActivity);
  24600. IRoxieServerActivity * activity = NULL;
  24601. if (donor.isGraphInvariant())
  24602. {
  24603. ThorActivityKind kind = donor.getKind();
  24604. switch (kind)
  24605. {
  24606. case TAKif:
  24607. case TAKchildif:
  24608. case TAKcase:
  24609. case TAKchildcase: // MORE RKC->GH - what about FILTER with a graph-invariant condition and other latestart activities?
  24610. {
  24611. Owned<IHThorArg> helper = &donor.getHelper();
  24612. helper->onCreate(&graphCodeContext, colocalParent, NULL);
  24613. helper->onStart(fixedParentExtract, NULL);
  24614. unsigned branch;
  24615. switch (kind)
  24616. {
  24617. case TAKif: case TAKchildif:
  24618. branch = static_cast<IHThorIfArg *>(helper.get())->getCondition() ? 0 : 1;
  24619. break;
  24620. case TAKcase: case TAKchildcase:
  24621. branch = static_cast<IHThorCaseArg *>(helper.get())->getBranch();
  24622. if (branch >= donor.numInputs())
  24623. branch = donor.numInputs() - 1;
  24624. break;
  24625. default:
  24626. throwUnexpected();
  24627. }
  24628. helper.clear();
  24629. unsigned outputidx;
  24630. unsigned source = donor.getInput(branch, outputidx);
  24631. if (source ==(unsigned) -1)
  24632. activity = createRoxieServerNullActivity(&graphSlaveContext, &donor, probeManager);
  24633. else
  24634. activity = createRoxieServerPassThroughActivity(&graphSlaveContext, &donor, probeManager);
  24635. activities.replace(*activity, whichActivity);
  24636. activity->onCreate(colocalParent);
  24637. if (source ==(unsigned) -1)
  24638. return;
  24639. recursiveCreateGraph(_ctx, source);
  24640. connectInput(whichActivity, 0, source, outputidx, loopCounter);
  24641. break;
  24642. }
  24643. }
  24644. }
  24645. if (!activity)
  24646. {
  24647. activity = donor.createActivity(&graphSlaveContext, probeManager);
  24648. activities.replace(*activity, whichActivity);
  24649. activity->onCreate(colocalParent);
  24650. activity->resetOutputsUsed();
  24651. unsigned inputidx = 0;
  24652. loop
  24653. {
  24654. unsigned outputidx;
  24655. unsigned source = donor.getInput(inputidx, outputidx);
  24656. if (source==(unsigned) -1)
  24657. break;
  24658. recursiveCreateGraph(_ctx, source);
  24659. connectInput(whichActivity, inputidx, source, outputidx, loopCounter);
  24660. inputidx++;
  24661. }
  24662. }
  24663. IntArray &dependencies = donor.queryDependencies();
  24664. IntArray &dependencyIndexes = donor.queryDependencyIndexes();
  24665. IntArray &dependencyControlIds = donor.queryDependencyControlIds();
  24666. ForEachItemIn(idx2, dependencies)
  24667. {
  24668. unsigned input = dependencies.item(idx2);
  24669. recursiveCreateGraph(_ctx, input);
  24670. activity->addDependency(activities.item(input),dependencyIndexes.item(idx2),dependencyControlIds.item(idx2));
  24671. }
  24672. }
  24673. virtual CGraphIterationInfo *selectGraphLoopOutput()
  24674. {
  24675. IRoxieServerActivity &sourceActivity = activities.item(graphOutputActivityIndex);
  24676. IFinalRoxieInput *sourceInput = sourceActivity.queryOutput(0);
  24677. return new CGraphIterationInfo(&sourceActivity, sourceInput, 0, loopCounter);
  24678. }
  24679. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor)
  24680. {
  24681. ForEachItemIn(i, activities)
  24682. activities.item(i).gatherIterationUsage(processor, fixedParentExtractSize, fixedParentExtract);
  24683. }
  24684. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor)
  24685. {
  24686. ForEachItemIn(i, activities)
  24687. activities.item(i).associateIterationOutputs(processor, fixedParentExtractSize, fixedParentExtract, probeManager, probes);
  24688. }
  24689. };
  24690. class CDelayedActivityGraph : implements IActivityGraph, public CInterface
  24691. {
  24692. StringAttr graphName;
  24693. ActivityArray & graphDefinition;
  24694. IProbeManager *probeManager;
  24695. unsigned id;
  24696. IRoxieSlaveContext * ctx;
  24697. IHThorArg * colocalParent;
  24698. public:
  24699. IMPLEMENT_IINTERFACE;
  24700. CDelayedActivityGraph(const char *_graphName, unsigned _id, ActivityArray &x, IProbeManager *_probeManager)
  24701. : probeManager(_probeManager), graphDefinition(x)
  24702. {
  24703. graphName.set(_graphName);
  24704. id = _id;
  24705. ctx = NULL;
  24706. colocalParent = NULL;
  24707. }
  24708. virtual const char *queryName() const { return graphName.get(); }
  24709. virtual void abort() { throwUnexpected(); }
  24710. virtual void reset() { }
  24711. virtual void execute() { throwUnexpected(); }
  24712. virtual void getProbeResponse(IPropertyTree *query) { throwUnexpected(); }
  24713. virtual void noteException(IException *E) { throwUnexpected(); }
  24714. virtual void checkAbort() { throwUnexpected(); }
  24715. virtual IThorChildGraph * queryChildGraph() { throwUnexpected(); }
  24716. virtual IEclGraphResults * queryLocalGraph() { throwUnexpected(); }
  24717. virtual IRoxieServerChildGraph * queryLoopGraph() { throwUnexpected(); }
  24718. virtual IRoxieServerActivity *queryActivity(unsigned _activityId) { return nullptr; } // MORE - may need something here!?
  24719. virtual void onCreate(IHThorArg *_colocalParent)
  24720. {
  24721. colocalParent = _colocalParent;
  24722. }
  24723. virtual IRoxieServerChildGraph * createGraphLoopInstance(IRoxieSlaveContext *ctx, unsigned loopCounter, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &logctx)
  24724. {
  24725. Owned<CIterationActivityGraph> ret = new CIterationActivityGraph(graphName, id, graphDefinition, probeManager, loopCounter, ctx, colocalParent, parentExtractSize, parentExtract, logctx);
  24726. ret->createIterationGraph(ctx);
  24727. return ret.getClear();
  24728. }
  24729. };
  24730. IActivityGraph *createActivityGraph(IRoxieSlaveContext *ctx, const char *_graphName, unsigned id, ActivityArray &childFactories, IRoxieServerActivity *parentActivity, IProbeManager *_probeManager, const IRoxieContextLogger &_logctx, unsigned numParallel)
  24731. {
  24732. if (childFactories.isDelayed())
  24733. {
  24734. assertex(numParallel==1);
  24735. return new CDelayedActivityGraph(_graphName, id, childFactories, _probeManager);
  24736. }
  24737. else
  24738. {
  24739. if (numParallel==1 || _probeManager != nullptr)
  24740. {
  24741. Owned<IProbeManager> childProbe;
  24742. if (_probeManager)
  24743. childProbe.setown(_probeManager->startChildGraph(id, parentActivity));
  24744. Owned<CActivityGraph> ret = new CActivityGraph(ctx, _graphName, id, childFactories, childProbe, _logctx);
  24745. ret->createGraph(ctx);
  24746. if (_probeManager)
  24747. _probeManager->endChildGraph(childProbe, parentActivity);
  24748. return ret.getClear();
  24749. }
  24750. else
  24751. return new CProxyActivityGraph(ctx, _graphName, id, childFactories, _logctx, numParallel);
  24752. }
  24753. }
  24754. //================================================================================================================
  24755. #ifdef _USE_CPPUNIT
  24756. #include "unittests.hpp"
  24757. // 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...
  24758. #if _MSC_VER==1200
  24759. #undef protected
  24760. #endif
  24761. static const char *sortAlgorithm;
  24762. class TestMetaData : public CInterface, implements IOutputMetaData
  24763. {
  24764. public:
  24765. IMPLEMENT_IINTERFACE;
  24766. virtual size32_t getRecordSize(const void *) { return 10; }
  24767. virtual size32_t getMinRecordSize() const { return 10; }
  24768. virtual size32_t getFixedSize() const { return 10; }
  24769. virtual void toXML(const byte * self, IXmlWriter & out) {}
  24770. virtual unsigned getVersion() const { return OUTPUTMETADATA_VERSION; }
  24771. virtual unsigned getMetaFlags() { return 0; }
  24772. virtual void destruct(byte * self) {}
  24773. virtual IOutputRowSerializer * createDiskSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  24774. virtual IOutputRowDeserializer * createDiskDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  24775. virtual ISourceRowPrefetcher * createDiskPrefetcher(ICodeContext * ctx, unsigned activityId) { return NULL; }
  24776. virtual IOutputMetaData * querySerializedDiskMeta() { return NULL; }
  24777. virtual IOutputRowSerializer * createInternalSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  24778. virtual IOutputRowDeserializer * createInternalDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  24779. virtual void walkIndirectMembers(const byte * self, IIndirectMemberVisitor & visitor) {}
  24780. virtual IOutputMetaData * queryChildMeta(unsigned i) { return NULL; }
  24781. } testMeta;
  24782. class TestInput : public CInterface, implements IFinalRoxieInput, implements IEngineRowStream
  24783. {
  24784. char const * const *input;
  24785. IRoxieSlaveContext *ctx;
  24786. unsigned endSeen;
  24787. bool eof;
  24788. unsigned count;
  24789. ActivityTimeAccumulator totalCycles;
  24790. size32_t recordSize;
  24791. unsigned activityId;
  24792. public:
  24793. enum { STATEreset, STATEstarted, STATEstopped } state;
  24794. bool allRead;
  24795. unsigned repeat;
  24796. IMPLEMENT_IINTERFACE;
  24797. TestInput(IRoxieSlaveContext *_ctx, char const * const *_input)
  24798. {
  24799. ctx = _ctx;
  24800. input = _input;
  24801. count = 0;
  24802. eof = false;
  24803. allRead = false;
  24804. endSeen = 0;
  24805. recordSize = testMeta.getFixedSize();
  24806. state = STATEreset;
  24807. activityId = 1;
  24808. repeat = 0;
  24809. }
  24810. virtual IOutputMetaData * queryOutputMeta() const { return &testMeta; }
  24811. virtual void prestart(unsigned parentExtractSize, const byte *parentExtract)
  24812. {
  24813. ASSERT(state == STATEreset);
  24814. }
  24815. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  24816. {
  24817. ASSERT(state == STATEreset);
  24818. state = STATEstarted;
  24819. }
  24820. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  24821. {
  24822. streams.append(this);
  24823. return NULL;
  24824. }
  24825. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { assertex(whichInput==0); return this; }
  24826. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { assertex(idx==0); return nullptr; }
  24827. virtual IRoxieServerActivity *queryActivity()
  24828. {
  24829. throwUnexpected();
  24830. }
  24831. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  24832. {
  24833. throwUnexpected();
  24834. }
  24835. virtual void stop()
  24836. {
  24837. state = STATEstopped;
  24838. }
  24839. virtual void reset()
  24840. {
  24841. ASSERT(state == STATEstopped);
  24842. eof = false; count = 0; endSeen = 0; allRead = false; state = STATEreset;
  24843. }
  24844. virtual void resetEOF()
  24845. {
  24846. throwUnexpected();
  24847. }
  24848. virtual void checkAbort() {}
  24849. virtual unsigned queryId() const { return activityId; };
  24850. virtual const void *nextRow()
  24851. {
  24852. ActivityTimer t(totalCycles, ctx->queryOptions().timeActivities);
  24853. ASSERT(state == STATEstarted);
  24854. ASSERT(allRead || !eof);
  24855. if (eof)
  24856. return NULL;
  24857. again:
  24858. const char *nextSource = input[count++];
  24859. if (nextSource)
  24860. {
  24861. endSeen = 0;
  24862. void *ret = ctx->queryRowManager().ALLOCATE(recordSize);
  24863. memset(ret, 0, recordSize);
  24864. strncpy((char *) ret, nextSource, recordSize);
  24865. return ret;
  24866. }
  24867. else if (repeat)
  24868. {
  24869. repeat--;
  24870. count = 0;
  24871. goto again;
  24872. }
  24873. else
  24874. {
  24875. endSeen++;
  24876. if (endSeen==2)
  24877. eof = true;
  24878. return NULL;
  24879. }
  24880. }
  24881. virtual bool nextGroup(ConstPointerArray & group)
  24882. {
  24883. const void * next;
  24884. while ((next = nextRow()) != NULL)
  24885. group.append(next);
  24886. if (group.ordinality())
  24887. return true;
  24888. return false;
  24889. }
  24890. virtual unsigned __int64 queryTotalCycles() const { return totalCycles.totalCycles; }
  24891. virtual unsigned __int64 queryLocalCycles() const { return totalCycles.totalCycles; }
  24892. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  24893. {
  24894. return NULL;
  24895. }
  24896. };
  24897. struct SortActivityTest : public ccdserver_hqlhelper::CThorSortArg {
  24898. public:
  24899. struct CompareClass : public ICompare {
  24900. virtual int docompare(const void * _left, const void * _right) const {
  24901. return memcmp(_left, _right, 5);
  24902. }
  24903. } compare;
  24904. virtual ICompare * queryCompare() { return &compare; }
  24905. virtual IOutputMetaData * queryOutputMeta()
  24906. {
  24907. return &testMeta;
  24908. }
  24909. virtual unsigned getAlgorithmFlags() { return TAFunstable; }
  24910. virtual const char * getAlgorithm() { return sortAlgorithm; }
  24911. };
  24912. extern "C" IHThorArg * sortActivityTestFactory() { return new SortActivityTest; }
  24913. struct MergeActivityTest : public ccdserver_hqlhelper::CThorMergeArg {
  24914. static bool isDedup;
  24915. public:
  24916. struct CompareClass : public ICompare {
  24917. virtual int docompare(const void * _left, const void * _right) const {
  24918. return memcmp(_left, _right, 5);
  24919. }
  24920. } compare;
  24921. virtual ICompare * queryCompare() { return &compare; }
  24922. virtual IOutputMetaData * queryOutputMeta()
  24923. {
  24924. return &testMeta;
  24925. }
  24926. virtual bool dedup() { return isDedup; }
  24927. };
  24928. bool MergeActivityTest::isDedup = false;
  24929. extern "C" IHThorArg * mergeActivityTestFactory() { return new MergeActivityTest; }
  24930. struct SplitActivityTest : public ccdserver_hqlhelper::CThorSplitArg {
  24931. public:
  24932. virtual unsigned numBranches() { return 2; }
  24933. virtual IOutputMetaData * queryOutputMeta()
  24934. {
  24935. return &testMeta;
  24936. }
  24937. };
  24938. extern "C" IHThorArg * splitActivityTestFactory() { return new SplitActivityTest; }
  24939. class CcdServerTest : public CppUnit::TestFixture
  24940. {
  24941. CPPUNIT_TEST_SUITE(CcdServerTest);
  24942. CPPUNIT_TEST(testSetup);
  24943. CPPUNIT_TEST(testHeapSort);
  24944. CPPUNIT_TEST(testQuickSort);
  24945. CPPUNIT_TEST(testMerge);
  24946. CPPUNIT_TEST(testMergeDedup);
  24947. CPPUNIT_TEST(testMiscellaneous);
  24948. CPPUNIT_TEST(testSplitter);
  24949. CPPUNIT_TEST(testCleanup);
  24950. CPPUNIT_TEST_SUITE_END();
  24951. protected:
  24952. SlaveContextLogger logctx;
  24953. Owned<const IQueryDll> queryDll;
  24954. Owned<IRoxiePackage> package;
  24955. Owned<IPropertyTree> stateInfo;
  24956. Owned<IQueryFactory> queryFactory;
  24957. Owned<IRoxieSlaveContext> ctx;
  24958. void testSetup()
  24959. {
  24960. selfTestMode = true;
  24961. roxiemem::setTotalMemoryLimit(false, true, false, 100 * 1024 * 1024, 0, NULL, NULL);
  24962. }
  24963. void testCleanup()
  24964. {
  24965. roxiemem::releaseRoxieHeap();
  24966. }
  24967. void init()
  24968. {
  24969. package.setown(createRoxiePackage(NULL, NULL));
  24970. queryDll.setown(createExeQueryDll("roxie"));
  24971. stateInfo.setown(createPTreeFromXMLString("<test memoryLimit='50000000'/>"));
  24972. queryFactory.setown(createServerQueryFactory("test", queryDll.getLink(), *package, stateInfo, false, false));
  24973. ctx.setown(createSlaveContext(queryFactory, logctx, NULL, false));
  24974. queryActiveTimer()->reset();
  24975. }
  24976. void testActivity(IRoxieServerActivity *activity, char const * const *input, char const * const *output)
  24977. {
  24978. testActivity(activity, input, NULL, output);
  24979. }
  24980. void testActivity(IRoxieServerActivity *activity, char const * const *input, char const * const *input2, char const * const *output, unsigned outputIdx = 0)
  24981. {
  24982. TestInput in(ctx, input);
  24983. TestInput in2(ctx, input2);
  24984. activity->setInput(0, 0, &in);
  24985. if (input2)
  24986. activity->setInput(1, 0, &in2);
  24987. IFinalRoxieInput *out = activity->queryOutput(outputIdx);
  24988. IEngineRowStream *outStream = connectSingleStream(ctx, out, outputIdx, true);
  24989. IOutputMetaData *meta = out->queryOutputMeta();
  24990. void *buf = alloca(meta->getFixedSize());
  24991. for (unsigned iteration = 0; iteration < 8; iteration++)
  24992. {
  24993. // 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)
  24994. // This should be true whether we read all, some, or none of the data.
  24995. // Should not matter if an activity is not started
  24996. if (iteration % 4 == 0)
  24997. activity->onCreate(NULL);
  24998. unsigned count = 0;
  24999. if (iteration % 4 != 3)
  25000. {
  25001. activity->start(0, NULL, false);
  25002. ASSERT(in.state == TestInput::STATEstarted);
  25003. ASSERT(!input2 || in2.state == TestInput::STATEstarted);
  25004. loop
  25005. {
  25006. const void *next = outStream->nextRow();
  25007. if (!next)
  25008. {
  25009. ASSERT(output[count++] == NULL);
  25010. next = outStream->nextRow();
  25011. if (!next)
  25012. {
  25013. ASSERT(output[count++] == NULL);
  25014. break;
  25015. }
  25016. }
  25017. ASSERT(output[count] != NULL);
  25018. unsigned outsize = meta->getRecordSize(next);
  25019. memset(buf, 0, outsize);
  25020. strncpy((char *) buf, output[count++], outsize);
  25021. ASSERT(memcmp(next, buf, outsize) == 0);
  25022. ReleaseRoxieRow(next);
  25023. if (iteration % 4 == 2)
  25024. break;
  25025. }
  25026. if (iteration % 4 != 2)
  25027. {
  25028. // Check that reading after end is harmless
  25029. in.allRead = true;
  25030. const void *next = outStream->nextRow();
  25031. ASSERT(next == NULL);
  25032. }
  25033. }
  25034. activity->stop();
  25035. ASSERT(in.state == TestInput::STATEstopped);
  25036. ASSERT(!input2 || in2.state == TestInput::STATEstopped);
  25037. activity->reset();
  25038. ASSERT(in.state == TestInput::STATEreset);
  25039. ASSERT(!input2 || in2.state == TestInput::STATEreset);
  25040. ctx->queryRowManager().reportLeaks();
  25041. ASSERT(ctx->queryRowManager().numPagesAfterCleanup(true) == 0);
  25042. }
  25043. }
  25044. void testSplitActivity(IRoxieServerActivityFactory *factory, char const * const *input, char const * const *output, unsigned numOutputs, unsigned repeat)
  25045. {
  25046. Owned <IRoxieServerActivity> activity = factory->createActivity(ctx, NULL);
  25047. TestInput in(ctx, input);
  25048. in.repeat = repeat;
  25049. activity->setInput(0, 0, &in);
  25050. ArrayOf<IFinalRoxieInput *> out;
  25051. for (unsigned i = 0; i < numOutputs; i++)
  25052. {
  25053. out.append(activity->queryOutput(i));
  25054. }
  25055. activity->onCreate(NULL);
  25056. class casyncfor: public CAsyncFor
  25057. {
  25058. public:
  25059. casyncfor(CcdServerTest *_parent, IRoxieServerActivity *_activity, ArrayOf<IFinalRoxieInput *> &_outputs, char const * const *_input, char const * const *_output, unsigned _repeat)
  25060. : parent(_parent), activity(_activity), outputs(_outputs), input(_input), output(_output), repeat(_repeat)
  25061. {}
  25062. void Do(unsigned i)
  25063. {
  25064. IFinalRoxieInput *out = outputs.item(i);
  25065. IEngineRowStream *outStream = connectSingleStream(NULL, out, 0, true);
  25066. out->start(0, NULL, false);
  25067. IOutputMetaData *meta = out->queryOutputMeta();
  25068. void *buf = alloca(meta->getFixedSize());
  25069. unsigned count = 0;
  25070. unsigned repeats = repeat;
  25071. loop
  25072. {
  25073. const void *next = outStream->nextRow();
  25074. if (!next)
  25075. {
  25076. ASSERT(repeats==0);
  25077. ASSERT(output[count] == NULL);
  25078. count++;
  25079. next = outStream->nextRow();
  25080. if (!next)
  25081. {
  25082. ASSERT(output[count] == NULL);
  25083. count++;
  25084. break;
  25085. }
  25086. }
  25087. if (output[count] == NULL && repeats)
  25088. {
  25089. repeats--;
  25090. count = 0;
  25091. }
  25092. ASSERT(output[count] != NULL);
  25093. unsigned outsize = meta->getRecordSize(next);
  25094. memset(buf, 0, outsize);
  25095. strncpy((char *) buf, output[count++], outsize);
  25096. ASSERT(memcmp(next, buf, outsize) == 0);
  25097. ReleaseRoxieRow(next);
  25098. }
  25099. outStream->stop();
  25100. }
  25101. private:
  25102. IRoxieServerActivity *activity;
  25103. ArrayOf<IFinalRoxieInput *> &outputs;
  25104. char const * const *input;
  25105. char const * const *output;
  25106. unsigned repeat;
  25107. CcdServerTest *parent;
  25108. } afor(this, activity, out, input, output, repeat);
  25109. afor.For(numOutputs, numOutputs);
  25110. ASSERT(in.state == TestInput::STATEstopped);
  25111. for (unsigned i2 = 0; i2 < numOutputs; i2++)
  25112. {
  25113. out.item(i2)->reset();
  25114. }
  25115. ASSERT(in.state == TestInput::STATEreset);
  25116. ctx->queryRowManager().reportLeaks();
  25117. ASSERT(ctx->queryRowManager().numPagesAfterCleanup(true) == 0);
  25118. }
  25119. static int compareFunc(const void *l, const void *r)
  25120. {
  25121. return strcmp(*(char **) l, *(char **) r);
  25122. }
  25123. void testSort(unsigned type)
  25124. {
  25125. init();
  25126. sortAlgorithm = NULL;
  25127. if (type==2)
  25128. sortAlgorithm = "heapSort";
  25129. else
  25130. sortAlgorithm = "quickSort";
  25131. DBGLOG("Testing %s activity", sortAlgorithm);
  25132. Owned<IPropertyTree> dummyNode = createPTree("node");
  25133. Owned <IRoxieServerActivityFactory> factory = createRoxieServerSortActivityFactory(1, 1, *queryFactory, sortActivityTestFactory, TAKsort, *dummyNode);
  25134. Owned <IRoxieServerActivity> activity = factory->createActivity(ctx, NULL);
  25135. const char * test[] = { NULL, NULL };
  25136. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  25137. const char * test54321[] = { "5", "4", "3", "2", "1", NULL, NULL };
  25138. const char * test11111[] = { "1", "1", "1", "1", "1", NULL, NULL };
  25139. const char * test11111_12345[] = { "1", "1", "1", "1", "1", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  25140. const char * test11111_54321[] = { "1", "1", "1", "1", "1", NULL, "5", "4", "3", "2", "1", NULL, NULL };
  25141. const char * test54321_54321[] = { "5", "4", "3", "2", "1", NULL, "5", "4", "3", "2", "1", NULL, NULL };
  25142. const char * test12345_12345[] = { "1", "2", "3", "4", "5", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  25143. testActivity(activity, test, test);
  25144. testActivity(activity, test12345, test12345);
  25145. testActivity(activity, test54321, test12345);
  25146. testActivity(activity, test11111, test11111);
  25147. testActivity(activity, test11111_12345, test11111_12345);
  25148. testActivity(activity, test11111_54321, test11111_12345);
  25149. testActivity(activity, test54321_54321, test12345_12345);
  25150. // A few larger tests
  25151. char *input[2002];
  25152. char *output[2002];
  25153. input[2000] = input[2001] = output[2000] = output[2001] = NULL;
  25154. unsigned i;
  25155. // identical
  25156. for (i=0; i<2000; i++)
  25157. {
  25158. input[i] = new char[11];
  25159. output[i] = new char[11];
  25160. sprintf(input[i], "1");
  25161. sprintf(output[i], "1");
  25162. }
  25163. testActivity(activity, input, output);
  25164. // Ascending
  25165. for (i=0; i<2000; i++)
  25166. {
  25167. sprintf(input[i], "%04d", i);
  25168. sprintf(output[i], "%04d", i);
  25169. }
  25170. testActivity(activity, input, output);
  25171. // Almost sorted
  25172. for (i=0; i<20; i++)
  25173. {
  25174. unsigned h = i*100;
  25175. sprintf(input[h], "%04d", 1900-h);
  25176. }
  25177. testActivity(activity, input, output);
  25178. // Descending
  25179. for (i=0; i<2000; i++)
  25180. {
  25181. sprintf(input[i], "%04d", 1999-i);
  25182. sprintf(output[i], "%04d", i);
  25183. }
  25184. testActivity(activity, input, output);
  25185. // Random
  25186. for (i=0; i<2000; i++)
  25187. {
  25188. unsigned r = rand() % 1500;
  25189. sprintf(input[i], "%04d", r);
  25190. sprintf(output[i], "%04d", r);
  25191. }
  25192. qsort(output, 2000, sizeof(output[0]), compareFunc);
  25193. testActivity(activity, input, output);
  25194. unsigned __int64 us = cycle_to_nanosec(factory->queryLocalCycles()/1000);
  25195. DBGLOG("Simple %s sorts: activity time %u.%u ms", type==2?"Heap" : (type==1 ? "Insertion" : "Quick"), (int)(us/1000), (int)(us%1000));
  25196. factory->resetNodeProgressInfo();
  25197. if (type)
  25198. {
  25199. // Other than quicksort, it's supposed to be stable. Let's check that it is
  25200. // All sort identical
  25201. for (i=0; i<2000; i++)
  25202. {
  25203. sprintf(input[i], "1 %d", i);
  25204. sprintf(output[i], "1 %d", i);
  25205. }
  25206. testActivity(activity, input, output);
  25207. // Already sorted
  25208. for (i=0; i<2000; i++)
  25209. {
  25210. sprintf(input[i], "%04d %d", i / 10, i);
  25211. sprintf(output[i], "%04d %d", i / 10, i);
  25212. }
  25213. testActivity(activity, input, output);
  25214. // Reverse order
  25215. for (i=0; i<2000; i++)
  25216. {
  25217. sprintf(input[i], "%04d %d", 199 - (i / 10), i%10);
  25218. sprintf(output[i], "%04d %d", i / 10, i%10);
  25219. }
  25220. testActivity(activity, input, output);
  25221. }
  25222. for (i=0; i<2000; i++)
  25223. {
  25224. delete [] input[i];
  25225. delete [] output[i];
  25226. }
  25227. DBGLOG("Finished testing %s sort", type==2?"Heap" : (type==1 ? "Insertion" : "Quick"));
  25228. }
  25229. void testQuickSort()
  25230. {
  25231. testSort(0);
  25232. }
  25233. void testHeapSort()
  25234. {
  25235. testSort(2);
  25236. }
  25237. void testMerge()
  25238. {
  25239. DBGLOG("testMerge");
  25240. init();
  25241. Owned<IPropertyTree> splitterNode = createPTree();
  25242. Owned <IRoxieServerActivityFactory> factory = createRoxieServerMergeActivityFactory(1, 1, *queryFactory, mergeActivityTestFactory, TAKmerge, *splitterNode);
  25243. factory->setInput(0,0,0);
  25244. factory->setInput(1,0,0);
  25245. Owned <IRoxieServerActivity> activity = factory->createActivity(ctx, NULL);
  25246. const char * test[] = { NULL, NULL };
  25247. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  25248. const char * test1122334455[] = { "1", "1", "2", "2", "3", "3", "4", "4", "5", "5", NULL, NULL };
  25249. const char * test11111[] = { "1", "1", "1", "1", "1", NULL, NULL };
  25250. const char * test1111111111[] = { "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", NULL, NULL };
  25251. const char * test11111_12345[] = { "1", "1", "1", "1", "1", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  25252. const char * test1111112345[] = { "1", "1", "1", "1", "1", "1", "2", "3", "4", "5", NULL, NULL };
  25253. 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 };
  25254. testActivity(activity, test, test, test);
  25255. testActivity(activity, test12345, test, test12345);
  25256. testActivity(activity, test, test12345, test12345);
  25257. testActivity(activity, test12345, test12345, test1122334455);
  25258. testActivity(activity, test11111, test, test11111);
  25259. testActivity(activity, test, test11111, test11111);
  25260. testActivity(activity, test11111, test11111, test1111111111);
  25261. testActivity(activity, test11111_12345, test, test1111112345);
  25262. testActivity(activity, test11111_12345, test11111_12345, test11111111111122334455);
  25263. // Should really test WHICH side gets kept...
  25264. // Should test with more than 2 inputs...
  25265. DBGLOG("testMerge done");
  25266. }
  25267. void testMergeDedup()
  25268. {
  25269. DBGLOG("testMergeDedup");
  25270. init();
  25271. MergeActivityTest::isDedup = true;
  25272. Owned<IPropertyTree> splitterNode = createPTree();
  25273. Owned <IRoxieServerActivityFactory> factory = createRoxieServerMergeActivityFactory(1, 1, *queryFactory, mergeActivityTestFactory, TAKmerge, *splitterNode);
  25274. factory->setInput(0,0,0);
  25275. factory->setInput(1,0,0);
  25276. Owned <IRoxieServerActivity> activity = factory->createActivity(ctx, NULL);
  25277. const char * test[] = { NULL, NULL };
  25278. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  25279. const char * test11111[] = { "1", "1", "1", "1", "1", NULL, NULL };
  25280. const char * test11111_12345[] = { "1", "1", "1", "1", "1", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  25281. const char * test1111112345[] = { "1", "1", "1", "1", "1", "1", "2", "3", "4", "5", NULL, NULL };
  25282. testActivity(activity, test11111, test, test11111); // No dedup within a stream
  25283. testActivity(activity, test11111, test11111, test11111); // No dedup within a stream
  25284. testActivity(activity, test, test11111, test11111);
  25285. testActivity(activity, test, test, test);
  25286. testActivity(activity, test12345, test, test12345);
  25287. testActivity(activity, test, test12345, test12345);
  25288. testActivity(activity, test12345, test12345, test12345);
  25289. testActivity(activity, test11111_12345, test, test1111112345);
  25290. testActivity(activity, test11111_12345, test11111_12345, test1111112345);
  25291. // Should really test WHICH side gets kept...
  25292. // Should test with more than 2 inputs...
  25293. DBGLOG("testMergeDedup done");
  25294. }
  25295. void doTestSplitter(unsigned numOutputs)
  25296. {
  25297. DBGLOG("testSplit %d", numOutputs);
  25298. init();
  25299. Owned<IPropertyTree> splitterNode = createPTree();
  25300. Owned <IRoxieServerActivityFactory> factory = createRoxieServerThroughSpillActivityFactory(*queryFactory, splitActivityTestFactory, numOutputs, *splitterNode);
  25301. factory->setInput(0,0,0);
  25302. Owned <IRoxieServerActivity> activity = factory->createActivity(ctx, NULL);
  25303. const char * test[] = { NULL, NULL };
  25304. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  25305. unsigned start = msTick();
  25306. testSplitActivity(factory, test, test, numOutputs, 0);
  25307. testSplitActivity(factory, test12345, test12345, numOutputs, 0);
  25308. testSplitActivity(factory, test12345, test12345, numOutputs, 100);
  25309. unsigned elapsed = msTick() - start;
  25310. DBGLOG("testSplit %d done in %dms", numOutputs, elapsed);
  25311. }
  25312. void testSplitter()
  25313. {
  25314. doTestSplitter(1);
  25315. doTestSplitter(2);
  25316. doTestSplitter(3);
  25317. doTestSplitter(10);
  25318. }
  25319. void testMiscellaneous()
  25320. {
  25321. DBGLOG("sizeof(CriticalSection)=%u", (unsigned) sizeof(CriticalSection));
  25322. DBGLOG("sizeof(SpinLock)=%u", (unsigned) sizeof(SpinLock));
  25323. DBGLOG("sizeof(CJoinGroup)=%u", (unsigned) sizeof(CJoinGroup));
  25324. ASSERT(sizeof(CJoinGroup) <= 120);
  25325. }
  25326. };
  25327. CPPUNIT_TEST_SUITE_REGISTRATION( CcdServerTest );
  25328. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( CcdServerTest, "CcdServerTest" );
  25329. #endif